Merge main into feat/print-custom-scale-link

This commit is contained in:
dotCooCoo committed 2026-11-16 09:27:43 -08:00
commit 1712dbd247
147 files changed
+12782 -685

No files matched your search

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, .. } => {
+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
@@ -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")));
}
+26 -7
View File
@@ -14,7 +14,8 @@
//! bounded by its art (`crop: "bounding"`).
//! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by
//! its art: the document an EPS file of ours carries, else what its PostScript draws, else its
//! preview ([`fileio::load`]).
//! preview ([`fileio::load`]). With Link, one placed from a file becomes a placed document
//! instead, as a PDF page does.
//! - A DCS file, an EPS file with one program per printing plate, becomes one linked image of its
//! plates ([`dcs`]); it is never embedded.
//! - A PDF/.ai/.ait page or a native document's artboard becomes one group, clipped to the page
@@ -81,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot p Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its pl Line truncated
has_doc,
place
),
@@ -125,8 +126,8 @@ enum Art {
/// A text file's, an RTF file's or a Word document's text, placed as area type filling the
/// natural box.
Text(text::Story),
/// A VectorCraft document or a PDF/.ai page placed linked: the file read, the link, and
/// whether the art's bounds (not the artboard or page) are shown.
/// A VectorCraft document, a PDF/.ai page or an EPS file placed linked: the file read, the
/// link, and whether the art's bounds (not the artboard or page) are shown.
Document(document::Source, LinkInfo, bool),
/// A DCS file: one linked image of its plates, clipped by its clipping path ([`dcs`]).
Dcs(Box<dcs::DcsArt>),
@@ -158,6 +159,16 @@ struct Loaded {
/// of its art, and their options.
type Slices = Vec<(Rect, SliceOptions)>;
/// The most bytes [`head_is_dcs`] reads from the start of a file.
pub const DCS_HEAD_BYTES: usize = dcs::HEAD_BYTES;
/// Does `head`, the start of a file `size` bytes long (at most [`DCS_HEAD_BYTES`] of it, or all of
/// it), name DCS plates? `file.place` places such a file as a linked image, never as a placed
/// document. `None` when `head` can't tell.
pub fn head_is_dcs(head: &[u8], size: u64) -> Option<bool> {
dcs::head_is_dcs(head, size)
}
/// Points per pixel of a raster image at the resolution it declares (72 ppi when none).
pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
let (x, y) = ppi.unwrap_or((72.0, 72.0));
@@ -177,9 +188,9 @@ fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Res
}
/// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board`
/// (unless the params name their own box). A PDF/.ai page read from a path is placed linked with
/// Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB file's slices
/// go to `slices`.
/// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed
/// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB
/// file's slices go to `slices`.
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
let src = fileio::source(p, cmd)?;
let name = fileio::file_name(src.name);
@@ -324,6 +335,14 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
}
// An EPS file (or a PostScript .ai) with Link: placed like a PDF page, its art read as below.
if let Some(path) = src.path.filter(|_| link_pdf && bool_or(p, "link", true) && document::is_postscript(&src.bytes)) {
let page = page as u32;
let s = document::source(src.name, &src.bytes, Some(path), page, !crop, PageBox::Crop, cmd)?;
let link = LinkInfo { page: Some(page), ..super::links::link_info(path, &src.bytes) };
let (natural, warnings) = (s.frame, s.warnings.clone());
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
}
let anchored = format.id == "dxf" && (opts.dxf.fit || !opts.dxf.center);
let (mut doc, warnings) = {
// Of the open options, only a DXF drawing's apply (the colour mode stays the file's).
+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",
+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");
+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"})),
+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() {
+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")),
+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:?}");
}
}
}
}
+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
+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 {
+46
View File
@@ -1505,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]
);
}
}
+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
}
+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;
+1
View File
@@ -339,6 +339,7 @@ registry! {
Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC,
ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC,
ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC,
ResetActions: [confirm::RESET_ACTIONS] => confirm::RESET_ACTIONS_SPEC,
NewSwatch: [new_swatch::KIND] => new_swatch::SPEC,
NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC,
GraphData: [graph_data::KIND] => graph_data::SPEC,
+22
View File
@@ -134,6 +134,28 @@ fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
Ok(Value::Null)
}
/// The dialog kind of the question Reset Actions asks in the Actions panel menu
/// ([`ask_reset_actions`]). Fields: `message`, `detail`, `append` (set by Append).
pub const RESET_ACTIONS: &str = "resetActions";
pub(super) const RESET_ACTIONS_SPEC: DialogSpec = DialogSpec { confirm: reset_actions, alternate: Some(("Append", "append")), ..SPEC };
/// Ask whether to replace the Actions panel's sets with the built-in set. OK replaces them, Append
/// adds the built-in set after them ([`crate::panels::actions::reset`]), and Cancel or Escape
/// changes nothing.
pub(crate) fn ask_reset_actions(app: &mut VectorcraftApp) {
let message = tl!("Replace the current actions with the default set?");
let detail = tl!("Append adds the default set after the current sets instead.");
app.ui.dialog = Some(Dialog::new(RESET_ACTIONS, json!({"message": message, "detail": detail, "append": false})));
}
/// OK or Append on [`ask_reset_actions`]: closes, then resets the action sets.
fn reset_actions(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let mode = if d.fields.get("append").and_then(Value::as_bool) == Some(true) { "append" } else { "replace" };
app.ui.dialog = None;
app.run(crate::panels::actions::RESET, json!({ "mode": mode }))
}
/// Most messages kept for later while a dialog is open ([`tell`]).
const MAX_WAITING: usize = 16;
+67 -16
View File
@@ -30,7 +30,11 @@
//! Remove Color tool removes the color whose marker is clicked; a bar's right-click menu has Remove
//! Color too. The base color can't be removed. A removed color's row goes, unless it has current
//! colors and art or a group is open: it then keeps them, with no new color, so that art keeps its
//! colors and the group's swatch at that place goes. With art, the Prominent Colors bar under the wheel shows the new
//! colors and the group's swatch at that place goes. Under the tools, a button switches both wheels
//! to hue and brightness (black at the center, full brightness at the edge, at the base color's
//! saturation; a marker drag sets hue and brightness, Add Color adds the hue and brightness clicked
//! at the base color's saturation, and the slider under the wheel is a Saturation slider) and back;
//! switching changes no color, and the dialog opens on hue and saturation. With art, the Prominent Colors bar under the wheel shows the new
//! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the
//! edge between two parts moves width between them, and when the drag ends the rows' current
//! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color
@@ -60,7 +64,8 @@
//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s
//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`;
//! unset: `smooth`), `wheelTool` (`add`: the Add Color tool, `remove`: the Remove Color tool;
//! unset: neither, a click on the wheel selects a marker), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! unset: neither, a click on the wheel selects a marker), `wheelAxes` (`hueBrightness`: the wheels
//! show hue and brightness; `hueSaturation`, unset or any other value: hue and saturation), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as
//! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is
//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a
@@ -1488,12 +1493,27 @@ const DRAG: &str = "__drag";
/// The field of the Edit tab's wheel tools: `add` (Add Color) or `remove` (Remove Color).
const WHEEL_TOOL: &str = "wheelTool";
/// The new color the Add Color tool gives a click at hue `h` (degrees) and saturation `s`: at the
/// brightness of `base` (the base color, whose brightness the wheel shows; full without one), the
/// segmented wheel's patch color with `segmented`, in `base`'s model.
fn added_color(base: Option<Color>, h: f32, s: f32, segmented: bool) -> Color {
let v = base.map_or(1.0, |b| b.to_hsb()[2]);
let c = if segmented { widgets::segment_color(h, s, v) } else { Color::from_hsb(h, s, v) };
/// The field of what the Edit tab's wheels show: `hueBrightness` (hue and brightness), or anything
/// else (hue and saturation).
const WHEEL_AXES: &str = "wheelAxes";
/// What the Edit tab's wheels show, from [`WHEEL_AXES`].
fn wheel_axes(d: &Dialog) -> widgets::WheelAxes {
if d.str(WHEEL_AXES) == "hueBrightness" { widgets::WheelAxes::HueBrightness } else { widgets::WheelAxes::HueSaturation }
}
/// The new color the Add Color tool gives a click at hue `h` (degrees) and `t`, the saturation (or
/// with [`widgets::WheelAxes::HueBrightness`] the brightness) clicked: with the other component of
/// `base` (the base color, whose other component the wheel shows; full without one), the segmented
/// wheel's patch color with `segmented`, in `base`'s model.
fn added_color(base: Option<Color>, h: f32, t: f32, segmented: bool, axes: widgets::WheelAxes) -> Color {
let o = base.map_or(1.0, |b| b.to_hsb()[axes.other()]);
let c = if segmented {
widgets::segment_color_on(axes, h, t, o)
} else {
let [h, s, v] = axes.hsb(h, t, o);
Color::from_hsb(h, s, v)
};
base.map_or(c, |b| keep_model(b, c))
}
@@ -1594,6 +1614,7 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Va
let marked = base.and_then(|b| active.iter().position(|&i| i == b));
let display = d.str("display");
let tool = d.str(WHEEL_TOOL);
let axes = wheel_axes(d);
// The tools act on either wheel, not on the color bars.
let on_wheel = display != "bars";
let mut w = widgets::WheelResponse::default();
@@ -1618,18 +1639,25 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Va
d.fields.insert(WHEEL_TOOL.into(), if on { Value::Null } else { json!(id) });
}
}
// What the wheels show: a click switches between hue and saturation, and hue and
// brightness. It changes no color.
ui.add_space(8.0);
let bright = axes == widgets::WheelAxes::HueBrightness;
let tip = if bright { tl!("Show saturation and hue on wheel") } else { tl!("Show brightness and hue on wheel") };
if widgets::icon_button_enabled(ui, "sun", tip, bright && on_wheel, on_wheel, 24.0).clicked() {
d.fields.insert(WHEEL_AXES.into(), json!(if bright { "hueSaturation" } else { "hueBrightness" }));
}
});
ui.vertical(|ui| match display.as_str() {
"segmented" => w = widgets::segmented_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
"bars" => changed |= color_bars(ui, d, rows, &active, base),
_ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
_ => w = widgets::wheel_of(ui, "recolor-wheel", WHEEL, &colors, marked, display == "segmented", axes),
});
});
// A click with a wheel tool adds a color there, or removes the color of the marker clicked.
let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove"));
if let Some((hit, [h, s])) = clicked {
if let Some((hit, [h, out])) = clicked {
if tool == "add" {
let c = added_color(base.and_then(|b| to_color(&rows[b])), h, s, display == "segmented");
let c = added_color(base.and_then(|b| to_color(&rows[b])), h, out, display == "segmented", axes);
let i = add_color(rows, &c);
d.fields.insert("__sel".into(), json!([i]));
d.fields.remove(COMPS);
@@ -1881,12 +1909,35 @@ mod tests {
#[test]
fn an_added_color_takes_the_base_colors_brightness_and_model() {
let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
let sat = widgets::WheelAxes::HueSaturation;
let base = Color::from_hsb(10.0, 0.8, 0.6);
assert!(near(added_color(Some(base), 120.0, 0.5, false).to_hsb(), [120.0, 0.5, 0.6]));
assert!(near(added_color(None, 200.0, 0.25, false).to_hsb(), [200.0, 0.25, 1.0]));
assert!(near(added_color(None, 7.0, 0.95, true).to_hsb(), [0.0, 0.9, 1.0]), "the patch's color");
assert!(near(added_color(Some(base), 120.0, 0.5, false, sat).to_hsb(), [120.0, 0.5, 0.6]));
assert!(near(added_color(None, 200.0, 0.25, false, sat).to_hsb(), [200.0, 0.25, 1.0]));
assert!(near(added_color(None, 7.0, 0.95, true, sat).to_hsb(), [0.0, 0.9, 1.0]), "the patch's color");
let cmyk = color_value(&json!("cmyk 0 100 100 0")).unwrap();
assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false), Color::Cmyk { .. }));
assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false, sat), Color::Cmyk { .. }));
}
/// On the hue and brightness wheel an added color is the hue and brightness clicked at the base
/// color's saturation (full without one), the patch's color on the segmented wheel (its ring is
/// a brightness step), in the base color's model. A black base adds a gray of the brightness
/// clicked, and the wheel's center is black.
#[test]
fn an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation() {
let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
let bright = widgets::WheelAxes::HueBrightness;
let base = Color::from_hsb(10.0, 0.8, 0.6);
assert!(near(added_color(Some(base), 120.0, 0.5, false, bright).to_hsb(), [120.0, 0.8, 0.5]));
assert!(near(added_color(None, 200.0, 0.25, false, bright).to_hsb(), [200.0, 1.0, 0.25]));
assert!(near(added_color(Some(base), 7.0, 0.95, true, bright).to_hsb(), [0.0, 0.8, 0.9]), "the patch's color");
assert!(near(added_color(Some(base), 7.0, 0.0, true, bright).to_hsb(), [0.0, 0.8, 0.1]), "the innermost ring");
let black = Color::from_hsb(0.0, 0.0, 0.0);
let [_, s, v] = added_color(Some(black), 90.0, 0.4, false, bright).to_hsb();
assert!(s.abs() < 1e-3 && (v - 0.4).abs() < 1e-3, "a gray: {s} {v}");
let [_, _, v] = added_color(Some(base), 33.0, 0.0, false, bright).to_hsb();
assert!(v.abs() < 1e-3, "black at the center");
let cmyk = color_value(&json!("cmyk 0 100 100 0")).unwrap();
assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false, bright), Color::Cmyk { .. }));
}
/// With a color group and art, a row without a new color removes its swatch in its place, the
+33
View File
@@ -2524,6 +2524,39 @@ fn flare_options_alt_turns_cancel_into_reset() {
);
}
/// Reset Actions' question: OK replaces the action sets with the built-in set, Append adds the
/// built-in set after them, and Cancel or Escape (`cancel`) leaves them as they are.
#[test]
fn reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets() {
use crate::panels::actions::{ActionSet, default_sets};
let names = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.name.clone()).collect::<Vec<_>>();
let mut app = app();
app.ui.action_sets.push(ActionSet::new("Mine", vec![]));
app.ui.action_set = Some(1);
let mut f = Frames::new();
for (answer, want, current) in [
(Some("Cancel"), vec!["Default Actions", "Mine"], Some(1)),
(None, vec!["Default Actions", "Mine"], Some(1)),
(Some("Append"), vec!["Default Actions", "Mine", "Default Actions 2"], Some(1)),
(Some("OK"), vec!["Default Actions"], Some(0)),
] {
crate::dialogs::confirm::ask_reset_actions(&mut app);
match answer {
Some(label) => {
let at = f.button(&mut app, label);
f.press(&mut app, at, true);
f.press(&mut app, at, false);
}
None => cancel(&mut app),
}
assert!(app.ui.dialog.is_none(), "{answer:?} closes the question");
assert_eq!(names(&app), want, "{answer:?}");
assert_eq!(app.ui.action_set, current, "{answer:?}");
}
let saved = |sets: &[ActionSet]| serde_json::to_value(sets).unwrap();
assert_eq!(saved(&app.ui.action_sets), saved(&default_sets()), "OK leaves the built-in set as it comes");
}
/// The slider that screen readers name `label` in `out`'s tree: its node id, number and text.
fn slider_node(out: &egui::FullOutput, label: &str) -> (egui::accesskit::NodeId, Option<f64>, Option<String>) {
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
+22 -8
View File
@@ -4,7 +4,9 @@
//! the main window, it is a window inside the app's window, as floating panels are
//! ([`crate::panel_docking`]). The current document's window holds the canvas
//! ([`crate::canvas::show`]); each other window draws its document as a Tile pane does
//! ([`crate::canvas::pane`]), and a press in it makes its document the current one.
//! ([`crate::canvas::pane`]), and a press in it makes its document the current one. In a window
//! inside the app's window, a Selection drag released over that pane drops the dragged artwork into
//! its document ([`crate::canvas::release_on_noted`]); an OS window's pane does not take it.
//!
//! A document tab dragged off the tab strip floats its document in a window under the pointer,
//! and a document window dragged onto the tab strip by its title bar (an OS window by the tab at
@@ -95,6 +97,10 @@ pub struct Windows {
known: Vec<u64>,
/// The documents' views beyond the one each shows ([`views`]).
pub(crate) views: Views,
/// The panes the last frame drew outside Tile that a Selection drag's artwork can be released
/// in ([`crate::canvas::note_drop`]): each window's view ([`views::key`]), the part of its pane
/// inside its rulers and scroll bars in the main window's points, and the layer it drew in.
pub(crate) drops: Vec<((u64, u32), egui::Rect, egui::LayerId)>,
}
impl Windows {
@@ -325,7 +331,7 @@ pub(crate) fn dock_all(app: &mut VectorcraftApp) {
/// floats panels by the same rule), and no control channel is attached. With a control channel the
/// windows stay inside the main window, where `ui.click`, `ui.drag` and `ui.screenshot` reach them
/// and `canvasRect` is in the main window's coordinates.
fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
pub(crate) fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
if ctx.embed_viewports() || app.control_rx.is_some() {
return false;
}
@@ -469,6 +475,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
activate = Some(win);
}
}
// After every canvas, which sets the cursor of the drag it holds.
crate::canvas::noted_cursor(app, ctx);
// The tab strip a dragged window would go back under shows where it lands.
if let Some(strip) = app.canvas.windows.strip.filter(|_| over_strip) {
let t = crate::theme::Tokens::get(ctx);
@@ -499,9 +507,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// Window `win`'s body in `ui`: the canvas for the current window, else (and while `blocked` by a
/// modal) a pane. The view fits the body again when the body changed size since `fit` and the view
/// has not moved. → whether a press in the pane asks for its window to become the current one, the
/// body's rect and the fit after this frame.
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool), fit: Option<Fit>) -> (bool, egui::Rect, Option<Fit>) {
/// has not moved. With `drops`, a pane drawn while no modal blocks it is noted as a place a Selection
/// drag's artwork can be released in ([`crate::canvas::note_drop`]). → whether a press in the pane
/// asks for its window to become the current one, the body's rect and the fit after this frame.
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool), fit: Option<Fit>, drops: bool) -> (bool, egui::Rect, Option<Fit>) {
let t = crate::theme::Tokens::get(ui.ctx());
let rect = ui.available_rect_before_wrap();
ui.painter().rect_filled(rect, 0.0, t.pasteboard);
@@ -517,7 +526,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool)
crate::canvas::show(app, ui);
false
} else {
crate::canvas::pane(app, ui, win, rect)
let pressed = crate::canvas::pane(app, ui, win, rect);
if drops && !blocked {
crate::canvas::note_drop(app, ui, win, rect);
}
pressed
};
ui.advance_cursor_after_rect(rect);
let fit = match view(app, win) {
@@ -564,7 +577,8 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win,
}
let tab = crate::chrome::window_tab(app, ui, win);
let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, ((w.uid, w.view), origin), &tab, strip) };
let (pressed, rect, fit) = body(app, ui, (win, blocked), w.fit);
// The OS window's points are not the main window's: its pane takes no artwork.
let (pressed, rect, fit) = body(app, ui, (win, blocked), w.fit, false);
let activate = pressed || (!blocked && (tab.clicked() || tab.drag_started()));
// Keys the window's widgets left over run the main window's shortcuts and tool keys, as a
// floating panel's do.
@@ -649,7 +663,7 @@ fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win
.frame(frame)
.open(&mut open)
.show(ctx, |ui| {
let (pressed, r, f) = body(app, ui, (win, blocked), fit);
let (pressed, r, f) = body(app, ui, (win, blocked), fit, true);
(activate, rect, fit) = (pressed, Some(r), f);
});
// A press on its title bar or edges, which brings the window to the front, also makes its
+300
View File
@@ -925,3 +925,303 @@ fn switching_views_targets_the_artboard_the_view_shows() {
show_window(&mut app, (0, 2));
assert_eq!(app.session.tool_options()["active"], json!(1));
}
/// One headless frame as the app runs it: a Selection move released off the canvas ends first
/// ([`crate::canvas::release_over_panel`]), then the tabs and the canvas or panes, then the floating
/// document windows. → the cursor.
fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::CursorIcon {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
max_texture_side: Some(8192),
events,
..Default::default()
};
let mut out = ctx.run_ui(raw, |ui| {
crate::canvas::release_over_panel(app, ui.ctx());
app.canvas_area(ui);
show(app, ui.ctx());
});
out.textures_delta.clear();
out.platform_output.cursor_icon
}
/// Two 400 × 300 pt documents on `ctx`: the first, current under its tab, holds a 50 pt square at
/// 300, 230, and the second, in a floating window, a 50 pt square at 50, 50. The Selection tool is
/// chosen.
fn floating_pair(ctx: &egui::Context) -> VectorcraftApp {
let mut app = app_with(0);
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("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 50, "height": 50})).unwrap();
app.run("window.arrange.floatInWindow", json!({})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.select_tool("selection");
app.ui.task_bar = false;
app_frame(&mut app, ctx, vec![]);
app_frame(&mut app, ctx, vec![]);
app
}
/// Press on document point `at` on the canvas, clear of document 1's window when it floats, and
/// move the pointer 10 × 5 points: the Selection tool moves the art under it.
fn grab(app: &mut VectorcraftApp, ctx: &egui::Context, at: vectorcraft_geom::Point) {
let p = crate::canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(at);
if app.session.documents().len() > 1 && app.session.active_index() != Some(1) && is_floating(app, 1) {
assert!(!window_of(app, ctx, 1).contains(p), "the art is clear of the floating window");
}
app_frame(app, ctx, vec![egui::Event::PointerMoved(p), button(p, true)]);
app_frame(app, ctx, vec![egui::Event::PointerMoved(p + vec2(10.0, 5.0))]);
assert!(app.session.in_interaction(), "the Selection tool moves the art");
}
/// The screen point that shows document point `at` in window `w`'s pane, which the last frame noted
/// as a place to release artwork in.
fn in_noted(app: &VectorcraftApp, w: Win, at: vectorcraft_geom::Point) -> Pos2 {
let k = key(app, w).unwrap();
let (_, area, _) = app.canvas.windows.drops.iter().find(|(s, _, _)| *s == k).unwrap();
crate::canvas::Xf::at(*area, view(app, w).unwrap(), 1.0).to_screen(at)
}
/// 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 center of the one object selected in the current document.
fn selected_center(app: &VectorcraftApp) -> vectorcraft_geom::Point {
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().center()
}
#[test]
fn a_selection_drag_released_in_another_documents_floating_window_copies_the_art_there() {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
// The target's view differs from the source's: the grab point still lands under the pointer.
let v = view_mut(&mut app, (1, 1)).unwrap();
v.zoom *= 0.6;
v.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, vectorcraft_geom::Point::new(325.0, 255.0));
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(170.0, 120.0));
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
assert_eq!(cursor, egui::CursorIcon::Copy, "over another document's window the art is copied");
assert_eq!(app.session.active_index(), Some(0), "holding the art over the window does not switch documents");
app_frame(&mut app, &ctx, vec![button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(1), "the window's document is the current one");
assert_eq!(objects(&app, 1), 2, "the copy joins the target's square");
let placed = selected_center(&app);
assert!((placed.x - 170.0).abs() < 0.01 && (placed.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);
}
#[test]
fn a_release_in_the_first_frame_over_a_floating_window_still_copies_the_art() {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
let source = app.session.documents()[0].doc.clone();
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
// The canvas has not handed the move over yet: the pane takes it before the canvas sees the
// release.
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));
assert_eq!(objects(&app, 1), 2);
let placed = selected_center(&app);
assert!((placed.x - 200.0).abs() < 0.01 && (placed.y - 150.0).abs() < 0.01, "{placed:?}");
assert_eq!(app.session.documents()[0].doc, source);
}
#[test]
fn a_floating_window_drop_lands_where_the_button_went_up() {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
let later = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(120.0, 220.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
// A pointer move later in the frame of the release does not move the drop.
app_frame(&mut app, &ctx, vec![button(drop, false), egui::Event::PointerMoved(later)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(1));
assert_eq!(objects(&app, 1), 2);
let placed = selected_center(&app);
assert!((placed.x - 200.0).abs() < 0.01 && (placed.y - 150.0).abs() < 0.01, "{placed:?}");
}
#[test]
fn art_dragged_from_a_floating_window_drops_into_the_main_windows_document() {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
show_window(&mut app, (1, 1));
app_frame(&mut app, &ctx, vec![]);
app_frame(&mut app, &ctx, vec![]);
assert!(current_floats(&app), "the floating window holds the canvas");
let target = app.session.documents()[1].doc.clone();
grab(&mut app, &ctx, vectorcraft_geom::Point::new(75.0, 75.0));
// The main window draws document 0 as a pane; this point is clear of the floating window.
let at = vectorcraft_geom::Point::new(360.0, 40.0);
let drop = in_noted(&app, (0, 1), at);
assert!(!window_of(&app, &ctx, 1).contains(drop), "{drop:?}");
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
assert_eq!(cursor, egui::CursorIcon::Copy);
app_frame(&mut app, &ctx, vec![button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(0), "the main window's document is the current one");
assert_eq!(objects(&app, 0), 2);
let placed = selected_center(&app);
assert!((placed.x - at.x).abs() < 0.01 && (placed.y - at.y).abs() < 0.01, "{placed:?}");
assert_eq!(app.session.documents()[1].doc, target, "the source in the floating window is untouched");
}
#[test]
fn a_selection_drag_into_a_floating_view_of_its_document_moves_the_art() {
let ctx = egui::Context::default();
let mut app = app_with(0);
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("window.newWindow", json!({})).unwrap();
app.run("window.arrange.floatInWindow", json!({})).unwrap();
show_window(&mut app, (0, 1));
app.select_tool("selection");
app.ui.task_bar = false;
app_frame(&mut app, &ctx, vec![]);
app_frame(&mut app, &ctx, vec![]);
assert!(floats(&app, (0, 2)) && current(&app) == Some((0, 1)));
let undo = app.session.documents()[0].history.undo.len();
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
let drop = in_noted(&app, (0, 2), vectorcraft_geom::Point::new(150.0, 100.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!(current(&app), Some((0, 2)), "the floating view is the current window");
assert_eq!(objects(&app, 0), 1, "the square moved, not copied");
let moved = selected_center(&app);
assert!((moved.x - 150.0).abs() < 0.01 && (moved.y - 100.0).abs() < 0.01, "{moved:?}");
assert_eq!(app.session.documents()[0].history.undo.len(), undo + 1);
}
#[test]
fn a_drag_released_on_a_floating_windows_title_bar_or_after_escape_changes_nothing() {
for (case, escape) in [("title bar", false), ("art area after Escape", true)] {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
let docs: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
let (window, body) = (window_of(&app, &ctx, 1), body_of(&app, 1));
let at = if escape {
in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0))
} else {
pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0)
};
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 a_tab_transfer_whose_source_changed_drops_nothing_in_a_floating_window() {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
app.run("file.new", json!({"width": 400, "height": 300, "name": "Third"})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.select_tool("selection");
app_frame(&mut app, &ctx, vec![]);
let tab = tab_at(&frame(&mut app, &ctx, vec![]), "Third");
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
// Held over the third document's tab, the drag becomes a transfer to that document.
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab)]);
for _ in 0..60 {
if app.session.active_index() == Some(2) {
break;
}
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.session.active_index(), Some(2), "the tab hover switched documents");
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
// The source changes between frames, as a command from the control channel would change it.
app.session.set_active(0);
app.session.execute("shape.ellipse", &json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap();
app.session.set_active(2);
let target = app.session.documents()[1].doc.clone();
let target_undo = app.session.documents()[1].history.undo.len();
app_frame(&mut app, &ctx, vec![button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.documents()[1].doc, target, "the floating window's document does not take the changed art");
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo);
assert_eq!(app.session.active_index(), Some(2), "the window does not become current");
}
#[test]
fn a_tab_transfer_whose_target_is_no_longer_current_drops_nothing_in_a_floating_window() {
let ctx = egui::Context::default();
let mut app = floating_pair(&ctx);
app.run("file.new", json!({"width": 400, "height": 300, "name": "Third"})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.select_tool("selection");
app_frame(&mut app, &ctx, vec![]);
let tab = tab_at(&frame(&mut app, &ctx, vec![]), "Third");
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab)]);
for _ in 0..60 {
if app.session.active_index() == Some(2) {
break;
}
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.session.active_index(), Some(2), "the tab hover switched documents");
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
// Another document becomes current between frames, as a command from the control channel
// would make it.
app.session.set_active(0);
let target = app.session.documents()[1].doc.clone();
let target_undo = app.session.documents()[1].history.undo.len();
app_frame(&mut app, &ctx, vec![button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.documents()[1].doc, target, "the floating window's document does not take the art");
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo);
assert_eq!(app.session.active_index(), Some(0), "the window does not become current");
}
#[test]
fn an_os_windows_pane_is_not_a_place_to_release_art_in_the_main_windows_points() {
let _host = native_host();
let ctx = egui::Context::default();
ctx.set_embed_viewports(false);
if !native(&app_with(0), &ctx) {
// Wayland: the windows are inside the main window.
return;
}
let mut app = floating_pair(&ctx);
assert!(app.canvas.windows.drops.is_empty(), "the other document's OS window is not noted");
show_window(&mut app, (1, 1));
app_frame(&mut app, &ctx, vec![]);
assert!(app.canvas.windows.drops.is_empty(), "nor is the main window's pane while an OS window holds the canvas");
}
+120 -6
View File
@@ -1,4 +1,5 @@
//! A selection dragged across document tabs remains editable and leaves its source intact.
//! A selection dragged across document tabs, or into another document's tiled pane or floating
//! window, remains editable and leaves its source intact.
use std::sync::Arc;
@@ -90,13 +91,15 @@ pub(crate) fn cleanup(app: &VectorcraftApp, ctx: &Context) {
|| i.multi_touch().is_some()
|| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::Cancel, .. }))
});
let outside_release =
ctx.input(|i| i.pointer.primary_released() && !app.canvas_rect.is_some_and(|r| i.pointer.interact_pos().is_some_and(|p| r.contains(p))));
// The canvas and the other windows' tiled panes take a release ([`drop_on_pane`]).
let target = |p: egui::Pos2| app.canvas_rect.is_some_and(|r| r.contains(p)) || app.canvas.panes.last.iter().any(|(_, r)| r.contains(p));
let outside_release = ctx.input(|i| i.pointer.primary_released() && !released_at(i).is_some_and(target));
if !valid || cancel || outside_release || app.ui.dialog.is_some() {
egui::DragAndDrop::clear_payload(ctx);
}
}
if !ctx.input(|i| i.pointer.primary_down()) {
// The source and grab point last through the release, for the pane it is released over.
if !ctx.input(|i| i.pointer.primary_down() || i.pointer.primary_released()) {
ctx.data_mut(|d| {
d.remove::<Origin>(origin_id());
d.remove::<Hover>(hover_id());
@@ -193,11 +196,17 @@ pub(crate) fn drop_on_canvas(app: &mut VectorcraftApp, resp: &Response, xf: &can
if resp.contains_pointer() {
resp.ctx.set_cursor_icon(if same && !copy { egui::CursorIcon::Move } else { egui::CursorIcon::Copy });
}
if let Some(art) = resp.dnd_release_payload::<Artwork>()
&& let Some(at) = resp.ctx.input(|i| i.pointer.interact_pos()).map(|p| xf.to_doc(p))
// The canvas takes a release where the button went up, as [`cleanup`] judges it, and not where
// a later move in the same frame leaves the pointer.
let ctx = &resp.ctx;
let over = |p: egui::Pos2| resp.interact_rect.contains(p) && !ctx.layer_id_at(p).is_some_and(|l| l != resp.layer_id);
if let Some(p) = ctx.input(|i| i.pointer.primary_released().then(|| released_at(i)).flatten()).filter(|p| over(*p))
&& let Some(art) = egui::DragAndDrop::take_payload::<Artwork>(ctx)
{
let at = xf.to_doc(p);
let result = if same {
// Back in the source tab, resume the ordinary move (Alt copies).
let copy = release_alt(&resp.ctx);
app.run("object.move", json!({"ids": art.ids, "dx": at.x-art.origin.grab.x, "dy": at.y-art.origin.grab.y, "copy": copy}))
} else {
app.run(
@@ -210,3 +219,108 @@ pub(crate) fn drop_on_canvas(app: &mut VectorcraftApp, resp: &Response, xf: &can
}
}
}
/// The artwork a Selection drag carries out of its canvas, taken by another window's tiled pane
/// ([`take_for_pane`]): its source and grab point, and the objects that travel.
pub(crate) struct Carried {
origin: Origin,
ids: Vec<NodeId>,
}
/// The artwork a Selection drag carries: the transfer a tab hover started, or a Selection move of
/// the current document that left its canvas. The canvas hands that move over as a panel drag
/// ([`widgets::PanelDrag::Art`]) the frame after the pointer leaves, and Escape drops that; until
/// then the move under way is the drag. Either way the objects the move started with travel, not
/// an Alt-drag's preview copies.
fn carried(app: &VectorcraftApp, ctx: &Context) -> Option<Carried> {
if ctx.input(|i| !i.focused || i.multi_touch().is_some() || i.key_pressed(egui::Key::Escape)) || app.ui.dialog.is_some() {
return None;
}
if let Some(art) = egui::DragAndDrop::payload::<Artwork>(ctx) {
// The same checks as [`cleanup`]: a floating window's pane takes the release before cleanup
// runs, and an edited or closed source, or a target that is no longer the current
// document, carries nothing.
let source = app.session.documents().iter().any(|d| d.uid == art.origin.uid && d.same_content(&art.source));
let target = app.session.active().is_some_and(|d| d.uid == art.target);
return (source && target).then(|| Carried { origin: art.origin.clone(), ids: art.ids.clone() });
}
let origin = ctx.data(|d| d.get_temp::<Origin>(origin_id()))?;
let st = app.session.active().filter(|d| d.uid == origin.uid)?;
let ids = match egui::DragAndDrop::payload::<widgets::PanelDrag>(ctx).as_deref() {
Some(widgets::PanelDrag::Art(ids)) => ids.clone(),
Some(_) => return None,
None if canvas::art_out(ctx) => return None,
None => st.interaction.as_ref().filter(|i| i.label == "Move" || i.label == "Copy")?.selection.objects.clone(),
};
(!ids.is_empty()).then_some(Carried { origin, ids })
}
/// Over the tiled pane of a window of document `uid`, while a Selection drag carries artwork: the
/// cursor that shows a move for another view of the source document without Alt, and a copy
/// otherwise. None when no artwork is carried.
pub(crate) fn pane_cursor(app: &VectorcraftApp, ctx: &Context, uid: u64) -> Option<egui::CursorIcon> {
let c = carried(app, ctx)?;
let copy = ctx.input(|i| i.modifiers.alt);
Some(if c.origin.uid == uid && !copy { egui::CursorIcon::Move } else { egui::CursorIcon::Copy })
}
/// A release over another window's tiled pane takes the carried artwork: the drag ends, and a
/// move still under way on the canvas goes back to where it started, before the canvas sees the
/// release ([`canvas::end_art_move`]).
pub(crate) fn take_for_pane(app: &mut VectorcraftApp, ctx: &Context) -> Option<Carried> {
let c = carried(app, ctx)?;
let moving = !egui::DragAndDrop::has_payload_of_type::<Artwork>(ctx) && app.session.in_interaction();
egui::DragAndDrop::clear_payload(ctx);
ctx.data_mut(|d| d.remove::<Origin>(origin_id()));
if moving {
canvas::end_art_move(app, ctx);
}
Some(c)
}
/// The artwork `c` taken over window `w`'s tiled pane ([`take_for_pane`]), released at document
/// point `at` in that pane's view: `w` becomes the current window, and the artwork lands with its
/// grab point at `at`. Into another document it is copied (`edit.dropSelection`), and the source
/// stays as it was; in another view of the source document it moves, and Alt copies it
/// (`object.move`). When the command fails, the window that was current stays current and the
/// status bar shows the error.
pub(crate) fn drop_on_pane(app: &mut VectorcraftApp, ctx: &Context, w: crate::doc_windows::Win, at: Point, c: Carried) {
let Carried { origin, ids } = c;
let Some(uid) = app.session.documents().get(w.0).map(|d| d.uid) else { return };
let before = crate::doc_windows::current(app);
app.ui.home = None;
crate::doc_windows::show_window(app, w);
let result = if uid == origin.uid {
let copy = release_alt(ctx);
app.run("object.move", json!({"ids": ids, "dx": at.x - origin.grab.x, "dy": at.y - origin.grab.y, "copy": copy}))
} else {
app.run("edit.dropSelection", json!({"sourceDocument": origin.uid, "ids": ids, "grab": [origin.grab.x, origin.grab.y], "at": [at.x, at.y]}))
};
if let Err(e) = result {
if let Some(b) = before {
crate::doc_windows::show_window(app, b);
}
app.status(e);
}
ctx.request_repaint();
}
/// The primary button's release in this frame: where it went up, and the modifiers held then.
fn primary_release(i: &egui::InputState) -> Option<(egui::Pos2, egui::Modifiers)> {
i.events.iter().find_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } => Some((*pos, *modifiers)),
_ => None,
})
}
/// Where the primary button went up in this frame, else where the pointer is. A pointer move later
/// in the frame of the release does not change where the artwork is released.
pub(crate) fn released_at(i: &egui::InputState) -> Option<egui::Pos2> {
primary_release(i).map(|(p, _)| p).or(i.pointer.interact_pos())
}
/// Whether Alt was held when the primary button went up in this frame, else whether it is held now.
/// Alt let go later in the frame of the release still copies.
fn release_alt(ctx: &Context) -> bool {
ctx.input(|i| primary_release(i).map_or(i.modifiers.alt, |(_, m)| m.alt))
}
+33 -2
View File
@@ -1504,6 +1504,8 @@ font-technology Variable Променливи
Show smooth color wheel Показване на плавно цветово колело
Show segmented color wheel Показване на сегментирано цветово колело
Show color bars Показване на цветни ленти
Show brightness and hue on wheel Показване на яркост и оттенък на колелото
Show saturation and hue on wheel Показване на насищане и оттенък на колелото
Add Color Tool Инструмент „Добавяне на цвят“
Remove Color Tool Инструмент „Премахване на цвят“
Remove Color Премахване на цвят
@@ -2571,6 +2573,10 @@ font-technology Variable Променливи
Play Current Selection Изпълнение на текущия избор
Save Actions… Запазване на действия…
Load Actions… Зареждане на действия…
Reset Actions Нулиране на действия
Replace the current actions with the default set? Да се заменят ли текущите действия с набора по подразбиране?
Append adds the default set after the current sets instead. С „Добавяне“ наборът по подразбиране се добавя след текущите набори.
Append Добавяне
Plug-in Info Информация за приставката
Plug-ins Приставки
Plug-in… Приставка…
@@ -3182,8 +3188,12 @@ digits Malayalam Малаялам
Scripts Скриптове
Search Търсене
Search All Търсене във всички
Search commands and tools Търсене на команди и инструменти
Search commands and tools… Търсене на команди и инструменти…
Search commands, tools, panels and effects Търсене на команди, инструменти, панели и ефекти
Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти…
No commands match Няма съвпадащи команди
{pos} of {total}: {name} {pos} от {total}: {name}
@plural {n} result|{n} results {n} резултат|{n} резултата
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните.
Recent Commands Последни команди
No recent commands Няма последни команди
Search Commands… Търсене на команди…
@@ -4165,6 +4175,7 @@ imageTrace Outline Контур
to set spacing and orientation за задаване на разстояние и ориентация
: :
Isolate Selected Group Изолиране на избраната група
Isolate Selected Path Изолиране на избрания път
Release Clipping Mask Освобождаване на маска за изрязване
Make Compound Path Създаване на съставен път
Release Compound Path Освобождаване на съставен път
@@ -7089,4 +7100,24 @@ breakText Glyphs Глифи
No objects are selected. Няма избрани обекти.
Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване.
Remove Fold Line Role Премахни вида на линията
Check Провери
Check Fold Lines Провери линиите на сгъване
@msg No cut lines are in the selection. В селекцията няма линии за рязане.
@msg No cut lines are in the document. В документа няма линии за рязане.
@msg The cut lines do not enclose an area. Линиите за рязане не ограждат площ.
@msg A cut line ends without meeting another cut line. Линия за рязане завършва, без да срещне друга линия за рязане.
@msg A gap between cut lines was closed. Процеп между линии за рязане беше затворен.
@msg The fold lines are too complex to check. Линиите на сгъване са твърде сложни за проверка.
@msg A cut line and a crease lie on top of each other. Линия за рязане и линия за биговане лежат една върху друга.
@msg No cut lines are among the given objects. Сред дадените обекти няма линии за рязане.
@msg Two fold lines lie on top of each other. Две линии на сгъване лежат една върху друга.
@msg A crease ends inside a panel. Линия за биговане завършва вътре в панел.
@msg A crease does not divide two panels. Линия за биговане не разделя два панела.
@msg A crease lies outside the cut outline, wholly or in part. Линия за биговане лежи изцяло или отчасти извън контура за рязане.
@msg The pieces of a hinge are not on one straight line. Частите на една панта не лежат на една права линия.
@msg A gap between cut lines is too narrow to tell apart. Процеп между линии за рязане е твърде тесен, за да се различи.
@msg A cut-out area holds other fold lines or another blank. Изрязана област съдържа други линии на сгъване или друг разкрой.
@msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане.
@msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Can't render this file because it is too large.
+33 -2
View File
@@ -880,6 +880,7 @@
Auto Color Automatska boja
Automatic Automatski
Isolate Selected Group Izoliraj odabranu grupu
Isolate Selected Path Izoliraj odabranu putanju
Isolate Selected Object Izoliraj odabrani objekat
Exit Isolation Mode Izađi iz načina izolacije
Make Clipping Mask Napravi masku isijecanja
@@ -1300,7 +1301,7 @@ lighting Light Svjetlo
Name* @ 66.67% (RGB/Preview) Naziv* @ 66,67% (RGB/pregled)
No Document Nema dokumenta
Press Pritisnite
Search commands and tools Pretraži naredbe i alate
Search commands, tools, panels and effects Pretraži naredbe, alate, panele i efekte
Style: Stil:
Switch workspace Promijeni radni prostor
Show all open documents Prikaži sve otvorene dokumente
@@ -1502,6 +1503,10 @@ lighting Light Svjetlo
Play Current Selection Reprodukuj trenutni odabir
Save Actions… Sačuvaj akcije…
Load Actions… Učitaj akcije…
Reset Actions Vrati akcije na početno
Replace the current actions with the default set? Zamijeniti trenutne akcije zadanim skupom?
Append adds the default set after the current sets instead. Dugme Dodaj umjesto toga dodaje zadani skup iza trenutnih skupova.
Append Dodaj
Reflect Horizontal Odrazi vodoravno
Rotate 90° CW Rotiraj za 90° u smjeru kazaljke
Set 1 Skup 1
@@ -2928,6 +2933,8 @@ digits Malayalam Malajalam
Show smooth color wheel Prikaži glatki kotač boja
Show segmented color wheel Prikaži segmentirani kotač boja
Show color bars Prikaži trake boja
Show brightness and hue on wheel Prikaži svjetlinu i nijansu na kotaču
Show saturation and hue on wheel Prikaži zasićenje i nijansu na kotaču
Add Color Tool Alat za dodavanje boje
Remove Color Tool Alat za uklanjanje boje
Remove Color Ukloni boju
@@ -4382,7 +4389,11 @@ font-technology Variable Varijabilni
Saved {path} Sačuvano: {path}
Saving Čuvanje
Saving {} Čuvanje {}
Search commands and tools… Pretraži naredbe i alate…
Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte…
No commands match Nijedna naredba se ne podudara
{pos} of {total}: {name} {pos} od {total}: {name}
@plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.
Recent Commands Nedavne naredbe
No recent commands Nema nedavnih naredbi
Dashed Line Isprekidana linija
@@ -7143,4 +7154,24 @@ shape Open Otvoren
No objects are selected. Nijedan objekat nije odabran.
Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja.
Remove Fold Line Role Ukloni vrstu linije
Check Provjeri
Check Fold Lines Provjeri linije savijanja
@msg No cut lines are in the selection. U odabiru nema linija rezanja.
@msg No cut lines are in the document. U dokumentu nema linija rezanja.
@msg The cut lines do not enclose an area. Linije rezanja ne zatvaraju nijednu površinu.
@msg A cut line ends without meeting another cut line. Linija rezanja završava a da ne susreće drugu liniju rezanja.
@msg A gap between cut lines was closed. Razmak između linija rezanja je zatvoren.
@msg The fold lines are too complex to check. Linije savijanja su previše složene za provjeru.
@msg A cut line and a crease lie on top of each other. Linija rezanja i linija bigovanja leže jedna preko druge.
@msg No cut lines are among the given objects. Među zadanim objektima nema linija rezanja.
@msg Two fold lines lie on top of each other. Dvije linije savijanja leže jedna preko druge.
@msg A crease ends inside a panel. Linija bigovanja završava unutar panela.
@msg A crease does not divide two panels. Linija bigovanja ne razdvaja dva panela.
@msg A crease lies outside the cut outline, wholly or in part. Linija bigovanja leži potpuno ili djelimično izvan konture rezanja.
@msg The pieces of a hinge are not on one straight line. Dijelovi jedne šarke ne leže na jednoj pravoj liniji.
@msg A gap between cut lines is too narrow to tell apart. Razmak između linija rezanja je preuzak da bi se razlikovao.
@msg A cut-out area holds other fold lines or another blank. Izrezana površina sadrži druge linije savijanja ili drugi kroj.
@msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja.
@msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+66 -35
View File
@@ -2044,6 +2044,8 @@ digits Malayalam Malaiàlam
Show smooth color wheel Mostra la roda de color contínua
Show segmented color wheel Mostra la roda de color segmentada
Show color bars Mostra les barres de color
Show brightness and hue on wheel Mostra la lluentor i el to a la roda
Show saturation and hue on wheel Mostra la saturació i el to a la roda
Add Color Tool Eina Afegeix color
Remove Color Tool Eina Elimina color
Remove Color Elimina el color
@@ -2265,6 +2267,7 @@ digits Malayalam Malaiàlam
Isolate Blending Aïlla la fusió
Isolate Group Aïlla el grup
Isolate Selected Group Aïlla el grup seleccionat
Isolate Selected Path Aïlla el traçat seleccionat
Isolate Selected Object Aïlla l’objecte seleccionat
Isometric Bottom Isomètrica inferior
Isometric Left Isomètrica esquerra
@@ -3329,6 +3332,10 @@ digits Malayalam Malaiàlam
Play Current Selection Reprodueix la selecció actual
Save Actions… Desa les accions…
Load Actions… Carrega accions…
Reset Actions Restableix les accions
Replace the current actions with the default set? Voleu reemplaçar les accions actuals pel conjunt predeterminat?
Append adds the default set after the current sets instead. Amb Afegeix, el conjunt predeterminat s’afegeix després dels conjunts actuals.
Append Afegeix
Play: Reprodueix:
Plug-in Info Informació del complement
Plug-ins Complements
@@ -3976,42 +3983,42 @@ digits Malayalam Malaiàlam
Saved Desat
Saved recovery data for {title} S’han desat les dades de recuperació de {title}
Saved Selection 1 Selecció desada 1
Saved Selection 10 Selecció desada 2
Saved Selection 11 Selecció desada 3
Saved Selection 12 Selecció desada 4
Saved Selection 13 Selecció desada 5
Saved Selection 14 Selecció desada 6
Saved Selection 15 Selecció desada 7
Saved Selection 16 Selecció desada 8
Saved Selection 17 Selecció desada 9
Saved Selection 18 Selecció desada 10
Saved Selection 19 Selecció desada 11
Saved Selection 2 Selecció desada 12
Saved Selection 20 Selecció desada 13
Saved Selection 21 Selecció desada 14
Saved Selection 22 Selecció desada 15
Saved Selection 23 Selecció desada 16
Saved Selection 24 Selecció desada 17
Saved Selection 25 Selecció desada 18
Saved Selection 3 Selecció desada 19
Saved Selection 4 Selecció desada 20
Saved Selection 5 Selecció desada 21
Saved Selection 6 Selecció desada 22
Saved Selection 7 Selecció desada 23
Saved Selection 8 Selecció desada 24
Saved Selection 9 Selecció desada 25
Saved Selection 10 Selecció desada 10
Saved Selection 11 Selecció desada 11
Saved Selection 12 Selecció desada 12
Saved Selection 13 Selecció desada 13
Saved Selection 14 Selecció desada 14
Saved Selection 15 Selecció desada 15
Saved Selection 16 Selecció desada 16
Saved Selection 17 Selecció desada 17
Saved Selection 18 Selecció desada 18
Saved Selection 19 Selecció desada 19
Saved Selection 2 Selecció desada 2
Saved Selection 20 Selecció desada 20
Saved Selection 21 Selecció desada 21
Saved Selection 22 Selecció desada 22
Saved Selection 23 Selecció desada 23
Saved Selection 24 Selecció desada 24
Saved Selection 25 Selecció desada 25
Saved Selection 3 Selecció desada 3
Saved Selection 4 Selecció desada 4
Saved Selection 5 Selecció desada 5
Saved Selection 6 Selecció desada 6
Saved Selection 7 Selecció desada 7
Saved Selection 8 Selecció desada 8
Saved Selection 9 Selecció desada 9
Saved Selections Seleccions desades
Saved to User Defined: {} Desat a Definit per l’usuari: {}
Saved View 1 Vista desada 1
Saved View 10 Vista desada 2
Saved View 11 Vista desada 3
Saved View 12 Vista desada 4
Saved View 13 Vista desada 5
Saved View 14 Vista desada 6
Saved View 15 Vista desada 7
Saved View 16 Vista desada 8
Saved View 17 Vista desada 9
Saved View 18 Vista desada 10
Saved View 10 Vista desada 10
Saved View 11 Vista desada 11
Saved View 12 Vista desada 12
Saved View 13 Vista desada 13
Saved View 14 Vista desada 14
Saved View 15 Vista desada 15
Saved View 16 Vista desada 16
Saved View 17 Vista desada 17
Saved View 18 Vista desada 18
Saved View 19 Vista desada 19
Saved View 2 Vista desada 2
Saved View 20 Vista desada 20
@@ -4110,8 +4117,12 @@ digits Malayalam Malaiàlam
Scrub Numeric Fields by Dragging Canvia els camps numèrics arrossegant
Search Cerca
Search All Cerca a tot
Search commands and tools Cerca ordres i eines
Search commands and tools… Cerca ordres i eines…
Search commands, tools, panels and effects Cerca ordres, eines, panells i efectes
Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes…
No commands match Cap ordre coincideix
{pos} of {total}: {name} {pos} de {total}: {name}
@plural {n} result|{n} results {n} resultat|{n} resultats
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los.
Recent Commands Ordres recents
No recent commands No hi ha ordres recents
Search Commands… Cerca ordres…
@@ -7950,4 +7961,24 @@ breakText Glyphs Glifs
No objects are selected. No hi ha cap objecte seleccionat.
Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat.
Remove Fold Line Role Elimina el tipus de línia
Check Comprova
Check Fold Lines Comprova les línies de plegat
@msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció.
@msg No cut lines are in the document. No hi ha cap línia de tall al document.
@msg The cut lines do not enclose an area. Les línies de tall no tanquen cap àrea.
@msg A cut line ends without meeting another cut line. Una línia de tall acaba sense trobar cap altra línia de tall.
@msg A gap between cut lines was closed. S’ha tancat un buit entre línies de tall.
@msg The fold lines are too complex to check. Les línies de plegat són massa complexes per comprovar-les.
@msg A cut line and a crease lie on top of each other. Una línia de tall i una d’hendit estan superposades.
@msg No cut lines are among the given objects. No hi ha cap línia de tall entre els objectes indicats.
@msg Two fold lines lie on top of each other. Dues línies de plegat estan superposades.
@msg A crease ends inside a panel. Una línia d’hendit acaba dins d’un panell.
@msg A crease does not divide two panels. Una línia d’hendit no separa dos panells.
@msg A crease lies outside the cut outline, wholly or in part. Una línia d’hendit és fora del contorn de tall, del tot o en part.
@msg The pieces of a hinge are not on one straight line. Els trams d’una frontissa no són en una sola línia recta.
@msg A gap between cut lines is too narrow to tell apart. Un buit entre línies de tall és massa estret per distingir-lo.
@msg A cut-out area holds other fold lines or another blank. Una àrea retallada conté altres línies de plegat o un altre troquelat.
@msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit.
@msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+33 -2
View File
@@ -893,6 +893,7 @@
Auto Color Automatická barva
Automatic Automaticky
Isolate Selected Group Izolovat vybranou skupinu
Isolate Selected Path Izolovat vybranou cestu
Isolate Selected Object Izolovat vybraný objekt
Exit Isolation Mode Ukončit izolovaný režim
Make Clipping Mask Vytvořit ořezovou masku
@@ -1324,7 +1325,7 @@ lighting Light Světlo
Name* @ 66.67% (RGB/Preview) Název* @ 66,67 % (RGB/náhled)
No Document Žádný dokument
Press Klávesou
Search commands and tools Hledat příkazy a nástroje
Search commands, tools, panels and effects Hledat příkazy, nástroje, panely a efekty
Style: Styl:
Switch workspace Přepnout pracovní prostor
Show all open documents Zobrazit všechny otevřené dokumenty
@@ -1530,6 +1531,10 @@ lighting Light Světlo
Play Current Selection Přehrát aktuální výběr
Save Actions… Uložit akce…
Load Actions… Načíst akce…
Reset Actions Obnovit akce
Replace the current actions with the default set? Nahradit aktuální akce výchozí sadou?
Append adds the default set after the current sets instead. Tlačítko Připojit místo toho přidá výchozí sadu za aktuální sady.
Append Připojit
Reflect Horizontal Zrcadlit vodorovně
Rotate 90° CW Otočit o 90° po směru hodin
Set 1 Sada 1
@@ -3012,6 +3017,8 @@ digits Malayalam Malajálamské
Show smooth color wheel Zobrazit plynulé barevné kolo
Show segmented color wheel Zobrazit segmentované barevné kolo
Show color bars Zobrazit barevné pruhy
Show brightness and hue on wheel Zobrazit jas a odstín na kole
Show saturation and hue on wheel Zobrazit sytost a odstín na kole
Add Color Tool Nástroj Přidat barvu
Remove Color Tool Nástroj Odstranit barvu
Remove Color Odstranit barvu
@@ -4486,7 +4493,11 @@ font-technology Variable Variabilní
Saved {path} Uloženo: {path}
Saving Ukládání
Saving {} Ukládání {}
Search commands and tools… Hledat příkazy a nástroje…
Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty…
No commands match Žádný příkaz neodpovídá
{pos} of {total}: {name} {pos} z {total}: {name}
@plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.
Recent Commands Nedávné příkazy
No recent commands Žádné nedávné příkazy
Dashed Line Čárkovaná čára
@@ -9747,3 +9758,23 @@ breakText Glyphs Glyfy
No objects are selected. Nejsou vybrány žádné objekty.
Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu.
Remove Fold Line Role Odstranit typ linie
Check Zkontrolovat
Check Fold Lines Zkontrolovat linie skladu
@msg No cut lines are in the selection. Ve výběru nejsou žádné linie řezu.
@msg No cut lines are in the document. V dokumentu nejsou žádné linie řezu.
@msg The cut lines do not enclose an area. Linie řezu neohraničují žádnou plochu.
@msg A cut line ends without meeting another cut line. Linie řezu končí, aniž by se setkala s jinou linií řezu.
@msg A gap between cut lines was closed. Mezera mezi liniemi řezu byla uzavřena.
@msg The fold lines are too complex to check. Linie skladu jsou příliš složité na kontrolu.
@msg A cut line and a crease lie on top of each other. Linie řezu a linie bigu leží přes sebe.
@msg No cut lines are among the given objects. Mezi zadanými objekty nejsou žádné linie řezu.
@msg Two fold lines lie on top of each other. Dvě linie skladu leží přes sebe.
@msg A crease ends inside a panel. Linie bigu končí uvnitř panelu.
@msg A crease does not divide two panels. Linie bigu nerozděluje dva panely.
@msg A crease lies outside the cut outline, wholly or in part. Linie bigu leží zcela nebo zčásti mimo obrys řezu.
@msg The pieces of a hinge are not on one straight line. Části jednoho pantu neleží na jedné přímce.
@msg A gap between cut lines is too narrow to tell apart. Mezera mezi liniemi řezu je příliš úzká na rozlišení.
@msg A cut-out area holds other fold lines or another blank. Vyříznutá oblast obsahuje další linie skladu nebo jiný přířez.
@msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu.
@msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings}
Can't render this file because it is too large.
+33 -2
View File
@@ -3500,6 +3500,7 @@ liquify-list-end {0}, {1} {0} og {1}
Auto Color Autofarve
Automatic Automatisk
Isolate Selected Group Isolér valgt gruppe
Isolate Selected Path Isolér valgt kurve
Exit Isolation Mode Afslut isoleringstilstand
Make Clipping Mask Opret beskæringsmask
Release Clipping Mask Frigør beskæringsmask
@@ -3901,7 +3902,7 @@ lighting Light Lys
Name* @ 66.67% (RGB/Preview) Navn* @ 66.67% (RGB/forhåndsvisning)
No Document Intet dokument
Press Tryk på
Search commands and tools Søg i kommandoer og værktøjer
Search commands, tools, panels and effects Søg i kommandoer, værktøjer, paneler og effekter
Style: Typografi:
Switch workspace Skift arbejdsområde
Show all open documents Vis alle åbne dokumenter
@@ -4103,6 +4104,10 @@ lighting Light Lys
Play Current Selection Afspil aktuel markering
Save Actions… Gem handlinger…
Load Actions… Indlæs handlinger…
Reset Actions Nulstil handlinger
Replace the current actions with the default set? Vil du erstatte de aktuelle handlinger med standardsættet?
Append adds the default set after the current sets instead. Tilføj tilføjer i stedet standardsættet efter de aktuelle sæt.
Append Tilføj
Reflect Horizontal Spejl vandret
Rotate 90° CW Rotér 90° med uret
Set 1 Sæt 1
@@ -5460,6 +5465,8 @@ digits Malayalam Malayalam
Show smooth color wheel Vis glat farvehjul
Show segmented color wheel Vis segmenteret farvehjul
Show color bars Vis farvebjælker
Show brightness and hue on wheel Vis lysstyrke og farvetone på hjulet
Show saturation and hue on wheel Vis mætning og farvetone på hjulet
Add Color Tool Værktøjet Tilføj farve
Remove Color Tool Værktøjet Fjern farve
Remove Color Fjern farve
@@ -6860,7 +6867,11 @@ font-technology Variable Variable
Saved {path} Gemte {path}
Saving Gemmer
Saving {} Gemmer {}
Search commands and tools… Søg i kommandoer og værktøjer…
Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter…
No commands match Ingen kommandoer passer
{pos} of {total}: {name} {pos} af {total}: {name}
@plural {n} result|{n} results {n} resultat|{n} resultater
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem.
Recent Commands Seneste kommandoer
No recent commands Ingen seneste kommandoer
Dashed Line Stiplet linje
@@ -9849,4 +9860,24 @@ breakText Glyphs Glyffer
No objects are selected. Ingen objekter er markeret.
Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer.
Remove Fold Line Role Fjern linjetype
Check Kontrollér
Check Fold Lines Kontrollér foldelinjer
@msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen.
@msg No cut lines are in the document. Der er ingen skærelinjer i dokumentet.
@msg The cut lines do not enclose an area. Skærelinjerne omslutter ikke et område.
@msg A cut line ends without meeting another cut line. En skærelinje slutter uden at møde en anden skærelinje.
@msg A gap between cut lines was closed. Et mellemrum mellem skærelinjer blev lukket.
@msg The fold lines are too complex to check. Foldelinjerne er for komplekse til at kontrollere.
@msg A cut line and a crease lie on top of each other. En skærelinje og en rillelinje ligger oven på hinanden.
@msg No cut lines are among the given objects. Der er ingen skærelinjer blandt de angivne objekter.
@msg Two fold lines lie on top of each other. To foldelinjer ligger oven på hinanden.
@msg A crease ends inside a panel. En rillelinje slutter inde i et panel.
@msg A crease does not divide two panels. En rillelinje deler ikke to paneler.
@msg A crease lies outside the cut outline, wholly or in part. En rillelinje ligger helt eller delvist uden for skærekonturen.
@msg The pieces of a hinge are not on one straight line. Delene af et hængsel ligger ikke på én ret linje.
@msg A gap between cut lines is too narrow to tell apart. Et mellemrum mellem skærelinjer er for smalt til at skelne.
@msg A cut-out area holds other fold lines or another blank. Et udskåret område indeholder andre foldelinjer eller et andet emne.
@msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje.
@msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine"
Can't render this file because it is too large.
+33 -2
View File
@@ -1554,6 +1554,8 @@ file-filter Templates Vorlagen
Show smooth color wheel Stufenlosen Farbkreis anzeigen
Show segmented color wheel Segmentierten Farbkreis anzeigen
Show color bars Farbbalken anzeigen
Show brightness and hue on wheel Helligkeit und Farbton im Farbkreis anzeigen
Show saturation and hue on wheel Sättigung und Farbton im Farbkreis anzeigen
Add Color Tool Farbe-hinzufügen-Werkzeug
Remove Color Tool Farbe-entfernen-Werkzeug
Remove Color Farbe entfernen
@@ -2617,6 +2619,10 @@ diagnostics ui Oberfläche
Play Current Selection Aktuelle Auswahl abspielen
Save Actions… Aktionen speichern…
Load Actions… Aktionen laden…
Reset Actions Aktionen zurücksetzen
Replace the current actions with the default set? Aktuelle Aktionen durch den Standardsatz ersetzen?
Append adds the default set after the current sets instead. Mit „Anhängen“ wird der Standardsatz stattdessen nach den aktuellen Sätzen hinzugefügt.
Append Anhängen
Plug-in Info Plug-in-Informationen
Plug-ins Plug-ins
Plug-in… Plug-in…
@@ -3246,8 +3252,12 @@ digits Malayalam Malayalam
Filter Layers Panel Rows Zeilen im Ebenenbedienfeld filtern
@msg `Custom` stands for changed settings: save the preset under another name `Custom` steht für geänderte Einstellungen: Speichern Sie die Vorgabe unter einem anderen Namen
@msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1}
Search commands and tools Befehle und Werkzeuge suchen
Search commands and tools… Befehle und Werkzeuge suchen…
Search commands, tools, panels and effects Befehle, Werkzeuge, Bedienfelder und Effekte suchen
Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen…
No commands match Keine passenden Befehle
{pos} of {total}: {name} {pos} von {total}: {name}
@plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen.
Recent Commands Zuletzt verwendete Befehle
No recent commands Keine zuletzt verwendeten Befehle
Search Commands… Befehle suchen…
@@ -4223,6 +4233,7 @@ imageTrace Outline Kontur
to set spacing and orientation legt Abstand und Ausrichtung fest
: :
Isolate Selected Group Ausgewählte Gruppe isolieren
Isolate Selected Path Ausgewählten Pfad isolieren
Isolate Selected Object Ausgewähltes Objekt isolieren
Release Clipping Mask Schnittmaske zurückwandeln
Make Compound Path Zusammengesetzten Pfad erstellen
@@ -9345,3 +9356,23 @@ breakText Glyphs Glyphen
No objects are selected. Es sind keine Objekte ausgewählt.
Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen.
Remove Fold Line Role Linienart entfernen
Check Prüfen
Check Fold Lines Faltlinien prüfen
@msg No cut lines are in the selection. Die Auswahl enthält keine Schnittlinien.
@msg No cut lines are in the document. Das Dokument enthält keine Schnittlinien.
@msg The cut lines do not enclose an area. Die Schnittlinien umschließen keine Fläche.
@msg A cut line ends without meeting another cut line. Eine Schnittlinie endet, ohne auf eine andere Schnittlinie zu treffen.
@msg A gap between cut lines was closed. Eine Lücke zwischen Schnittlinien wurde geschlossen.
@msg The fold lines are too complex to check. Die Faltlinien sind zu komplex für die Prüfung.
@msg A cut line and a crease lie on top of each other. Eine Schnittlinie und eine Rilllinie liegen übereinander.
@msg No cut lines are among the given objects. Die angegebenen Objekte enthalten keine Schnittlinien.
@msg Two fold lines lie on top of each other. Zwei Faltlinien liegen übereinander.
@msg A crease ends inside a panel. Eine Rilllinie endet innerhalb eines Felds.
@msg A crease does not divide two panels. Eine Rilllinie trennt keine zwei Felder.
@msg A crease lies outside the cut outline, wholly or in part. Eine Rilllinie liegt ganz oder teilweise außerhalb der Schnittkontur.
@msg The pieces of a hinge are not on one straight line. Die Teile eines Scharniers liegen nicht auf einer geraden Linie.
@msg A gap between cut lines is too narrow to tell apart. Eine Lücke zwischen Schnittlinien ist zu schmal, um sie zu unterscheiden.
@msg A cut-out area holds other fold lines or another blank. Ein ausgeschnittener Bereich enthält weitere Faltlinien oder einen anderen Zuschnitt.
@msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden.
@msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings}
Can't render this file because it is too large.
+33 -2
View File
@@ -1486,6 +1486,8 @@ font-technology Variable Μεταβλητές
Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού
Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού
Show color bars Εμφάνιση χρωματικών ράβδων
Show brightness and hue on wheel Εμφάνιση φωτεινότητας και απόχρωσης στον τροχό
Show saturation and hue on wheel Εμφάνιση κορεσμού και απόχρωσης στον τροχό
Add Color Tool Εργαλείο προσθήκης χρώματος
Remove Color Tool Εργαλείο αφαίρεσης χρώματος
Remove Color Αφαίρεση χρώματος
@@ -3525,6 +3527,10 @@ theme Appearance Εμφάνιση
Play Current Selection Αναπαραγωγή τρέχουσας επιλογής
Save Actions… Αποθήκευση ενεργειών…
Load Actions… Φόρτωση ενεργειών…
Reset Actions Επαναφορά ενεργειών
Replace the current actions with the default set? Να αντικατασταθούν οι τρέχουσες ενέργειες με το προεπιλεγμένο σύνολο;
Append adds the default set after the current sets instead. Η Προσάρτηση προσθέτει αντί γι’ αυτό το προεπιλεγμένο σύνολο μετά τα τρέχοντα σύνολα.
Append Προσάρτηση
Plug-in Info Πληροφορίες προσθέτου
Plug-in… Πρόσθετο…
Point Text Objects Αντικείμενα κειμένου σημείου
@@ -3948,8 +3954,12 @@ digits Malayalam Μαλαγιάλαμ
Scribble… Μουτζούρωμα…
Script / Brush Σενάριο / Πινέλο
Search All Αναζήτηση όλων
Search commands and tools Αναζήτηση εντολών και εργαλείων
Search commands and tools… Αναζήτηση εντολών και εργαλείων…
Search commands, tools, panels and effects Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ
Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ…
No commands match Καμία εντολή δεν ταιριάζει
{pos} of {total}: {name} {pos} από {total}: {name}
@plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.
Recent Commands Πρόσφατες εντολές
No recent commands Δεν υπάρχουν πρόσφατες εντολές
Search Commands… Αναζήτηση εντολών…
@@ -4685,6 +4695,7 @@ digits Malayalam Μαλαγιάλαμ
“{file}” is protected by a password. Το «{file}» προστατεύεται με κωδικό.
● Recording ● Εγγραφή
Isolate Selected Group Απομόνωση επιλεγμένης ομάδας
Isolate Selected Path Απομόνωση επιλεγμένης διαδρομής
Make Compound Path Δημιουργία σύνθετης διαδρομής
Release Compound Path Αποδέσμευση σύνθετης διαδρομής
— substituted by {style} — αντικαταστάθηκε από {style}
@@ -7924,4 +7935,24 @@ breakText Glyphs Γλύφοι
No objects are selected. Δεν έχουν επιλεγεί αντικείμενα.
Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του.
Remove Fold Line Role Αφαίρεση τύπου γραμμής
Check Έλεγχος
Check Fold Lines Έλεγχος γραμμών δίπλωσης
@msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής.
@msg No cut lines are in the document. Το έγγραφο δεν περιέχει γραμμές κοπής.
@msg The cut lines do not enclose an area. Οι γραμμές κοπής δεν περικλείουν καμία περιοχή.
@msg A cut line ends without meeting another cut line. Μια γραμμή κοπής τελειώνει χωρίς να συναντήσει άλλη γραμμή κοπής.
@msg A gap between cut lines was closed. Ένα κενό ανάμεσα σε γραμμές κοπής κλείστηκε.
@msg The fold lines are too complex to check. Οι γραμμές δίπλωσης είναι πολύ σύνθετες για έλεγχο.
@msg A cut line and a crease lie on top of each other. Μια γραμμή κοπής και μια γραμμή πτύχωσης βρίσκονται η μία πάνω στην άλλη.
@msg No cut lines are among the given objects. Τα δοσμένα αντικείμενα δεν περιέχουν γραμμές κοπής.
@msg Two fold lines lie on top of each other. Δύο γραμμές δίπλωσης βρίσκονται η μία πάνω στην άλλη.
@msg A crease ends inside a panel. Μια γραμμή πτύχωσης τελειώνει μέσα σε ένα πάνελ.
@msg A crease does not divide two panels. Μια γραμμή πτύχωσης δεν χωρίζει δύο πάνελ.
@msg A crease lies outside the cut outline, wholly or in part. Μια γραμμή πτύχωσης βρίσκεται εν όλω ή εν μέρει έξω από το περίγραμμα κοπής.
@msg The pieces of a hinge are not on one straight line. Τα τμήματα ενός μεντεσέ δεν βρίσκονται σε μία ευθεία.
@msg A gap between cut lines is too narrow to tell apart. Ένα κενό ανάμεσα σε γραμμές κοπής είναι πολύ στενό για να διακριθεί.
@msg A cut-out area holds other fold lines or another blank. Μια αποκομμένη περιοχή περιέχει άλλες γραμμές δίπλωσης ή άλλο ανάπτυγμα.
@msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης.
@msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine"
Can't render this file because it is too large.
+33 -2
View File
@@ -1569,6 +1569,8 @@ font-technology Variable Variables
Show smooth color wheel Mostrar rueda de color continua
Show segmented color wheel Mostrar rueda de color segmentada
Show color bars Mostrar barras de color
Show brightness and hue on wheel Mostrar brillo y tono en la rueda
Show saturation and hue on wheel Mostrar saturación y tono en la rueda
Add Color Tool Herramienta Añadir color
Remove Color Tool Herramienta Eliminar color
Remove Color Eliminar color
@@ -2660,6 +2662,10 @@ font-technology Variable Variables
Play Current Selection Reproducir la selección actual
Save Actions… Guardar acciones…
Load Actions… Cargar acciones…
Reset Actions Restablecer acciones
Replace the current actions with the default set? ¿Reemplazar las acciones actuales por el conjunto predeterminado?
Append adds the default set after the current sets instead. Añadir agrega en su lugar el conjunto predeterminado después de los conjuntos actuales.
Append Añadir
Plug-in Info Información del plugin
Plug-ins Plugins
Plug-in… Plugin…
@@ -3284,8 +3290,12 @@ digits Malayalam Malayálam
Filter Layers Panel Rows Filtrar filas del panel Capas
@msg `Custom` stands for changed settings: save the preset under another name `Custom` representa ajustes modificados: guarda el preajuste con otro nombre
@msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1}
Search commands and tools Buscar comandos y herramientas
Search commands and tools… Buscar comandos y herramientas…
Search commands, tools, panels and effects Buscar comandos, herramientas, paneles y efectos
Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos…
No commands match Ningún comando coincide
{pos} of {total}: {name} {pos} de {total}: {name}
@plural {n} result|{n} results {n} resultado|{n} resultados
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos.
Recent Commands Comandos recientes
No recent commands No hay comandos recientes
Search Commands… Buscar comandos…
@@ -4310,6 +4320,7 @@ imageTrace Outline Contorno
to set spacing and orientation para definir espaciado y orientación
: :
Isolate Selected Group Aislar grupo seleccionado
Isolate Selected Path Aislar trazado seleccionado
Isolate Selected Object Aislar objeto seleccionado
Release Clipping Mask Soltar máscara de recorte
Make Compound Path Crear trazado compuesto
@@ -7911,4 +7922,24 @@ breakText Glyphs Glifos
No objects are selected. No hay objetos seleccionados.
Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado.
Remove Fold Line Role Quitar tipo de línea
Check Comprobar
Check Fold Lines Comprobar líneas de plegado
@msg No cut lines are in the selection. No hay líneas de corte en la selección.
@msg No cut lines are in the document. No hay líneas de corte en el documento.
@msg The cut lines do not enclose an area. Las líneas de corte no encierran ningún área.
@msg A cut line ends without meeting another cut line. Una línea de corte termina sin llegar a otra línea de corte.
@msg A gap between cut lines was closed. Se cerró un hueco entre líneas de corte.
@msg The fold lines are too complex to check. Las líneas de plegado son demasiado complejas para comprobarlas.
@msg A cut line and a crease lie on top of each other. Una línea de corte y una de hendido están superpuestas.
@msg No cut lines are among the given objects. No hay líneas de corte entre los objetos indicados.
@msg Two fold lines lie on top of each other. Dos líneas de plegado están superpuestas.
@msg A crease ends inside a panel. Una línea de hendido termina dentro de un panel.
@msg A crease does not divide two panels. Una línea de hendido no separa dos paneles.
@msg A crease lies outside the cut outline, wholly or in part. Una línea de hendido está fuera del contorno de corte, total o parcialmente.
@msg The pieces of a hinge are not on one straight line. Los tramos de una bisagra no están en una sola línea recta.
@msg A gap between cut lines is too narrow to tell apart. Un hueco entre líneas de corte es demasiado estrecho para distinguirlo.
@msg A cut-out area holds other fold lines or another blank. Un área recortada contiene otras líneas de plegado u otro troquelado.
@msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido.
@msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+33 -2
View File
@@ -884,6 +884,7 @@
Auto Color Automaattinen väri
Automatic Automaattinen
Isolate Selected Group Eristä valittu ryhmä
Isolate Selected Path Eristä valittu polku
Exit Isolation Mode Poistu eristystilasta
Make Clipping Mask Luo leikkausmaski
Release Clipping Mask Vapauta leikkausmaski
@@ -1302,7 +1303,7 @@ lighting Light Valo
Name* @ 66.67% (RGB/Preview) Nimi* @ 66.67% (RGB/esikatselu)
No Document Ei asiakirjaa
Press Paina
Search commands and tools Hae komentoja ja työkaluja
Search commands, tools, panels and effects Hae komentoja, työkaluja, paneeleita ja tehosteita
Style: Tyyli:
Switch workspace Vaihda työtilaa
Show all open documents Näytä kaikki avoimet asiakirjat
@@ -1504,6 +1505,10 @@ lighting Light Valo
Play Current Selection Toista nykyinen valinta
Save Actions… Tallenna toiminnot…
Load Actions… Lataa toiminnot…
Reset Actions Palauta toiminnot
Replace the current actions with the default set? Korvataanko nykyiset toiminnot oletussarjalla?
Append adds the default set after the current sets instead. Lisää-painike lisää sen sijaan oletussarjan nykyisten sarjojen perään.
Append Lisää
Reflect Horizontal Peilaa vaakasuunnassa
Rotate 90° CW Kierrä 90° myötäpäivään
Set 1 Sarja 1
@@ -2956,6 +2961,8 @@ digits Malayalam Malajalam
Show smooth color wheel Näytä liukuva väriympyrä
Show segmented color wheel Näytä segmentoitu väriympyrä
Show color bars Näytä väripalkit
Show brightness and hue on wheel Näytä kirkkaus ja sävy ympyrässä
Show saturation and hue on wheel Näytä kylläisyys ja sävy ympyrässä
Add Color Tool Lisää väri -työkalu
Remove Color Tool Poista väri -työkalu
Remove Color Poista väri
@@ -4405,7 +4412,11 @@ font-technology Variable Muuttuvat
Saved {path} Tallennettu {path}
Saving Tallennetaan
Saving {} Tallennetaan {}
Search commands and tools… Hae komentoja ja työkaluja…
Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita…
No commands match Mikään komento ei vastaa hakua
{pos} of {total}: {name} {pos}/{total}: {name}
@plural {n} result|{n} results {n} tulos|{n} tulosta
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.
Recent Commands Viimeisimmät komennot
No recent commands Ei viimeisimpiä komentoja
Dashed Line Katkoviiva
@@ -8007,4 +8018,24 @@ breakText Glyphs Merkit
No objects are selected. Objekteja ei ole valittu.
Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat.
Remove Fold Line Role Poista viivatyyppi
Check Tarkista
Check Fold Lines Tarkista taittoviivat
@msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja.
@msg No cut lines are in the document. Asiakirjassa ei ole leikkausviivoja.
@msg The cut lines do not enclose an area. Leikkausviivat eivät rajaa aluetta.
@msg A cut line ends without meeting another cut line. Leikkausviiva päättyy kohtaamatta toista leikkausviivaa.
@msg A gap between cut lines was closed. Leikkausviivojen välinen rako suljettiin.
@msg The fold lines are too complex to check. Taittoviivat ovat liian monimutkaisia tarkistettaviksi.
@msg A cut line and a crease lie on top of each other. Leikkausviiva ja nuuttausviiva ovat päällekkäin.
@msg No cut lines are among the given objects. Annetuissa objekteissa ei ole leikkausviivoja.
@msg Two fold lines lie on top of each other. Kaksi taittoviivaa on päällekkäin.
@msg A crease ends inside a panel. Nuuttausviiva päättyy paneelin sisään.
@msg A crease does not divide two panels. Nuuttausviiva ei jaa kahta paneelia.
@msg A crease lies outside the cut outline, wholly or in part. Nuuttausviiva on kokonaan tai osittain leikkausääriviivan ulkopuolella.
@msg The pieces of a hinge are not on one straight line. Saranan osat eivät ole yhdellä suoralla.
@msg A gap between cut lines is too narrow to tell apart. Leikkausviivojen välinen rako on liian kapea erotettavaksi.
@msg A cut-out area holds other fold lines or another blank. Leikattu alue sisältää muita taittoviivoja tai toisen aihion.
@msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla.
@msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+33 -2
View File
@@ -1558,6 +1558,8 @@ font-technology Variable Variables
Show smooth color wheel Afficher la roue chromatique continue
Show segmented color wheel Afficher la roue chromatique segmentée
Show color bars Afficher les barres de couleur
Show brightness and hue on wheel Afficher la luminosité et la teinte sur la roue
Show saturation and hue on wheel Afficher la saturation et la teinte sur la roue
Add Color Tool Outil Ajouter une couleur
Remove Color Tool Outil Supprimer une couleur
Remove Color Supprimer la couleur
@@ -2648,6 +2650,10 @@ font-technology Variable Variables
Play Current Selection Exécuter la sélection actuelle
Save Actions… Enregistrer les scripts…
Load Actions… Charger des scripts…
Reset Actions Réinitialiser les scripts
Replace the current actions with the default set? Remplacer les scripts actuels par le jeu par défaut ?
Append adds the default set after the current sets instead. Le bouton Ajouter ajoute plutôt le jeu par défaut après les jeux actuels.
Append Ajouter
Plug-in Info Informations sur le module externe
Plug-ins Modules externes
Plug-in… Module externe…
@@ -3272,8 +3278,12 @@ digits Malayalam Malayalam
Filter Layers Panel Rows Filtrer les lignes du panneau Calques
@msg `Custom` stands for changed settings: save the preset under another name `Custom` désigne des réglages modifiés : enregistrez le paramètre prédéfini sous un autre nom
@msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1}
Search commands and tools Chercher commandes et outils
Search commands and tools… Chercher commandes et outils…
Search commands, tools, panels and effects Chercher commandes, outils, panneaux et effets
Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets…
No commands match Aucune commande ne correspond
{pos} of {total}: {name} {pos} sur {total} : {name}
@plural {n} result|{n} results {n} résultat|{n} résultats
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner.
Recent Commands Commandes récentes
No recent commands Aucune commande récente
Search Commands… Rechercher des commandes…
@@ -4295,6 +4305,7 @@ imageTrace Outline Contour
to set spacing and orientation pour définir l’espacement et l’orientation
:  :
Isolate Selected Group Isoler le groupe sélectionné
Isolate Selected Path Isoler le tracé sélectionné
Isolate Selected Object Isoler l’objet sélectionné
Release Clipping Mask Annuler le masque d’écrêtage
Make Compound Path Créer un tracé transparent
@@ -9732,4 +9743,24 @@ breakText Glyphs Glyphes
No objects are selected. Aucun objet n’est sélectionné.
Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage.
Remove Fold Line Role Supprimer le type de ligne
Check Vérifier
Check Fold Lines Vérifier les lignes de pliage
@msg No cut lines are in the selection. La sélection ne contient aucune ligne de découpe.
@msg No cut lines are in the document. Le document ne contient aucune ligne de découpe.
@msg The cut lines do not enclose an area. Les lignes de découpe n’entourent aucune zone.
@msg A cut line ends without meeting another cut line. Une ligne de découpe se termine sans rejoindre une autre ligne de découpe.
@msg A gap between cut lines was closed. Un écart entre des lignes de découpe a été fermé.
@msg The fold lines are too complex to check. Les lignes de pliage sont trop complexes pour être vérifiées.
@msg A cut line and a crease lie on top of each other. Une ligne de découpe et une ligne de rainage se superposent.
@msg No cut lines are among the given objects. Les objets indiqués ne contiennent aucune ligne de découpe.
@msg Two fold lines lie on top of each other. Deux lignes de pliage se superposent.
@msg A crease ends inside a panel. Une ligne de rainage se termine à l’intérieur d’un panneau.
@msg A crease does not divide two panels. Une ligne de rainage ne sépare pas deux panneaux.
@msg A crease lies outside the cut outline, wholly or in part. Une ligne de rainage se trouve en tout ou en partie hors du contour de découpe.
@msg The pieces of a hinge are not on one straight line. Les morceaux d’une charnière ne sont pas sur une seule ligne droite.
@msg A gap between cut lines is too narrow to tell apart. Un écart entre des lignes de découpe est trop étroit pour être distingué.
@msg A cut-out area holds other fold lines or another blank. Une zone découpée contient d’autres lignes de pliage ou un autre flan.
@msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage.
@msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s)
@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution
Can't render this file because it is too large.
+33 -2
View File
@@ -1858,6 +1858,7 @@
Isolate Blending બ્લેન્ડિંગ અલગ કરો
Isolate Group ગ્રૂપ અલગ કરો
Isolate Selected Group પસંદ કરેલું ગ્રૂપ અલગ કરો
Isolate Selected Path પસંદ કરેલો પાથ અલગ કરો
Isolate Selected Object પસંદ કરેલી ઑબ્જેક્ટ અલગ કરો
Isometric Bottom આઇસોમેટ્રિક નીચે
Isometric Left આઇસોમેટ્રિક ડાબે
@@ -2051,6 +2052,10 @@
Live curve fitting લાઇવ કર્વ ફિટિંગ
Live preview લાઇવ પૂર્વાવલોકન
Load Actions… ઍક્શન લોડ કરો…
Reset Actions ઍક્શન રીસેટ કરો
Replace the current actions with the default set? વર્તમાન ઍક્શનને ડિફૉલ્ટ સેટથી બદલવા છે?
Append adds the default set after the current sets instead. ઉમેરો તેના બદલે ડિફૉલ્ટ સેટને વર્તમાન સેટ પછી ઉમેરે છે.
Append ઉમેરો
Load All Styles બધી સ્ટાઇલ લોડ કરો
Load All Styles… બધી સ્ટાઇલ લોડ કરો…
Load Character Styles કેરેક્ટર સ્ટાઇલ લોડ કરો
@@ -3388,8 +3393,12 @@
Search Commands… આદેશો શોધો…
Search Fonts Folder ફોન્ટ ફોલ્ડર શોધો
Search Preferences પસંદગીઓ શોધો
Search commands and tools આદેશો અને ટૂલ્સ શોધો
Search commands and tools… આદેશો અને ટૂલ્સ શોધો…
Search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો
Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો…
No commands match કોઈ આદેશ મેળ ખાતો નથી
{pos} of {total}: {name} {total} માંથી {pos}: {name}
@plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો.
Recent Commands તાજેતરના આદેશો
No recent commands કોઈ તાજેતરના આદેશો નથી
Search images છબીઓ શોધો
@@ -3607,6 +3616,8 @@
Show all plates બધી પ્લેટ બતાવો
Show axis અક્ષ બતાવો
Show color bars રંગ બાર બતાવો
Show brightness and hue on wheel વ્હીલ પર તેજ અને હ્યૂ બતાવો
Show saturation and hue on wheel વ્હીલ પર સંતૃપ્તિ અને હ્યૂ બતાવો
Add Color Tool રંગ ઉમેરો સાધન
Remove Color Tool રંગ દૂર કરો સાધન
Remove Color રંગ દૂર કરો
@@ -4846,6 +4857,26 @@ swatch [Registration] [રજિસ્ટ્રેશન]
No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી.
Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો.
Remove Fold Line Role લાઇન પ્રકાર દૂર કરો
Check ચેક કરો
Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો
@msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી.
@msg No cut lines are in the document. ડૉક્યુમેન્ટમાં કોઈ કટ લાઇન નથી.
@msg The cut lines do not enclose an area. કટ લાઇન્સ કોઈ વિસ્તાર ઘેરતી નથી.
@msg A cut line ends without meeting another cut line. એક કટ લાઇન બીજી કટ લાઇનને મળ્યા વિના પૂરી થાય છે.
@msg A gap between cut lines was closed. કટ લાઇન્સ વચ્ચેનો ગેપ બંધ કરવામાં આવ્યો.
@msg The fold lines are too complex to check. ફોલ્ડ લાઇન્સ ચેક કરવા માટે ખૂબ જટિલ છે.
@msg A cut line and a crease lie on top of each other. એક કટ લાઇન અને એક ક્રીઝ લાઇન એકબીજા પર છે.
@msg No cut lines are among the given objects. આપેલા ઑબ્જેક્ટ્સમાં કોઈ કટ લાઇન નથી.
@msg Two fold lines lie on top of each other. બે ફોલ્ડ લાઇન્સ એકબીજા પર છે.
@msg A crease ends inside a panel. એક ક્રીઝ લાઇન પેનલની અંદર પૂરી થાય છે.
@msg A crease does not divide two panels. એક ક્રીઝ લાઇન બે પેનલને અલગ કરતી નથી.
@msg A crease lies outside the cut outline, wholly or in part. એક ક્રીઝ લાઇન પૂરેપૂરી અથવા આંશિક રીતે કટ આઉટલાઇનની બહાર છે.
@msg The pieces of a hinge are not on one straight line. એક હિન્જના ભાગો એક સીધી લાઇન પર નથી.
@msg A gap between cut lines is too narrow to tell apart. કટ લાઇન્સ વચ્ચેનો ગેપ ઓળખવા માટે ખૂબ સાંકડો છે.
@msg A cut-out area holds other fold lines or another blank. એક કટ-આઉટ વિસ્તારમાં બીજી ફોલ્ડ લાઇન્સ અથવા બીજું બ્લેન્ક છે.
@msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી.
@msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings}
Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા)
Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા)
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
Can't render this file because it contains an unexpected character in line 72 and column 5.
+33 -2
View File
@@ -2508,6 +2508,7 @@ antiAlias Sharp शार्प
Isolate Blending ब्लेंडिंग अलग करें
Isolate Group अलग समूह
Isolate Selected Group सिलेक्टेड समूह अलग करें
Isolate Selected Path सिलेक्टेड पाथ अलग करें
Isolate Selected Object सिलेक्टेड ऑब्जेक्ट को अलग करें
Isometric Bottom आइसोमेट्रिक बॉटम
Isometric Left आइसोमेट्रिक लेफ्ट
@@ -2756,6 +2757,10 @@ antiAlias Sharp शार्प
Live Shape लाइव आकार
Live Shape Properties लाइव शेप प्रॉपर्टीज़
Load Actions… एक्शन्स लोड करें…
Reset Actions एक्शन्स रीसेट करें
Replace the current actions with the default set? मौजूदा एक्शन्स को डिफ़ॉल्ट सेट से बदलें?
Append adds the default set after the current sets instead. जोड़ें इसके बजाय डिफ़ॉल्ट सेट को मौजूदा सेट के बाद जोड़ता है।
Append जोड़ें
Load Color Profile… लोड कलर प्रोफ़ाइल…
Load EPS into Clipboard ईपीएस को क्लिपबोर्ड में लोड करें
Load Image into Clipboard क्लिपबोर्ड में इमेज लोड करें
@@ -4462,8 +4467,12 @@ antiAlias Sharp शार्प
Search खोजें
Search All सभी खोजें
Search artboards खोज आर्टबोर्ड
Search commands and tools खोज आदेश और टूल
Search commands and tools… आदेश और टूल खोजें…
Search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें
Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें…
No commands match कोई आदेश मेल नहीं खाता
{pos} of {total}: {name} {total} में से {pos}: {name}
@plural {n} result|{n} results {n} परिणाम|{n} परिणाम
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।
Recent Commands हाल के आदेश
No recent commands कोई हाल का आदेश नहीं
Search Commands… कमांड खोजें…
@@ -4687,6 +4696,8 @@ antiAlias Sharp शार्प
Show Center Mark शो सेंटर मार्क
Show Code कोड दिखाएं
Show color bars रंग सलाखों दिखाएँ
Show brightness and hue on wheel व्हील पर ब्राइटनेस और ह्यू दिखाएँ
Show saturation and hue on wheel व्हील पर सैचुरेशन और ह्यू दिखाएँ
Add Color Tool रंग जोड़ें टूल
Remove Color Tool रंग हटाएँ टूल
Remove Color रंग हटाएँ
@@ -9352,3 +9363,23 @@ theme Appearance अपीयरेंस
No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है।
Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें।
Remove Fold Line Role लाइन प्रकार हटाएँ
Check चेक करें
Check Fold Lines फ़ोल्ड लाइनें चेक करें
@msg No cut lines are in the selection. सिलेक्शन में कोई कट लाइन नहीं है।
@msg No cut lines are in the document. डॉक्यूमेंट में कोई कट लाइन नहीं है।
@msg The cut lines do not enclose an area. कट लाइनें कोई एरिया नहीं घेरतीं।
@msg A cut line ends without meeting another cut line. एक कट लाइन किसी दूसरी कट लाइन से मिले बिना खत्म हो जाती है।
@msg A gap between cut lines was closed. कट लाइनों के बीच का गैप बंद कर दिया गया।
@msg The fold lines are too complex to check. फ़ोल्ड लाइनें चेक करने के लिए बहुत जटिल हैं।
@msg A cut line and a crease lie on top of each other. एक कट लाइन और एक क्रीज़ लाइन एक-दूसरे के ऊपर हैं।
@msg No cut lines are among the given objects. दिए गए ऑब्जेक्ट में कोई कट लाइन नहीं है।
@msg Two fold lines lie on top of each other. दो फ़ोल्ड लाइनें एक-दूसरे के ऊपर हैं।
@msg A crease ends inside a panel. एक क्रीज़ लाइन किसी पैनल के अंदर खत्म होती है।
@msg A crease does not divide two panels. एक क्रीज़ लाइन दो पैनलों को अलग नहीं करती।
@msg A crease lies outside the cut outline, wholly or in part. एक क्रीज़ लाइन पूरी तरह या आंशिक रूप से कट आउटलाइन के बाहर है।
@msg The pieces of a hinge are not on one straight line. एक हिंज के हिस्से एक सीधी लाइन पर नहीं हैं।
@msg A gap between cut lines is too narrow to tell apart. कट लाइनों के बीच का गैप पहचानने के लिए बहुत पतला है।
@msg A cut-out area holds other fold lines or another blank. एक कट-आउट एरिया में दूसरी फ़ोल्ड लाइनें या दूसरा ब्लैंक है।
@msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है।
@msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है।
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings}
Can't render this file because it is too large.
+33 -2
View File
@@ -1972,6 +1972,8 @@ file-filter Templates Sablonok
Show smooth color wheel Folytonos színkör megjelenítése
Show segmented color wheel Szegmentált színkör megjelenítése
Show color bars Színsávok megjelenítése
Show brightness and hue on wheel Fényesség és színárnyalat megjelenítése a színkörön
Show saturation and hue on wheel Telítettség és színárnyalat megjelenítése a színkörön
Add Color Tool Szín hozzáadása eszköz
Remove Color Tool Szín eltávolítása eszköz
Remove Color Szín eltávolítása
@@ -2266,6 +2268,7 @@ file-filter Templates Sablonok
Isolate Blending Keverés elkülönítése
Isolate Group Csoport elkülönítése
Isolate Selected Group Kijelölt csoport elkülönítése
Isolate Selected Path Kijelölt útvonal elkülönítése
Isolate Selected Object Kijelölt objektum elkülönítése
Italian Olasz
Italic Dőlt
@@ -3206,6 +3209,10 @@ diagnostics ui felület
Play Current Selection Kijelölt művelet lejátszása
Save Actions… Műveletek mentése…
Load Actions… Műveletek betöltése…
Reset Actions Műveletek visszaállítása
Replace the current actions with the default set? Lecseréled az aktuális műveleteket az alapértelmezett készletre?
Append adds the default set after the current sets instead. A Hozzáfűzés ehelyett az aktuális készletek után adja hozzá az alapértelmezett készletet.
Append Hozzáfűzés
Plug-in Info Bővítmény adatai
Plug-ins Bővítmények
Plug-in… Bővítmény…
@@ -3904,8 +3911,12 @@ mark-style Japanese Japán
Filter Layers Panel Rows Rétegek panel sorainak szűrése
@msg `Custom` stands for changed settings: save the preset under another name a `Custom` a módosított beállításokat jelöli: mentsd az előbeállítást más néven
@msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1}
Search commands and tools Parancsok és eszközök keresése
Search commands and tools… Parancsok és eszközök keresése…
Search commands, tools, panels and effects Parancsok, eszközök, panelek és effektusok keresése
Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése…
No commands match Nincs egyező parancs
{pos} of {total}: {name} {pos}/{total}: {name}
@plural {n} result|{n} results {n} találat
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez.
Recent Commands Legutóbbi parancsok
No recent commands Nincsenek legutóbbi parancsok
Search Commands… Parancsok keresése…
@@ -9735,3 +9746,23 @@ breakText Glyphs Glifák
No objects are selected. Nincs kijelölt objektum.
Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez.
Remove Fold Line Role Vonaltípus eltávolítása
Check Ellenőrzés
Check Fold Lines Hajtásvonalak ellenőrzése
@msg No cut lines are in the selection. A kijelölésben nincs vágóvonal.
@msg No cut lines are in the document. A dokumentumban nincs vágóvonal.
@msg The cut lines do not enclose an area. A vágóvonalak nem zárnak közre területet.
@msg A cut line ends without meeting another cut line. Egy vágóvonal úgy ér véget, hogy nem találkozik másik vágóvonallal.
@msg A gap between cut lines was closed. A vágóvonalak közötti rés le lett zárva.
@msg The fold lines are too complex to check. A hajtásvonalak túl összetettek az ellenőrzéshez.
@msg A cut line and a crease lie on top of each other. Egy vágóvonal és egy bigvonal egymáson fekszik.
@msg No cut lines are among the given objects. A megadott objektumok között nincs vágóvonal.
@msg Two fold lines lie on top of each other. Két hajtásvonal egymáson fekszik.
@msg A crease ends inside a panel. Egy bigvonal egy panelen belül ér véget.
@msg A crease does not divide two panels. Egy bigvonal nem választ el két panelt.
@msg A crease lies outside the cut outline, wholly or in part. Egy bigvonal teljesen vagy részben a vágási körvonalon kívül van.
@msg The pieces of a hinge are not on one straight line. Egy zsanér részei nem egy egyenesen vannak.
@msg A gap between cut lines is too narrow to tell apart. A vágóvonalak közötti rés túl keskeny a megkülönböztetéshez.
@msg A cut-out area holds other fold lines or another blank. Egy kivágott terület további hajtásvonalakat vagy egy másik kiterítéket tartalmaz.
@msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez.
@msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings}
Can't render this file because it is too large.
+33 -2
View File
@@ -826,6 +826,7 @@
Auto Color Warna otomatis
Automatic Otomatis
Isolate Selected Group Isolasi grup terseleksi
Isolate Selected Path Isolasi jalur terseleksi
Exit Isolation Mode Keluar dari mode isolasi
Make Clipping Mask Buat masker kliping
Release Clipping Mask Lepaskan masker kliping
@@ -1227,7 +1228,7 @@ lighting Light Cahaya
Name* @ 66.67% (RGB/Preview) Nama* @ 66.67% (RGB/Pratinjau)
No Document Tidak ada dokumen
Press Tekan
Search commands and tools Cari perintah dan alat
Search commands, tools, panels and effects Cari perintah, alat, panel, dan efek
Style: Gaya:
Switch workspace Ganti ruang kerja
Show all open documents Tampilkan semua dokumen terbuka
@@ -1429,6 +1430,10 @@ lighting Light Cahaya
Play Current Selection Putar seleksi saat ini
Save Actions… Simpan tindakan…
Load Actions… Muat tindakan…
Reset Actions Atur ulang tindakan
Replace the current actions with the default set? Ganti tindakan saat ini dengan set default?
Append adds the default set after the current sets instead. Tambahkan justru menambahkan set default setelah set saat ini.
Append Tambahkan
Reflect Horizontal Pencerminan horizontal
Rotate 90° CW Putar 90° searah jarum jam
Set 1 Set 1
@@ -2737,6 +2742,8 @@ digits Malayalam Malayalam
Show smooth color wheel Tampilkan roda warna halus
Show segmented color wheel Tampilkan roda warna bersegmen
Show color bars Tampilkan bilah warna
Show brightness and hue on wheel Tampilkan kecerahan dan rona pada roda
Show saturation and hue on wheel Tampilkan saturasi dan rona pada roda
Add Color Tool Alat Tambah Warna
Remove Color Tool Alat Hapus Warna
Remove Color Hapus Warna
@@ -4137,7 +4144,11 @@ font-technology Variable Variabel
Saved {path} Berhasil menyimpan {path}
Saving Menyimpan
Saving {} Menyimpan {}
Search commands and tools… Cari perintah dan alat…
Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek…
No commands match Tidak ada perintah yang cocok
{pos} of {total}: {name} {pos} dari {total}: {name}
@plural {n} result|{n} results {n} hasil
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya.
Recent Commands Perintah terbaru
No recent commands Tidak ada perintah terbaru
Dashed Line Garis putus-putus
@@ -7104,4 +7115,24 @@ breakText Glyphs Glif
No objects are selected. Tidak ada objek yang dipilih.
Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya.
Remove Fold Line Role Hapus jenis garis
Check Periksa
Check Fold Lines Periksa garis lipat
@msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi.
@msg No cut lines are in the document. Tidak ada garis potong dalam dokumen.
@msg The cut lines do not enclose an area. Garis potong tidak melingkupi area apa pun.
@msg A cut line ends without meeting another cut line. Sebuah garis potong berakhir tanpa bertemu garis potong lain.
@msg A gap between cut lines was closed. Celah di antara garis potong telah ditutup.
@msg The fold lines are too complex to check. Garis lipat terlalu rumit untuk diperiksa.
@msg A cut line and a crease lie on top of each other. Sebuah garis potong dan sebuah garis lekuk bertumpuk.
@msg No cut lines are among the given objects. Tidak ada garis potong di antara objek yang diberikan.
@msg Two fold lines lie on top of each other. Dua garis lipat bertumpuk.
@msg A crease ends inside a panel. Sebuah garis lekuk berakhir di dalam panel.
@msg A crease does not divide two panels. Sebuah garis lekuk tidak membagi dua panel.
@msg A crease lies outside the cut outline, wholly or in part. Sebuah garis lekuk berada seluruhnya atau sebagian di luar kontur potong.
@msg The pieces of a hinge are not on one straight line. Bagian-bagian sebuah engsel tidak berada pada satu garis lurus.
@msg A gap between cut lines is too narrow to tell apart. Celah di antara garis potong terlalu sempit untuk dibedakan.
@msg A cut-out area holds other fold lines or another blank. Area yang dipotong berisi garis lipat lain atau bentangan lain.
@msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun.
@msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings}
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2495 and column 5.
+33 -2
View File
@@ -1588,6 +1588,8 @@ file-filter Templates Modelli
Show smooth color wheel Mostra ruota dei colori continua
Show segmented color wheel Mostra ruota dei colori segmentata
Show color bars Mostra barre di colore
Show brightness and hue on wheel Mostra luminosità e tonalità sulla ruota
Show saturation and hue on wheel Mostra saturazione e tonalità sulla ruota
Add Color Tool Strumento Aggiungi colore
Remove Color Tool Strumento Rimuovi colore
Remove Color Rimuovi colore
@@ -2698,6 +2700,10 @@ diagnostics ui interfaccia
Play Current Selection Esegui selezione corrente
Save Actions… Salva azioni…
Load Actions… Carica azioni…
Reset Actions Ripristina azioni
Replace the current actions with the default set? Sostituire le azioni correnti con il set predefinito?
Append adds the default set after the current sets instead. Aggiungi aggiunge invece il set predefinito dopo i set correnti.
Append Aggiungi
Plug-in Info Informazioni plug-in
Plug-ins Plug-in
Plug-in… Plug-in…
@@ -3327,8 +3333,12 @@ digits Malayalam Malayalam
Filter Layers Panel Rows Filtra righe del pannello Livelli
@msg `Custom` stands for changed settings: save the preset under another name `Custom` indica impostazioni modificate: salva il preset con un altro nome
@msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1}
Search commands and tools Cerca comandi e strumenti
Search commands and tools… Cerca comandi e strumenti…
Search commands, tools, panels and effects Cerca comandi, strumenti, pannelli ed effetti
Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti…
No commands match Nessun comando corrisponde
{pos} of {total}: {name} {pos} di {total}: {name}
@plural {n} result|{n} results {n} risultato|{n} risultati
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli.
Recent Commands Comandi recenti
No recent commands Nessun comando recente
Search Commands… Cerca comandi…
@@ -4358,6 +4368,7 @@ imageTrace Outline Contorno
to set spacing and orientation per impostare spaziatura e orientamento
: :
Isolate Selected Group Isola gruppo selezionato
Isolate Selected Path Isola tracciato selezionato
Isolate Selected Object Isola oggetto selezionato
Release Clipping Mask Rilascia maschera di ritaglio
Make Compound Path Crea tracciato composto
@@ -9379,3 +9390,23 @@ breakText Glyphs Glifi
No objects are selected. Nessun oggetto selezionato.
Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega.
Remove Fold Line Role Rimuovi tipo di linea
Check Verifica
Check Fold Lines Verifica linee di piega
@msg No cut lines are in the selection. Nella selezione non ci sono linee di taglio.
@msg No cut lines are in the document. Nel documento non ci sono linee di taglio.
@msg The cut lines do not enclose an area. Le linee di taglio non racchiudono alcuna area.
@msg A cut line ends without meeting another cut line. Una linea di taglio termina senza incontrare un’altra linea di taglio.
@msg A gap between cut lines was closed. È stato chiuso uno spazio tra linee di taglio.
@msg The fold lines are too complex to check. Le linee di piega sono troppo complesse da verificare.
@msg A cut line and a crease lie on top of each other. Una linea di taglio e una di cordonatura sono sovrapposte.
@msg No cut lines are among the given objects. Tra gli oggetti indicati non ci sono linee di taglio.
@msg Two fold lines lie on top of each other. Due linee di piega sono sovrapposte.
@msg A crease ends inside a panel. Una linea di cordonatura termina all’interno di un pannello.
@msg A crease does not divide two panels. Una linea di cordonatura non divide due pannelli.
@msg A crease lies outside the cut outline, wholly or in part. Una linea di cordonatura si trova del tutto o in parte fuori dal contorno di taglio.
@msg The pieces of a hinge are not on one straight line. I tratti di una cerniera non sono su un’unica linea retta.
@msg A gap between cut lines is too narrow to tell apart. Uno spazio tra linee di taglio è troppo stretto per essere distinto.
@msg A cut-out area holds other fold lines or another blank. Un’area ritagliata contiene altre linee di piega o un altro fustellato.
@msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura.
@msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings}
Can't render this file because it is too large.
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more