Merge main into feat/ellipse-dialog-height-copies-width

This commit is contained in:
dotCooCoo
2026-11-16 08:13:38 -08:00
130 changed files with 9319 additions and 361 deletions
Generated
+2
View File
@@ -6841,6 +6841,7 @@ dependencies = [
"vectorcraft-svg",
"vectorcraft-testkit",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-tools",
"vectorcraft-trace",
"wat",
@@ -7154,6 +7155,7 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
"proptest",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
]
+1
View File
@@ -135,6 +135,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
+3
View File
@@ -575,6 +575,9 @@ pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0;
pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01;
pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0;
/// The weight of the black outline Draw Filled Lines draws around each band, in points.
pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25;
impl GraphSpec {
/// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A
/// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the
+3 -2
View File
@@ -97,8 +97,9 @@ pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH,
MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength,
ValueAxisSide,
};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
+2
View File
@@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true }
vectorcraft-text = { workspace = true }
vectorcraft-render = { workspace = true }
vectorcraft-pathops = { workspace = true }
# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines).
vectorcraft-three-d = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-trace = { workspace = true }
vectorcraft-svg = { workspace = true }
+4
View File
@@ -893,6 +893,10 @@ pub use buildcmds::live_paint_gaps;
/// Control bar enable it when it changes one).
pub use brushsym::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
/// frame without running the command).
pub use brushsym::current_symbol;
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
+6 -2
View File
@@ -1,9 +1,11 @@
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod check;
mod roles;
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
@@ -11,7 +13,9 @@ pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
roles::specs()
let mut v = roles::specs();
v.extend(check::specs());
v
}
#[cfg(test)]
@@ -0,0 +1,179 @@
//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and
//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`].
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use super::roles::{Role, RoleTable, can_carry, role_targets};
use crate::{Result, Session};
const CHECK: &str = "addon.packaging.check";
/// How far apart the ends of two lines may be and still be joined, in points.
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.packaging.check",
"Check Fold Lines",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}",
has_doc,
check
)]
}
/// The English message for an issue (the Fold Lines panel shows it in the interface language).
fn message(code: IssueCode, scope: &str) -> &'static str {
match code {
IssueCode::NoCut if scope == "document" => "No cut lines are in the document.",
IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.",
IssueCode::NoCut => "No cut lines are in the selection.",
IssueCode::Open => "The cut lines do not enclose an area.",
IssueCode::LooseEnd => "A cut line ends without meeting another cut line.",
IssueCode::Gap => "A gap between cut lines was closed.",
IssueCode::TooComplex => "The fold lines are too complex to check.",
IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.",
IssueCode::Duplicate => "Two fold lines lie on top of each other.",
IssueCode::DanglingCrease => "A crease ends inside a panel.",
IssueCode::NoSplit => "A crease does not divide two panels.",
IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.",
IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.",
IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.",
IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.",
IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.",
IssueCode::NonPrinting => "A fold line is on a non-printing layer.",
}
}
/// Every object of the document that can carry a role and is shown: on a shown layer, in shown
/// groups, and shown itself.
fn shown_targets(d: &Document) -> Vec<NodeId> {
fn walk(n: &Node, out: &mut Vec<NodeId>) {
if !n.visible {
return;
}
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ if can_carry(n) => out.push(n.id),
_ => {}
}
}
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &mut out));
out
}
/// The path of object `n` in document coordinates: a path's own, or a compound path's members'.
fn path_of(n: &Node) -> Option<PathData> {
match &n.kind {
NodeKind::Path { path, .. } => Some(path.clone()),
NodeKind::Compound { children, .. } => Some(PathData::new(
children
.iter()
.filter_map(|c| match &c.kind {
NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()),
_ => None,
})
.flatten()
.collect(),
)),
_ => None,
}
}
/// Whether object `id` is on a layer, or a sublayer, that does not print.
fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
}
fn kind(role: Role) -> LineKind {
match role {
Role::Cut => LineKind::Cut,
Role::Crease => LineKind::Crease,
Role::PartialCut => LineKind::PartialCut,
Role::Perforation => LineKind::Perforation,
}
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = match length_given(p, "tolerance", CHECK)? {
None => TOLERANCE.1,
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
};
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, CHECK)?;
let d = &s.doc()?.doc;
// Hidden lines are left out in every scope, members of a selected group included.
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
let (scope, targets) = match (given, roots.is_empty()) {
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
(false, true) => ("document", shown_targets(d)),
};
let table = RoleTable::of(d);
let mut lines = vec![];
let mut non_printing = vec![];
let mut segments = 0usize;
for id in targets {
// Once the lines have more segments than the check takes, it reports them as too complex:
// the rest are not copied.
if segments > MAX_SEGMENTS {
break;
}
let Some(n) = d.node(id) else { continue };
let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue };
if on_non_printing_layer(d, id) {
non_printing.push(id.0);
}
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
}
let (found, mut issues) = blanks(&lines, tolerance);
if !non_printing.is_empty() {
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
}
let ok = !issues.iter().any(|i| i.code.is_error());
let rows: Vec<Value> = issues
.iter()
.map(|i| {
let mut row = json!({
"severity": if i.code.is_error() { "error" } else { "warning" },
"code": i.code.id(),
"message": message(i.code, scope),
"ids": i.keys,
});
if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) {
o.insert("at".into(), json!([at.x, at.y]));
}
row
})
.collect();
if select {
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
ids.sort_unstable_by_key(|id| id.0);
ids.dedup();
if !ids.is_empty() {
s.select(|_, sel| sel.set(ids.iter().copied()))?;
}
}
Ok(json!({
"ok": ok,
"blanks": found.len(),
"panels": found.iter().map(|b| b.panels.len()).sum::<usize>(),
"hinges": found.iter().map(|b| b.hinges.len()).sum::<usize>(),
"holes": found.iter().map(|b| b.holes.len()).sum::<usize>(),
"issues": rows,
"scope": scope,
}))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,180 @@
//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a
//! document.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn check(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.check", &p).unwrap()
}
fn codes(r: &Value) -> Vec<&str> {
r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect()
}
/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the
/// base's four sides creases → (outline, creases).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
#[test]
fn a_tray_checks_clean_with_five_panels_and_four_hinges() {
let mut s = session();
tray(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}");
assert!(codes(&r).is_empty(), "{r}");
assert_eq!(r["scope"], "document");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step");
}
#[test]
fn the_selection_or_ids_limit_the_check_to_their_lines() {
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap();
let r = check(&mut s, json!({}));
assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false)));
assert_eq!(codes(&r), ["noCut"]);
assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection.");
let r = check(&mut s, json!({ "ids": [outline] }));
assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}");
let r = check(&mut s, json!({ "ids": [creases[1]] }));
assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"]));
assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects.");
// No fold lines at all in the document.
let mut s = session();
let r = check(&mut s, json!({}));
assert_eq!(codes(&r), ["noCut"]);
assert_eq!(r["issues"][0]["message"], "No cut lines are in the document.");
}
#[test]
fn issues_name_their_lines_and_select_selects_them() {
let mut s = session();
let (_, creases) = tray(&mut s);
// A slit from the outline that stops in the middle of the base.
let slit = path(&mut s, "M190 100 L190 190");
role(&mut s, "cut", &[slit]);
s.execute("select.none", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], false);
let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap();
assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}");
assert_eq!(loose["at"], json!([190.0, 190.0]));
assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays");
let r = check(&mut s, json!({ "select": true }));
let named: std::collections::BTreeSet<u64> =
r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect();
let selected: std::collections::BTreeSet<u64> = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}");
assert!(!selected.contains(&creases[1]));
}
#[test]
fn a_clean_check_with_select_leaves_the_selection_alone() {
let mut s = session();
let (outline, _) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [outline] })).unwrap();
let r = check(&mut s, json!({ "ids": [outline], "select": true }));
assert!(codes(&r).is_empty(), "{r}");
assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), [outline]);
}
#[test]
fn tolerance_is_checked_and_joins_gaps_up_to_it() {
let mut s = session();
tray(&mut s);
for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] {
let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string();
assert!(e.contains("tolerance"), "{e}");
}
let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string();
assert!(e.contains("select"), "{e}");
for edge in [json!(0.01), json!(10), json!("2 mm")] {
assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true);
}
// A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt.
let mut s = session();
tray(&mut s);
let slit = path(&mut s, "M190 100 L190 139.5");
role(&mut s, "cut", &[slit]);
s.execute("select.none", &json!({})).unwrap();
assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd"));
let near = check(&mut s, json!({ "tolerance": 1 }));
assert!(!codes(&near).contains(&"looseEnd"), "{near}");
}
#[test]
fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() {
let mut s = session();
let (_, creases) = tray(&mut s);
// A hidden crease is not checked while nothing is selected: the tray has three hinges and a
// panel joined by none.
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
s.execute("select.none", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
// The same in a selected group, and with the group named by `ids`: the hidden member is left
// out too.
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
for p in [json!({}), json!({ "ids": [group] })] {
let r = check(&mut s, p);
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
}
// A cut line on a layer that does not print.
let mut s = session();
s.execute("layer.new", &json!({ "printable": false })).unwrap();
let (outline, _) = tray(&mut s);
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], true, "a warning only");
let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap();
assert_eq!(note["severity"], "warning");
assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}");
assert_eq!(note["message"], "A fold line is on a non-printing layer.");
}
#[test]
fn a_compound_path_and_a_grouped_line_are_checked() {
let mut s = session();
let (outline, creases) = tray(&mut s);
// A window: a closed cut line in the base, made a compound path with nothing else.
let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z");
s.execute("select.set", &json!({ "ids": [window] })).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64();
let window = compound.unwrap_or(window);
role(&mut s, "cut", &[window]);
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap();
s.execute("object.group", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!(r["scope"], "selection");
assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}");
}
@@ -186,7 +186,7 @@ fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
/// guide, or a compound path.
fn can_carry(n: &Node) -> bool {
pub(super) fn can_carry(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
NodeKind::Compound { .. } => true,
@@ -199,7 +199,7 @@ fn can_carry(n: &Node) -> bool {
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
/// are on a locked artboard are left out and counted as skipped.
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
match &n.kind {
NodeKind::Group { children, .. } => {
@@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
};
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center()));
// Centers closer than a billionth of the larger path's size count as one point: no line.
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center()));
let fill = Paint::None;
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
@@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() {
}
}
#[test]
fn tiny_paths_close_together_still_get_the_centerline() {
// Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four
// tangents, and centers apart by far more than their sizes' rounding.
let mut s = session();
let a = circle(&mut s, 1.0, 1.0, 1e-10);
let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10);
let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}");
assert_eq!(r["centerline"], r["ids"][4]);
}
#[test]
fn the_lines_take_the_current_stroke_and_no_fill() {
let mut s = session();
+3
View File
@@ -27,6 +27,9 @@ use crate::EngineError;
/// Whether Reset Transformation changes a symbol instance.
pub use symbols::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it.
pub use symbols::current_symbol;
mod brushes;
mod dynamic;
mod symbols;
+12 -11
View File
@@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
if d.symbols.is_sorted_by_key(key) {
return ok();
}
let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
let current = current_symbol(d);
s.edit("Sort by Name", |d, _| {
if let Some(name) = current {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
@@ -173,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
fn symbol_names(d: &Document) -> Vec<String> {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
fn current_symbol(d: &Document) -> Option<String> {
d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string)
/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol
/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols.
pub fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get(CURRENT_SYMBOL)
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.or_else(|| d.symbols.first().map(|s| s.name.as_str()))
.map(str::to_string)
}
pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
@@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
})
})
.collect();
Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) }))
Ok(json!({ "symbols": list, "current": current_symbol(d) }))
}
/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the
@@ -398,9 +401,7 @@ fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
match str_param(p, "name") {
Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()),
Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))),
None => {
current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into()))
}
None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())),
}
}
+1 -1
View File
@@ -31,6 +31,6 @@ mod freehand;
mod smooth;
pub use commands::specs;
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+1 -1
View File
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Split Path",
[],
None,
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
has_doc,
split
),
+20
View File
@@ -406,6 +406,26 @@ pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result
Ok(n)
}
/// Set every stroke of node `id`, and every stroke of the compound path it is a member of (whose
/// strokes its members show), to Center alignment. Every other stroke and fill setting stays as it
/// is, and an appearance whose strokes are all centered stays shared with its other copies.
pub(in super::super) fn center_strokes(d: &mut Document, id: NodeId) {
use vectorcraft_doc::{AppearanceItem, StrokeAlign};
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
for n in [Some(id), parent].into_iter().flatten() {
let Some(n) = d.node_mut(n) else { continue };
let off = |it: &AppearanceItem| matches!(it, AppearanceItem::Stroke(st) if st.align != StrokeAlign::Center);
if !n.appearance.items.iter().any(off) {
continue;
}
for it in &mut n.appearance.items {
if let AppearanceItem::Stroke(st) = it {
st.align = StrokeAlign::Center;
}
}
}
}
/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above
/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids.
pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
+6 -2
View File
@@ -1,6 +1,6 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds,
pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
@@ -225,14 +225,17 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, 0));
};
// The paths a cut makes keep the source's appearance with every stroke centered.
if sp.closed {
path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?;
center_strokes(d, id);
pick(sel, id, si);
return Ok(vec![id]);
}
let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?;
if path.subpaths.len() == 1 {
path.subpaths[0] = left;
center_strokes(d, id);
let node = sibling_with(d, id, PathData::single(right))?;
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let nid = d.insert(parent, idx + 1, node)?;
@@ -241,6 +244,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
} else {
path.subpaths[si] = left;
path.subpaths.insert(si + 1, right);
center_strokes(d, id);
pick(sel, id, si + 1);
Ok(vec![id])
}
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
has_doc,
screens::export_for_screens
),
+9 -3
View File
@@ -350,8 +350,8 @@ struct ScreenParams {
/// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as
/// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`.
folders: Option<String>,
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or
/// `multiple` (a file per artboard, the default).
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file; refused
/// with assets, layers or `selection: "each"`) or `multiple` (a file per artboard, the default).
pdfs: Option<String>,
}
@@ -399,12 +399,18 @@ impl ScreenParams {
if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) }
}
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given.
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given,
/// and when `pdfs: "single"` is given with `assets`, `layers` or `selection: "each"`, whose
/// files each hold the art of one item.
fn one_source(&self) -> Result<()> {
let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count();
if sources > 1 {
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
}
let per_piece = self.assets.is_some() || self.layers.is_some() || self.selection.as_deref() == Some("each");
if per_piece && self.pdfs.as_deref() == Some("single") {
return Err(bad(C, "pdfs `single` writes artboards as the pages of one PDF: assets, layers and selection `each` write a PDF each"));
}
Ok(())
}
@@ -1245,6 +1245,41 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
/// Export PDFs As › Single file holds artboards: with assets, layers or a file per selected object,
/// whose files each hold one item's art, it is refused (the Example line too) instead of writing
/// the first item alone under the document's name; Multiple files writes a PDF of each item. The
/// selection as one file is one PDF either way.
#[test]
fn single_file_pdfs_are_refused_for_assets_layers_and_each_object() {
let mut s = session(1);
s.execute("layer.new", &json!({"name": "Second"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 30, "y": 5, "width": 8, "height": 8})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let layers: Vec<u64> = doc.layers.iter().map(|l| l.id.0).collect();
let art: Vec<u64> = doc.layers.iter().filter_map(|l| l.children()).flatten().map(|c| c.id.0).collect();
assert_eq!((layers.len(), art.len()), (2, 2));
let a = s.execute("assets.add", &json!({"ids": [art[0]], "name": "Square"})).unwrap()["assets"][0].as_u64().unwrap();
let b = s.execute("assets.add", &json!({"ids": [art[1]], "name": "Dot"})).unwrap()["assets"][0].as_u64().unwrap();
s.execute("select.all", &json!({})).unwrap();
let pdf = json!([{"format": "pdf"}]);
for source in [json!({"assets": [a, b]}), json!({"layers": layers}), json!({"selection": "each"})] {
let mut p = source.clone();
p["formats"] = pdf.clone();
p["pdfs"] = json!("multiple");
let r = export(&mut s, p.clone());
assert_eq!(names(&r).len(), 2, "a PDF each: {:?} ({source})", names(&r));
for (name, bytes) in files(&r) {
assert_eq!(vectorcraft_pdf::import(&bytes).unwrap().artboards.len(), 1, "{name}");
}
p["pdfs"] = json!("single");
let e = s.execute("document.exportForScreens", &p).unwrap_err().to_string();
assert!(e.contains("pdfs `single`"), "{e} ({source})");
assert!(super::screens::first_file(&s, &p).is_err(), "{source}");
}
let r = export(&mut s, json!({"selection": "one", "pdfs": "single", "formats": pdf}));
assert_eq!(names(&r), ["Selection.pdf"]);
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
+1 -1
View File
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show Similar Fonts",
[],
None,
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind; a family that shares none of these numbers with it comes after those that share one); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
always,
similar_fonts
),
+1 -1
View File
@@ -244,7 +244,7 @@ impl Gen<'_> {
let slot = g.series_paints.get(s);
let fill =
slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone().filter(|st| !st.is_none()))).unwrap_or_else(|| default_series_paint(s));
return self.path(band, fill, Paint::solid(Color::BLACK), 0.25);
return self.path(band, fill, Paint::solid(Color::BLACK), vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH);
}
let (fill, stroke, w) = series_marks(g, s, false, default_series_paint(s), 1.0);
self.path(pd, fill, stroke, w)
+52
View File
@@ -9505,6 +9505,58 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() {
}
}
/// A line graph the graph tools draw with Draw Filled Lines, saved as `.ai` in either form, opens again as the same graph
/// with its filled lines and Line Width, the default 3 pt included, and without a warning about graphs. A Line Width past
/// the records' 100 pt is saved as the graph's art, with the warning.
#[test]
fn a_drawn_graph_with_filled_lines_saved_as_ai_opens_with_them() {
let dir = vectorcraft_testkit::temp_dir("graph-ai-filled");
for (width, live) in [(None, true), (Some(8.0), true), (Some(150.0), false)] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6";
let id = s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap();
let mut options = json!({"id": id, "filledLines": true});
if let Some(w) = width {
options["lineWidth"] = json!(w);
}
s.execute("graph.setType", &options).unwrap();
let written = spec(&s, NodeId(id));
assert_eq!((written.filled_lines, written.line_width), (true, width));
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
let path = dir.join(format!("{width:?}-{name}"));
let mut p = json!({"path": path, "format": "ai"});
if let Some(v) = version {
p["aiVersion"] = json!(v);
}
let r = s.execute("file.saveAs", &p).unwrap();
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art")));
assert_eq!(warned, !live, "{width:?} {name}: {r}");
let mut again = Session::new();
again.execute("document.open", &json!({"path": path})).unwrap();
let mut graphs = vec![];
again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().map(|g| (n.id, g.clone()))));
assert_eq!(graphs.len(), usize::from(live), "{width:?} {name}");
if let Some((gid, g)) = graphs.first() {
assert_eq!((g.kind, g.cells(), g.filled_lines, g.line_width), (written.kind, written.cells(), true, width), "{width:?} {name}");
assert_eq!(g.filled_line_width(), written.filled_line_width(), "{width:?} {name}");
// With Draw Filled Lines turned off, each series draws its thin 1 pt line again.
again.execute("select.set", &json!({"ids": [gid.0]})).unwrap();
again.execute("graph.setType", &json!({"id": gid.0, "filledLines": false})).unwrap();
for series in 0..2 {
let line = series_parts(&again, *gid, series)
.into_iter()
.any(|p| p.appearance.fill_paint().is_none() && !p.appearance.stroke_paint().is_none() && p.appearance.stroke_width() == 1.0);
assert!(line, "{width:?} {name}: series {series} draws no thin line");
}
}
}
}
}
/// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the
/// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept
/// on the series, with or without a weight of its own, is on the swatch too.
+1 -10
View File
@@ -6,6 +6,7 @@ use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, str_param};
@@ -97,13 +98,3 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"id": id.0, "caret": caret}))
}
/// The Symbols panel's current symbol, else the first one.
fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get("currentSymbol")
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.map(str::to_string)
.or_else(|| d.symbols.first().map(|s| s.name.clone()))
}
+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) {
@@ -40,6 +40,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.colorMask",
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.check",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
+222 -31
View File
@@ -5,13 +5,14 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind};
use super::select::selectable_ids;
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, has_doc, object_param, str_param, switch_or};
/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in
/// points, opacity in percent.
/// Magic Wand panel settings. Tolerances: colors as a Euclidean distance, 0–255 between RGB
/// values in an RGB document and 0–100 between CMYK percentages in a CMYK document; stroke
/// weight in points; opacity in percent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WandSettings {
@@ -58,33 +59,68 @@ pub fn specs() -> Vec<CommandSpec> {
"Magic Wand Options",
["Window", "Magic Wand"],
None,
"{fillColor?, fillTolerance?: 0-255, strokeColor?, strokeTolerance?: 0-255, strokeWeight?, weightTolerance?: pt, opacity?, opacityTolerance?: %, blendingMode?, reset?: bool} → the settings",
"{fillColor?, fillTolerance?: 0-255 in an RGB document or 0-100 in a CMYK one, strokeColor?, strokeTolerance?: as fillTolerance, strokeWeight?, weightTolerance?: 0-1000 pt, opacity?, opacityTolerance?: 0-100 %, blendingMode?, reset?: bool} → the settings; a value out of range is an error and changes nothing, and an omitted one keeps its setting",
always,
set
),
cmd!(query "magicWand.options", "Magic Wand Settings", [], None, "{} → the Magic Wand settings", always, |s, _| Ok(json!(s.menu.wand))),
cmd!(
query "magicWand.options",
"Magic Wand Settings",
[],
None,
"{} → the Magic Wand settings (color tolerances at most 100 in a CMYK document)",
always,
|s, _| Ok(json!(s.menu.wand.effective(active_mode(s))))
),
]
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "reset", false) {
s.menu.wand = WandSettings::default();
/// The active document's color mode, RGB with no document open.
fn active_mode(s: &Session) -> ColorMode {
s.doc().map(|st| st.doc.color_mode).unwrap_or_default()
}
/// The largest Fill Color and Stroke Color tolerance in a document of `mode`.
pub fn color_tolerance_max(mode: ColorMode) -> f64 {
match mode {
ColorMode::Rgb => 255.0,
ColorMode::Cmyk => 100.0,
}
let mut v = serde_json::to_value(&s.menu.wand).map_err(|e| EngineError::Other(e.to_string()))?;
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
for (k, val) in src {
if o.contains_key(k) {
o.insert(k.clone(), val.clone());
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "magicWand.set";
let mode = active_mode(s);
let color_max = color_tolerance_max(mode);
let mut w = if switch_or(p, "reset", false, CMD)? { WandSettings::default() } else { s.menu.wand.clone() };
for (key, flag) in [
("fillColor", &mut w.fill_color),
("strokeColor", &mut w.stroke_color),
("strokeWeight", &mut w.stroke_weight),
("opacity", &mut w.opacity),
("blendingMode", &mut w.blending_mode),
] {
// Only a missing key keeps the setting; null, like any other value that isn't true or
// false, is an error.
if let Some(v) = p.get(key) {
*flag = v.as_bool().ok_or_else(|| bad(CMD, format!("`{key}` must be true or false")))?;
}
}
let mut w: WandSettings = serde_json::from_value(v).map_err(|e| bad("magicWand.set", e.to_string()))?;
w.fill_tolerance = w.fill_tolerance.clamp(0.0, 255.0);
w.stroke_tolerance = w.stroke_tolerance.clamp(0.0, 255.0);
w.weight_tolerance = w.weight_tolerance.clamp(0.0, 1000.0);
w.opacity_tolerance = w.opacity_tolerance.clamp(0.0, 100.0);
for (key, value, max) in [
("fillTolerance", &mut w.fill_tolerance, color_max),
("strokeTolerance", &mut w.stroke_tolerance, color_max),
("weightTolerance", &mut w.weight_tolerance, 1000.0),
("opacityTolerance", &mut w.opacity_tolerance, 100.0),
] {
let Some(v) = p.get(key) else { continue };
let n = v.as_f64().ok_or_else(|| bad(CMD, format!("`{key}` must be a number, not {v}")))?;
if !(n.is_finite() && (0.0..=max).contains(&n)) {
return Err(bad(CMD, format!("`{key}` must be from 0 to {max}, not {n}")));
}
*value = n;
}
s.menu.wand = w;
Ok(json!(s.menu.wand))
Ok(json!(s.menu.wand.effective(mode)))
}
/// The fill an object shows: type's comes from its characters (the first run speaks for all; type
@@ -104,25 +140,48 @@ pub(crate) fn stroke_of(n: &Node) -> (Paint, f64) {
}
}
/// Are two paints within `tol` (0–255 Euclidean RGB distance)? Non-solid paints must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64) -> bool {
/// Are two paints within `tol`? In an RGB document `tol` is a 0–255 Euclidean distance between
/// the display RGB values; in a CMYK document it is a 0–100 Euclidean distance between the CMYK
/// percentages (a CMYK color's own values, any other color converted to CMYK). Non-solid paints
/// must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64, mode: ColorMode) -> bool {
match (a.color(), b.color()) {
(Some(x), Some(y)) => {
let (x, y) = (x.to_rgb(), y.to_rgb());
let d: f64 = (0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt();
d <= tol + 1e-6
let (d, margin) = match mode {
ColorMode::Rgb => {
let (x, y) = (x.to_rgb(), y.to_rgb());
((0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt(), 1e-6)
}
// CMYK components are f32 fractions, so a distance of exactly `tol` points can come
// out a few millionths over.
ColorMode::Cmyk => {
let (x, y) = (x.to_cmyk(), y.to_cmyk());
((0..4).map(|i| ((x[i] - y[i]) as f64 * 100.0).powi(2)).sum::<f64>().sqrt(), 1e-4)
}
};
d <= tol + margin
}
_ => a == b,
}
}
impl WandSettings {
/// Does `n` match `reference` on every enabled attribute?
pub fn matches(&self, reference: &Node, n: &Node) -> bool {
/// The settings in effect in a document of `mode`: the color tolerances are capped at that
/// mode's maximum, so a larger value set in an RGB document applies as 100 in a CMYK one and
/// comes back in an RGB one.
pub fn effective(&self, mode: ColorMode) -> WandSettings {
let max = color_tolerance_max(mode);
WandSettings { fill_tolerance: self.fill_tolerance.min(max), stroke_tolerance: self.stroke_tolerance.min(max), ..self.clone() }
}
/// Does `n` match `reference` on every enabled attribute, comparing colors as in a document of
/// `mode`?
pub fn matches(&self, reference: &Node, n: &Node, mode: ColorMode) -> bool {
let w = self.effective(mode);
let (rs, rw) = stroke_of(reference);
let (ns, nw) = stroke_of(n);
(!self.fill_color || similar_paint(&fill_of(reference), &fill_of(n), self.fill_tolerance))
&& (!self.stroke_color || similar_paint(&rs, &ns, self.stroke_tolerance))
(!w.fill_color || similar_paint(&fill_of(reference), &fill_of(n), w.fill_tolerance, mode))
&& (!w.stroke_color || similar_paint(&rs, &ns, w.stroke_tolerance, mode))
&& (!self.stroke_weight || (rw - nw).abs() <= self.weight_tolerance + 1e-9)
&& (!self.opacity || ((reference.opacity - n.opacity).abs() as f64 * 100.0) <= self.opacity_tolerance + 1e-6)
&& (!self.blending_mode || reference.blend == n.blend)
@@ -156,12 +215,13 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
let w = s.menu.wand.clone();
let mode = st.doc.color_mode;
// In isolation mode only the isolated group's contents can be picked, as for Select Same.
let inside = st.isolation.map(|iso| selectable_ids(&st.doc, Some(iso)));
let hits: Vec<NodeId> = paintable(&st.doc)
.into_iter()
.filter(|i| inside.as_ref().is_none_or(|set| set.contains(i)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
.collect();
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
@@ -232,6 +292,137 @@ mod tests {
assert_eq!(selected(&s), [b]);
}
/// A 10 × 10 rectangle at `x` filled and stroked with the given colors (JSON color values).
fn painted(s: &mut Session, x: f64, fill: Value, stroke: Value) -> u64 {
let id = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({ "color": fill })).unwrap();
s.execute("paint.setStroke", &json!({ "color": stroke })).unwrap();
id
}
fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value {
json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k})
}
#[test]
fn cmyk_document_compares_fill_and_stroke_colors_in_cmyk() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let white = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.1, 0.0, 0.0, 0.0), white.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.0), white.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.1, 0.0, 0.0), white.clone());
// a to b is 10 points of cyan; a to c is 10 points of cyan and 10 of magenta (14.1).
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
s.execute("magicWand.set", &json!({"fillTolerance": 14.2})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
// Stroke Color alone, the same rule: d's stroke is 5 points of black from a's.
let d = painted(&mut s, 60.0, cmyk(1.0, 1.0, 1.0, 1.0), cmyk(0.0, 0.0, 0.0, 0.05));
s.execute("magicWand.set", &json!({"fillColor": false, "strokeColor": true, "strokeTolerance": 5})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [a, b, c, d]);
s.execute("magicWand.set", &json!({"strokeTolerance": 4.9})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [d]);
}
#[test]
fn cmyk_document_compares_gray_as_black_ink() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, json!({"gray": 0.5}), none.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.5), none.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.0, 0.0, 0.6), none);
s.execute("magicWand.set", &json!({"fillTolerance": 0})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
}
#[test]
fn rgb_document_keeps_the_rgb_distance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
let a = rect(&mut s, 0.0, "#000000", 1.0);
let b = rect(&mut s, 20.0, "#0a0000", 1.0);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 255})).unwrap()["fillTolerance"], 255.0);
}
#[test]
fn set_rejects_tolerances_out_of_range_and_changes_nothing() {
let mut s = Session::new();
// With no document the color range is the RGB one.
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 256})).is_err());
s.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 40, "strokeTolerance": 50})).unwrap();
let before = s.execute("magicWand.options", &json!({})).unwrap();
for bad_value in [
json!({"fillTolerance": 101}),
json!({"strokeTolerance": 100.5}),
json!({"fillTolerance": -1}),
json!({"fillTolerance": "40"}),
json!({"weightTolerance": 1001}),
json!({"opacityTolerance": -0.5}),
json!({"fillColor": "yes"}),
json!({"fillTolerance": null}),
json!({"strokeColor": null}),
json!({"reset": "yes", "fillColor": false}),
json!({"reset": true, "fillTolerance": 101}),
json!({"fillColor": false, "strokeTolerance": 101}),
] {
let e = s.execute("magicWand.set", &bad_value).unwrap_err().to_string();
assert!(e.contains("magicWand.set"), "{bad_value}: {e}");
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap(), before, "{bad_value} changed the settings");
}
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 101})).unwrap_err().to_string().contains("from 0 to 100"));
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 100})).unwrap()["fillTolerance"], 100.0);
// An omitted value keeps its setting.
assert_eq!(s.execute("magicWand.set", &json!({"strokeColor": true})).unwrap()["strokeTolerance"], 50.0);
}
#[test]
fn a_larger_rgb_tolerance_applies_as_100_in_a_cmyk_document_and_comes_back() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 200, "strokeTolerance": 60})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let o = s.execute("magicWand.options", &json!({})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(100.0), Some(60.0)));
// Setting another field does not overwrite the stored fill tolerance.
assert_eq!(s.execute("magicWand.set", &json!({"opacity": true})).unwrap()["fillTolerance"], 100.0);
// 100 applies: two colors 100 points apart in one channel match, 100 apart in two do not.
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.0, 0.0, 0.0, 0.0), none.clone());
let b = painted(&mut s, 20.0, cmyk(1.0, 0.0, 0.0, 0.0), none.clone());
let c = painted(&mut s, 40.0, cmyk(1.0, 1.0, 0.0, 0.0), none);
s.execute("magicWand.set", &json!({"opacity": false})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
assert!(!selected(&s).contains(&c));
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap()["fillTolerance"], 200.0);
// Reset gives 32 in either mode.
s.execute("document.activate", &json!({"index": 1})).unwrap();
let o = s.execute("magicWand.set", &json!({"reset": true})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
}
#[test]
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
let mut s = Session::new();
+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");
}
+130
View File
@@ -3219,6 +3219,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 +4020,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] {
+66
View File
@@ -149,6 +149,72 @@ fn a_shape_tool_turns_the_shape_from_just_outside_a_corner() {
assert_eq!(angle(&s, id), 0.0, "rounding does not turn it");
}
/// How many objects the first layer holds.
fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.layers[0].children().map(|c| c.len()).unwrap_or_default()
}
/// Feed the pointer events `(kind, x, y, backtick held)` to the active tool, with no modifier.
fn quote_gesture(s: &mut Session, events: &[(PointerKind, f64, f64, bool)]) {
for (k, x, y, held) in events {
s.pointer(&PointerEvent { backquote: *held, ..PointerEvent::new(*k, *x, *y) }, view()).unwrap();
}
}
/// A Rectangle tool drag from (50, 50) with Backtick held from (100, 100) to (140, 100), let go
/// before (160, 120), all moved by `o` along both axes: two copies, 70 × 50 and 90 × 50 pt, and
/// the 110 × 70 pt rectangle it ends with. With `release`, the drag is let go; without, it is
/// still in progress.
fn trail(s: &mut Session, o: f64, release: bool) {
use PointerKind::{Down, Drag, Up};
quote_gesture(
s,
&[
(Down, 50.0 + o, 50.0 + o, false),
(Drag, 100.0 + o, 100.0 + o, true),
(Drag, 120.0 + o, 100.0 + o, true),
(Drag, 140.0 + o, 100.0 + o, true),
],
);
quote_gesture(s, &[(Drag, 160.0 + o, 120.0 + o, false)]);
if release {
quote_gesture(s, &[(Up, 160.0 + o, 120.0 + o, false)]);
}
}
/// The sizes of the first layer's objects, back to front.
fn sizes(s: &Session) -> Vec<(f64, f64)> {
let ids: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default();
ids.into_iter().map(|id| bounds(s, id)).map(|r| (r.width(), r.height())).collect()
}
/// Backtick held while a rectangle is dragged out leaves copies of it along the drag: each its own
/// object, and the release keeps them with the last rectangle as one undo step, with Real-time
/// Drawing and Editing on or off. Escape takes the copies back with the shape being drawn.
#[test]
fn a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step() {
for real_time in [true, false] {
let mut s = new_doc();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap();
s.select_tool("rectangle", view()).unwrap();
let steps = undo_steps(&s);
trail(&mut s, 0.0, true);
assert_eq!(sizes(&s), vec![(70.0, 50.0), (90.0, 50.0), (110.0, 70.0)], "real time {real_time}");
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s), 0, "Undo takes all three back");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(objects(&s), 3, "Redo puts all three back");
// Escape takes back the copies and the shape being drawn, away from the selection.
let steps = undo_steps(&s);
trail(&mut s, 200.0, false);
s.tool_key(ToolKey::Escape, NONE, view()).unwrap();
quote_gesture(&mut s, &[(PointerKind::Up, 360.0, 320.0, false)]);
assert_eq!(objects(&s), 3, "real time {real_time}: nothing new");
assert_eq!(undo_steps(&s), steps, "no step");
}
}
/// The Selection tool takes the centre point of an unfilled shape too: a drag there moves it
/// instead of starting a marquee.
#[test]
+3
View File
@@ -1011,6 +1011,9 @@ fn structured_junk() {
("addon.packaging.roles", json!({"ids": [-1, 1e300]})),
("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})),
("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})),
("addon.packaging.check", json!({"ids": [u64::MAX, -1], "select": "yes", "tolerance": 1e308})),
("addon.packaging.check", json!({"tolerance": "-5 mm", "select": true})),
("addon.packaging.check", json!({"ids": [], "tolerance": null})),
// Smart Pen add-on.
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),
+27 -1
View File
@@ -2888,6 +2888,32 @@ proptest! {
paste_from_elsewhere("clipboard.importEps", json!({"dataBase64": vectorcraft_format::base64_encode(ps.as_bytes())}))?;
}
/// Any bytes read by `readhexstring` or `readline` into strings of any length, from the
/// program's own file, through a filter decoded when first read, or from a file being run:
/// read as data, or as an error.
#[test]
fn eps_readhexstring_and_readline_data_never_panic(
data in prop::collection::vec(prop::sample::select(vec![b'0', b'9', b'a', b'F', b'g', b' ', b'\t', b'\r', b'\n', b'>', b'%', b'(', 0u8, 0xff]), 0..300),
len in 0usize..40,
line in any::<bool>(),
source in 0usize..3,
) {
let op = if line { "readline" } else { "readhexstring" };
let file = if source == 1 { "currentfile /ASCIIHexDecode filter" } else { "currentfile" };
let reads = format!("/s {len} string def /f {file} def 30 {{ f s {op} pop pop }} repeat");
let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
if source == 2 {
bytes.extend_from_slice(format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{reads}\n").as_bytes());
bytes.extend_from_slice(&data);
bytes.extend_from_slice(b"\nendstream\nshowpage\n");
} else {
bytes.extend_from_slice(format!("{reads}\n").as_bytes());
bytes.extend_from_slice(&data);
bytes.extend_from_slice(b"\nshowpage\n");
}
survive("readhexstring and readline data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
/// Damaged or hostile CMYK images (a CMYK JPEG, an image with a key color): read as images,
/// or as an error.
#[test]
@@ -3133,7 +3159,7 @@ fn arb_ps_token() -> impl Strategy<Value = String> {
"gsave", "grestore", "save", "restore", "concat", "translate", "scale", "rotate", "setlinewidth", "setdash", "setgray",
"setrgbcolor", "setcmykcolor", "sethsbcolor", "setcolorspace", "setcolor", "setpattern", "makepattern", "shfill", "arc", "arcn",
"arct", "arcto", "rectfill", "rectclip", "rectstroke", "image", "imagemask", "colorimage", "currentfile", "filter",
"readhexstring", "readstring", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont",
"readhexstring", "readstring", "readline", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont",
"def", "bind", "load", "dup", "exch", "pop", "roll", "index", "copy", "for", "repeat", "loop", "exit", "if", "ifelse", "exec",
"stopped", "begin", "end", "dict", "array", "string", "get", "put", "getinterval", "putinterval", "aload", "astore", "forall",
"[", "]", "<<", ">>", "{", "}", "matrix", "currentmatrix", "setmatrix", "transform", "itransform", "invertmatrix", "pathbbox",
+147 -25
View File
@@ -17,8 +17,8 @@ use std::fmt::Write;
use kurbo::{PathSeg, Point};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{
Appearance, AppearanceItem, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, Node, NodeId, NodeKind, PiePosition,
PieSort, TickLength, ValueAxisSide,
Appearance, AppearanceItem, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES,
MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, Node, NodeId, NodeKind, PiePosition, PieSort, TickLength, ValueAxisSide,
};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, Rect};
@@ -46,6 +46,9 @@ const EDGE: f64 = 0.01;
/// Most values one `Gc` takes.
const CELLS_PER_RECORD: usize = 15;
/// Widest `lineShapeWidth` the records give, in points (appendix A, `Gy`).
const MAX_LINE_WIDTH: f64 = 100.0;
/// A graph's records: what goes before its group (`%_Gs` to `%_GC`), and the `Go` line that follows
/// each series' group, by the group's id. `%_GS` follows the group.
pub(crate) struct Records {
@@ -89,7 +92,8 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> {
(r.is_finite() && r.width() > 0.0 && r.height() > 0.0).then_some(())?;
let plot = to_art.transform_rect_bbox(r);
(plot.is_finite() && plot.width() > 0.0 && plot.height() > 0.0).then_some(())?;
let tags = series_groups(children, width, first_col, g.kind == GraphKind::Line)?;
let line = g.kind == GraphKind::Line;
let tags = series_groups(children, width, first_col, line, line && g.filled_lines)?;
draws_axes(n, r).then_some(())?;
let placed = n.geometric_bounds()?;
(r.x0 >= placed.x0 - EDGE && r.y0 >= placed.y0 - EDGE && r.x1 <= placed.x1 + EDGE && r.y1 <= placed.y1 + EDGE).then_some(())?;
@@ -97,14 +101,17 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> {
let mut head = String::from("%_Gs\n");
let _ = writeln!(head, "%_{} {} {} {} Gb", real(plot.x0), real(plot.y1), real(plot.x1), real(plot.y0));
let flag = |b: bool| u8::from(b);
// `lineShapeWidth`: the width filled lines are drawn at, the graph's default included.
let _ = writeln!(
head,
"%_{ty} {} {} 14 {} {} 0 {} 6 44 Gy",
"%_{ty} {} {} 14 {} {} {} {} {} 44 Gy",
flag(g.drop_shadow),
flag(g.first_row_in_front),
flag(g.mark_points),
flag(g.connect_points),
flag(g.legend_across_top)
flag(g.filled_lines),
flag(g.legend_across_top),
real(g.line_width.unwrap_or(DEFAULT_FILLED_LINE_WIDTH))
);
let _ =
writeln!(head, "%_10 2 {} 0 {} {} {} Gd", flag(g.first_column_in_front), real(g.column_width), real(g.cluster_width), flag(g.edge_to_edge));
@@ -233,10 +240,11 @@ fn tick(t: TickLength) -> u8 {
}
/// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across
/// the top, every series of the graph's type, one value axis on the left, lines not filled and no
/// Line Width of their own, no graph
/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most
/// [`MAX_TICK_MARKS`] tick marks a division.
/// the top, every series of the graph's type, one value axis on the left, lines filled only where
/// they connect the points (the records ignore the setting otherwise), a Line Width of 0.01 to
/// [`MAX_LINE_WIDTH`] points, with filled lines no series stroked as the bands' outline
/// ([`band_outline`]), which the reader reads as bands, no graph designs, label formatting or pie settings, column and
/// cluster widths of 1% to 1000%, and at most [`MAX_TICK_MARKS`] tick marks a division.
fn settings_kept(g: &GraphSpec) -> bool {
let percent = |p: f64| (1.0..=1000.0).contains(&p);
g.legend
@@ -244,8 +252,9 @@ fn settings_kept(g: &GraphSpec) -> bool {
&& g.value_axis == ValueAxisSide::Left
&& !g.separate_scales
&& g.right_series.is_empty()
&& !g.filled_lines
&& g.line_width.is_none()
&& (g.connect_points || !g.filled_lines)
&& g.line_width.is_none_or(|w| (MIN_FILLED_LINE_WIDTH..=MAX_LINE_WIDTH).contains(&w))
&& !(g.kind == GraphKind::Line && g.filled_lines && g.series_paints.iter().any(|p| band_outline(&p.stroke.clone().zip(p.stroke_width))))
&& g.series_markers.iter().all(Option::is_none)
&& g.series_columns.iter().all(Option::is_none)
&& g.label_styles == LabelStyles::default()
@@ -320,10 +329,13 @@ fn plain_paint(p: &Node) -> Option<(Option<Paint>, Option<(Paint, f64)>)> {
/// The `Go` line of each series' group among `children`: a group whose series index is one of the
/// `series` the table has, each once, of paths [`as_drawn`] with one fill and one line alike
/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). Its column is the
/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). With filled lines
/// (`bands`), a filled path outlined as [`band_outline`] says is a band, any other filled path is a
/// [`square`] marker or swatch, and the line of the paths that are not bands is the series' line,
/// as the reader reads it. Its column is the
/// table's: after the label column when there is one (`first_col`). `None` when a series has no
/// such group.
fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool) -> Option<HashMap<NodeId, String>> {
fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool, bands: bool) -> Option<HashMap<NodeId, String>> {
let mut tags = HashMap::new();
let mut seen = vec![false; series];
for c in children {
@@ -334,21 +346,63 @@ fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: us
*slot = true;
let NodeKind::Group { children: paths, clip: false } = &c.kind else { return None };
(as_drawn(c) && *c.appearance == Appearance::default() && !paths.is_empty()).then_some(())?;
let mut paints = vec![];
let (mut paints, mut strokes) = (vec![], vec![]);
for p in paths {
as_drawn(p).then_some(())?;
paints.push(plain_paint(p)?);
let (fill, outline) = plain_paint(p)?;
if bands && fill.is_some() && band_outline(&outline) {
// A band, or a mark outlined as one, which the reader reads as a band.
} else if bands && fill.is_some() && !square(p) {
return None;
} else {
strokes.push(outline);
}
paints.push(fill);
}
let fill = paints.iter().find_map(|(f, _)| f.clone());
paints.iter().all(|(f, _)| f.is_none() || *f == fill).then_some(())?;
(line || paints.iter().all(|(f, _)| f.is_some())).then_some(())?;
let stroke = paints.first().and_then(|(_, s)| s.clone());
paints.iter().all(|(_, s)| *s == stroke).then_some(())?;
let fill = paints.iter().find_map(Clone::clone);
paints.iter().all(|f| f.is_none() || *f == fill).then_some(())?;
(line || paints.iter().all(Option::is_some)).then_some(())?;
let stroke = strokes.first().cloned().flatten();
strokes.iter().all(|s| *s == stroke).then_some(())?;
tags.insert(c.id, format!("%_2 {} 0 0 Go", s + first_col));
}
seen.iter().all(|s| *s).then_some(tags)
}
/// Whether `stroke`, a path's line and its weight, is the thin black outline Draw Filled Lines
/// draws around a band, whatever the series' own line.
pub(crate) fn band_outline(stroke: &Option<(Paint, f64)>) -> bool {
stroke
.as_ref()
.is_some_and(|(paint, width)| *width == FILLED_LINE_OUTLINE_WIDTH && paint.color().is_some_and(|c| c.to_rgb_uncalibrated() == [0.0; 3]))
}
/// Whether path `p` is a square with sides along the page's axes, as a data point's default
/// marker and a legend swatch are: four straight sides, closed, as wide as it is tall. In a series
/// with filled lines, every other filled path is a band.
pub(crate) fn square(p: &Node) -> bool {
let NodeKind::Path { path, .. } = &p.kind else { return false };
if path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count() != 1 {
return false;
}
let near = |a: f64, b: f64| (a - b).abs() <= EDGE;
let mut sides = vec![];
for s in path.to_bezpath().segments() {
let PathSeg::Line(l) = s else { return false };
if !(near(l.p0.x, l.p1.x) && near(l.p0.y, l.p1.y)) {
sides.push(l);
}
}
let [first, _, _, last] = sides.as_slice() else { return false };
let (x0, x1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.x), hi.max(l.p0.x)));
let (y0, y1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.y), hi.max(l.p0.y)));
near(last.p1.x, first.p0.x)
&& near(last.p1.y, first.p0.y)
&& sides.iter().all(|l| near(l.p0.x, l.p1.x) || near(l.p0.y, l.p1.y))
&& x1 - x0 > EDGE
&& near(x1 - x0, y1 - y0)
}
/// Whether `art` draws plot `plot`'s left edge and its bottom edge (the document's y runs down) as
/// straight lines, each a shown path of one subpath with a plain line ([`plain_paint`]) in a shown
/// group, as the reader finds the axes.
@@ -409,7 +463,8 @@ pub(crate) mod sample {
}
/// Graph `g` drawn as a group: a group of each series' marks (a line graph's series as an unfilled
/// line, the others' as filled columns), its axes on the plot's left and bottom edges, and a
/// line, or with filled lines as an outlined band and its markers, the others' as filled
/// columns), its axes on the plot's left and bottom edges, and a
/// legend of a swatch for each series; its series groups named after the series.
pub(crate) fn graph(doc: &mut Document, g: GraphSpec) -> Node {
let r = g.rect;
@@ -430,7 +485,27 @@ pub(crate) mod sample {
row.get(s).copied().flatten().map(|v| Point::new(r.x0 + 20.0 + 60.0 * c as f64 + 15.0 * s as f64, r.y1 - v * 10.0))
})
.collect();
let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line {
let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line && g.filled_lines {
// A band around the line, as wide as the Line Width, with the thin black outline, and a
// marker on each point.
let half = g.filled_line_width() / 2.0;
let mut bp = kurbo::BezPath::new();
for (i, p) in points.iter().enumerate() {
if i == 0 { bp.move_to((p.x, p.y - half)) } else { bp.line_to((p.x, p.y - half)) }
}
for p in points.iter().rev() {
bp.line_to((p.x, p.y + half));
}
bp.close_path();
let band = Node::path(
doc.alloc_id(),
PathData::from_bezpath(&bp),
Appearance::basic(gray.clone(), Paint::solid(Color::BLACK), super::FILLED_LINE_OUTLINE_WIDTH),
);
let mut marks = vec![Arc::new(band)];
marks.extend(points.iter().map(|p| path(doc, shapes::rectangle(Rect::from_center_size(*p, (5.0, 5.0))), gray.clone(), Paint::None)));
marks
} else if g.kind == GraphKind::Line {
let mut bp = kurbo::BezPath::new();
for (i, p) in points.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
@@ -472,7 +547,7 @@ pub(crate) mod sample {
/// Graphs whose records read back whole: each type the records give, every setting they keep
/// changed, labels with parentheses, backslashes and non-ASCII characters, a label of 255 bytes,
/// and a table without labels.
/// a table without labels, and line graphs with filled lines and Line Widths the records give.
pub(crate) fn kept() -> Vec<(&'static str, Document)> {
let mut cases = vec![
("column", document(spec(GraphKind::Column))),
@@ -497,6 +572,18 @@ pub(crate) mod sample {
let mut g = spec(GraphKind::Column);
(g.series, g.categories) = (vec![], vec![]);
cases.push(("no labels", document(g)));
let line = |f: &dyn Fn(&mut GraphSpec)| {
let mut g = spec(GraphKind::Line);
f(&mut g);
document(g)
};
cases.extend([
("filled lines", line(&|g| g.filled_lines = true)),
("filled lines 8 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(8.0)))),
("filled lines 100 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(100.0)))),
("filled lines 0.01 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(0.01)))),
("a Line Width without filled lines", line(&|g| g.line_width = Some(8.0))),
]);
cases
}
@@ -515,8 +602,20 @@ pub(crate) mod sample {
.collect();
cases.extend([
("no legend", with(&|g| g.legend = false)),
("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))),
("a filled line width", with(&|g| (g.kind, g.line_width) = (GraphKind::Line, Some(8.0)))),
("a Line Width past 100 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(150.0)))),
("a Line Width under 0.01 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(0.001)))),
("filled lines without connected points", with(&|g| (g.kind, g.filled_lines, g.connect_points) = (GraphKind::Line, true, false))),
(
"filled lines with series stroked as their outline",
with(&|g| {
(g.kind, g.filled_lines) = (GraphKind::Line, true);
g.series_paints = vec![vectorcraft_doc::SeriesPaint {
stroke: Some(Paint::solid(Color::BLACK)),
stroke_width: Some(super::FILLED_LINE_OUTLINE_WIDTH),
..Default::default()
}];
}),
),
("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])),
("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])),
("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])),
@@ -645,6 +744,29 @@ mod tests {
assert_eq!(marks, ["1", "1", "1"], "{head}");
}
/// A marker or swatch is a square along the page's axes; a band, a rotated square, a rectangle
/// of other proportions and an open path are not.
#[test]
fn markers_are_squares_and_bands_are_not() {
use vectorcraft_geom::shapes;
let node = |p: vectorcraft_geom::PathData| Node::path(NodeId(1), p, Appearance::default());
assert!(square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 15.0, 15.0)))), "a 5 pt marker");
assert!(!square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 13.0)))), "a band along a level line");
let mut diamond = kurbo::BezPath::new();
diamond.move_to((0.0, 5.0));
diamond.line_to((5.0, 0.0));
diamond.line_to((10.0, 5.0));
diamond.line_to((5.0, 10.0));
diamond.close_path();
assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&diamond))), "a rotated square");
let mut open = kurbo::BezPath::new();
open.move_to((0.0, 0.0));
for p in [(5.0, 0.0), (5.0, 5.0), (0.0, 5.0), (0.0, 1.0)] {
open.line_to(p);
}
assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&open))), "an open path");
}
/// A table's cells go fifteen to a record, with one string at most in each.
#[test]
fn cells_go_fifteen_to_a_record_with_one_string_each() {
+2
View File
@@ -68,6 +68,8 @@ mod tests_images;
#[cfg(test)]
mod tests_native;
#[cfg(test)]
mod tests_reads;
#[cfg(test)]
mod tests_type1;
#[cfg(test)]
mod tests_type42;
+98 -17
View File
@@ -14,10 +14,14 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use kurbo::{PathSeg, Point};
use vectorcraft_doc::{Appearance, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, SeriesPaint, TickLength};
use vectorcraft_doc::{
Appearance, DEFAULT_FILLED_LINE_WIDTH, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, SeriesPaint,
TickLength,
};
use super::types::{GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, Kind};
use super::{Affine, AppearanceItem, BlendMode, Node, NodeId, NodeKind, Paint, Reader, Rect, V, obj};
use crate::ai_graph::{band_outline, square};
/// Most cells of a graph's table, its label row and column included.
const MAX_CELLS: usize = 2_600_000;
@@ -293,11 +297,20 @@ impl Records {
self.spec.legend = true;
self.spec.mark_points = flag(marks)?;
self.spec.connect_points = flag(lines)?;
// Lines drawn as shapes have a width the model doesn't keep.
(!flag(shapes)?).then_some(())?;
self.spec.filled_lines = false;
// Lines drawn as shapes (Draw Filled Lines); without connected points the flag is ignored.
self.spec.filled_lines = flag(shapes)? && self.spec.connect_points;
self.spec.legend_across_top = flag(across)?;
finite(width).filter(|w| (0.0..=100.0).contains(w))?;
// `lineShapeWidth`, in points from 0 to 100. The model holds widths from 0.01 points, 3 points
// being its default; a smaller width is left out while the lines aren't filled, and keeps
// filled lines plain.
let width = finite(width).filter(|w| (0.0..=100.0).contains(w))?;
self.spec.line_width = if width == DEFAULT_FILLED_LINE_WIDTH {
None
} else if width >= MIN_FILLED_LINE_WIDTH {
Some(width)
} else {
(!self.spec.filled_lines).then_some(None)?
};
// 44: the series are measured against the left axis; 45 (right) isn't kept per series.
(int(axis)? == 44).then_some(())?;
if let Some([percentage, digits]) = pie {
@@ -471,20 +484,36 @@ fn as_drawn(n: &Node) -> bool {
/// Each series' fill and stroke, read from its group (`tags`), which holds paths only, one at
/// least: the paths with a fill share it, and every path has the same stroke or none. Only a line
/// graph (`line`) has paths without a fill: its lines. `None` when they differ, or the group, its
/// own appearance or a path is drawn otherwise than [`as_drawn`].
fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option<Vec<SeriesPaint>> {
/// graph (`line`) has paths without a fill: its lines. With filled lines (`bands`), a filled path
/// outlined as [`band_outline`] says is a band or a mark drawn like one and gives no stroke; any
/// other filled path but a [`square`] marker or legend swatch is a band outlined otherwise. The
/// other paths give the series' stroke, and without them the series has none. A series with a band
/// and no stroke on its other paths keeps no stroke at all, so with filled lines turned off its thin
/// line is drawn in the series color at 1 pt, as for a graph drawn here. `None` when they
/// differ, a band has another outline, or the group, its own appearance or a path is drawn
/// otherwise than [`as_drawn`].
fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool, bands: bool) -> Option<Vec<SeriesPaint>> {
let mut paints = vec![SeriesPaint::default(); tags.len()];
for group in art.children().into_iter().flatten() {
let Some(slot) = tags.get(&group.id).and_then(|i| paints.get_mut(usize::try_from(*i).ok()?)) else { continue };
(as_drawn(group) && *group.appearance == Appearance::default()).then_some(())?;
let paths: Vec<&Arc<Node>> = group.children().into_iter().flatten().collect();
(!paths.is_empty() && paths.iter().all(|p| matches!(p.kind, NodeKind::Path { .. }))).then_some(())?;
let (mut fills, mut strokes) = (vec![], vec![]);
let (mut fills, mut strokes, mut banded) = (vec![], vec![], false);
for p in &paths {
as_drawn(p).then_some(())?;
fills.extend(shown(p, true).ok()?);
strokes.push(shown(p, false).ok()?);
let filled = shown(p, true).ok()?;
let outline = shown(p, false).ok()?;
if bands && filled.is_some() && band_outline(&outline) {
// A band, or a mark outlined as one: the graph keeps no stroke for a series that draws bands.
banded = true;
} else if bands && filled.is_some() && !square(p) {
// A band outlined otherwise: the graph draws it again with the thin black outline only.
return None;
} else {
strokes.push(outline);
}
fills.extend(filled);
}
let fill = fills.first().map(|(paint, _)| paint.clone());
fills.iter().all(|(paint, _)| Some(paint) == fill.as_ref()).then_some(())?;
@@ -494,6 +523,7 @@ fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option<
slot.fill = fill;
(slot.stroke, slot.stroke_width) = match stroke {
Some((paint, width)) => (Some(paint), Some(width)),
None if banded => (None, None),
None => (Some(Paint::None), None),
};
}
@@ -628,7 +658,8 @@ impl<'a> Reader<'a> {
if r.x0 < placed.x0 - EDGE || r.y0 < placed.y0 - EDGE || r.x1 > placed.x1 + EDGE || r.y1 > placed.y1 + EDGE {
return false;
}
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
let line = spec.kind == GraphKind::Line;
let Some(paints) = series_paints(art, &tags, line, line && spec.filled_lines) else { return false };
spec.series_paints = paints;
spec.placed = Some(placed);
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c));
@@ -646,6 +677,7 @@ impl<'a> Reader<'a> {
mod tests {
use super::*;
use vectorcraft_color::Color;
use vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH;
use vectorcraft_geom::shapes;
/// A graph's art: one series group (id 2) holding one mark painted `ap`, the group changed by
@@ -665,9 +697,58 @@ mod tests {
let mut two = one.clone();
two.items.extend(one.items.iter().find(|i| i.is_fill()).cloned());
let tags = HashMap::from([(NodeId(2), 0)]);
let kept = series_paints(&art(one, |_| {}), &tags, false).expect("one fill");
let kept = series_paints(&art(one, |_| {}), &tags, false, false).expect("one fill");
assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref()), (Some(&red), Some(&Paint::None)));
assert!(series_paints(&art(two, |_| {}), &tags, false).is_none());
assert!(series_paints(&art(two, |_| {}), &tags, false, false).is_none());
}
/// With filled lines, a band's thin black outline is not the series' stroke: its markers' stroke
/// is, and with unstroked markers or none the series keeps no stroke. A band outlined otherwise
/// than its markers has no one stroke.
#[test]
fn a_filled_line_bands_outline_is_not_its_series_stroke() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let series = |band: Appearance, marker: Appearance| {
let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), band));
let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), marker));
Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))])
};
let tags = HashMap::from([(NodeId(2), 0)]);
let outlined = Appearance::basic(red.clone(), Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), FILLED_LINE_OUTLINE_WIDTH);
let marker = Appearance::basic(red.clone(), Paint::None, 0.0);
let kept = series_paints(&series(outlined.clone(), marker.clone()), &tags, true, true).expect("a band and a marker");
assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&red), None, None));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let stroked = Appearance::basic(red.clone(), blue.clone(), 2.0);
let kept = series_paints(&series(outlined.clone(), stroked), &tags, true, true).expect("a band and a stroked marker");
assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&blue), Some(2.0)));
let bands_only = Node::group(
NodeId(1),
vec![Arc::new(Node::group(
NodeId(2),
vec![Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), outlined.clone()))],
))],
);
let kept = series_paints(&bands_only, &tags, true, true).expect("a band alone");
assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a band alone");
// A band as long as it is wide is a square, and still a band: its outline is not the series' stroke.
let square_band = |marker: Appearance| {
let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 3.0, 3.0)), outlined.clone()));
let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(10.0, 0.0, 15.0, 5.0)), marker));
Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))])
};
let kept = series_paints(&square_band(marker.clone()), &tags, true, true).expect("a square band and a marker");
assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a square band");
assert!(series_paints(&series(outlined, marker.clone()), &tags, true, false).is_none(), "lines not filled");
let thick = Appearance::basic(red.clone(), Paint::solid(Color::BLACK), 1.0);
assert!(series_paints(&series(thick, marker), &tags, true, true).is_none(), "a 1 pt outline");
// A band outlined as its markers are stroked is drawn again with the thin black outline.
assert!(series_paints(&series(stroked_like(&blue), stroked_like(&blue)), &tags, true, true).is_none(), "a band outlined in blue");
}
/// A red mark stroked 2 pt in `paint`.
fn stroked_like(paint: &Paint) -> Appearance {
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), paint.clone(), 2.0)
}
/// A series group that is hidden, see-through or in another blending mode is not drawn again so.
@@ -675,8 +756,8 @@ mod tests {
fn a_series_group_drawn_otherwise_has_no_series_paint() {
let ap = || Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let tags = HashMap::from([(NodeId(2), 0)]);
assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false).is_none(), "hidden");
assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false).is_none(), "50% opaque");
assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false).is_none(), "Multiply");
assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false, false).is_none(), "hidden");
assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false, false).is_none(), "50% opaque");
assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false, false).is_none(), "Multiply");
}
}
+63 -1
View File
@@ -11418,6 +11418,68 @@ fn a_graphs_type_and_settings_come_from_its_records() {
assert!(art(&r.doc)[0].extras().graph.is_some());
}
/// A series of a line graph drawn with filled lines at `x`: a band filled with the series' color and
/// outlined in a thin black line, and a marker filled alike with no outline.
fn band_series(x: f64) -> String {
format!("0.5 0 0 0 k\n0 0 0 1 K\n0.25 w\n{}B\n1 w\n{}f\n", rect_path(x, 120.0, x + 40.0, 128.0), rect_path(x + 18.0, 122.0, x + 23.0, 127.0))
}
/// [`live_graph`] as a line graph with style record `style`, each series drawn by [`band_series`].
fn band_graph(style: &str) -> String {
live_graph().replace(LIVE_STYLE, style).replace(&series_bar(110.0), &band_series(110.0)).replace(&series_bar(140.0), &band_series(140.0))
}
/// A line graph whose lines are drawn as shapes (`drawLinesAsShapes` 1 with `drawLines` 1) keeps
/// Draw Filled Lines and its Line Width (`lineShapeWidth`, in points): 3 points is the graph's
/// default. Its series keep their bands' fill, and the bands' thin black outline is not taken as the
/// series' stroke. With `drawLines` 0 the flag is ignored, and the width is kept for later.
#[test]
fn a_line_graph_drawn_with_filled_lines_keeps_them_and_their_width() {
let live = |text: String| {
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{text}: {:?}", r.warnings);
let a = art(&r.doc);
let g = a[0].extras().graph.clone().unwrap_or_else(|| panic!("{text}: a live graph"));
(g, live_graphs(&r.doc).1)
};
let (g, tagged) = live(band_graph("%_7 0 0 14 1 1 1 0 8 44 Gy\n"));
assert_eq!((g.kind, g.filled_lines, g.line_width, tagged), (GraphKind::Line, true, Some(8.0), 2));
let fill = Some(Paint::solid(Color::cmyk(0.5, 0.0, 0.0, 0.0)));
assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke.is_none() && p.stroke_width.is_none()), "{:?}", g.series_paints);
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 3 44 Gy\n")).0.line_width, None, "3 pt");
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 6 44 Gy\n")).0.line_width, Some(6.0), "6 pt");
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 100 44 Gy\n")).0.line_width, Some(100.0), "100 pt");
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 0.01 44 Gy\n")).0.line_width, Some(0.01), "0.01 pt");
// Without filled lines, the series are drawn as the graph's columns are.
let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 0 1 0 8 44 Gy\n"));
assert_eq!((g.connect_points, g.filled_lines, g.line_width), (false, false, Some(8.0)), "points not connected");
let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 1 0 0 0 44 Gy\n"));
assert_eq!((g.filled_lines, g.line_width), (false, None), "lines not filled, 0 pt");
}
/// A graph with filled lines whose Line Width the model doesn't hold (0, under 0.01 points, or out of
/// the records' 0 to 100), or with a lines-as-shapes value other than 0 and 1, keeps its drawn art
/// as plain objects, with one note.
#[test]
fn filled_lines_of_a_width_the_model_cant_hold_stay_plain_art() {
for style in [
"%_7 0 0 14 1 1 1 0 0 44 Gy\n",
"%_7 0 0 14 1 1 1 0 0.001 44 Gy\n",
"%_7 0 0 14 1 1 1 0 101 44 Gy\n",
"%_7 0 0 14 1 1 1 0 -2 44 Gy\n",
"%_7 0 0 14 1 1 1 0 1e999 44 Gy\n",
"%_7 0 0 14 1 1 0 0 101 44 Gy\n",
"%_7 0 0 14 1 1 2 0 8 44 Gy\n",
] {
let r = read(stream7(&layer7("Graph", &band_graph(style))).as_bytes()).unwrap_or_else(|e| panic!("{style}: {e}"));
assert_eq!(r.warnings, [GRAPH_PLAIN], "{style}");
assert_eq!(live_graphs(&r.doc), (vec![], 0), "{style}");
let mut kept = false;
r.doc.walk(|n| kept |= n.children().is_some_and(|c| c.len() == 3));
assert!(kept, "{style}: the drawn art is kept");
}
}
/// A graph keeps its drawn art and stays plain, with one note, when a record has a shape or value
/// appendix A doesn't give, sets what the model doesn't keep, or the table, the series tags or the
/// art don't fit the graph.
@@ -11433,7 +11495,7 @@ fn graphs_the_model_cant_keep_stay_plain_art() {
("type 11", live_graph().replace("%_5 0 0 14", "%_11 0 0 14")),
("legends in wedges", live_graph().replace("%_5 0 0 14", "%_5 0 0 15")),
("the right axis", live_graph().replace("6 44 Gy", "6 45 Gy")),
("lines as shapes", live_graph().replace("%_5 0 0 14 0 1 0", "%_5 0 0 14 0 1 1")),
("lines as shapes 0 pt wide", live_graph().replace("%_5 0 0 14 0 1 0 0 6", "%_5 0 0 14 0 1 1 0 0")),
("both axes alike", live_graph().replace(LIVE_DIALOG, "%_10 2 0 1 90 80 0 Gd\n")),
("a subscription", live_graph().replace(LIVE_DIALOG, &format!("{LIVE_DIALOG}%_0 0 1 1 1 Gj\n"))),
("a customization", live_graph().replace("GC\n", "GC\n%_2 Gt\n%_(Bars) GD\n%_GT\n")),
+60 -42
View File
@@ -31,6 +31,7 @@ pub(super) enum Source {
}
impl Interp<'_> {
#[allow(clippy::cognitive_complexity)] // One arm for each file operator, most of them a few lines.
pub fn data_op(&mut self, op: Op) -> Res {
use Op::*;
match op {
@@ -50,23 +51,7 @@ impl Interp<'_> {
ReadLine => {
let s = self.pop_str()?;
let Obj::File { stream: f, .. } = self.pop()? else { return ps_err("typecheck", "") };
let n = s.len();
let mut line = vec![];
let mut ended = false;
while line.len() < n {
match self.read(&f, 1)?.first() {
Some(b'\n') | None => {
ended = true;
break;
}
Some(b'\r') => {
self.skip_lf(&f);
ended = true;
break;
}
Some(b) => line.push(*b),
}
}
let (line, ended) = self.read_line(&f, s.len())?;
self.fill(s, &line)?;
self.push(Obj::Bool(ended))?;
}
@@ -219,38 +204,71 @@ impl Interp<'_> {
})
}
/// After `readline` consumes CR, consume only an immediately following LF. PostScript
/// treats CR/LF as one line ending (PLRM §3.8); raw reads must keep every other byte.
/// The preceding `read` has already materialized any pending filter.
fn skip_lf(&mut self, f: &Rc<RefCell<Stream>>) {
match &mut *f.borrow_mut() {
/// Run `scan` over the bytes left in file `f`, in one slice, and consume as many of them as
/// it says it used. A file still pending after `materialize` has no bytes left.
fn scan<T>(&mut self, f: &Rc<RefCell<Stream>>, scan: impl FnOnce(&[u8]) -> (T, usize)) -> Res<T> {
self.materialize(f)?;
Ok(match &mut *f.borrow_mut() {
Stream::Current => {
if self.lex.rest().first() == Some(&b'\n') {
self.lex.advance(1);
}
let (found, used) = scan(self.lex.data());
self.lex.advance(used);
found
}
Stream::Buf { data, pos, .. } => {
if data.get(*pos) == Some(&b'\n') {
*pos += 1;
}
let start = (*pos).min(data.len());
let (found, used) = scan(data.get(start..).unwrap_or_default());
*pos = start.saturating_add(used).min(data.len());
found
}
Stream::Pending { .. } => {}
}
Stream::Pending { .. } => scan(&[]).0,
})
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped).
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
let Some(&b) = self.read(f, 1)?.first() else { break };
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
/// `readline` from `f` into a string of `n` bytes: the line, and whether it ended at a line
/// ending or at the end of the data. The line ending is consumed and left out of the line.
/// CR LF is one line ending (PLRM §3.8), and a lone CR leaves the byte after it unread. A
/// line that fills the string leaves the bytes after it unread, a line ending included.
pub(in super::super) fn read_line(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<(Vec<u8>, bool)> {
if n == 0 {
return Ok((vec![], false));
}
Ok(out)
self.scan(f, |data| {
let room = data.get(..n).unwrap_or(data);
match room.iter().position(|b| matches!(b, b'\n' | b'\r')) {
Some(i) => {
let crlf = room.get(i) == Some(&b'\r') && data.get(i + 1) == Some(&b'\n');
((room.get(..i).unwrap_or_default().to_vec(), true), i + 1 + usize::from(crlf))
}
None if room.len() == n => ((room.to_vec(), false), n),
None => ((room.to_vec(), true), room.len()),
}
})
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). The read
/// stops at the digit that completes the `n`th byte and leaves what follows unread. A lone
/// digit at the end of the data gives no byte.
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
if n == 0 {
return Ok(vec![]);
}
self.scan(f, |data| {
let mut out = Vec::with_capacity(n.min(data.len() / 2));
let mut high: Option<u8> = None;
let mut used = 0;
for &b in data {
if out.len() == n {
break;
}
used += 1;
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
}
(out, used)
})
}
/// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the
+17
View File
@@ -106,6 +106,23 @@ fn image_data_comes_from_the_file_being_run() {
);
}
/// An image whose procedure reads its rows with `readhexstring` comes out with the same pixels as
/// the same samples given as one hexadecimal string, with the digits broken by CR LF, LF, tabs,
/// spaces and characters that are not digits, read from the program's own file and from a file
/// being run.
#[test]
fn hex_rows_read_by_a_procedure_match_a_hexadecimal_string() {
let rgb: Vec<u8> = (0..36u32).map(|i| (i * 37 % 256) as u8).collect();
let digits = hex(&rgb);
let breaks = ["\r\n", "\n", "\t", " z", "%"];
let broken: String = digits.as_bytes().chunks(5).zip(breaks.iter().cycle()).map(|(d, b)| format!("{}{b}", String::from_utf8_lossy(d))).collect();
let want = pixels(&read(&format!("10 10 scale 4 3 8 [4 0 0 -3 0 3] <{digits}> false 3 colorimage")), 4, 3);
assert_eq!(want, rgb.chunks(3).map(|p| [p[0], p[1], p[2], 255]).collect::<Vec<_>>());
let image = "10 10 scale 4 3 8 [4 0 0 -3 0 3] {currentfile 12 string readhexstring pop} false 3 colorimage";
assert_eq!(pixels(&read(&format!("{image}\r\n{broken}\n")), 4, 3), want);
assert_eq!(pixels(&read(&format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{image}\n{broken}\nendstream\n")), 4, 3), want);
}
/// A filter waits until it is first read, then reads the file it was made over, wherever the
/// program runs by then: one over the program's own file, read in a file being run, and one over
/// a file being run, read in a file that one runs.
+359
View File
@@ -0,0 +1,359 @@
//! `readhexstring` and `readline` (PLRM 3rd ed., §8.2) read the data left in a file in one pass.
//! The tests run the one-pass readers next to reference readers that take one byte per call, on the
//! same data in the same interpreter state: the program's own file after the whitespace that ends
//! the last token, a decoded buffer read from its start or part way in, and a filter decoded when it
//! is first read. The bytes, the result or error, and every byte left unread must agree.
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;
use std::time::{Duration, Instant};
use vectorcraft_doc::Document;
use vectorcraft_geom::{Affine, Rect};
use super::data::Stream;
use super::graphics::{GState, Out};
use super::interp::Interp;
use super::obj::{Obj, Res};
type File = Rc<RefCell<Stream>>;
/// Bytes as hexadecimal digits.
fn hex(data: &[u8]) -> String {
data.iter().map(|b| format!("{b:02x}")).collect()
}
/// An interpreter that has run `src` up to its `quit`, and the file object the program left on the
/// operand stack. What follows `quit` in `src` is still unread.
fn file_after(src: &[u8]) -> (Interp<'_>, File) {
let mut doc = Document::new(100.0, 100.0);
doc.layers.clear();
let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0)));
assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src));
let Ok(Obj::File { stream, .. }) = it.pop() else { panic!("no file on the stack: {}", String::from_utf8_lossy(src)) };
(it, stream)
}
/// The reference `readline`: one byte per call, a CR followed by an LF ending the line once.
fn line_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> {
let mut line = vec![];
let mut ended = false;
while line.len() < n {
match it.read(f, 1)?.first() {
Some(b'\n') | None => {
ended = true;
break;
}
Some(b'\r') => {
match &mut *f.borrow_mut() {
Stream::Current => {
if it.lex.rest().first() == Some(&b'\n') {
it.lex.advance(1);
}
}
Stream::Buf { data, pos, .. } => {
if data.get(*pos) == Some(&b'\n') {
*pos += 1;
}
}
Stream::Pending { .. } => {}
}
ended = true;
break;
}
Some(b) => line.push(*b),
}
}
Ok((line, ended))
}
/// The reference `readhexstring`: one byte per call, characters that are not hexadecimal digits
/// skipped.
fn hex_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
let Some(&b) = it.read(f, 1)?.first() else { break };
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
}
Ok(out)
}
fn line_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> {
it.read_line(f, n)
}
fn hex_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
it.read_hex(f, n)
}
/// Hexadecimal data as CID `StartData` reads it: the digits, then a closing `>` if one is next.
fn hex_and_end_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let d = it.read_hex(f, n)?;
it.skip_hex_end(f)?;
Ok(d)
}
fn hex_and_end_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let d = hex_by_bytes(it, f, n)?;
it.skip_hex_end(f)?;
Ok(d)
}
/// How the program reaches the data.
#[derive(Clone, Copy, Debug)]
enum Form {
/// `currentfile`, with this whitespace after the token before the data.
Current(&'static [u8]),
/// A buffer decoded at once, with this many bytes of it read before the data.
Buf(usize),
/// An `ASCIIHexDecode` filter over `currentfile`, decoded when it is first read, with this
/// whitespace after the token before the digits.
Pending(&'static [u8]),
}
const FORMS: [Form; 13] = [
Form::Current(b" "),
Form::Current(b"\n"),
Form::Current(b"\r"),
Form::Current(b"\r\n"),
Form::Current(b"\r\r\n"),
Form::Current(b"\n\r"),
Form::Current(b"\t\t"),
Form::Buf(0),
Form::Buf(2),
Form::Buf(3),
Form::Pending(b"\n"),
Form::Pending(b"\r\n"),
Form::Pending(b" "),
];
/// A program that leaves a file over `data` on the operand stack, in form `form`.
fn program(form: Form, data: &[u8]) -> Vec<u8> {
match form {
Form::Current(lead) => [b"currentfile quit".as_slice(), lead, data].concat(),
Form::Buf(0) => format!("<{}> /ReusableStreamDecode filter quit", hex(data)).into_bytes(),
Form::Buf(skip) => {
let before = b"\r\n\r".get(..skip).unwrap_or(b"\r\n\r".as_slice());
format!("<{}{}> /ReusableStreamDecode filter dup {skip} string readstring pop pop quit", hex(before), hex(data)).into_bytes()
}
Form::Pending(lead) => [b"currentfile /ASCIIHexDecode filter quit".as_slice(), lead, hex(data).as_bytes(), b"> tail"].concat(),
}
}
type Reader<T> = fn(&mut Interp, &File, usize) -> Res<T>;
/// Read `data` in `form` with `one_pass` and with `by_bytes` in two interpreters in the same state,
/// and check that they agree on the result and on everything left to read.
fn agree<T: PartialEq + Debug>(form: Form, data: &[u8], n: usize, one_pass: Reader<T>, by_bytes: Reader<T>) {
let src = program(form, data);
let (mut a, fa) = file_after(&src);
let (mut b, fb) = file_after(&src);
let at = || format!("{form:?}, {:?}, n = {n}", String::from_utf8_lossy(data));
assert_eq!(one_pass(&mut a, &fa, n), by_bytes(&mut b, &fb, n), "result: {}", at());
assert_eq!(a.lex.rest(), b.lex.rest(), "program left unread: {}", at());
assert_eq!(a.read(&fa, usize::MAX), b.read(&fb, usize::MAX), "file left unread: {}", at());
assert_eq!(a.lex.rest(), b.lex.rest(), "program left after the file: {}", at());
a.release();
b.release();
}
/// A fixed sequence of pseudo-random numbers (xorshift), so a failure repeats.
struct Rng(u64);
impl Rng {
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % n.max(1) as u64) as usize
}
}
/// `chosen`, then `count` strings of up to 24 bytes from `alphabet`.
fn samples(chosen: &[&[u8]], alphabet: &[u8], count: usize, rng: &mut Rng) -> Vec<Vec<u8>> {
let random = (0..count).map(|_| {
let len = rng.below(25);
(0..len).filter_map(|_| alphabet.get(rng.below(alphabet.len())).copied()).collect()
});
chosen.iter().map(|s| s.to_vec()).chain(random).collect()
}
/// String lengths to read `data` with: none, one, past its end, exactly its length and one more,
/// and one at random.
fn lengths(data: &[u8], rng: &mut Rng) -> [usize; 6] {
[0, 1, 3, data.len(), data.len() + 1, rng.below(data.len() + 3)]
}
#[test]
fn readline_reads_in_one_pass_as_byte_by_byte() {
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let chosen: [&[u8]; 16] = [
b"",
b"\n",
b"\r",
b"\r\n",
b"\n\r",
b"\r\r\n",
b"abc",
b"abc\n",
b"abc\r",
b"abc\rX",
b"abc\r\nX",
b"abc\n\nX",
b"abcdefgh\r\nX",
b"abcdefgh\nX",
b"a\0b\xff\rX",
b"abc\r\n",
];
for data in samples(&chosen, b"ab\r\n\r\n x\0\xff", 40, &mut rng) {
for form in FORMS {
for n in lengths(&data, &mut rng) {
agree(form, &data, n, line_one_pass, line_by_bytes);
}
}
}
}
#[test]
fn readhexstring_reads_in_one_pass_as_byte_by_byte() {
let mut rng = Rng(0x2545_f491_4f6c_dd1d);
let chosen: [&[u8]; 14] = [
b"",
b"0",
b"a",
b"0a",
b"0a1",
b"0 a\r\n1b>X",
b"zz0g1",
b"ff\r\n00\nAA",
b"0a1b2c3d",
b"0a1b\r\n2c>",
b"\r\n0a",
b"a b c d e",
b"0a>",
b"0a \r\n >X",
];
for data in samples(&chosen, b"0123456789abcdefABCDEFg \r\n\t>z%", 40, &mut rng) {
for form in FORMS {
for n in lengths(&data, &mut rng) {
agree(form, &data, n, hex_one_pass, hex_by_bytes);
agree(form, &data, n, hex_and_end_one_pass, hex_and_end_by_bytes);
}
}
}
}
/// `readline` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `line` and `ended`
/// and leaves `left` unread.
fn line_case(data: &[u8], n: usize, line: &[u8], ended: bool, left: &[u8]) {
let src = program(Form::Current(b"\r\n"), data);
let (mut it, f) = file_after(&src);
assert_eq!(it.read_line(&f, n), Ok((line.to_vec(), ended)), "{:?}", String::from_utf8_lossy(data));
assert_eq!(it.read(&f, usize::MAX), Ok(left.to_vec()), "{:?}", String::from_utf8_lossy(data));
it.release();
}
/// `readhexstring` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `bytes` and
/// leaves `left` unread in the program.
fn hex_case(data: &[u8], n: usize, bytes: &[u8], left: &[u8]) {
let src = program(Form::Current(b"\r\n"), data);
let (mut it, f) = file_after(&src);
assert_eq!(it.read_hex(&f, n), Ok(bytes.to_vec()), "{:?}", String::from_utf8_lossy(data));
assert_eq!(it.lex.rest(), left, "{:?}", String::from_utf8_lossy(data));
it.release();
}
/// The results the one-pass readers give at the edges of the data, stated directly.
#[test]
fn one_pass_reads_stop_where_their_data_ends() {
// A CR LF ends one line; a lone CR leaves the next byte unread.
line_case(b"ab\r\nX", 8, b"ab", true, b"X");
line_case(b"ab\rX", 8, b"ab", true, b"X");
line_case(b"ab\nX", 8, b"ab", true, b"X");
// A line that fills the string leaves its line ending unread.
line_case(b"abcd\nX", 4, b"abcd", false, b"\nX");
line_case(b"abc\r\nX", 3, b"abc", false, b"\r\nX");
// The end of the data ends the line.
line_case(b"ab", 8, b"ab", true, b"");
line_case(b"", 8, b"", true, b"");
// The read stops on the digit that completes the last byte.
hex_case(b"0a\r\n1b>X", 2, &[0x0a, 0x1b], b">X");
// Characters that are not digits are skipped.
hex_case(b"z0 g\ta%", 1, &[0x0a], b"%");
// A lone digit at the end of the data gives no byte.
hex_case(b"0a1", 2, &[0x0a], b"");
hex_case(b"\r\n", 2, &[], b"");
// No byte to read takes nothing, not even the whitespace after the token.
hex_case(b"0a", 0, &[], b"\r\n0a");
}
/// The median of `runs`.
fn median(runs: &[Duration]) -> Duration {
let mut sorted = runs.to_vec();
sorted.sort();
sorted.get(sorted.len() / 2).copied().unwrap_or_default()
}
/// Read all of `src`'s data with `reader` in strings of `n` bytes, `calls` times, and how long it
/// took. The interpreter is made before the clock starts.
fn timed<T>(src: &[u8], reader: Reader<T>, n: usize, calls: usize) -> (Vec<T>, Duration) {
let (mut it, f) = file_after(src);
let start = Instant::now();
let got: Vec<T> = (0..calls).map(|_| reader(&mut it, &f, n).unwrap_or_else(|e| panic!("{e:?}"))).collect();
let took = start.elapsed();
it.release();
(got, took)
}
/// Time both readers on `src` in 7 runs, alternating which goes first, check that they read the
/// same, and print every run and the medians.
fn compare<T: PartialEq>(what: &str, src: &[u8], one_pass: Reader<T>, by_bytes: Reader<T>, n: usize, calls: usize) {
let (mut old, mut new) = (vec![], vec![]);
for run in 0..7 {
let order: [bool; 2] = if run % 2 == 0 { [false, true] } else { [true, false] };
let mut got = vec![];
for one in order {
let (read, took) = timed(src, if one { one_pass } else { by_bytes }, n, calls);
if one {
new.push(took)
} else {
old.push(took)
}
got.push(read);
}
assert!(got.first() == got.get(1), "{what}: the readers differ");
}
let ms = |d: &Duration| format!("{:.1}", d.as_secs_f64() * 1000.0);
println!("{what}: {} bytes of data, {calls} calls of {n} bytes", src.len());
println!(" byte by byte, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" "));
println!(" one pass, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" "));
let (o, w) = (median(&old), median(&new));
println!(" median: byte by byte {} ms, one pass {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9));
}
/// Times the one-pass readers against the byte-at-a-time reference readers on the same data in one
/// process: the hexadecimal samples of a 1000 × 1000 RGB image in lines of 64 digits, read a row
/// of 3,000 bytes at a time, and 200,000 lines of 40 bytes read by `readline` into an 80-byte
/// string. Run it in release:
/// `cargo test --release -p vectorcraft-eps --lib tests_reads::one_pass_reads_timed -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn one_pass_reads_timed() {
let rgb: Vec<u8> = (0..3_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
let digits = hex(&rgb);
let mut data = Vec::with_capacity(digits.len() + digits.len() / 64 + 1);
for line in digits.as_bytes().chunks(64) {
data.extend_from_slice(line);
data.push(b'\n');
}
compare("readhexstring", &program(Form::Current(b"\n"), &data), hex_one_pass, hex_by_bytes, 3_000, 1_000);
let lines: Vec<u8> = (0..200_000).flat_map(|i| format!("{:<39}\n", format!("line {i}")).into_bytes()).collect();
compare("readline", &program(Form::Current(b"\n"), &lines), line_one_pass, line_by_bytes, 80, 200_000);
}
+2 -2
View File
@@ -209,7 +209,7 @@ pub fn tool_definitions() -> Vec<Value> {
"x": num("Document x (pt)"),
"y": num("Document y (pt)"),
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint"},
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"},
"pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on, and the pressure the Paintbrush records"),
"tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"),
"tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"),
@@ -218,7 +218,7 @@ pub fn tool_definitions() -> Vec<Value> {
}), &["kind", "x", "y"]),
},
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint"},
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"},
}),
&["events"],
),
+6
View File
@@ -1647,6 +1647,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}",
),
(
"ui.actionSet.reset",
"Reset Actions",
"",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
),
("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"),
(
"docInfo.save",
+8
View File
@@ -61,6 +61,14 @@ Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` t
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas.
```rust
pub struct Adjacency { pub faces: Vec<MapFace>, pub edges: Vec<MapEdge>, pub slivers: Vec<PathData>, pub outlines: Vec<MapOutline> }
pub struct MapEdge { pub path: PathData, pub sources: Vec<usize>, pub left: Option<usize>, pub right: Option<usize>, pub piece: usize }
pub fn adjacency(shapes: &[Shape], precision: f64) -> Option<Adjacency>;
```
`adjacency` maps the paths as `live_paint` does and also reports, for each edge, every input it lies on and the faces on its left and right as it runs along its path (document coordinates, y down). A line drawn on top of another keeps both inputs on the edge, whatever the input order. A piece of line that ends inside a face has that face on both sides. Faces narrower than `precision` are listed as slivers, and `outlines` holds the outer boundary of each connected piece of the paths. It returns `None` for more than `SHAPE_BUILDER_MAX_SEGMENTS` segments, non-finite input or a `precision` that is not a positive number.
## Offset / stroke
```rust
+146 -22
View File
@@ -77,7 +77,10 @@ impl Outline {
pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> {
let [a, b, c, d, e, f] = unit.as_coeffs();
let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs());
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm {
// The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may
// belong to a map with no area. An ellipse whose determinant is larger is measured
// exactly.
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm {
return Err(OutlineError::Empty);
}
Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] })
@@ -153,6 +156,16 @@ impl Outline {
if segments.iter().any(|s| bends_against(s, sign)) {
return Err(OutlineError::NotConvex);
}
// A corner can also turn inward between two of the points: each join is checked by the
// directions the segments leave and reach it in. Segments of no length are passed over.
let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot());
let ends: Vec<(Vec2, Vec2)> = segments
.iter()
.filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])))
.collect();
if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) {
return Err(OutlineError::NotConvex);
}
let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point();
if !center.x.is_finite() || !center.y.is_finite() {
return Err(OutlineError::Empty);
@@ -246,7 +259,7 @@ impl Outline {
}
/// The diagonal of the bounds (an ellipse's: of the box its axes span).
fn size(&self) -> f64 {
pub fn size(&self) -> f64 {
match self {
Outline::Ellipse { m, .. } => {
let [a, b, c, d] = *m;
@@ -270,11 +283,13 @@ impl Outline {
}
}
/// The points of the outline on the line `p · n = h`, its support value: the point where
/// `p · n` is largest, and the ends of any straight side along the line. Another point counts
/// when it lies within `tol` of the line plus `slope` times its distance from that largest
/// point, where `slope` is how far off the normal's angle may be.
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec<Point> {
/// The points of the outline on the line `p · n = h`, its support value, which is reached on
/// segment `at`: the point where `p · n` is largest, and the ends of any straight side along
/// the line. Another point counts when it lies within `tol` of the line plus `slope` times its
/// distance from that largest point, where `slope` is how far off the normal's angle may be.
/// On a convex outline the points that count form one run around the largest one, so the
/// segments are measured from `at` outward both ways until a segment's end does not count.
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec<Point> {
match self {
Outline::Ellipse { center, m: [a, b, c, d] } => {
let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y);
@@ -282,9 +297,25 @@ impl Outline {
vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)]
}
Outline::Convex { segments, .. } => {
let len = segments.len();
let mut all = vec![];
for s in segments {
each_extreme(s, n, |p, v| all.push((p, v)));
let Some(first) = segments.get(at % len.max(1)) else { return vec![] };
each_extreme(first, n, |p, v| all.push((p, v)));
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot();
let mut ahead = 0;
for j in 1..len {
match segments.get((at + j) % len) {
Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))),
_ => break,
}
ahead = j;
}
for j in 1..len - ahead {
match segments.get((at + len - j) % len) {
Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))),
_ => break,
}
}
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect()
@@ -293,8 +324,6 @@ impl Outline {
}
}
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
/// the curve runs square to `n`) and the value there.
/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product
/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared
/// with the segment's control polygon length squared.
@@ -321,7 +350,17 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool {
low < -1e-9 * scale
}
#[cfg(test)]
thread_local! {
/// How many times [`each_extreme`] has measured a segment on this thread, for the tests.
static EXTREMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
/// the curve runs square to `n`) and the value there.
fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) {
#[cfg(test)]
EXTREMES.with(|n| n.set(n.get() + 1));
let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n));
f(s.p0, v0);
f(s.p3, v3);
@@ -396,10 +435,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincid
let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0);
let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?;
let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?;
let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb });
let mut out = Vec::with_capacity(external.len() + internal.len());
for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] {
for root in list {
let t = tangent_at(a, b, kind, dir(root.angle), root.double, size);
let t = tangent_at(&a, &b, kind, root.angle, root.double, size);
out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t });
}
}
@@ -414,21 +454,47 @@ struct Root {
double: bool,
}
/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value,
/// and `b` on the same side (external) or the other side (internal). `double` when the outlines
/// touch there.
fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent {
/// An outline with the segment it is touched on at each sampled normal angle.
struct Hinted<'a> {
o: &'a Outline,
at: &'a [f64],
hints: &'a [usize],
}
impl Hinted<'_> {
/// The support value at the normal angle `angle` and the segment it is reached on, walking on
/// from the segment of the sample at or before `angle`.
fn support(&self, angle: f64) -> (f64, usize) {
let angle = angle.rem_euclid(TAU);
// Before the first sample, the last one (taken 2π back) comes before `angle`.
let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1));
self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0))
}
}
/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's
/// value, and `b` on the same side (external) or the other side (internal). `double` when the
/// outlines touch there.
fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent {
let n = dir(angle);
// The rounding allowed in `p · n` grows with each outline's own size and its distance from the
// origin.
let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size());
let (tol_a, tol_b) = (rounding(a), rounding(b));
let (tol_a, tol_b) = (rounding(a.o), rounding(b.o));
// Bisection finds a simple root's angle to about the rounding of the support values; the
// golden-section search finds a double root's to about 1e-8 radians.
let slope = if double { 1e-7 } else { 1e-10 };
let ha = a.support(n);
let (on_a, on_b) = match kind {
TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)),
TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)),
let (ha, sa) = a.support(angle);
let on_a = a.o.touching(n, ha, tol_a, slope, sa);
let on_b = match kind {
TangentKind::External => {
let (hb, sb) = b.support(angle);
b.o.touching(n, hb, tol_b, slope, sb)
}
TangentKind::Internal => {
let (hb, sb) = b.support(angle + TAU / 2.0);
b.o.touching(-n, hb, tol_b, slope, sb)
}
};
// Positions along the line, which runs square to `n` through `n * ha`.
let t = Vec2::new(-n.y, n.x);
@@ -441,7 +507,7 @@ fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool
// stand a little apart.
let (from, to) = if double && hi - lo <= 1e-6 * size {
// Touching at one point: the narrower outline's width along the line, centered there.
let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min);
let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min);
let mid = (lo + hi) / 2.0;
(mid - width / 2.0, mid + width / 2.0)
} else if mean(&on_a) <= mean(&on_b) {
@@ -575,6 +641,8 @@ fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) {
#[cfg(test)]
mod tests {
use std::cell::Cell;
use kurbo::Rect;
use vectorcraft_geom::shapes;
@@ -850,6 +918,53 @@ mod tests {
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first());
}
#[test]
fn each_tangent_measures_only_the_segments_near_where_it_touches() {
// Two regular 2,000-gons about one center, one turned half a step: 4,000 external
// tangents. Measuring every segment of both outlines for every tangent takes about 8,000
// measurements per tangent.
let sides = 2_000;
let gon = |turn: f64| {
let pts: Vec<Point> = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect();
SubPath::polyline(&pts, true)
};
let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap());
EXTREMES.with(|c| c.set(0));
let all = common_tangents(&a, &b).unwrap();
let calls = EXTREMES.with(Cell::get);
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides);
assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len());
let r = 100.0 * (TAU / (4 * sides) as f64).sin();
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first());
}
#[test]
fn a_very_thin_ellipse_is_measured_exactly() {
// Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned
// 30 degrees: the tangents run from the ellipse's tips to the circle.
for deg in [0.0, 30.0] {
let turn = Affine::rotate(f64::to_radians(deg));
let thin = turn * Affine::scale_non_uniform(1e6, 1e-7);
let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]);
let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap();
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}");
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}");
let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000));
for t in &all {
check_against_samples(t, &sa, &sb, 1e-3);
// The end on the ellipse, taken back to the unturned figure.
let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to);
let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to };
assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}");
}
}
// A determinant a few times its rounding is taken; one lost in the rounding of the map's
// entries is still refused.
assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok());
assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty));
assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty));
}
#[test]
fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() {
// p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is
@@ -877,6 +992,15 @@ mod tests {
bp.close_path();
let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex));
// A triangle whose first side is a cubic that leaves its start a little the wrong way: the
// corner there turns inward, though the checked points and the curve itself turn one way.
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((0.0, 0.0));
bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0));
bp.line_to((50.0, 100.0));
bp.close_path();
let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
assert_eq!(Outline::convex(&notch).err(), Some(OutlineError::NotConvex));
// A square traced twice around winds around twice.
let twice: Vec<Point> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect();
assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex));
+2 -2
View File
@@ -30,8 +30,8 @@ pub use fit::{fit_cubics, fit_cubics_through};
pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path};
pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within};
pub use planar::{
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point,
live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
};
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
+2
View File
@@ -26,12 +26,14 @@ use vectorcraft_geom::{FillRule, PathData, SubPath};
use crate::boolean::{DEFAULT_PRECISION, Seg, Tidy, eps_for, is_sliver, segs_to_subpath, snap_horizontals, tidy_segments, to_seg};
use crate::pathfinder::{Region, Shape};
mod adjacency;
mod graph;
mod index;
mod live_paint;
mod map;
mod shape_builder;
pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency};
pub(crate) use graph::pin_ends;
#[cfg(test)]
use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done};
+169
View File
@@ -0,0 +1,169 @@
//! Which faces of a planar map each edge separates, and every input each edge lies on.
//!
//! [`live_paint`](super::live_paint) gives each edge under its front-most input only, and says
//! nothing about the faces on its sides. [`adjacency`] reads both from the same planar map, so a
//! caller can tell which faces a line divides and which lines lie on top of each other.
use super::graph::{find, half_segs, twin, unshear};
use super::index::RectIndex;
use super::map::{Map, map_with};
use super::*;
/// A planar map of some paths with each edge's sides and inputs ([`adjacency`]).
#[derive(Clone, Debug, Default)]
pub struct Adjacency {
pub faces: Vec<MapFace>,
pub edges: Vec<MapEdge>,
/// Bounded areas left out as slivers: narrower than the precision on average, such as a thin
/// gap between two lines.
pub slivers: Vec<PathData>,
/// The outer boundary of each connected piece of the paths.
pub outlines: Vec<MapOutline>,
}
/// A bounded face: its outline, then the outer boundaries of the pieces inside it (as holes), and
/// its area without them.
#[derive(Clone, Debug)]
pub struct MapFace {
pub path: PathData,
pub area: f64,
/// The connected piece of the paths whose edges bound it.
pub piece: usize,
}
/// An edge: a piece of one or more inputs between two places where paths meet.
#[derive(Clone, Debug)]
pub struct MapEdge {
pub path: PathData,
/// Every input it lies on (indices into the inputs, ascending).
pub sources: Vec<usize>,
/// The faces on each side of it as it runs along `path`, seen on the page (document
/// coordinates, y down): `left` on the left. `None` outside every bounded face, or in a sliver.
/// A piece of line that ends loose inside a face has that face on both sides.
pub left: Option<usize>,
pub right: Option<usize>,
pub piece: usize,
}
/// The outer boundary of a connected piece of the paths.
#[derive(Clone, Debug)]
pub struct MapOutline {
pub path: PathData,
pub piece: usize,
}
/// The planar map of `shapes`, every path an edge as in [`live_paint`](super::live_paint), with
/// faces refit to `precision` and slivers narrower than it left out. `None` when the paths can't be
/// swept (non-finite, too degenerate, or more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments), when
/// `precision` is not a positive number, and when no path has two anchors.
pub fn adjacency(shapes: &[Shape], precision: f64) -> Option<Adjacency> {
if !(precision.is_finite() && precision > 0.0) {
return None;
}
let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(SubPath::segment_count).sum();
if segments > SHAPE_BUILDER_MAX_SEGMENTS {
return None;
}
let m = map_with(shapes, false, precision)?;
Some(read(&m))
}
fn read(m: &Map) -> Adjacency {
let path = |cycle: &[usize], closed: bool| {
let segs: Vec<Seg> = cycle.iter().flat_map(|&h| half_segs(&m.edges, h)).collect();
segs_to_subpath(&tidy_segments(segs, closed, &m.tidy), closed)
};
let unsheared = |subpaths: Vec<SubPath>| unshear(PathData::new(subpaths), &m.anchors, m.snap);
// Connected pieces, by the vertices the edges join, numbered in the order they are first met.
let vertices = m.edges.iter().flat_map(|e| e.ends).max().map_or(0, |v| v + 1);
let mut parent: Vec<usize> = (0..vertices).collect();
for e in &m.edges {
let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1]));
if let Some(p) = parent.get_mut(a) {
*p = b;
}
}
let mut number: Vec<Option<usize>> = vec![None; vertices];
let mut pieces = 0;
let mut piece_of_vertex = |v: usize| {
let root = find(&mut parent, v);
match number.get_mut(root) {
Some(Some(n)) => *n,
Some(slot) => {
*slot = Some(pieces);
pieces += 1;
pieces - 1
}
None => 0,
}
};
let edge_pieces: Vec<usize> = m.edges.iter().map(|e| piece_of_vertex(e.ends[0])).collect();
let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| edge_pieces.get(h / 2)).copied().unwrap_or(0);
// The face on each half-edge's side: a face's own cycle, and the outer boundaries of the
// pieces inside it, bound it.
let mut face_of: Vec<Option<usize>> = vec![None; 2 * m.edges.len()];
let mut faces = Vec::with_capacity(m.faces.len());
for (i, (cycle, _, area)) in m.faces.iter().enumerate() {
let holes: Vec<&(Vec<usize>, BezPath)> = m.face_holes.get(i).into_iter().flatten().filter_map(|&k| m.holes.get(k)).collect();
for &h in cycle.iter().chain(holes.iter().flat_map(|(c, _)| c)) {
if let Some(f) = face_of.get_mut(h) {
*f = Some(i);
}
}
let mut subpaths: Vec<SubPath> = path(cycle, true).into_iter().collect();
subpaths.extend(holes.iter().filter_map(|(c, _)| path(c, true)));
// A hole's outer boundary winds the other way: its area is negative.
let area = area + holes.iter().map(|(_, bp)| bp.area()).sum::<f64>();
faces.push(MapFace { path: unsheared(subpaths), area, piece: piece_of(cycle) });
}
// A face walk leaves out the edges that end loose (spurs): such an edge lies inside the face
// around its middle, on both sides.
let mut on_cycle = vec![false; 2 * m.edges.len()];
let cycles = m.faces.iter().map(|f| &f.0).chain(m.holes.iter().map(|h| &h.0)).chain(m.slivers.iter().map(|s| &s.0));
for &h in cycles.flatten() {
if let Some(c) = on_cycle.get_mut(h) {
*c = true;
}
}
let spur = |e: usize| !on_cycle.get(2 * e).copied().unwrap_or(true) && !on_cycle.get(twin(2 * e)).copied().unwrap_or(true);
// The faces by their bounds, so that each spur tests only the faces whose bounds hold it;
// built only when there is a spur.
let bezpaths: Vec<BezPath> = if (0..m.edges.len()).any(spur) { faces.iter().map(|f| f.path.to_bezpath()).collect() } else { vec![] };
let face_index = RectIndex::new(bezpaths.iter().enumerate().map(|(i, bp)| (bp.bounding_box(), i)).collect());
let face_around = |p: Point| {
face_index
.at(p, 0.0)
.copied()
.filter(|&i| bezpaths.get(i).is_some_and(|bp| bp.winding(p) != 0))
.min_by(|&a, &b| faces.get(a).map_or(f64::INFINITY, |f| f.area).total_cmp(&faces.get(b).map_or(f64::INFINITY, |f| f.area)))
};
// A face cycle winds so its face is on the side where the cross product of the half-edge's
// direction and the way to the face is positive: on the page, with y down, that is the right.
let edges = m
.edges
.iter()
.enumerate()
.filter_map(|(e, edge)| {
let sp = path(&[2 * e], false)?;
let path = unsheared(vec![sp]);
let (left, right) = if spur(e) {
let around = path.to_bezpath().segments().next().map(|s| s.eval(0.5)).and_then(face_around);
(around, around)
} else {
(face_of.get(twin(2 * e)).copied().flatten(), face_of.get(2 * e).copied().flatten())
};
Some(MapEdge { path, sources: edge.sources.clone(), left, right, piece: edge_pieces.get(e).copied().unwrap_or(0) })
})
.collect();
let slivers = m.slivers.iter().filter_map(|(cycle, _)| path(cycle, true)).map(|sp| unsheared(vec![sp])).collect();
let outlines =
m.holes.iter().filter_map(|(cycle, _)| Some(MapOutline { path: unsheared(vec![path(cycle, true)?]), piece: piece_of(cycle) })).collect();
Adjacency { faces, edges, slivers, outlines }
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,200 @@
use super::*;
use kurbo::{ParamCurveNearest, Vec2};
use proptest::prelude::*;
use vectorcraft_geom::{FillRule, Rect, shapes};
fn line(a: (f64, f64), b: (f64, f64)) -> Shape {
Shape::new(PathData::single(SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)), FillRule::NonZero, 0)
}
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Shape {
Shape::new(shapes::rectangle(Rect::new(x0, y0, x1, y1)), FillRule::NonZero, 0)
}
fn inside(f: &MapFace, p: Point) -> bool {
f.path.to_bezpath().winding(p) != 0
}
/// The edges whose middle lies within 0.01 of `p`.
fn edges_at(a: &Adjacency, p: Point) -> Vec<&MapEdge> {
a.edges
.iter()
.filter(|e| {
let bp = e.path.to_bezpath();
bp.segments().any(|s| {
let n = s.nearest(p, 1e-6);
n.distance_sq < 1e-4
})
})
.collect()
}
#[test]
fn a_line_across_a_rectangle_divides_two_faces_it_lies_between() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((40.0, -10.0), (40.0, 60.0))], DEFAULT_PRECISION).unwrap();
assert_eq!(a.faces.len(), 2, "{:?}", a.faces);
let left_face = a.faces.iter().position(|f| inside(f, Point::new(20.0, 25.0))).unwrap();
let right_face = a.faces.iter().position(|f| inside(f, Point::new(70.0, 25.0))).unwrap();
assert_ne!(left_face, right_face);
assert!((a.faces[left_face].area - 2000.0).abs() < 1e-6 && (a.faces[right_face].area - 3000.0).abs() < 1e-6);
let shared = edges_at(&a, Point::new(40.0, 25.0));
assert_eq!(shared.len(), 1, "{shared:?}");
let e = shared[0];
assert_eq!(e.sources, vec![1]);
let mut sides = [e.left.unwrap(), e.right.unwrap()];
sides.sort_unstable();
let mut want = [left_face, right_face];
want.sort_unstable();
assert_eq!(sides, want);
// The rectangle's own sides have a face on one side only; the line's ends stick out into no face.
let side = edges_at(&a, Point::new(70.0, 0.0));
assert_eq!(side.len(), 1);
assert_eq!([side[0].left, side[0].right].iter().flatten().count(), 1);
let stub = edges_at(&a, Point::new(40.0, -5.0));
assert_eq!((stub[0].left, stub[0].right), (None, None));
assert!(a.faces.iter().all(|f| f.piece == 0) && a.edges.iter().all(|e| e.piece == 0));
}
#[test]
fn a_line_that_ends_inside_a_face_has_that_face_on_both_sides() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((50.0, 0.0), (50.0, 30.0)), line((20.0, 10.0), (30.0, 20.0))], DEFAULT_PRECISION).unwrap();
assert_eq!(a.faces.len(), 1);
for at in [Point::new(50.0, 15.0), Point::new(25.0, 15.0)] {
let e = edges_at(&a, at);
assert_eq!(e.len(), 1, "{at:?}");
assert_eq!((e[0].left, e[0].right), (Some(0), Some(0)), "{at:?}");
}
}
#[test]
fn loose_lines_in_many_faces_look_only_at_the_faces_near_them() {
// A 40 × 40 grid of separate squares, then the same with a loose line in each.
let squares: Vec<Shape> =
(0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| rect(x, y, x + 10.0, y + 10.0)).collect();
let started = super::super::index::work_done();
assert_eq!(adjacency(&squares, DEFAULT_PRECISION).unwrap().faces.len(), 1600);
let plain = super::super::index::work_done() - started;
let mut all = squares.clone();
all.extend((0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| line((x + 5.0, y), (x + 5.0, y + 5.0))));
let started = super::super::index::work_done();
let a = adjacency(&all, DEFAULT_PRECISION).unwrap();
let work = super::super::index::work_done() - started - plain;
let loose: Vec<&MapEdge> = a.edges.iter().filter(|e| e.sources.len() == 1 && e.sources[0] >= 1600).collect();
assert_eq!(loose.len(), 1600);
for e in loose {
let mid = e.path.to_bezpath().segments().next().unwrap().eval(0.5);
let face = a.faces.iter().position(|f| inside(f, mid));
assert_eq!((e.left, e.right), (face, face));
assert!(face.is_some());
}
// Testing every face for each loose line would read 1,600 faces per line.
assert!(work <= 64 * 1600, "{work} reads");
}
#[test]
fn a_line_on_a_rectangle_side_keeps_both_inputs_in_either_order() {
for flip in [false, true] {
let (r, l) = (rect(0.0, 0.0, 100.0, 50.0), line((-10.0, 50.0), (110.0, 50.0)));
let shapes = if flip { vec![l, r] } else { vec![r, l] };
let a = adjacency(&shapes, DEFAULT_PRECISION).unwrap();
let on = edges_at(&a, Point::new(30.0, 50.0));
assert_eq!(on.len(), 1, "flip {flip}: {on:?}");
assert_eq!(on[0].sources, vec![0, 1], "flip {flip}");
}
}
#[test]
fn each_side_names_the_face_seen_on_that_side_of_the_edge() {
// A tray-like outline with a crease grid, edges drawn in every direction.
let a = adjacency(
&[
rect(0.0, 0.0, 90.0, 60.0),
line((30.0, 0.0), (30.0, 60.0)),
line((60.0, 60.0), (60.0, 0.0)),
line((90.0, 20.0), (0.0, 20.0)),
line((0.0, 40.0), (90.0, 40.0)),
],
DEFAULT_PRECISION,
)
.unwrap();
assert_eq!(a.faces.len(), 9);
let mut checked = 0;
for e in &a.edges {
let bp = e.path.to_bezpath();
let Some(seg) = bp.segments().next() else { continue };
let (p, d) = (seg.eval(0.5), seg.end() - seg.start());
let n = d.normalize();
// On the page (y down), the left of a direction (dx, dy) is (dy, -dx).
let (left_at, right_at) = (p + Vec2::new(n.y, -n.x) * 0.5, p + Vec2::new(-n.y, n.x) * 0.5);
for (side, at) in [(e.left, left_at), (e.right, right_at)] {
match side {
Some(f) => assert!(inside(&a.faces[f], at), "{e:?}"),
None => assert!(a.faces.iter().all(|f| !inside(f, at)), "{e:?}"),
}
checked += 1;
}
}
assert!(checked >= 24, "{checked}");
}
#[test]
fn a_slot_narrower_than_the_precision_is_a_sliver() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 50.004, 40.0)], DEFAULT_PRECISION).unwrap();
assert_eq!(a.slivers.len(), 1, "{:?}", a.slivers);
assert_eq!(a.faces.len(), 1);
let b = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 51.0, 40.0)], DEFAULT_PRECISION).unwrap();
assert!(b.slivers.is_empty());
assert_eq!(b.faces.len(), 2, "the slot is a face of its own");
}
#[test]
fn a_ring_is_a_face_with_a_hole_and_two_pieces() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 100.0), rect(30.0, 30.0, 70.0, 70.0)], DEFAULT_PRECISION).unwrap();
assert_eq!(a.faces.len(), 2);
let ring = a.faces.iter().find(|f| inside(f, Point::new(10.0, 10.0))).unwrap();
assert!(!inside(ring, Point::new(50.0, 50.0)), "the inner square is a hole in the ring");
assert!((ring.area - 8400.0).abs() < 1e-6, "{}", ring.area);
assert_eq!(a.outlines.len(), 2);
assert_ne!(a.outlines[0].piece, a.outlines[1].piece);
let inner = a.faces.iter().find(|f| inside(f, Point::new(50.0, 50.0))).unwrap();
assert_ne!(inner.piece, ring.piece);
let inner_side = edges_at(&a, Point::new(50.0, 30.0));
let mut sides = [inner_side[0].left, inner_side[0].right];
sides.sort_unstable();
assert!(sides.iter().all(Option::is_some), "a ring face on one side, the inner square on the other: {sides:?}");
}
#[test]
fn bad_input_gives_no_map() {
assert!(adjacency(&[], DEFAULT_PRECISION).is_none());
assert!(adjacency(&[line((0.0, 0.0), (f64::NAN, 1.0))], DEFAULT_PRECISION).is_none());
assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], 0.0).is_none());
assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], f64::INFINITY).is_none());
let mut points: Vec<Point> = (0..=SHAPE_BUILDER_MAX_SEGMENTS + 1).map(|i| Point::new(i as f64, (i % 2) as f64)).collect();
let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0);
assert!(adjacency(&[open], DEFAULT_PRECISION).is_none(), "over the segment limit");
points.truncate(64);
let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0);
assert!(adjacency(&[open], DEFAULT_PRECISION).is_some());
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
/// Random lines and boxes never panic, and every side an edge names is a face.
#[test]
fn random_lines_give_a_consistent_map(
segs in proptest::collection::vec((-50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..12),
boxed in any::<bool>(),
) {
let mut shapes: Vec<Shape> = segs.iter().map(|&(a, b, c, d)| line((a, b), (c, d))).collect();
if boxed {
shapes.push(rect(-40.0, -40.0, 40.0, 40.0));
}
if let Some(a) = adjacency(&shapes, DEFAULT_PRECISION) {
for e in &a.edges {
prop_assert!(e.left.is_none_or(|f| f < a.faces.len()) && e.right.is_none_or(|f| f < a.faces.len()));
prop_assert!(e.sources.iter().all(|&s| s < shapes.len()));
}
}
}
}
+8 -8
View File
@@ -15,23 +15,23 @@ pub(crate) struct Rest {
/// The planar graph of `shapes` (in the sweep's frame) with its faces walked: what [`build`] makes
/// Live Paint faces and edges from, and what [`Map::merge`] merges faces in.
pub(crate) struct Map {
edges: Vec<Edge>,
pub(super) edges: Vec<Edge>,
around: Vec<Vec<usize>>,
slot_of: Vec<usize>,
/// Bounded faces: their cycle of half-edges, path and area; and, by their bounds, which can
/// hold a point, so finding the face around one tests only those.
faces: Vec<(Vec<usize>, BezPath, f64)>,
pub(super) faces: Vec<(Vec<usize>, BezPath, f64)>,
face_index: RectIndex<usize>,
/// Bounded faces left out as slivers ([`is_sliver`]): their cycle of half-edges and the inputs
/// whose fill covers them (none for a gap, such as a thin cutout).
pub(super) slivers: Vec<(Vec<usize>, Vec<usize>)>,
/// Outer boundaries of connected pieces, and the face each one is a hole in.
holes: Vec<(Vec<usize>, BezPath)>,
face_holes: Vec<Vec<usize>>,
tidy: Tidy,
pub(super) holes: Vec<(Vec<usize>, BezPath)>,
pub(super) face_holes: Vec<Vec<usize>>,
pub(super) tidy: Tidy,
/// The inputs' anchors (sorted by x) and how close results snap back onto them.
anchors: Vec<Point>,
snap: f64,
pub(super) anchors: Vec<Point>,
pub(super) snap: f64,
}
/// With `cover`, also finds which inputs cover each sliver, which only [`Map::merge`] reads;
@@ -41,7 +41,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
}
/// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped.
fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
let mut inputs: Vec<(BezPath, usize)> = Vec::new();
for (i, s) in shapes.iter().enumerate() {
let mut bp = BezPath::new();
+3 -1
View File
@@ -153,7 +153,9 @@ impl FontDb {
/// neither, as [`FontTraits`] tells), then the others, each group nearest first by
/// [`FontLikeness::distance`](super::FontLikeness::distance) of their
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
/// counting 2 further. Families equally far keep their order in `families`. Reads no font
/// counting 2 further. A family that shares none of those numbers with `family` comes after
/// every family that shares one in its group. Families equally far keep their order in
/// `families`. Reads no font
/// file, as `family_traits` does not.
pub fn similar_families(&self, family: &str, families: &[String]) -> Vec<String> {
let base = self.family_traits(family);
+10 -2
View File
@@ -174,11 +174,15 @@ impl FontLikeness {
/// How unlike two faces look: 0 for faces whose numbers are all the same, more the further
/// apart they are. A number one of the faces does not give is left out. PANOSE digits are
/// compared only between faces of the same PANOSE family kind; faces of different kinds count
/// 3 apart. The weights and scales are VectorCraft's own.
/// 3 apart. Faces that share no number to compare (neither a PANOSE family kind, a weight, a
/// width, a height, an average width nor an italic angle) are `f32::INFINITY` apart, further
/// than any faces that share one. The weights and scales are VectorCraft's own.
pub fn distance(&self, other: &Self) -> f32 {
let mut d = 0.0;
let mut compared = false;
let (kind, other_kind) = (self.panose[0], other.panose[0]);
if kind > 1 && other_kind > 1 {
compared = true;
if kind == other_kind {
for (a, b) in self.panose.iter().zip(&other.panose).skip(1) {
if *a > 1 && *b > 1 {
@@ -190,21 +194,25 @@ impl FontLikeness {
}
}
if self.weight != 0 && other.weight != 0 {
compared = true;
d += f32::from(self.weight.abs_diff(other.weight)) / 200.0;
}
if self.width != 0 && other.width != 0 {
compared = true;
d += f32::from(self.width.abs_diff(other.width)) * 0.5;
}
for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)]
{
if a != 0 && b != 0 {
compared = true;
d += f32::from(a.abs_diff(b)) / 1000.0 * scale;
}
}
if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) {
compared = true;
d += f32::from(a.abs_diff(b)) / 50.0;
}
d
if compared { d } else { f32::INFINITY }
}
}
+24
View File
@@ -365,6 +365,30 @@ pub fn height_outside_font() -> Option<Vec<u8>> {
heights_font(HEIGHT_OUTSIDE_FAMILY, Some((HEIGHT_OUTSIDE_X, HEIGHT_OUTSIDE_CAP)), false)
}
/// The family of [`numberless_font`].
pub const NUMBERLESS_FAMILY: &str = "Numberlesstest Sans";
/// The bundled Source Sans 3 Regular as family [`NUMBERLESS_FAMILY`], without its OS/2 and `post`
/// tables, so it gives none of the numbers Show Similar Fonts compares faces by. `None` when it
/// can't be built.
pub fn numberless_font() -> Option<Vec<u8>> {
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let full = format!("{NUMBERLESS_FAMILY} Regular");
let postscript = format!("{}-Regular", NUMBERLESS_FAMILY.replace(' ', ""));
let name = name_table(&[(1, NUMBERLESS_FAMILY), (2, "Regular"), (4, &full), (6, &postscript)])?;
let mut builder = FontBuilder::new();
builder.add_raw(Tag::new(b"name"), name);
for r in font.table_directory.table_records() {
let tag = Tag::new(&r.tag().to_be_bytes());
if builder.contains(tag) || tag == Tag::new(b"OS/2") || tag == Tag::new(b"post") {
continue;
}
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes().to_vec());
}
Some(builder.build())
}
/// The bundled Source Sans 3 Regular as `family`: with the x height and cap height `heights` in
/// its OS/2 table, else a version 1 OS/2 table, which holds neither; with `base`, the `BASE`
/// table of [`height_font`].
+30 -2
View File
@@ -3,7 +3,9 @@
use skrifa::raw::TableProvider;
use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font};
use crate::test_fonts::{
HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, NUMBERLESS_FAMILY, VARIABLE_FAMILY, height_font, numberless_font, variable_font,
};
use crate::*;
/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without
@@ -88,8 +90,14 @@ fn likeness_is_a_distance() {
assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric");
assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0);
// A number a face does not give is left out, not counted as 0.
assert_eq!(sans.distance(&FontLikeness { x_height: 0, cap_height: 0, ..sans }), 0.0);
// Faces that share no number are further apart than any faces that share one, not alike.
let unknown = FontLikeness::default();
assert_eq!(sans.distance(&unknown), 0.0);
assert_eq!(sans.distance(&unknown), f32::INFINITY);
assert_eq!(unknown.distance(&sans), f32::INFINITY, "symmetric");
assert_eq!(unknown.distance(&unknown), f32::INFINITY);
let weight_only = FontLikeness { weight: 400, ..unknown };
assert_eq!(sans.distance(&weight_only), 0.0, "the weight alone is compared");
let lighter = FontLikeness { weight: 300, ..sans };
assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart");
}
@@ -117,3 +125,23 @@ fn families_are_ordered_by_likeness() {
assert_eq!(without[0], HEIGHTLESS_FAMILY);
assert!(db.similar_families("Source Sans 3", &[]).is_empty());
}
/// A family that gives none of the numbers comes after every family that shares one with the
/// family asked about, instead of first as though it looked the same.
#[test]
fn a_family_without_numbers_comes_after_the_measured_ones() {
let db = db();
assert_eq!(db.add_font(numberless_font().expect("the test font builds")), 1);
assert_eq!(db.family_traits(NUMBERLESS_FAMILY).likeness, FontLikeness::default());
let families = names(&[NUMBERLESS_FAMILY, "JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]);
let order = db.similar_families("Source Sans 3", &families);
assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}");
assert_eq!(order.last().map(String::as_str), Some(NUMBERLESS_FAMILY), "{order:?}");
// The measured families keep the order they have without it.
let measured: Vec<String> = order.iter().filter(|f| *f != NUMBERLESS_FAMILY).cloned().collect();
assert_eq!(measured, db.similar_families("Source Sans 3", &families[1..]));
// Asked about itself, it comes first even from the end of the list, and the families it shares
// no number with keep their order in the list.
let last = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3", NUMBERLESS_FAMILY]);
assert_eq!(db.similar_families(NUMBERLESS_FAMILY, &last), families);
}
+3
View File
@@ -11,3 +11,6 @@ workspace = true
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-pathops = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
File diff suppressed because it is too large Load Diff
+916
View File
@@ -0,0 +1,916 @@
use super::*;
use proptest::prelude::*;
use vectorcraft_geom::Rect;
const TOL: f64 = 0.1;
fn p(x: f64, y: f64) -> Point {
Point::new(x, y)
}
fn poly(points: &[(f64, f64)], closed: bool) -> PathData {
PathData::single(SubPath::polyline(&points.iter().map(|&(x, y)| p(x, y)).collect::<Vec<_>>(), closed))
}
fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine {
FoldLine { path: poly(points, closed), kind, key }
}
fn cut(points: &[(f64, f64)], key: u64) -> FoldLine {
line(LineKind::Cut, points, true, key)
}
fn crease(a: (f64, f64), b: (f64, f64), key: u64) -> FoldLine {
line(LineKind::Crease, &[a, b], false, key)
}
fn codes(issues: &[Issue]) -> Vec<&'static str> {
issues.iter().map(|i| i.code.id()).collect()
}
fn areas(b: &Blank) -> Vec<i64> {
let mut a: Vec<i64> = b.panels.iter().map(|p| (p.area * 1000.0).round() as i64).collect();
a.sort_unstable();
a
}
/// A tray: a 100 × 60 base with a 30 pt wall on each side, drawn as one closed cross, and the four
/// creases round the base (keys 10 to 13).
fn tray() -> Vec<FoldLine> {
vec![
cut(
&[
(30.0, 0.0),
(130.0, 0.0),
(130.0, 30.0),
(160.0, 30.0),
(160.0, 90.0),
(130.0, 90.0),
(130.0, 120.0),
(30.0, 120.0),
(30.0, 90.0),
(0.0, 90.0),
(0.0, 30.0),
(30.0, 30.0),
],
1,
),
crease((30.0, 30.0), (130.0, 30.0), 10),
crease((130.0, 30.0), (130.0, 90.0), 11),
crease((130.0, 90.0), (30.0, 90.0), 12),
crease((30.0, 90.0), (30.0, 30.0), 13),
]
}
/// The outline of a slotted box in the style of FEFCO 0201 (glue flap, four body panels 100, 60,
/// 100 and 60 wide and 80 high, 30 pt flaps top and bottom) with its 4 pt slots drawn as notches.
const NOTCHED: [(f64, f64); 30] = [
(20.0, 0.0),
(118.0, 0.0),
(118.0, 30.0),
(122.0, 30.0),
(122.0, 0.0),
(178.0, 0.0),
(178.0, 30.0),
(182.0, 30.0),
(182.0, 0.0),
(278.0, 0.0),
(278.0, 30.0),
(282.0, 30.0),
(282.0, 0.0),
(340.0, 0.0),
(340.0, 140.0),
(282.0, 140.0),
(282.0, 110.0),
(278.0, 110.0),
(278.0, 140.0),
(182.0, 140.0),
(182.0, 110.0),
(178.0, 110.0),
(178.0, 140.0),
(122.0, 140.0),
(122.0, 110.0),
(118.0, 110.0),
(118.0, 140.0),
(20.0, 140.0),
(20.0, 110.0),
(0.0, 110.0),
];
/// The slotted box's creases: the glue flap's and the body panels' (vertical), and the flaps'
/// (horizontal, from slot to slot).
fn box_creases() -> Vec<FoldLine> {
let mut out = vec![];
for (k, x) in [20.0, 120.0, 180.0, 280.0].into_iter().enumerate() {
out.push(crease((x, 30.0), (x, 110.0), 100 + k as u64));
}
for (k, (x0, x1)) in [(20.0, 118.0), (122.0, 178.0), (182.0, 278.0), (282.0, 340.0)].into_iter().enumerate() {
out.push(crease((x0, 30.0), (x1, 30.0), 110 + k as u64));
out.push(crease((x0, 110.0), (x1, 110.0), 120 + k as u64));
}
out
}
fn notched_box() -> Vec<FoldLine> {
let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec();
outline.extend([(0.0, 30.0), (20.0, 30.0)]);
let mut lines = vec![cut(&outline, 1)];
lines.extend(box_creases());
lines
}
fn check(lines: &[FoldLine]) -> (Vec<Blank>, Vec<Issue>) {
blanks(lines, TOL)
}
#[test]
fn a_tray_has_a_base_four_walls_and_four_hinges() {
let (b, issues) = check(&tray());
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 6_000_000]);
assert_eq!(b[0].hinges.len(), 4);
for h in &b[0].hinges {
assert!(h.straight && h.keys.len() == 1, "{h:?}");
assert!((h.from.distance(h.to) - if h.keys[0] % 2 == 0 { 100.0 } else { 60.0 }).abs() < 1e-6, "{h:?}");
}
assert_eq!(base_panel(&b[0].panels).map(|i| (b[0].panels[i].area).round()), Some(6000.0));
}
#[test]
fn a_slotted_box_gives_the_same_panels_however_its_slots_and_outline_are_drawn() {
let (notched, issues) = check(&notched_box());
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(notched.len(), 1);
assert_eq!(notched[0].panels.len(), 13, "glue flap, four body panels, eight flaps");
assert_eq!(notched[0].hinges.len(), 12);
assert!(notched[0].holes.is_empty());
// The slots as rectangles across a plain outline.
let mut across =
vec![cut(&[(20.0, 0.0), (340.0, 0.0), (340.0, 140.0), (20.0, 140.0), (20.0, 110.0), (0.0, 110.0), (0.0, 30.0), (20.0, 30.0)], 1)];
for (k, x) in [120.0, 180.0, 280.0].into_iter().enumerate() {
across.push(cut(&[(x - 2.0, -5.0), (x + 2.0, -5.0), (x + 2.0, 30.0), (x - 2.0, 30.0)], 2 + k as u64));
across.push(cut(&[(x - 2.0, 110.0), (x + 2.0, 110.0), (x + 2.0, 145.0), (x - 2.0, 145.0)], 5 + k as u64));
}
across.extend(box_creases());
let (b, issues) = check(&across);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), areas(&notched[0]));
assert_eq!(b[0].hinges.len(), 12);
// The notched outline as four open paths, end to end.
let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec();
outline.extend([(0.0, 30.0), (20.0, 30.0), (20.0, 0.0)]);
let mut open: Vec<FoldLine> =
[0..9, 8..17, 16..25, 24..33].into_iter().enumerate().map(|(k, r)| line(LineKind::Cut, &outline[r], false, 1 + k as u64)).collect();
open.extend(box_creases());
let (b, issues) = check(&open);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(areas(&b[0]), areas(&notched[0]));
assert_eq!(b[0].hinges.len(), 12);
// Input order does not change the result.
let mut reversed = notched_box();
reversed.reverse();
let (b, _) = check(&reversed);
assert_eq!(areas(&b[0]), areas(&notched[0]));
}
#[test]
fn a_round_tuck_flap_folds_like_any_panel() {
let mut bp = BezPath::new();
bp.move_to(p(0.0, 40.0));
bp.line_to(p(0.0, 140.0));
bp.line_to(p(100.0, 140.0));
bp.line_to(p(100.0, 40.0));
bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0));
bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0));
bp.close_path();
let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)];
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].panels.len(), 2);
assert_eq!(b[0].hinges.len(), 1);
}
#[test]
fn a_window_is_a_hole_in_its_panel() {
let mut lines = tray();
lines.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].holes.len(), 1);
assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 4_800_000]);
}
/// The tray's outline as one open path whose end stops `short` before its start.
fn tray_with_gap(short: f64) -> Vec<FoldLine> {
let mut lines = tray();
lines[0] = line(
LineKind::Cut,
&[
(30.0 + short, 0.0),
(130.0, 0.0),
(130.0, 30.0),
(160.0, 30.0),
(160.0, 90.0),
(130.0, 90.0),
(130.0, 120.0),
(30.0, 120.0),
(30.0, 90.0),
(0.0, 90.0),
(0.0, 30.0),
(30.0, 30.0),
(30.0, 0.0),
],
false,
1,
);
lines
}
#[test]
fn a_gap_within_the_tolerance_is_closed_and_one_past_it_is_a_loose_end() {
let (closed, _) = check(&tray());
let (b, issues) = check(&tray_with_gap(0.05));
assert_eq!(codes(&issues), vec!["gap"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1]);
assert_eq!(areas(&b[0]), areas(&closed[0]));
assert_eq!(b[0].hinges.len(), 4);
// The tolerance boundary.
let (_, issues) = blanks(&tray_with_gap(0.05), 0.06);
assert_eq!(codes(&issues), vec!["gap"]);
let (b, issues) = blanks(&tray_with_gap(0.05), 0.04);
assert!(codes(&issues).starts_with(&["open", "looseEnd", "looseEnd"]) || codes(&issues).starts_with(&["looseEnd"]), "{issues:?}");
assert!(issues.iter().any(|i| i.code == IssueCode::LooseEnd && i.at.is_some_and(|a| a.distance(p(30.05, 0.0)) < 1e-9)), "{issues:?}");
assert!(b.iter().all(|b| b.panels.len() < 5), "the outline does not close");
}
#[test]
fn no_cut_lines_or_no_enclosed_area_build_nothing() {
let (b, issues) = check(&[crease((0.0, 0.0), (10.0, 0.0), 1)]);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["noCut"]);
let (b, issues) = check(&[]);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["noCut"]);
let (b, issues) = check(&[line(LineKind::Cut, &[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0)], false, 1)]);
assert!(b.is_empty());
assert!(codes(&issues).contains(&"open") && codes(&issues).contains(&"looseEnd"), "{issues:?}");
// A non-finite line is left out.
let mut lines = tray();
lines.push(line(LineKind::Crease, &[(0.0, 0.0), (f64::NAN, 1.0)], false, 9));
let (b, issues) = check(&lines);
assert!(issues.is_empty() && b[0].panels.len() == 5, "{issues:?}");
}
#[test]
fn a_cut_end_inside_the_blank_is_a_loose_end() {
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 20.0)], false, 2));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}");
assert_eq!((issues[0].keys.clone(), issues[0].at), (vec![2], Some(p(80.0, 20.0))));
assert_eq!(b[0].panels.len(), 5, "a cut into a wall does not divide it");
// A slit that ends on a crease is not loose: it cuts the wall in two.
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 30.0)], false, 2));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((b[0].panels.len(), b[0].hinges.len()), (6, 5));
}
#[test]
fn a_cut_line_that_comes_back_through_its_own_end_meets_it() {
// From (80, 10) out to (90, 20), then back through (80, 10) to the outline at (70, 0): the
// start lies on the line's own second segment, so it is not loose.
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(80.0, 10.0), (90.0, 20.0), (70.0, 0.0)], false, 2));
let (_, issues) = check(&lines);
assert!(!codes(&issues).contains(&"looseEnd"), "{issues:?}");
// A first segment shorter than the tolerance does not make the second one meet the end.
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(90.0, 25.0), (90.05, 25.0), (80.0, 20.0), (80.0, 0.0)], false, 2));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}");
assert_eq!(issues[0].at, Some(p(90.0, 25.0)));
}
#[test]
fn two_outlines_joined_by_a_cut_line_are_both_material() {
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(150.0, 0.0), (180.0, 0.0), (180.0, 30.0), (150.0, 30.0)], 2),
line(LineKind::Cut, &[(100.0, 10.0), (150.0, 10.0)], false, 3),
];
let (b, issues) = check(&lines);
assert_eq!(b.len(), 1, "one connected piece");
assert_eq!(areas(&b[0]), vec![900_000, 10_000_000], "{issues:?}");
assert!(b[0].holes.is_empty());
// A slot drawn across the outline is still cut out, not made material where it sticks out.
let lines =
vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)];
let (b, _) = check(&lines);
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]);
// The same slot drawn as four open lines end to end, one of them backwards.
let slot = [(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)];
let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1)];
lines.push(line(LineKind::Cut, &[slot[0], slot[1]], false, 2));
lines.push(line(LineKind::Cut, &[slot[2], slot[1]], false, 3));
lines.push(line(LineKind::Cut, &[slot[2], slot[3]], false, 4));
lines.push(line(LineKind::Cut, &[slot[3], slot[0]], false, 5));
let (b, issues) = check(&lines);
assert_eq!(b.len(), 1, "{issues:?}");
assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]);
// And with a gap within the tolerance at one corner.
lines[4] = line(LineKind::Cut, &[slot[3], (48.0, -9.95)], false, 5);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["gap"], "{issues:?}");
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]);
// A slot right across the blank, with no corner inside the outline and no outline corner
// inside the slot, cuts it in two.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(10.0, -210.0), (20.0, -210.0), (20.0, 110.0), (10.0, 110.0)], 2),
];
let (b, _) = check(&lines);
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![1_000_000, 8_000_000]);
}
#[test]
fn an_outline_drawn_twice_keeps_its_material() {
let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let (b, issues) = check(&[cut(&square, 1), cut(&square, 2)]);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1, 2]);
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![10_000_000]);
// The same two squares as the subpaths of one compound path.
let mut twice = poly(&square, true);
twice.subpaths.extend(poly(&square, true).subpaths);
let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1]);
assert_eq!(areas(&b[0]), vec![10_000_000]);
}
#[test]
fn a_large_tolerance_still_closes_nearly_touching_ends_and_short_outlines() {
// Ends 0.0005 apart, closer than 1/10,000 of the tolerance.
let nearly = line(LineKind::Cut, &[(0.0005, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)], false, 1);
let (b, issues) = blanks(&[nearly], 10.0);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(areas(&b[0]), vec![10_000_000]);
// An outline shorter than the tolerance, 0.05 pt open: a gap, and no loose end.
let short = line(LineKind::Cut, &[(0.05, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1);
let (b, issues) = blanks(&[short], 10.0);
assert_eq!(codes(&issues), vec!["gap"], "{issues:?}");
assert_eq!(areas(&b[0]), vec![1000]);
}
#[test]
fn a_lookup_wider_than_the_occupied_cells_reads_only_those_cells() {
// Two points 1e-9 apart make cells about 2.4e-13 wide: a lookup 1e-6 around one spans some
// 10^14 cells, and finds both points by reading the two cells that hold them.
let cells = Cells::new(vec![(Rect::from_points(p(0.0, 0.0), p(0.0, 0.0)), 1), (Rect::from_points(p(1e-9, 0.0), p(1e-9, 0.0)), 2)], 0.0, 4096.0);
assert_eq!(cells.near(p(0.0, 0.0), 1e-6), vec![1, 2]);
assert_eq!(cells.near(p(5.0, 5.0), 1e-6), Vec::<i32>::new());
// A square open by 0.0000011 pt at a 10 pt tolerance.
let square = line(LineKind::Cut, &[(0.0000011, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1);
let (b, issues) = blanks(&[square], 10.0);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b.len(), 1);
}
#[test]
fn a_window_of_open_lines_with_a_slit_to_its_corner_is_still_a_hole() {
let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1);
let window = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)];
let slit = line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2);
let (closed, issues) = check(&[outline.clone(), slit.clone(), cut(&window, 3)]);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((closed[0].holes.len(), areas(&closed[0])), (1, vec![10_000_000 - 400_000]));
let mut lines = vec![outline, slit];
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
let (open, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((open[0].holes.len(), areas(&open[0])), (1, areas(&closed[0])));
// The outline as four open lines too, the slit from its corner to the window's.
let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let mut lines: Vec<FoldLine> = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect();
lines.push(line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 2));
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0])));
// A cut across the window of open lines, so that three lines meet at two of its corners.
let mut lines = vec![cut(&corners, 1), line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2)];
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
lines.push(line(LineKind::Cut, &[(40.0, 40.0), (60.0, 60.0)], false, 20));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0])));
// The outline and the window both as open lines, joined by two slits: the same as when both are
// closed.
let slits = [line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 30), line(LineKind::Cut, &[(100.0, 100.0), (60.0, 60.0)], false, 31)];
let (want, want_issues) = check(&[cut(&corners, 1), cut(&window, 3), slits[0].clone(), slits[1].clone()]);
let mut lines: Vec<FoldLine> = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect();
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
lines.extend(slits);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}");
assert_eq!((b[0].holes.len(), areas(&b[0])), (want[0].holes.len(), areas(&want[0])));
assert_eq!(want[0].holes.len(), 1);
}
#[test]
fn a_slot_drawn_across_the_outline_is_a_notch_not_a_hole() {
let outline = || cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1);
let (b, issues) = check(&[outline(), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)]);
assert!(issues.is_empty(), "{issues:?}");
assert!(b[0].holes.is_empty(), "{:?}", b[0].holes);
let notched = cut(&[(0.0, 0.0), (48.0, 0.0), (48.0, 20.0), (52.0, 20.0), (52.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1);
assert_eq!(areas(&b[0]), areas(&check(std::slice::from_ref(&notched)).0[0]));
// A crease in the notch lies outside the blank, and one that runs on into it from a panel too.
let slot = || cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2);
let (_, issues) = check(&[outline(), slot(), crease((49.0, 5.0), (51.0, 5.0), 3)]);
assert_eq!(codes(&issues), vec!["outside"], "{issues:?}");
let (_, issues) = check(&[outline(), slot(), crease((50.0, 5.0), (50.0, 100.0), 3)]);
let (_, want) = check(&[notched, crease((50.0, 5.0), (50.0, 100.0), 3)]);
assert_eq!(codes(&issues), codes(&want), "{issues:?}");
assert!(codes(&issues).contains(&"outside"), "{issues:?}");
// A cutout whose top side lies on the outline opens onto the outside directly.
let flush = || cut(&[(48.0, 0.0), (52.0, 0.0), (52.0, 20.0), (48.0, 20.0)], 2);
let (b, issues) = check(&[outline(), flush()]);
assert!(b[0].holes.is_empty() && !codes(&issues).contains(&"ambiguous"), "{:?} {issues:?}", b[0].holes);
let (_, issues) = check(&[outline(), flush(), crease((49.0, 5.0), (51.0, 5.0), 3)]);
assert!(codes(&issues).contains(&"outside") && !codes(&issues).contains(&"ambiguous"), "{issues:?}");
// A window joined to the outline by a slit stays a hole when a cut across it leaves a sliver.
let window = || cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 4);
let slit = || line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 5);
let (b, _) = check(&[outline(), window(), slit(), line(LineKind::Cut, &[(40.0, 40.004), (60.0, 40.004)], false, 6)]);
assert_eq!(b[0].holes.len(), 1, "{:?}", b[0].holes);
// And a window 0.004 pt below the outline, joined to it at both corners, leaving a sliver.
let near = cut(&[(40.0, 0.004), (60.0, 0.004), (60.0, 20.0), (40.0, 20.0)], 4);
let joins = [line(LineKind::Cut, &[(40.0, 0.0), (40.0, 0.004)], false, 5), line(LineKind::Cut, &[(60.0, 0.0), (60.0, 0.004)], false, 6)];
let (b, _) = check(&[outline(), near, joins[0].clone(), joins[1].clone()]);
assert_eq!(b[0].holes.len(), 1, "{:?}", b[0].holes);
}
#[test]
fn many_small_outlines_of_open_lines_fit_the_gap_search() {
// 784 unit squares 3 pt apart, each four open lines, at a tolerance of 0.5 pt.
let mut lines = vec![];
for i in 0..28u64 {
for j in 0..28u64 {
let (x, y) = (3.0 * i as f64, 3.0 * j as f64);
let c = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)];
for k in 0..4 {
lines.push(line(LineKind::Cut, &[c[k], c[(k + 1) % 4]], false, 4 * (28 * i + j) + k as u64));
}
}
}
let (b, issues) = blanks(&lines, 0.5);
assert!(!codes(&issues).contains(&"tooComplex"), "{issues:?}");
assert_eq!(b.len(), 784);
}
#[test]
fn thousands_of_cut_lines_on_top_of_each_other_are_too_complex_before_the_gap_search() {
let lines: Vec<FoldLine> = (0..3000u64).map(|k| line(LineKind::Cut, &[(0.0, 0.0), (100.0, 0.0)], false, k)).collect();
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["tooComplex"], "{issues:?}");
assert!(b.is_empty());
}
#[test]
fn cut_lines_that_cross_an_outline_of_open_lines_leave_every_cell_material() {
// A 90 pt square whose sides are open lines ending every 30 pt, and four cut lines right across
// it: nine pieces of material, as with a closed outline.
let mut lines = vec![];
for k in 0..3 {
let (a, b) = (30.0 * k as f64, 30.0 * (k + 1) as f64);
for (i, seg) in [[(a, 0.0), (b, 0.0)], [(90.0, a), (90.0, b)], [(b, 90.0), (a, 90.0)], [(0.0, b), (0.0, a)]].iter().enumerate() {
lines.push(line(LineKind::Cut, seg, false, 10 + 4 * k as u64 + i as u64));
}
}
let across = [[(30.0, 0.0), (30.0, 90.0)], [(60.0, 0.0), (60.0, 90.0)], [(0.0, 30.0), (90.0, 30.0)], [(0.0, 60.0), (90.0, 60.0)]];
for (i, seg) in across.iter().enumerate() {
lines.push(line(LineKind::Cut, seg, false, 30 + i as u64));
}
let mut closed = vec![cut(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], 1)];
closed.extend(lines.iter().skip(12).cloned());
let (want, want_issues) = check(&closed);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}");
let pieces = |b: &[Blank]| b.iter().map(|x| (x.panels.len(), x.holes.len())).collect::<Vec<_>>();
assert_eq!(pieces(&b), pieces(&want));
assert_eq!(b.iter().map(|x| x.panels.len()).sum::<usize>(), 9);
// With the crossing lines drawn in 30 pt pieces, the four pieces round the middle cell meet end
// to end and count as one closed cut line, whether the outline is closed or drawn in pieces.
let mut split = vec![];
for (i, seg) in across.iter().enumerate() {
let (a, b) = (seg[0], seg[1]);
for k in 0..3 {
let at = |t: f64| (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
split.push(line(LineKind::Cut, &[at(k as f64 / 3.0), at((k + 1) as f64 / 3.0)], false, 40 + 3 * i as u64 + k as u64));
}
}
let mut closed = vec![cut(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], 1)];
closed.extend(split.iter().cloned());
let (want, want_issues) = check(&closed);
let mut open: Vec<FoldLine> = lines.iter().take(12).cloned().collect();
open.extend(split);
let (b, issues) = check(&open);
assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}");
assert_eq!(pieces(&b), pieces(&want));
}
#[test]
fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() {
// A crease from corner to corner of a square: its curve strays about 10.1 pt from the diagonal,
// where samples at quarters of it see 9.8 pt.
let off = 35.0 / 2f64.sqrt();
let mut bp = BezPath::new();
bp.move_to(p(0.0, 0.0));
bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0));
let lines = vec![
cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1),
FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 },
];
let (b, issues) = blanks(&lines, 10.0);
assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}");
assert_eq!(b[0].hinges.len(), 1);
let (_, issues) = blanks(&lines, 10.5);
assert!(issues.is_empty(), "{issues:?}");
}
#[test]
fn a_grid_of_many_touching_outlines_is_classified_without_comparing_every_pair() {
// 100 × 100 touching squares, each its own closed outline: one piece of 10,000 panels.
let mut lines = vec![];
for i in 0..100u64 {
for j in 0..100u64 {
let (x, y) = (10.0 * i as f64, 10.0 * j as f64);
lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], 100 * i + j));
}
}
let (b, issues) = check(&lines);
assert!(b.is_empty());
assert!(codes(&issues).contains(&"tooComplex"), "{issues:?}");
}
#[test]
fn open_cut_lines_far_from_the_origin_are_checked_without_overflow() {
let lines = [
line(LineKind::Cut, &[(1e13, 0.0), (1e13 + 4096.0, 0.0), (1e13 + 4096.0, 4096.0)], false, 1),
line(LineKind::Cut, &[(1e13 + 4096.0, 4096.0), (1e13, 4096.0), (1e13, 0.0)], false, 2),
];
let (b, issues) = check(&lines);
assert!(b.len() <= 1, "{issues:?}");
}
#[test]
fn a_blank_in_the_hole_of_a_narrow_ring_is_a_blank_of_its_own() {
// The ring's own area (1,900) is less than the hole's (8,100), but the square lies in the hole.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(5.0, 5.0), (95.0, 5.0), (95.0, 95.0), (5.0, 95.0)], 2),
cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 3),
];
let (b, issues) = check(&lines);
assert_eq!(b.len(), 2, "{issues:?}");
assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}");
assert_eq!(issues[0].keys, vec![3]);
}
#[test]
fn too_many_segments_are_refused_before_the_lines_are_copied() {
// Many lines that together pass the limit by one segment.
let each: Vec<(f64, f64)> = (0..=64).map(|i| (i as f64, 0.0)).collect();
let lines: Vec<FoldLine> = (0..=(MAX_SEGMENTS / 64) as u64).map(|k| line(LineKind::Cut, &each, false, k)).collect();
assert!(lines.len() * 64 > MAX_SEGMENTS);
let (b, issues) = check(&lines);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["tooComplex"]);
}
#[test]
fn many_separate_blanks_each_with_a_window_are_told_apart() {
// A 50 × 40 grid of 10 pt squares 5 pt apart, each with a 4 pt window and a crease beside it.
let mut lines = vec![];
for i in 0..50u64 {
for j in 0..40u64 {
let (x, y) = (15.0 * i as f64, 15.0 * j as f64);
let k = 10 * (40 * i + j);
lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], k));
lines.push(cut(&[(x + 1.0, y + 1.0), (x + 5.0, y + 1.0), (x + 5.0, y + 5.0), (x + 1.0, y + 5.0)], k + 1));
lines.push(crease((x + 7.0, y), (x + 7.0, y + 10.0), k + 2));
}
}
let (blanks, issues) = check(&lines);
assert!(issues.is_empty(), "{:?}", issues.first());
assert_eq!(blanks.len(), 2000);
assert!(blanks.iter().all(|b| b.panels.len() == 2 && b.hinges.len() == 1 && b.holes.len() == 1));
}
#[test]
fn many_separate_cut_lines_are_checked_by_the_cells_near_each_end() {
// 2,000 short slits from the top edge of a long blank, each ending loose inside it.
let mut lines = vec![cut(&[(0.0, 0.0), (4000.0, 0.0), (4000.0, 100.0), (0.0, 100.0)], 1)];
for i in 0..2000u64 {
let x = 1.0 + 2.0 * i as f64;
lines.push(line(LineKind::Cut, &[(x, 0.0), (x, 50.0)], false, 10 + i));
}
let (_, issues) = check(&lines);
let loose: Vec<&Issue> = issues.iter().filter(|i| i.code == IssueCode::LooseEnd).collect();
assert_eq!(loose.len(), 2000);
assert!(loose.iter().all(|i| i.at.is_some_and(|at| (at.y - 50.0).abs() < 1e-9)));
}
#[test]
fn too_many_segments_or_panels_are_too_complex() {
// One point more than segments.
let mut zigzag: Vec<(f64, f64)> = (0..=MAX_SEGMENTS + 1).map(|i| (i as f64 * 0.5, (i % 2) as f64)).collect();
let (b, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["tooComplex"]);
zigzag.truncate(MAX_SEGMENTS + 1);
let (_, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]);
assert!(!codes(&issues).contains(&"tooComplex"), "at the limit");
// A grid of 16 × 16 panels is at the panel limit; 17 × 16 is past it.
let grid = |cols: usize| {
let mut lines = vec![cut(&[(0.0, 0.0), (cols as f64 * 10.0, 0.0), (cols as f64 * 10.0, 160.0), (0.0, 160.0)], 1)];
for i in 1..cols {
lines.push(crease((i as f64 * 10.0, 0.0), (i as f64 * 10.0, 160.0), 100 + i as u64));
}
for j in 1..16 {
lines.push(crease((0.0, j as f64 * 10.0), (cols as f64 * 10.0, j as f64 * 10.0), 200 + j as u64));
}
lines
};
let (b, issues) = check(&grid(16));
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].panels.len(), MAX_PANELS);
let (b, issues) = check(&grid(17));
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["tooComplex"]);
}
#[test]
fn lines_on_top_of_each_other_are_reported() {
let mut lines = tray();
lines.push(crease((40.0, 0.0), (120.0, 0.0), 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["cutOverCrease"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1, 20]);
let mut lines = tray();
lines.push(crease((130.0, 30.0), (30.0, 30.0), 20));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![10, 20]);
assert_eq!(b[0].hinges.len(), 4);
assert_eq!(b[0].hinges.iter().find(|h| h.keys.contains(&20)).map(|h| h.keys.clone()), Some(vec![10, 20]));
// A perforation over a crease, lines of two kinds that fold.
let mut lines = tray();
lines.push(line(LineKind::Perforation, &[(130.0, 30.0), (30.0, 30.0)], false, 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![10, 20]);
// A crease drawn twice outside the blank is reported where it lies as well.
let mut lines = tray();
lines.push(crease((200.0, 0.0), (250.0, 0.0), 20));
lines.push(crease((250.0, 0.0), (200.0, 0.0), 21));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate", "outside", "outside"], "{issues:?}");
assert_eq!((issues[1].keys.clone(), issues[2].keys.clone()), (vec![20], vec![21]));
}
#[test]
fn a_crease_that_runs_past_the_outline_is_reported() {
let outline = || cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1);
// 5 pt past the outline at each end: the hinge is built, and the line is reported.
let (b, issues) = check(&[outline(), crease((50.0, -5.0), (50.0, 55.0), 2)]);
assert_eq!(codes(&issues), vec!["outside"], "{issues:?}");
assert_eq!(issues[0].keys, vec![2]);
assert_eq!(b[0].hinges.len(), 1);
// Past it by less than the tolerance: no issue.
let (b, issues) = check(&[outline(), crease((50.0, -0.05), (50.0, 50.0), 2)]);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].hinges.len(), 1);
// A crease drawn round a sliver inside the blank does not run outside it.
let (_, issues) = check(&[outline(), line(LineKind::Crease, &[(50.0, 10.0), (50.004, 10.0), (50.004, 40.0), (50.0, 40.0)], true, 2)]);
assert!(!codes(&issues).contains(&"outside"), "{issues:?}");
}
#[test]
fn a_crease_that_ends_inside_a_panel_is_dangling() {
let mut lines = tray();
lines.push(crease((80.0, 30.0), (80.0, 60.0), 20));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}");
assert_eq!(issues[0].keys, vec![20]);
assert_eq!(b[0].panels.len(), 5);
}
#[test]
fn a_hinge_shorter_than_the_tolerance_divides_nothing_and_leaves_a_loose_panel() {
let lines = vec![
cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1),
crease((50.0, 49.95), (50.0, 50.0), 2),
];
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["noSplit", "loosePanel"], "{issues:?}");
assert_eq!(issues[0].keys, vec![2]);
assert!(b[0].hinges.is_empty());
// The same with a hinge as long as the panels: no issue.
let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1), crease((50.0, 0.0), (50.0, 50.0), 2)];
let (_, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
}
#[test]
fn hinge_pieces_far_apart_are_measured_by_their_own_length() {
// A window leaves two 0.02 pt strips joining the halves, each crossed by a crease: 0.04 pt of
// hinge, though its pieces span 100 pt.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(40.0, 0.02), (60.0, 0.02), (60.0, 99.98), (40.0, 99.98)], 2),
crease((50.0, 0.0), (50.0, 0.02), 3),
crease((50.0, 99.98), (50.0, 100.0), 4),
];
let (b, issues) = check(&lines);
assert!(codes(&issues).contains(&"noSplit"), "{issues:?}");
assert!(b[0].hinges.is_empty());
}
#[test]
fn a_window_split_by_a_cut_line_is_one_hole() {
let mut lines =
vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 2)];
lines.push(line(LineKind::Cut, &[(40.0, 50.0), (60.0, 50.0)], false, 3));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].holes.len(), 1);
let area = vectorcraft_pathops::area(&b[0].holes[0], FillRule::NonZero);
assert!((area - 400.0).abs() < 1e-3, "{area}");
}
#[test]
fn a_hinge_drawn_as_short_pieces_is_measured_whole() {
// Ten 5 pt pieces make a 50 pt hinge, longer than a 10 pt tolerance though each piece is not.
let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1)];
for k in 0..10u64 {
let y = 5.0 * k as f64;
lines.push(crease((50.0, y), (50.0, y + 5.0), 10 + k));
}
let (b, issues) = blanks(&lines, 10.0);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].hinges.len(), 1);
let h = &b[0].hinges[0];
assert!((h.from.distance(h.to) - 50.0).abs() < 1e-6 && h.keys.len() == 10, "{h:?}");
}
#[test]
fn a_crease_outside_the_blank_is_reported() {
let mut lines = tray();
lines.push(crease((200.0, 0.0), (250.0, 0.0), 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["outside"], "{issues:?}");
assert_eq!(issues[0].keys, vec![20]);
}
#[test]
fn a_bent_crease_folds_along_its_longest_piece() {
let mut lines = tray();
lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.0), (130.0, 32.0)], false, 10);
lines[0] = cut(
&[
(30.0, 0.0),
(130.0, 0.0),
(130.0, 32.0),
(160.0, 32.0),
(160.0, 90.0),
(130.0, 90.0),
(130.0, 120.0),
(30.0, 120.0),
(30.0, 90.0),
(0.0, 90.0),
(0.0, 30.0),
(30.0, 30.0),
],
1,
);
lines[2] = crease((130.0, 32.0), (130.0, 90.0), 11);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}");
let h = b[0].hinges.iter().find(|h| h.keys == vec![10]).unwrap();
assert!(!h.straight);
assert!((h.from.y - 30.0).abs() < 1e-9 && (h.to.y - 30.0).abs() < 1e-9, "along the 60 pt piece: {h:?}");
// Within the tolerance, a crease is straight.
let mut lines = tray();
lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.05), (130.0, 30.0)], false, 10);
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert!(b[0].hinges.iter().all(|h| h.straight));
}
#[test]
fn a_slot_too_narrow_to_map_is_a_sliver() {
let mut lines = tray();
lines.push(cut(&[(60.0, 45.0), (60.004, 45.0), (60.004, 75.0), (60.0, 75.0)], 2));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["sliver"], "{issues:?}");
assert!(issues[0].at.is_some_and(|a| Rect::new(59.9, 44.0, 60.1, 76.0).contains(a)));
}
#[test]
fn lines_in_a_hole_are_ambiguous() {
let mut window = tray();
window.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2));
let mut lines = window.clone();
lines.push(crease((70.0, 45.0), (70.0, 75.0), 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}");
assert_eq!(issues[0].keys, vec![20]);
let mut lines = window;
lines.push(cut(&[(70.0, 50.0), (90.0, 50.0), (90.0, 70.0), (70.0, 70.0)], 3));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}");
assert_eq!(issues[0].keys, vec![3]);
assert_eq!(b.len(), 2, "the square in the window is a blank of its own");
}
#[test]
fn partial_cuts_and_perforations_make_hinges_as_creases_do() {
let mut lines = tray();
lines[1].kind = LineKind::PartialCut;
lines[3].kind = LineKind::Perforation;
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let mut keys: Vec<Vec<u64>> = b[0].hinges.iter().map(|h| h.keys.clone()).collect();
keys.sort_unstable();
assert_eq!(keys, vec![vec![10], vec![11], vec![12], vec![13]]);
}
#[test]
fn every_code_has_an_id_and_a_severity() {
let ids: Vec<&str> = IssueCode::ALL.iter().map(|c| c.id()).collect();
assert_eq!(ids.len(), 15);
let mut unique = ids.clone();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), 15);
let errors: Vec<&str> = IssueCode::ALL.iter().filter(|c| c.is_error()).map(|c| c.id()).collect();
assert_eq!(errors, vec!["noCut", "open", "looseEnd", "tooComplex", "cutOverCrease"]);
let mut sorted = IssueCode::ALL;
sorted.sort();
assert_eq!(sorted, IssueCode::ALL, "listed in issue order");
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(48))]
/// Random fold lines never panic, and the panels and hinges they give are consistent.
#[test]
fn random_fold_lines_give_consistent_blanks(
segs in proptest::collection::vec((0u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..10),
boxed in any::<bool>(),
) {
let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation];
let mut lines: Vec<FoldLine> = segs
.iter()
.enumerate()
.map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64))
.collect();
if boxed {
lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99));
}
let (blanks, issues) = blanks(&lines, TOL);
for b in &blanks {
prop_assert!(!b.panels.is_empty() && b.panels.len() <= MAX_PANELS);
for h in &b.hinges {
prop_assert!(h.a < h.b && h.b < b.panels.len());
prop_assert!(h.from.is_finite() && h.to.is_finite());
}
}
let mut sorted = issues.clone();
sorted.sort_by_key(|i| i.code);
prop_assert_eq!(sorted, issues);
}
}
+3
View File
@@ -4,8 +4,11 @@
//! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front,
//! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer:
//! intersecting profiles can have ambiguous visibility and are not solid modelling inputs.
//!
//! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines.
#![forbid(unsafe_code)]
pub mod fold;
mod solid;
mod visibility;
pub use solid::{
+1
View File
@@ -34,6 +34,7 @@ pub mod pie;
pub mod place;
pub mod printtiling;
pub mod repeat_grid;
pub mod repeat_radial;
pub mod rulerguide;
pub mod select;
pub mod settings;
+684
View File
@@ -0,0 +1,684 @@
//! Radial Repeat's on-canvas handles: a handle below the repeat adds or removes instances, a
//! handle on the circle the instances sit on sets its radius, and a splitter on the circle hides
//! instances at the end of the ring while the others keep their places, as the public "Create
//! radial repeats" page describes. Drawing and hit testing share the document-space geometry of
//! [`RadialHandles::of`]; a drag previews the existing Repeat Options command and commits as one
//! undo step.
//!
//! A split ring is kept in the repeat's existing options: `instances` counts the instances shown,
//! and `endAngle` places them a full ring's step apart from `startAngle` (one step past it for a
//! single instance). The full ring's slot count is read back from that step, so dragging the
//! splitter forward shows the hidden instances again.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, RepeatKind, Selection};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::bbox::Handle;
use crate::{Action, Cursor, Mods, ToolContext};
/// The radius of the instances, radius and splitter handles (screen points).
pub const HANDLE_RADIUS: f32 = 5.0;
/// How far (screen points) the instances handle sits below the bounding box, clear of its own
/// handles and rotate zones.
pub const HANDLE_GAP: f64 = 22.0;
/// How far (screen points) the instances handle is dragged for each instance it adds or removes.
pub const INSTANCE_STEP: f64 = 16.0;
/// How near (screen points) a press must come to a handle to take it.
const REACH: f64 = 8.0;
/// The most instances a radial repeat has (as `object.repeat.options` accepts them).
const MAX_INSTANCES: f64 = 1000.0;
/// A control of [`RadialHandles`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RadialPart {
/// Below the repeat: drag down for more instances, up for fewer.
Instances,
/// On the circle, between the first two instances: drag outward for a larger radius, inward
/// for a smaller one.
Radius,
/// On the circle, half a step past the last instance shown: drag it back around the circle to
/// hide the instances it passes, forward to show them again.
Splitter,
}
/// The full ring a radial repeat's instances sit on.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Ring {
/// The instances a full turn holds at the repeat's step.
slots: u32,
/// Degrees from one instance to the next (negative when the instances run the other way).
step: f64,
}
impl Ring {
/// The ring of `instances` laid out from `start` to `end` degrees, when their step fits a
/// whole number of times (2 to 1,000, and no fewer than the instances) in a full turn.
fn of(instances: u32, start: f64, end: f64) -> Option<Self> {
let step = instance_step(instances, end - start);
let slots = 360.0 / step.abs();
let whole = slots.round();
((slots - whole).abs() < 1e-6 && (2.0..=MAX_INSTANCES).contains(&whole) && whole >= f64::from(instances))
.then(|| Self { slots: whole as u32, step: (360.0 / whole).copysign(step) })
}
/// The Repeat Options that show the first `shown` instances of the ring (1 to all of them),
/// laid out from `start` degrees.
fn options(&self, shown: u32, start: f64) -> Value {
let shown = shown.clamp(1, self.slots.max(1));
let sweep = if shown == self.slots { 360.0_f64.copysign(self.step) } else { self.step * f64::from(shown.saturating_sub(1).max(1)) };
json!({ "instances": shown, "endAngle": start + sweep })
}
/// The instances shown with the splitter `turn` degrees around the ring from the first
/// instance: those it has passed, one at least and the full ring at most.
fn shown(&self, turn: f64) -> u32 {
let k = (turn / self.step.abs()).floor() + 1.0;
if k.is_nan() { 1 } else { k.clamp(1.0, f64::from(self.slots)) as u32 }
}
}
/// Degrees between neighboring instances, as `repeat_transforms` spaces `instances` over `sweep`.
fn instance_step(instances: u32, sweep: f64) -> f64 {
let full = (sweep.abs() - 360.0).abs() < 1e-9;
if full || instances <= 1 { sweep / f64::from(instances.max(1)) } else { sweep / f64::from(instances - 1) }
}
/// `v` turned by `deg` degrees as `repeat_transforms` turns the instances.
fn turned(v: Vec2, deg: f64) -> Vec2 {
(Affine::rotate(deg.to_radians()) * v.to_point()).to_vec2()
}
/// The direction of `v` in counter-clockwise screen degrees.
fn screen_angle(v: Vec2) -> f64 {
(-v.y).atan2(v.x).to_degrees()
}
/// The controls of a selected radial repeat, in document space.
#[derive(Clone, Copy, Debug)]
pub struct RadialHandles {
pub id: NodeId,
instances: u32,
/// The circle the instances' centers sit on.
pub center: Point,
pub radius: f64,
/// The unit direction from the center to the radius handle.
out: Vec2,
/// Document points of drag for each instance.
step: f64,
start_angle: f64,
ring: Option<Ring>,
pub instances_at: Point,
pub radius_at: Point,
/// Where the splitter is: none when the instances' step does not divide a full turn, for a
/// single instance to a turn, or with a radius of 0.
pub splitter_at: Option<Point>,
}
impl RadialHandles {
/// The controls of a single editable radial repeat selected whole, the instances handle placed
/// below `frame` (the bounding box the Selection tool shows; its geometric bounds without one)
/// at `zoom`.
pub fn of(doc: &Document, selection: &Selection, frame: Option<OrientedBox>, zoom: f64) -> Option<Self> {
let [id] = selection.objects.as_slice() else { return None };
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
return None;
}
let n = doc.node(*id)?;
let NodeKind::Repeat(spec) = &n.kind else { return None };
let RepeatKind::Radial { instances, radius, center, start_angle, end_angle, .. } = spec.kind else { return None };
if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) {
return None;
}
let source = spec.source_bounds()?;
if !finite(source.center()) {
return None;
}
// As `repeat_transforms` lays the instances out: the first one at `start_angle` from the
// source's own direction, the rest a step apart.
let instances = instances.clamp(1, 1000);
let mut d = source.center() - center;
if d.hypot() < 1e-9 {
d = Vec2::new(0.0, -1.0);
}
let first = turned(d.normalize(), start_angle);
let step = instance_step(instances, end_angle - start_angle);
// Halfway between the first two instances; opposite a single one.
let out = turned(first, if instances == 1 { 180.0 } else { step / 2.0 });
let radius = radius.max(0.0);
let ring = Ring::of(instances, start_angle, end_angle);
// Half a step past the last instance shown.
let splitter_at = ring.filter(|_| radius > 0.0).map(|r| center + turned(first, r.step * (f64::from(instances) - 0.5)) * radius);
let frame = match frame {
Some(f) => aabb(f.corners())?,
None => n.geometric_bounds_with(&doc.symbol_boxes())?,
};
let h = Self {
id: *id,
instances,
center,
radius,
out,
step: INSTANCE_STEP / zoom,
start_angle,
ring,
instances_at: Point::new(frame.center().x, frame.y1 + HANDLE_GAP / zoom),
radius_at: center + out * radius,
splitter_at: splitter_at.filter(|p| finite(*p)),
};
(finite(h.instances_at) && finite(h.radius_at) && h.step.is_finite() && h.step > 0.0).then_some(h)
}
/// The controls with where they are.
pub fn parts(&self) -> Vec<(RadialPart, Point)> {
let mut parts = vec![(RadialPart::Instances, self.instances_at), (RadialPart::Radius, self.radius_at)];
parts.extend(self.splitter_at.map(|at| (RadialPart::Splitter, at)));
parts
}
/// The control under `p` (the nearer within reach) and the repeat's controls, unless a
/// bounding-box handle is there, which keeps its scaling.
fn hit(cx: &ToolContext, p: Point) -> Option<(Self, RadialPart)> {
if !cx.show_bbox || !finite(p) {
return None;
}
let h = Self::of(cx.doc, cx.selection, crate::select::selection_box(cx), cx.zoom)?;
let reach = cx.tol(REACH);
let (part, _) =
h.parts().into_iter().map(|(part, q)| (part, q.distance(p))).filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1))?;
(!crate::select::bbox_handle_at(cx, p)).then_some((h, part))
}
/// The Repeat Options that dragging `part` by `d` (document points) from the press gives;
/// none when the drag is too far to measure. The splitter's options are those it shows at the
/// press.
fn options(&self, part: RadialPart, d: Vec2) -> Option<Value> {
match part {
RadialPart::Instances => {
let n = f64::from(self.instances) + (d.y / self.step).round();
// NaN only comes from an infinite drag; the clamp keeps a huge one at the limit.
(!n.is_nan()).then(|| json!({ "instances": n.clamp(1.0, MAX_INSTANCES) as u32 }))
}
RadialPart::Radius => {
// Only the part of the drag along the line from the center moves the circle.
let r = ((self.radius + d.dot(self.out)).max(0.0) * 100.0).round() / 100.0;
r.is_finite().then(|| json!({ "radius": r }))
}
RadialPart::Splitter => self.ring.map(|r| r.options(self.instances, self.start_angle)),
}
}
/// Degrees around the ring from the first instance to the splitter, in the direction the
/// instances run.
fn splitter_turn(&self) -> f64 {
self.ring.map_or(0.0, |r| (f64::from(self.instances) - 0.5) * r.step.abs())
}
/// The direction of `p` from the center in degrees, as the instances are turned; none at the
/// center.
fn bearing(&self, p: Point) -> Option<f64> {
let v = p - self.center;
(finite(p) && v.hypot() > 1e-9).then(|| v.y.atan2(v.x).to_degrees())
}
/// The direction (counter-clockwise degrees) in which the radius handle moves the circle out.
fn out_angle(&self) -> f64 {
screen_angle(self.out)
}
/// The direction (counter-clockwise degrees) along the circle at the splitter.
fn splitter_angle(&self) -> f64 {
self.splitter_at.map_or(0.0, |at| screen_angle(at - self.center) + 90.0)
}
}
/// The page-square bounds of `corners`.
fn aabb(corners: [Point; 4]) -> Option<Rect> {
let r = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |r, p| r.union_pt(*p));
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r)
}
fn finite(p: Point) -> bool {
p.x.is_finite() && p.y.is_finite()
}
/// The resize cursor of `part`, turned with the view: up and down for the instances handle, along
/// the line from the center for the radius handle, and along the circle for the splitter.
fn part_cursor(cx: &ToolContext, h: &RadialHandles, part: RadialPart) -> Cursor {
match part {
RadialPart::Instances => crate::select::handle_cursor(Handle::Bottom, -cx.view_angle()),
RadialPart::Radius => crate::select::handle_cursor(Handle::Right, h.out_angle() - cx.view_angle()),
RadialPart::Splitter => crate::select::handle_cursor(Handle::Right, h.splitter_angle() - cx.view_angle()),
}
}
/// The cursor over a radial repeat's control at `p`, if one is there.
pub fn cursor(cx: &ToolContext, p: Point) -> Option<Cursor> {
let (h, part) = RadialHandles::hit(cx, p)?;
Some(part_cursor(cx, &h, part))
}
/// A drag of one of a radial repeat's controls.
#[derive(Clone, Debug)]
pub struct RadialDrag {
handles: RadialHandles,
part: RadialPart,
start: Point,
/// The options the press found, and the last ones previewed.
from: Value,
last: Option<Value>,
/// For the splitter: its degrees around the ring from the first instance, and the pointer's
/// last direction from the center.
turn: f64,
bearing: Option<f64>,
}
impl RadialDrag {
pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option<Self> {
if mods.cmd || mods.ctrl || mods.alt {
return None;
}
let (handles, part) = RadialHandles::hit(cx, p)?;
let from = handles.options(part, Vec2::ZERO)?;
Some(Self { handles, part, start: p, from, last: None, turn: handles.splitter_turn(), bearing: handles.bearing(p) })
}
/// Whether the drag has changed the repeat (and so previews it).
pub fn adjusting(&self) -> bool {
self.last.is_some()
}
pub fn cursor(&self, cx: &ToolContext) -> Cursor {
part_cursor(cx, &self.handles, self.part)
}
/// The options of the splitter with the pointer at `p`: it follows the pointer around the
/// circle, each move counted by the shorter way round.
fn split(&mut self, p: Point) -> Option<Value> {
let ring = self.handles.ring?;
if let Some(b) = self.handles.bearing(p) {
if let Some(last) = self.bearing {
self.turn += ((b - last + 180.0).rem_euclid(360.0) - 180.0) * ring.step.signum();
}
self.bearing = Some(b);
}
Some(ring.options(ring.shown(self.turn), self.handles.start_angle))
}
/// Preview the options the pointer at `p` gives, when they change; the first change opens
/// the undo step.
pub fn drag(&mut self, p: Point) -> Vec<Action> {
if !finite(p) {
return vec![];
}
let v = match self.part {
RadialPart::Splitter => self.split(p),
part => self.handles.options(part, p - self.start),
};
let Some(v) = v else { return vec![] };
if self.last.as_ref().unwrap_or(&self.from) == &v {
return vec![];
}
let mut out = vec![];
if self.last.is_none() {
out.push(Action::Begin("Repeat Options".into()));
}
out.push(Action::Preview("object.repeat.options".into(), v.clone()));
self.last = Some(v);
out
}
/// Commit the drag; one that ends where it began leaves no undo step.
pub fn finish(self) -> Vec<Action> {
match self.last {
Some(v) if v == self.from => vec![Action::Cancel],
Some(_) => vec![Action::Commit],
None => vec![],
}
}
pub fn cancel(self) -> Vec<Action> {
if self.last.is_some() { vec![Action::Cancel] } else { vec![] }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::{cx, doc_with_rect, paint};
use std::sync::Arc;
use vectorcraft_doc::pattern::RepeatSpec;
/// [`doc_with_rect`]'s 100 × 100 square at (100, 100) as a radial repeat of eight instances
/// with a radius of 100 pt about (150, 250), selected. The instances span (0, 100)–(300, 400).
fn radial() -> (Document, Selection) {
let (mut doc, id) = doc_with_rect();
let mut source = doc.node(id).unwrap().clone();
source.id = doc.alloc_id();
doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::radial(vec![Arc::new(source)], 8, Some(100.0)));
let mut selection = Selection::default();
selection.set([id]);
(doc, selection)
}
fn set(doc: &mut Document, selection: &Selection, f: impl FnOnce(&mut u32, &mut f64, &mut f64, &mut f64)) {
let NodeKind::Repeat(spec) = &mut doc.node_mut(selection.objects[0]).unwrap().kind else { panic!("a repeat") };
let RepeatKind::Radial { instances, radius, start_angle, end_angle, .. } = &mut spec.kind else { panic!("a radial repeat") };
f(instances, radius, start_angle, end_angle);
}
fn near(a: Point, b: Point) -> bool {
a.distance(b) < 1e-6
}
fn preview(out: &[Action]) -> Option<&Value> {
out.iter().find_map(|a| match a {
Action::Preview(cmd, v) if cmd == "object.repeat.options" => Some(v),
_ => None,
})
}
/// The point on the 100 pt circle about (150, 250) at `deg` degrees clockwise from straight up.
fn on_circle(deg: f64) -> Point {
let a = deg.to_radians();
Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos())
}
/// Apply the `instances` and `endAngle` of a preview to the repeat.
fn apply(doc: &mut Document, selection: &Selection, v: &Value) {
let n = v["instances"].as_u64().unwrap() as u32;
let end = v["endAngle"].as_f64().unwrap();
set(doc, selection, |i, _, _, e| (*i, *e) = (n, end));
}
/// Where the repeat's instances are, in paint order.
fn transforms(doc: &Document, selection: &Selection) -> Vec<Affine> {
let NodeKind::Repeat(spec) = &doc.node(selection.objects[0]).unwrap().kind else { panic!("a repeat") };
spec.transforms(Some(doc))
}
/// Drag the splitter from `from` to `to` degrees clockwise from straight up, 5° a move, and
/// return the last preview.
fn sweep(d: &mut RadialDrag, from: f64, to: f64) -> Option<Value> {
let mut last = None;
let moves = ((to - from).abs() / 5.0).ceil() as i32;
for k in 1..=moves {
if let Some(v) = preview(&d.drag(on_circle(from + (to - from) * f64::from(k) / f64::from(moves)))) {
last = Some(v.clone());
}
}
last
}
#[test]
fn the_handles_sit_below_the_repeat_and_on_its_circle_at_every_zoom() {
let (doc, selection) = radial();
// Halfway between the first instance (straight up from the center) and the second, 45°
// clockwise from it.
let on_circle = on_circle(22.5);
for zoom in [0.02, 1.0, 4.0] {
let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap();
assert!(near(h.instances_at, Point::new(150.0, 400.0 + HANDLE_GAP / zoom)), "{zoom}: {:?}", h.instances_at);
assert!(near(h.radius_at, on_circle), "{zoom}: {:?}", h.radius_at);
assert_eq!((h.center, h.radius), (Point::new(150.0, 250.0), 100.0));
}
// Placed below the bounding box the Selection tool shows.
let frame = OrientedBox::aligned(Rect::new(-10.0, 90.0, 310.0, 410.0));
let h = RadialHandles::of(&doc, &selection, Some(frame), 1.0).unwrap();
assert!(near(h.instances_at, Point::new(150.0, 410.0 + HANDLE_GAP)));
}
#[test]
fn the_radius_handle_follows_the_instances_angles() {
let (mut doc, selection) = radial();
// One instance: opposite it.
set(&mut doc, &selection, |n, _, _, _| *n = 1);
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.radius_at, Point::new(150.0, 350.0)), "{:?}", h.radius_at);
// Three instances over a quarter turn from 90°: between those at 90° and 135°.
set(&mut doc, &selection, |n, _, a, b| (*n, *a, *b) = (3, 90.0, 180.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
let a = 112.5_f64.to_radians();
assert!(near(h.radius_at, Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos())), "{:?}", h.radius_at);
// A radius of 0: at the center, still apart from the instances handle.
set(&mut doc, &selection, |_, r, _, _| *r = 0.0);
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.radius_at, Point::new(150.0, 250.0)));
assert!(h.radius_at.distance(h.instances_at) > 2.0 * REACH);
}
#[test]
fn no_handles_without_a_single_valid_radial_repeat() {
let (mut doc, mut selection) = radial();
for zoom in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert!(RadialHandles::of(&doc, &selection, None, zoom).is_none(), "{zoom}");
}
let paint = paint();
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
{
let mut c = cx(&doc, &selection, &paint);
assert!(cursor(&c, h.instances_at).is_some());
c.show_bbox = false;
assert!(cursor(&c, h.instances_at).is_none(), "the bounding box is hidden");
}
let id = selection.objects[0];
doc.node_mut(id).unwrap().locked = true;
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a locked repeat");
doc.node_mut(id).unwrap().locked = false;
doc.node_mut(id).unwrap().visible = false;
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a hidden repeat");
doc.node_mut(id).unwrap().visible = true;
for bad in [f64::NAN, f64::INFINITY] {
set(&mut doc, &selection, |_, r, _, _| *r = bad);
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "radius {bad}");
set(&mut doc, &selection, |_, r, a, _| (*r, *a) = (100.0, bad));
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "start angle {bad}");
set(&mut doc, &selection, |_, _, a, _| *a = 0.0);
}
let other = doc.alloc_id();
let mut second = doc.node(id).unwrap().clone();
second.id = other;
let layer = doc.layers[0].id;
doc.insert(Some(layer), 1, second).unwrap();
selection.set([id, other]);
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "two objects selected");
selection.set([id]);
let NodeKind::Repeat(spec) = &mut doc.node_mut(id).unwrap().kind else { panic!("a repeat") };
spec.kind = RepeatKind::Grid {
h_spacing: 10.0,
v_spacing: 10.0,
rows: 3,
cols: 3,
grid_type: Default::default(),
flip_rows: false,
flip_cols: false,
};
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a grid repeat");
}
#[test]
fn dragging_the_instances_handle_steps_the_count() {
let (doc, selection) = radial();
let paint = paint();
let mut c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert!(d.drag(h.instances_at + Vec2::new(0.0, 7.0)).is_empty(), "less than half a step changes nothing");
assert!(!d.adjusting());
// Two steps down, a little sideways: ten instances, one undo step.
let out = d.drag(h.instances_at + Vec2::new(5.0, 32.0));
assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}");
assert_eq!(preview(&out), Some(&json!({"instances": 10})));
assert!(d.drag(h.instances_at + Vec2::new(0.0, 36.0)).is_empty(), "the same count isn't previewed again");
assert!(d.adjusting());
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
// Far up: one instance at least; far down: 1,000 at most.
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 900.0))), Some(&json!({"instances": 1})));
assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 1e300))), Some(&json!({"instances": 1000})));
assert!(d.drag(Point::new(f64::NAN, 0.0)).is_empty(), "a non-finite pointer");
// Back where it began: no undo step.
assert_eq!(preview(&d.drag(h.instances_at)), Some(&json!({"instances": 8})));
assert!(matches!(d.finish().as_slice(), [Action::Cancel]));
// The step is the same on screen at every zoom: 16 px is a quarter point at 64.
c.zoom = 64.0;
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 0.25))), Some(&json!({"instances": 7})));
assert!(matches!(d.cancel().as_slice(), [Action::Cancel]));
// Alt, Cmd and Ctrl keep the Selection tool's own gestures.
assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none());
}
#[test]
fn dragging_the_radius_handle_moves_the_circle_in_and_out() {
let (doc, selection) = radial();
let paint = paint();
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let out = (h.radius_at - h.center) / 100.0;
let across = Vec2::new(-out.y, out.x);
let mut d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap();
// 25 pt out and 40 pt across: only the outward part counts.
let o = d.drag(h.radius_at + out * 25.0 + across * 40.0);
assert!(matches!(o.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{o:?}");
assert_eq!(preview(&o), Some(&json!({"radius": 125.0})));
assert!(d.drag(h.radius_at + across * 30.0).iter().any(|a| matches!(a, Action::Preview(_, v) if v == &json!({"radius": 100.0}))));
// Past the center: a radius of 0.
assert_eq!(preview(&d.drag(h.radius_at - out * 250.0)), Some(&json!({"radius": 0.0})));
// Too far to measure: nothing previewed.
assert!(d.drag(Point::new(f64::MAX, -f64::MAX)).is_empty());
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
// Escape before any change leaves nothing to undo.
let d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap();
assert!(d.cancel().is_empty());
}
#[test]
fn a_bounding_box_handle_wins_where_they_overlap() {
let (doc, selection) = radial();
let paint = paint();
let mut c = cx(&doc, &selection, &paint);
// Zoomed far out (the 300 pt repeat 6 px across), the radius handle lies on a
// bounding-box handle, which keeps its scaling; the instances handle stays clear of the box.
c.zoom = 0.02;
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
assert!(crate::select::bbox_handle_at(&c, h.radius_at));
assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_none());
assert!(cursor(&c, h.radius_at).is_none());
assert!(!crate::select::bbox_handle_at(&c, h.instances_at));
assert!(RadialDrag::hit(&c, h.instances_at, Mods::default()).is_some());
// At full size both are the repeat's, with resize cursors along their drags.
c.zoom = 1.0;
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_some());
assert_eq!(cursor(&c, h.instances_at), Some(Cursor::ResizeV));
// The radius handle points 22.5° clockwise from straight up: the up-and-down cursor.
assert_eq!(cursor(&c, h.radius_at), Some(Cursor::ResizeV));
}
#[test]
fn the_splitter_sits_half_a_step_past_the_last_instance_shown() {
let (mut doc, selection) = radial();
// A full ring of eight: between the last instance (315°) and the first.
for zoom in [0.02, 1.0, 4.0] {
let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(337.5)), "{zoom}: {:?}", h.splitter_at);
assert!(h.parts().contains(&(RadialPart::Splitter, h.splitter_at.unwrap())));
}
// Five of the eight shown: past the fifth (180°).
set(&mut doc, &selection, |n, _, _, e| (*n, *e) = (5, 180.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(202.5)), "{:?}", h.splitter_at);
// The instances running the other way from 90°: three of six, the splitter at -60 - 30.
set(&mut doc, &selection, |n, _, a, e| (*n, *a, *e) = (3, 90.0, -30.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(-60.0)), "{:?}", h.splitter_at);
// One of the eight shown: half a step past it, and the radius handle opposite it.
set(&mut doc, &selection, |n, _, a, e| (*n, *a, *e) = (1, 0.0, 45.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(22.5)), "{:?}", h.splitter_at);
assert!(near(h.radius_at, on_circle(180.0)), "{:?}", h.radius_at);
}
#[test]
fn no_splitter_where_the_ring_cannot_be_split() {
let (mut doc, selection) = radial();
// A single instance to a full turn, no turn at all, a step that does not divide a full
// turn, and a radius of 0.
for (n, end, r) in [(1, 360.0, 100.0), (2, 0.0, 100.0), (3, 100.0, 100.0), (8, 360.0, 0.0), (8, f64::MAX, 100.0)] {
set(&mut doc, &selection, |i, rad, _, e| (*i, *rad, *e) = (n, r, end));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert_eq!(h.splitter_at, None, "{n} over {end}° at {r}");
assert!(!h.parts().iter().any(|(p, _)| *p == RadialPart::Splitter));
}
// Two instances to a turn can be split.
set(&mut doc, &selection, |i, rad, _, e| (*i, *rad, *e) = (2, 100.0, 360.0));
assert!(RadialHandles::of(&doc, &selection, None, 1.0).unwrap().splitter_at.is_some());
}
#[test]
fn dragging_the_splitter_hides_instances_and_the_others_keep_their_places() {
let (mut doc, selection) = radial();
let full = transforms(&doc, &selection);
assert_eq!(full.len(), 8);
let paint = paint();
let (v, mut d) = {
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap();
assert!(cursor(&c, h.splitter_at.unwrap()).is_some());
// Back to 320°, short of the last instance: nothing changes.
assert_eq!(sweep(&mut d, 337.5, 320.0), None);
assert!(!d.adjusting());
// Back past the last instance (315°): seven shown, the full ring's step apart.
let out = d.drag(on_circle(300.0));
assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}");
let v = preview(&out).unwrap().clone();
assert_eq!(v, json!({"instances": 7, "endAngle": 270.0}));
(v, d)
};
apply(&mut doc, &selection, &v);
let seven = transforms(&doc, &selection);
assert_eq!(seven.len(), 7);
for (k, (a, b)) in seven.iter().zip(&full).enumerate() {
assert!(a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| (x - y).abs() < 1e-9), "instance {k} kept its place");
}
// Further back, past 0°: one shown at least.
assert_eq!(sweep(&mut d, 300.0, -200.0), Some(json!({"instances": 1, "endAngle": 45.0})));
// Forward again, past the start of the ring: all eight, a full turn.
assert_eq!(sweep(&mut d, -200.0, 400.0), Some(json!({"instances": 8, "endAngle": 360.0})));
assert!(matches!(d.finish().as_slice(), [Action::Cancel]), "back where it began: no undo step");
// From the seven shown, forward past 315°: the eighth shows again where it was.
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(292.5)));
let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap();
let v = sweep(&mut d, 292.5, 330.0).unwrap();
assert_eq!(v, json!({"instances": 8, "endAngle": 360.0}));
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap();
assert!(d.drag(h.center).is_empty(), "the center gives no direction");
assert_eq!(sweep(&mut d, 292.5, 250.0), Some(json!({"instances": 6, "endAngle": 225.0})));
assert!(matches!(d.cancel().as_slice(), [Action::Cancel]));
apply(&mut doc, &selection, &v);
assert_eq!(transforms(&doc, &selection), full);
}
#[test]
fn the_instances_handle_spreads_a_split_ring_over_the_same_arc() {
let (mut doc, selection) = radial();
// Seven of eight shown: the handle sets the count alone, as for any partial repeat.
set(&mut doc, &selection, |n, _, _, e| (*n, *e) = (7, 270.0));
let paint = paint();
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9})));
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
}
}
+38 -2
View File
@@ -147,6 +147,8 @@ enum State {
Mirror(crate::mirror::MirrorDrag),
/// Drag a grid repeat's row, column or corner handle or a spacing slider.
GridRepeat(crate::repeat_grid::GridDrag),
/// Drag a radial repeat's instances or radius handle.
RadialRepeat(crate::repeat_radial::RadialDrag),
/// Dragging a bracket of type on a path.
Bracket(BracketDrag),
/// Dragging a 9-slice guide of the symbol being edited.
@@ -826,6 +828,12 @@ impl Tool for SelectionTool {
{
return d.cancel();
}
if key == ToolKey::Escape
&& matches!(self.state, State::RadialRepeat(_))
&& let State::RadialRepeat(d) = std::mem::take(&mut self.state)
{
return d.cancel();
}
if key == ToolKey::Escape
&& matches!(self.state, State::NineSlice(_))
&& let State::NineSlice(d) = std::mem::take(&mut self.state)
@@ -875,7 +883,7 @@ impl Tool for SelectionTool {
State::Marquee { .. } => key == ToolKey::Letter('e'),
State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down),
State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right),
State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape,
State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape,
_ => false,
}
}
@@ -917,6 +925,7 @@ impl Tool for SelectionTool {
State::Bracket(b) => b.adjusting(),
State::Mirror(d) => d.adjusting(),
State::GridRepeat(d) => d.adjusting(),
State::RadialRepeat(d) => d.adjusting(),
_ => false,
}
}
@@ -1228,6 +1237,9 @@ impl Tool for SelectionTool {
if let State::GridRepeat(d) = &self.state {
return d.cursor(cx);
}
if let State::RadialRepeat(d) = &self.state {
return d.cursor(cx);
}
if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) {
return Cursor::Move;
}
@@ -1235,7 +1247,8 @@ impl Tool for SelectionTool {
&& !m.cmd
&& !m.ctrl
&& !m.alt
&& let Some(cursor) = crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p))
&& let Some(cursor) =
crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p))
{
return cursor;
}
@@ -1553,6 +1566,21 @@ impl SelectionTool {
_ => return Some(vec![]),
}
}
if let State::RadialRepeat(mut d) = self.state.clone() {
match ev.kind {
PointerKind::Drag | PointerKind::Up => {
let mut out = d.drag(ev.pos);
if ev.kind == PointerKind::Up {
out.extend(d.finish());
self.state = State::Idle;
} else {
self.state = State::RadialRepeat(d);
}
return Some(out);
}
_ => return Some(vec![]),
}
}
if matches!(self.state, State::Idle)
&& ev.kind == PointerKind::Down
&& let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods)
@@ -1569,6 +1597,14 @@ impl SelectionTool {
self.hover = None;
return Some(vec![]);
}
if matches!(self.state, State::Idle)
&& ev.kind == PointerKind::Down
&& let Some(d) = crate::repeat_radial::RadialDrag::hit(cx, ev.pos, ev.mods)
{
self.state = State::RadialRepeat(d);
self.hover = None;
return Some(vec![]);
}
None
}
+88 -2
View File
@@ -9,6 +9,10 @@
//! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a
//! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]).
//! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed.
//! Backtick (`` ` ``, the grave accent) held while dragging leaves a copy of the shape being drawn
//! every [`COPY_SPACING`] screen points the pointer travels, up to [`MAX_COPIES`] in one drag; the
//! release keeps the copies and the last shape as one undo step
//! (<https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469>).
//!
//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle,
//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at
@@ -38,6 +42,14 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool
/// value stop there too.
pub const MAX_CORNER_RADIUS: f64 = 1296.0;
/// How far (screen points) the pointer travels with Backtick held between two copies a shape drag
/// leaves: VectorCraft's own spacing.
pub const COPY_SPACING: f64 = 8.0;
/// The most copies one shape drag with Backtick held leaves, besides the shape it ends with:
/// VectorCraft's own limit.
pub const MAX_COPIES: usize = 128;
/// How far (screen points, along each axis) from a bounding-box handle's centre a shape tool's
/// press scales the selection: half the drawn handle square, which is 6 points wide at the default
/// Selection & Anchor Display › Size 3 and a point wider or narrower per step. The Selection tool
@@ -124,6 +136,12 @@ pub struct ShapeTool {
/// The move of the selection snapped to a point, a guide or the grid at its last step: the
/// arrow turns hollow, as the Selection tool's does.
snapped: bool,
/// The copies the drag has left with Backtick held, oldest first: each shape's command and
/// params as the drag showed it when the copy was left.
copies: Vec<(String, Value)>,
/// While Backtick is held in a drag, the pointer position the next copy is measured from: where
/// the last copy was left, or where the drag first had the key down.
copy_from: Option<Point>,
}
/// The options that keys and Ctrl/Cmd change while a shape is dragged out.
@@ -177,9 +195,56 @@ impl ShapeTool {
guides: vec![],
measure: None,
snapped: false,
copies: vec![],
copy_from: None,
}
}
/// With Backtick `held` at pointer `raw`, leave a copy of the shape the drag shows (`cmd` and
/// `params`) once the pointer is [`COPY_SPACING`] screen points from the last copy, or from
/// where the key was first held. A shape with no width, height or length, one the same as the
/// last copy, and any past [`MAX_COPIES`] are not left. Without the key, the next copy is
/// measured from where it goes down again.
fn leave_copy(&mut self, cx: &ToolContext, raw: Point, held: bool, cmd: &str, params: &Value) {
if !held {
self.copy_from = None;
return;
}
let Some(from) = self.copy_from else {
self.copy_from = Some(raw);
return;
};
let (x, y) = screen_offset(cx, raw - from);
if x.hypot(y) < COPY_SPACING || self.copies.len() >= MAX_COPIES || !draws_something(cmd, params) {
return;
}
self.copy_from = Some(raw);
if self.copies.last().is_some_and(|(c, p)| c == cmd && p == params) {
return;
}
self.copies.push((cmd.to_owned(), params.clone()));
}
/// The preview of the shape `cmd` with `params`: with copies left, a `command.batch` that draws
/// them and then the shape, unless it has no size or is the same as the last copy.
fn preview(&self, cmd: String, params: Value) -> Action {
if self.copies.is_empty() {
return Action::Preview(cmd, params);
}
let step = |c: &str, p: &Value| json!({ "command": c, "params": p });
let mut commands: Vec<Value> = self.copies.iter().map(|(c, p)| step(c, p)).collect();
if draws_something(&cmd, &params) && self.copies.last().is_none_or(|(c, p)| *c != cmd || *p != params) {
commands.push(step(&cmd, &params));
}
Action::Preview("command.batch".into(), json!({ "label": self.label(), "commands": commands }))
}
/// Forget the copies of the drag that ended.
fn clear_copies(&mut self) {
self.copies.clear();
self.copy_from = None;
}
fn drag_options(&self) -> DragOptions {
DragOptions { sides: self.sides, points: self.points, corner_radius: self.corner_radius, star_ratio: self.star_ratio }
}
@@ -500,6 +565,19 @@ impl ShapeTool {
}
}
/// Does the shape command `cmd` with `params` draw something: a box with a width and a height, a
/// polygon or star with a radius, a line with a length?
fn draws_something(cmd: &str, params: &Value) -> bool {
let n = |k: &str| params.get(k).and_then(Value::as_f64).unwrap_or(0.0);
match cmd {
// The drag gives a polygon or star a radius of at least 0.01 pt, even on its centre.
"shape.polygon" => n("radius") > 0.01,
"shape.star" => n("radius1") > 0.01,
"shape.line" => (n("x2") - n("x1")).hypot(n("y2") - n("y1")) > 0.0,
_ => n("width").abs() > 0.0 && n("height").abs() > 0.0,
}
}
/// The box a drag from `start` to `p` draws (from its centre with Alt, square with Shift),
/// measured along the page axes turned by Constrain Angle `base`: the box in those axes, and the
/// axes (`None` for the page's own: 0° or a whole turn, where the box is on the page exactly).
@@ -597,6 +675,11 @@ impl Tool for ShapeTool {
self.began = false;
self.inner = None;
self.before_drag = None;
self.clear_copies();
// Backtick already held at the press: the copies are measured from there.
if ev.backquote {
self.copy_from = Some(ev.pos);
}
vec![]
}
PointerKind::Drag => {
@@ -653,7 +736,8 @@ impl Tool for ShapeTool {
};
let (a, b) = tangent.unwrap_or((s, ev.pos));
let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle);
out.push(Action::Preview(c, v));
self.leave_copy(cx, raw, ev.backquote, &c, &v);
out.push(self.preview(c, v));
out
}
PointerKind::Up => {
@@ -662,6 +746,7 @@ impl Tool for ShapeTool {
self.tangent_line.clear();
self.inner = None;
self.before_drag = None;
self.clear_copies();
if self.began {
self.began = false;
vec![Action::Commit]
@@ -724,11 +809,12 @@ impl Tool for ShapeTool {
};
if changed {
let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle);
vec![Action::Preview(c, v)]
vec![self.preview(c, v)]
} else if key == ToolKey::Escape {
self.start = None;
self.began = false;
self.inner = None;
self.clear_copies();
if let Some(o) = self.before_drag.take() {
self.restore_drag_options(o);
}
+182
View File
@@ -1372,3 +1372,185 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() {
assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["matrix"][4] == json!(10.0)), "{a:?}");
assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow);
}
/// A drag event to `(x, y)` with Backtick held or not.
fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent {
PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) }
}
/// The shapes the last preview in `a` draws, as their commands and params: the steps of a
/// `command.batch`, or the one shape. The bool says whether it was a batch.
fn previewed_shapes(a: &[Action]) -> (bool, Vec<(String, Value)>) {
match a.last() {
Some(Action::Preview(c, v)) if c == "command.batch" => {
assert!(v.get("commands").and_then(Value::as_array).is_some(), "{v}");
let steps = v["commands"].as_array().into_iter().flatten();
(true, steps.map(|s| (s["command"].as_str().unwrap_or_default().to_owned(), s["params"].clone())).collect())
}
Some(Action::Preview(c, v)) => (false, vec![(c.clone(), v.clone())]),
_ => panic!("no preview: {a:?}"),
}
}
/// The widths of the rectangles the last preview in `a` draws, and whether it was a batch.
fn previewed_widths(a: &[Action]) -> (bool, Vec<f64>) {
let (batch, shapes) = previewed_shapes(a);
(batch, shapes.iter().map(|(_, p)| p["width"].as_f64().unwrap_or(f64::NAN)).collect())
}
/// Backtick held while a rectangle is dragged out leaves a copy every 8 screen points the pointer
/// travels from where the key was first held or the last copy was left; the shape being drawn
/// still follows the pointer. A key press without pointer travel leaves none, letting go stops
/// the copies and keeps those left, and pressing it again starts measuring afresh. The release
/// commits once.
#[test]
fn backtick_drag_leaves_copies_of_the_rectangle_being_drawn() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, false))), (false, vec![40.0]));
// The key goes down with the pointer still: no copy.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, true))), (false, vec![40.0]));
// 4 pt of travel is short of the spacing.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(54.0, 30.0, true))), (false, vec![44.0]));
// 10 pt: a copy, the same as the shape shown, so the batch draws it once.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(60.0, 30.0, true))), (true, vec![50.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(70.0, 30.0, true))), (true, vec![50.0, 60.0]));
// 5 pt past the last copy: none left, and the live shape follows.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(75.0, 30.0, true))), (true, vec![50.0, 60.0, 65.0]));
// Let go of the key: the copies stay and no more are left.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(90.0, 30.0, false))), (true, vec![50.0, 60.0, 80.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(120.0, 30.0, false))), (true, vec![50.0, 60.0, 110.0]));
// Pressed again: measured from where it went down.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(125.0, 30.0, true))), (true, vec![50.0, 60.0, 115.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(135.0, 30.0, true))), (true, vec![50.0, 60.0, 125.0]));
assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 135.0, 30.0) }), vec![Action::Commit]);
// The next drag starts with no copies.
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, false))), (false, vec![40.0]));
}
/// Backtick already held at the press measures the first copy from the pressed spot: the first
/// drag 10 pt away leaves one, and 5 pt more leaves none.
#[test]
fn backtick_held_at_the_press_measures_copies_from_there() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Down, 0.0, 0.0) });
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(10.0, 10.0, true))), (true, vec![10.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(15.0, 10.0, true))), (true, vec![10.0, 15.0]));
assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 15.0, 10.0) }), vec![Action::Commit]);
}
/// Every shape tool leaves copies of its own shape, drawn with the modifiers held when each copy
/// was left: Shift's square stays square, and Alt's from the centre stays centred.
#[test]
fn backtick_drag_leaves_copies_with_every_shape_tool_and_its_modifiers() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
for (id, cmd) in [
("rectangle", "shape.rectangle"),
("roundedRectangle", "shape.rectangle"),
("ellipse", "shape.ellipse"),
("polygon", "shape.polygon"),
("star", "shape.star"),
("lineSegment", "shape.line"),
] {
let mut t = ShapeTool::new(id);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(140.0, 130.0, true));
t.pointer(&c, &quote_drag(160.0, 130.0, true));
let (batch, shapes) = previewed_shapes(&t.pointer(&c, &quote_drag(180.0, 140.0, true)));
assert!(batch, "{id}");
assert_eq!(shapes.len(), 2, "{id}: two copies, the second the shape shown: {shapes:?}");
assert!(shapes.iter().all(|(c, _)| c == cmd), "{id}: {shapes:?}");
assert_ne!(shapes[0].1, shapes[1].1, "{id}: each copy as the drag showed it then");
}
// Shift and Alt: each copy is the square drawn from the centre at that moment.
let shift_alt = Mods { shift: true, alt: true, ..Default::default() };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(130.0, 120.0, true).with_mods(shift_alt));
let (_, shapes) = previewed_shapes(&t.pointer(&c, &quote_drag(150.0, 120.0, true).with_mods(shift_alt)));
let (_, r) = &shapes[0];
assert_eq!(r["width"], r["height"], "square: {r}");
assert_eq!(r["x"].as_f64().unwrap_or_default() + r["width"].as_f64().unwrap_or_default() / 2.0, 100.0, "centred: {r}");
}
/// ↑ during a polygon drag with copies left changes only the shape being drawn; Escape cancels
/// the copies with it, and the next drag starts without them.
#[test]
fn backtick_copies_keep_their_sides_and_escape_cancels_them() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("polygon");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(140.0, 100.0, true));
t.pointer(&c, &quote_drag(150.0, 100.0, true));
let (batch, shapes) = previewed_shapes(&t.key(&c, ToolKey::Up, Mods::default()));
assert!(batch);
let sides: Vec<_> = shapes.iter().map(|(_, p)| p["sides"].clone()).collect();
assert_eq!(sides, vec![json!(6), json!(7)], "the copy keeps its sides");
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
let (batch, _) = previewed_shapes(&t.pointer(&c, &quote_drag(140.0, 100.0, false)));
assert!(!batch, "no copies after Escape");
}
/// No copy is left of a shape without a height or a length, and one drag leaves at most
/// [`MAX_COPIES`] copies while the shape being drawn still follows the pointer.
#[test]
fn backtick_copies_skip_empty_shapes_and_stop_at_the_limit() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
// A rectangle with no height: nothing is left.
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
for x in [30.0, 40.0, 50.0, 60.0] {
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(x, 10.0, true))).0, "{x}");
}
// A line back on its start: no copy there.
let mut t = ShapeTool::new("lineSegment");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
t.pointer(&c, &quote_drag(30.0, 10.0, true));
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(10.0, 10.0, true))).0);
// The limit.
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &quote_drag(10.0, 10.0, true));
let mut last = vec![];
for i in 1..=(MAX_COPIES as u32 + 20) {
let at = 10.0 + f64::from(i) * 10.0;
last = t.pointer(&c, &quote_drag(at, at, true));
}
let (batch, widths) = previewed_widths(&last);
assert!(batch);
assert_eq!(widths.len(), MAX_COPIES + 1, "the copies and the shape being drawn");
assert_eq!(widths.last(), Some(&(10.0 + f64::from(MAX_COPIES as u32 + 20) * 10.0)), "the shape follows the pointer");
}
/// The spacing is measured on screen: at 400% zoom, 2 pt of travel is 8 screen points.
#[test]
fn backtick_copy_spacing_is_measured_on_screen() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, zoom: 4.0, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
t.pointer(&c, &quote_drag(20.0, 20.0, true));
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(21.5, 20.0, true))).0, "6 screen points");
assert!(previewed_shapes(&t.pointer(&c, &quote_drag(22.0, 20.0, true))).0, "8 screen points");
}
+194
View File
@@ -966,6 +966,168 @@ fn a_gray_between_black_and_white_is_one_shape() {
}
}
/// Flat Logo with the black of the tests below, `gray` and white named exactly.
fn black_gray_white(gray: [u8; 3]) -> TraceParams {
let logo_colors = vec!["#040403".into(), format!("#{:02X}{:02X}{:02X}", gray[0], gray[1], gray[2]), "#FFFFFF".into()];
TraceParams { logo_colors, ..logo_params() }
}
/// A black disc and a gray square on white, blurred by 1 to 3 pixels: the edge pixels around the
/// disc as light as the gray read as blends of black and white, so the gray is one shape (the
/// square) and no gray lines the disc, with the colors found or named. At a blur of 3 pixels, with
/// the colors named, a gray of 128 is still one shape, a gray of 200 leaves 4 slivers of no area,
/// and a light gray (230) leaves at most 8 slivers, touching the disc's edge at no more than 4 of
/// 192 samples. (Without named colors, an image blurred by 3 pixels traces without its gray.)
#[test]
fn blurred_black_edges_beside_gray_leave_no_gray_slivers() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
for blur in [1.0, 1.5, 2.0, 3.0] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 30.0).hypot(y - 30.0) <= 20.0 {
INK
} else if (60.0..=110.0).contains(&x) && (10.0..=50.0).contains(&y) {
gray
} else {
WHITE
})
});
for by_name in [false, true] {
if !by_name && blur > 2.0 {
continue;
}
let res = trace(&img, &if by_name { black_gray_white(gray) } else { logo_params() });
let what = format!("gray {}, blur {blur}, named {by_name}", gray[0]);
let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect();
assert_eq!(top_color(&res, Point::new(85.0, 30.0)), Some(gray), "{what}: the square; {paths:?}");
let mut rim = 0;
for r in [19.0, 20.0, 21.0] {
for k in 0..64 {
let a = f64::from(k) * std::f64::consts::TAU / 64.0;
if top_color(&res, Point::new(30.0 + r * a.cos(), 30.0 + r * a.sin())) == Some(gray) {
rim += 1;
}
}
}
let mut grays: Vec<_> = res.paths.iter().filter(|t| t.color == gray).map(|t| t.pixels).collect();
grays.sort_unstable();
grays.pop();
match (gray[0], blur == 3.0) {
(230, true) => {
assert!(grays.len() <= 8, "{what}: {} slivers; {paths:?}", grays.len());
assert!(rim <= 4, "{what}: {rim} of 192 samples along the disc's edge traced gray");
}
(200, true) => {
assert!(grays.len() <= 4 && grays.iter().all(|&n| n == 0), "{what}: slivers {grays:?}");
assert_eq!(rim, 0, "{what}: samples along the disc's edge traced gray");
}
_ => {
assert!(grays.is_empty(), "{what}: slivers {grays:?}; {paths:?}");
assert_eq!(rim, 0, "{what}: samples along the disc's edge traced gray");
}
}
}
}
}
}
/// A soft-edged gray band 2 to 4 pixels wide lying along a black disc, blurred by 1.5 or 2 pixels,
/// traces as black and white: its pixels are reached from the disc and from the white through
/// pixels that keep getting darker and lighter, as across a blurred black-to-white edge. A band 8
/// pixels wide keeps at least half of its gray. With sharp edges every band stays gray.
#[test]
fn a_soft_gray_band_along_black_traces_as_black_and_white() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
for blur in [0.0, 1.5, 2.0] {
for wide in [2u8, 3, 4, 8] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (40.0..43.0 + f64::from(wide)).contains(&x) && (20.0..36.0).contains(&y) {
gray
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(gray));
// The band's samples: 16 rows of its `wide` columns outside the disc.
let kept = (0..wide)
.flat_map(|c| (20..36).map(move |y| Point::new(43.5 + f64::from(c), f64::from(y) + 0.5)))
.filter(|&at| top_color(&res, at) == Some(gray))
.count();
let all = 16 * usize::from(wide);
let what = format!("gray {}, blur {blur}, {wide} px band: {kept} of {all} samples traced gray", gray[0]);
if blur == 0.0 {
assert_eq!(kept, all, "{what}");
} else if wide <= 4 {
assert_eq!(kept, 0, "{what}");
} else {
assert!(2 * kept >= all, "{what}");
}
}
}
}
}
/// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred
/// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest.
#[test]
fn a_soft_gray_spoke_loses_a_few_pixels_where_it_meets_black() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [128, 128, 128]] {
for blur in [1.0, 1.5] {
for wide in [2.0, 3.0] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (38.0..90.0).contains(&x) && (27.0..27.0 + wide).contains(&y) {
gray
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(gray));
let at = |x: i32| Point::new(f64::from(x) + 0.5, 27.0 + wide / 2.0);
let near = (44..60).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
let far = (60..86).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
let what = format!("gray {}, blur {blur}, {wide} px spoke", gray[0]);
assert!((12..=13).contains(&near), "{what}: {near} of the 16 samples nearest the disc traced gray");
assert_eq!(far, 26, "{what}: the rest of the spoke");
}
}
}
}
/// A soft-edged light gray stroke 2 pixels wide beside a black disc, blurred by 1.5 pixels: 2
/// pixels from the disc it keeps less than half of its gray, 4 pixels away it loses a few pixels,
/// and 6 or 8 pixels away it keeps all of it.
#[test]
fn a_soft_gray_stroke_near_black_loses_gray_by_its_distance() {
const INK: [u8; 3] = [4, 4, 3];
const GRAY: [u8; 3] = [230, 230, 230];
for gap in [2, 4, 6, 8] {
let x0 = 43.0 + f64::from(gap);
let img = render(120, 60, 1.5, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (x0..x0 + 2.0).contains(&x) && (8.0..50.0).contains(&y) {
GRAY
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(GRAY));
let kept = (12..46).filter(|&y| top_color(&res, Point::new(x0 + 1.0, f64::from(y) + 0.5)) == Some(GRAY)).count();
let what = format!("{gap} px from the disc: {kept} of 34 samples traced gray");
match gap {
2 => assert!(2 * kept < 34, "{what}"),
4 => assert!((24..34).contains(&kept), "{what}"),
_ => assert_eq!(kept, 34, "{what}"),
}
}
}
/// A one-pixel gray line between flat black and flat white, with the three colors named, stays a
/// gray line along its whole length, beside a black disc whose edge pixels are as light as the gray.
#[test]
@@ -1158,3 +1320,35 @@ fn a_noisy_hard_edged_gray_between_black_and_white_is_one_shape() {
}
}
}
#[test]
fn a_disc_on_a_gray_panel_on_a_paler_ground_has_no_slivers_of_the_ground() {
// The panel's gray lies on the line from the ground's gray to the disc's charcoal, so the disc's
// edge pixels are also a mix of the ground and the disc.
let (ground, panel, disc) = ([240, 240, 240], [200, 200, 200], [60, 60, 60]);
for blur in [0.0, 0.7] {
let grays = render(150, 150, blur, move |x, y| {
let (cx, cy) = (x.clamp(35.0, 115.0), y.clamp(35.0, 115.0));
Some(if (x - 75.0).hypot(y - 75.0) < 30.0 {
disc
} else if (20.0..130.0).contains(&x) && (20.0..130.0).contains(&y) && (x - cx).hypot(y - cy) < 15.0 {
panel
} else {
ground
})
});
for named in [false, true] {
let logo_colors = if named { vec!["#F0F0F0".into(), "#C8C8C8".into(), "#3C3C3C".into()] } else { Vec::new() };
let res = trace(&grays, &TraceParams { logo_colors, ..logo_params() });
let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect();
assert_eq!(res.paths.len(), 3, "blur {blur}, named {named}: one path per color; {paths:?}");
for k in 0..16 {
let a = f64::from(k) * std::f64::consts::TAU / 16.0;
let at = Point::new(75.0 + 31.0 * a.cos(), 75.0 + 31.0 * a.sin());
assert_eq!(top_color(&res, at), Some(panel), "blur {blur}, named {named}: beside the disc at {at:?}");
}
assert_eq!(top_color(&res, Point::new(8.0, 75.0)), Some(ground), "blur {blur}, named {named}: the ground");
assert_eq!(top_color(&res, Point::new(75.0, 75.0)), Some(disc), "blur {blur}, named {named}: the disc");
}
}
}
+217 -31
View File
@@ -5,8 +5,10 @@
//! runs, so each pixel is instead explained as a mix of at most three classes, whichever mix
//! reproduces the pixel best. When another mix also reproduces it (with a gray between black and
//! white among the classes, a black-to-white edge pixel is a mix of black and gray as well as of
//! black and white), the pixel takes the mix whose classes lie nearest it in the flat areas around it,
//! when its neighbors show an edge between those classes.
//! black and white, and a gray-to-black edge pixel is a mix of white and black as well as of gray
//! and black), the pixel takes the mix whose classes lie nearest it in the flat areas around it,
//! or, on an edge blurred over several pixels, along the pixels that lead across the edge, when its
//! neighbors show an edge between those classes.
use std::collections::{HashMap, HashSet};
@@ -21,6 +23,8 @@ const PURE: f64 = 4.0 / 255.0;
const REPRODUCES: f64 = PURE * PURE;
/// How far (in pixels, each way) a class is looked for around a pixel that two mixes reproduce.
const NEARBY: usize = 6;
/// How many steps a path across an edge takes at most ([`across_edge`]).
const WALK: usize = 5;
/// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area.
const FLAT: f64 = 1.5 / 255.0;
/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a
@@ -199,9 +203,11 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
if tied.is_empty() {
return (planes, residual, switched);
}
// A pixel two mixes reproduce takes another mix of two classes whose farthest class lies nearer
// it than the best mix's does, in the flat areas around it ([`flat_classes`], [`RowDistances::around`]),
// when the pixel lies on an edge between that mix's classes ([`across_edge`]). For the best mix,
// A pixel two mixes reproduce takes another mix of two classes, when the pixel lies on an edge
// between that mix's classes ([`across_edge`]) and that mix lies nearer it than the best mix
// does. A mix lies as near as its farthest class in the flat areas around the pixel
// ([`flat_classes`], [`RowDistances::around`]); the other mix lies as near as the steps that
// `across_edge` counts when those are fewer. For the best mix,
// the classes held by flat areas between two classes count as well ([`between_classes`]). A
// pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class
// (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white.
@@ -217,7 +223,11 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
continue;
}
let Some(mixes) = mixed.get(&key) else { continue };
let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, width, height, i, classes, &mixes.best, m)).collect();
let edges: Vec<(&Weights, usize)> = mixes
.tied
.iter()
.filter_map(|m| across_edge(pix, (&flat, &stands_for), (width, height), i, classes, &mixes.best, m).map(|r| (m, r)))
.collect();
if edges.is_empty() {
continue;
}
@@ -230,8 +240,8 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
}
}
let now = farthest(&mixes.best, &kept);
let other = edges.into_iter().filter(|m| farthest(m, &dist) < now).min_by_key(|m| farthest(m, &dist));
if let Some(other) = other {
let other = edges.into_iter().map(|(m, r)| (m, farthest(m, &dist).min(r))).filter(|&(_, d)| d < now).min_by_key(|&(_, d)| d);
if let Some((other, _)) = other {
switched.push((i, planes.iter().map(|pl| pl.get(i).copied().unwrap_or(0.0)).collect()));
// (`residual` keeps the best mix's error; the mix taken comes within `REPRODUCES` of the
// pixel as well.)
@@ -243,17 +253,39 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
}
/// Whether pixel `i` lies on an edge between the two classes of `other`, rather than in an area of
/// a class of `best` that `other` leaves out: for each such class, the pixel has a neighbor beyond
/// it toward each class of `other`, along the line between them. (A black-to-white edge pixel as
/// light as a gray has a darker neighbor and a lighter one; a gray stroke on white has no neighbor
/// darker than the gray.)
fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f64; 4]], best: &Weights, other: &Weights) -> bool {
let [(a, _), (b, _)] = other.as_slice() else { return false };
let (Some(ca), Some(cb)) = (classes.get(*a), classes.get(*b)) else { return false };
/// a class of `best` that `other` leaves out. For a class left out that lies between the classes of
/// `other` on the line between them, a path of pixels from `i` that keeps going toward one class of
/// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so
/// does one that keeps going toward the other. For a class left out that lies beyond both classes of
/// `other` on that line, the pixel has a neighbor on each side of that class, or a neighbor on each
/// side of the pixel itself, none past the class of `other` nearer the class left out, and a chain
/// of neighbors from the pixel to that nearer class or a flat area of it (`flat`), each nearer it
/// than the one before. (A black-to-white edge pixel as light as a gray has a darker neighbor and a
/// lighter one, or, on an edge blurred over several pixels, reaches darker and lighter pixels through
/// pixels that keep getting darker or lighter; from a gray stroke on white, a path that keeps getting
/// darker ends in the stroke, at the gray; a gray-to-black edge pixel has a lighter neighbor and a
/// darker one, and lighter pixels lead to the flat gray; a pale line one pixel wide on black has only
/// darker neighbors; the pixels beside a blurred pale line's middle reach no flat gray; and a white
/// gap between black and gray has a neighbor lighter than the gray.)
///
/// When it does, the number of steps the longer of the two paths takes to a pixel that stands for its
/// class of `other` (`stands_for`), the largest over the classes left out. It is `NEARBY + 1` when a
/// path does not come to such a pixel, and when a class left out lies beyond both classes of `other`.
fn across_edge(
pix: &[Px],
(flat, stands_for): (&[Option<usize>], &[Option<usize>]),
(width, height): (usize, usize),
i: usize,
classes: &[[f64; 4]],
best: &Weights,
other: &Weights,
) -> Option<usize> {
let [(a, _), (b, _)] = other.as_slice() else { return None };
let (ca, cb) = (classes.get(*a)?, classes.get(*b)?);
let ab: [f64; 4] = std::array::from_fn(|j| cb[j] - ca[j]);
let len2: f64 = ab.iter().map(|v| v * v).sum();
if len2 <= 1e-12 {
return false;
return None;
}
let len = len2.sqrt();
// Where `v` lies along the line from `a` to `b` (0 at `a`, 1 at `b`), and how far off it.
@@ -262,22 +294,102 @@ fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f6
let off = (0..4).map(|j| (v[j] - ca[j] - t * ab[j]).powi(2)).sum::<f64>().sqrt();
(t, off)
};
let (x, y) = (i % width.max(1), i / width.max(1));
let neighbors: Vec<f64> = (y.saturating_sub(1)..(y + 2).min(height))
.flat_map(|yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx))
.filter(|&j| j != i)
.filter_map(|j| pix.get(j))
.map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])]))
.filter(|&(_, off)| off <= 2.0 * PURE)
.map(|(t, _)| t)
.collect();
// Where pixel `j` lies along the line, when it lies within `2 * PURE` of it.
let at = |j: usize| {
pix.get(j)
.map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])]))
.filter(|&(_, off)| off <= 2.0 * PURE)
.map(|(t, _)| t)
};
// The pixels around pixel `j`.
let around = |j: usize| {
let (x, y) = (j % width.max(1), j / width.max(1));
(y.saturating_sub(1)..(y + 2).min(height))
.flat_map(move |yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx))
.filter(move |&n| n != j)
};
let neighbors: Vec<f64> = around(i).filter_map(at).collect();
let left_out: Vec<usize> = best.iter().filter(|&&(c, w)| w > 0.0 && c != *a && c != *b).map(|&(c, _)| c).collect();
!left_out.is_empty()
&& left_out.iter().all(|&c| {
let Some(&cv) = classes.get(c) else { return false };
let (tc, _) = place(cv);
neighbors.iter().any(|&t| (tc - t) * len > PURE) && neighbors.iter().any(|&t| (t - tc) * len > PURE)
})
// Whether the pixel has a neighbor on each side of place `t` along the line.
let straddled = |t: f64| neighbors.iter().any(|&tn| (t - tn) * len > PURE) && neighbors.iter().any(|&tn| (tn - t) * len > PURE);
// Whether pixel `j`, at place `t`, lies within `PURE` of class `c` (at place `to`), or in a flat
// area of class `c` ([`flat_classes`]), or beside one and within `PURE` of its color along the
// line (as when `c` is named some levels off the area's color).
let touches = |j: usize, t: f64, c: usize, to: f64| {
let in_c = |n: usize| flat.get(n).copied().flatten() == Some(c);
(t - to).abs() * len <= PURE || in_c(j) || around(j).any(|n| in_c(n) && at(n).is_some_and(|tn| (tn - t).abs() * len <= PURE))
};
// Whether a chain of neighbors from the pixel, each nearer place `to` than the one before and
// none past it (`past`), comes to class `c` ([`touches`]) in at most `NEARBY` steps. (From a
// pixel beside a pale line's middle, the middle is the only neighbor nearer the gray, and it has
// none, and it is far from the gray.)
let reaches = |to: f64, c: usize, past: &dyn Fn(f64) -> bool| {
let Some(t) = at(i) else { return false };
let mut front = vec![(i, t)];
let mut seen = HashSet::from([i]);
for step in 0..=NEARBY {
let mut next = Vec::new();
for &(j, t) in &front {
if touches(j, t, c, to) {
return true;
}
if step < NEARBY {
for n in around(j) {
if let Some(tn) = at(n).filter(|&tn| !past(tn) && (tn - to).abs() < (t - to).abs())
&& seen.insert(n)
{
next.push((n, tn));
}
}
}
}
if next.is_empty() {
return false;
}
front = next;
}
false
};
// A path from `i` toward `a` (`toward` -1) or `b` (`toward` 1): each step goes to the neighbor
// near the line that lies farthest that way, while it lies farther than the pixel before (the
// first step is taken whatever `i` itself is). `None` when it does not get more than `PURE` past
// `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that stands for `class`
// (`stands_for`), or `NEARBY + 1`.
let walk = |toward: f64, tc: f64, class: usize| {
let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward);
let mut past = false;
for step in 1..=WALK {
match around(cur).filter_map(|j| at(j).map(|tj| (j, tj))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward))) {
Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj),
_ => break,
}
past = past || (t - tc) * toward * len > PURE;
if past && stands_for.get(cur).copied().flatten() == Some(class) {
return Some(step);
}
}
past.then_some(NEARBY + 1)
};
if left_out.is_empty() {
return None;
}
let mut reach = 0;
for &c in &left_out {
let (tc, _) = place(*classes.get(c)?);
if (0.0..=1.0).contains(&tc) {
let ra = walk(-1.0, tc, *a)?;
let rb = walk(1.0, tc, *b)?;
reach = reach.max(ra.max(rb));
continue;
}
let beyond = |tn: f64| if tc < 0.0 { -tn * len > PURE } else { (tn - 1.0) * len > PURE };
let (to, near) = if tc < 0.0 { (0.0, *a) } else { (1.0, *b) };
if !(straddled(tc) || !neighbors.iter().any(|&tn| beyond(tn)) && at(i).is_some_and(straddled) && reaches(to, near, &beyond)) {
return None;
}
reach = NEARBY + 1;
}
Some(reach)
}
/// How far the farthest class of `mix` lies, by the distances `dist` ([`RowDistances::around`]).
@@ -670,6 +782,80 @@ mod tests {
}
}
#[test]
fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() {
// A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway
// to charcoal, flat charcoal. The edge pixel is a mix of the gray and the charcoal, with none
// of the ground in it.
let g = |v: f64| [v / 255.0, v / 255.0, v / 255.0, 1.0];
let classes = vec![g(240.0), g(200.0), g(60.0), [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]];
let px = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0];
let mut pix = vec![px(200.0); 5];
pix.push(px(130.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix, 11, 1, &classes);
assert_eq!(pl[0][5], 0.0, "ground in the edge pixel");
assert!((pl[1][5] - 0.5).abs() < 0.02 && (pl[2][5] - 0.5).abs() < 0.02, "gray {} charcoal {}", pl[1][5], pl[2][5]);
// The cases below are vertical lines: three rows alike, read in the middle row.
// The same edge with the panel's pixels three levels darker than the named gray.
let mut pix = vec![px(197.0); 5];
pix.push(px(130.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes);
assert_eq!(pl[0][11 + 5], 0.0, "ground in the edge pixel beside a gray three levels off");
// An edge pixel whose lightest neighbor leads nowhere, with another chain of lighter pixels
// to the gray.
let outer = [vec![px(200.0); 5], vec![px(170.0)], vec![px(60.0); 7]].concat();
let middle = [vec![px(200.0); 5], vec![px(170.0), px(130.0), px(180.0)], vec![px(60.0); 5]].concat();
let (pl, _, _) = unmix(&[outer.clone(), middle, outer].concat(), 13, 3, &classes);
assert_eq!(pl[0][13 + 6], 0.0, "ground in the edge pixel beside a dead end");
// A pixel half ground and half charcoal between charcoal pixels, flat gray three pixels off:
// a thin pale line on the charcoal, kept.
let mut pix = vec![px(200.0); 3];
pix.extend([px(60.0); 2]);
pix.push(px(150.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes);
assert!((pl[0][11 + 5] - 0.5).abs() < 0.02, "the line: ground {}", pl[0][11 + 5]);
// A gap of the ground's color one pixel wide between flat charcoal and flat gray: the pixel
// half charcoal and half ground beside it keeps its ground.
let mut pix = vec![px(60.0); 5];
pix.extend([px(150.0), px(236.0)]);
pix.extend([px(200.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 12, 3, &classes);
assert!((pl[0][12 + 5] - 0.5).abs() < 0.02, "the gap: ground {}", pl[0][12 + 5]);
// A pale line blurred over three pixels on the charcoal, flat gray five pixels off: the pixels
// beside its middle have a lighter neighbor and a darker one, and keep their ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(60.0); 3]);
pix.extend([px(103.0), px(154.0), px(103.0)]);
pix.extend([px(60.0); 9]);
let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes);
for j in [20 + 8, 20 + 10] {
assert!((pl[0][j] - 43.0 / 180.0).abs() < 0.02 && pl[1][j] == 0.0, "the blurred line at {j}: ground {} gray {}", pl[0][j], pl[1][j]);
}
// A pale line one pixel wide that falls between two pixels, covering half of one and three
// quarters of the other: both pixels keep their ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(60.0); 3]);
pix.extend([px(150.0), px(195.0)]);
pix.extend([px(60.0); 10]);
let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes);
for (j, want) in [(20 + 8, 0.5), (20 + 9, 0.75)] {
let (ground, gray) = (pl[0][j], pl[1][j]);
assert!((ground - want).abs() < 0.02 && gray == 0.0, "the line between pixels at {j}: ground {ground} gray {gray}");
}
// An edge from the gray to the charcoal blurred by 0.7 pixel: the pixels between take no
// ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(199.97), px(197.8), px(166.7), px(93.3), px(62.2)]);
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 15, 3, &classes);
for j in [15 + 7, 15 + 8] {
assert_eq!(pl[0][j], 0.0, "the blurred edge at {j}: ground");
}
}
#[test]
fn row_distances_match_a_scan_of_the_window_around_each_pixel() {
// Three classes scattered over 23 x 17 pixels, some pixels holding two, most none.
+143 -1
View File
@@ -2,10 +2,15 @@
//! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects
//! have it (of the whole document while nothing is selected); clicking a role gives the selected
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`).
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; the list is kept until the document changes.
use std::sync::{Arc, Weak};
use egui::{Align, Layout, Sense, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_engine::doc::Document;
use crate::VectorcraftApp;
use crate::menus::Item;
@@ -18,12 +23,16 @@ pub const ID: &str = "foldLines";
pub const SET_ROLE: &str = "addon.packaging.setRole";
/// The command that picks a role's swatch.
pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// The command that checks the fold lines.
pub const CHECK: &str = "addon.packaging.check";
/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them.
pub const ROLES: &[(&str, &str)] =
&[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")];
/// Where the panel keeps the last `addon.packaging.roles` answer (panel state).
const STATE: &str = "fold-lines";
/// Where the panel keeps the last check (panel state).
const CHECKED: &str = "fold-lines-check";
/// Object › Plug-ins › Packaging Tools.
pub fn menu() -> Vec<Item> {
@@ -35,9 +44,141 @@ pub fn menu() -> Vec<Item> {
make("Make Crease Line", "crease"),
make("Make Partial Cut Line", "partialCut"),
make("Make Perforation Line", "perforation"),
Item::Sep,
Item::Cmd("Check Fold Lines", CHECK, Value::Null),
]
}
/// One issue of a check: whether it is an error, its message (English) and the objects it names.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Issue {
pub error: bool,
pub message: String,
pub ids: Vec<u64>,
}
/// The document a check was made on: its id, and its content as it was then. Selecting changes
/// neither, so the issues stay listed while their Select buttons are used. The content is held
/// weakly: it is compared, never kept alive.
type DocKey = (u64, Weak<Document>);
/// The last check of a document.
#[derive(Clone, Debug, Default)]
pub(crate) struct Checked {
pub key: Option<DocKey>,
pub panels: u64,
pub hinges: u64,
pub issues: Vec<Issue>,
}
impl Checked {
/// The check `r` (an `addon.packaging.check` answer) of the document `key`.
fn of(key: DocKey, r: &Value) -> Checked {
let count = |k: &str| r[k].as_u64().unwrap_or(0);
let issues: Vec<Issue> = r["issues"]
.as_array()
.into_iter()
.flatten()
.map(|i| Issue {
error: i["severity"] == "error",
message: i["message"].as_str().unwrap_or_default().to_string(),
ids: i["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(),
})
.collect();
Checked { key: Some(key), panels: count("panels"), hinges: count("hinges"), issues }
}
/// The summary line, in English (the status bar and the panel show it translated).
fn summary(&self) -> String {
let errors = self.issues.iter().filter(|i| i.error).count();
crate::i18n::fmt(
"Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings}",
&[
("panels", &self.panels.to_string()),
("hinges", &self.hinges.to_string()),
("errors", &errors.to_string()),
("warnings", &(self.issues.len() - errors).to_string()),
],
)
}
}
/// The active document's [`DocKey`].
fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
app.session.active().map(|st| (st.uid, Arc::downgrade(&st.doc)))
}
/// Runs `addon.packaging.check` with `p` and shows its summary in the status bar → the check, kept
/// in `ctx` for the panel.
fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option<Checked> {
let r = app.run(CHECK, p).map_err(|e| app.status(e)).ok()?;
let checked = Checked::of(doc_key(app)?, &r);
app.status(checked.summary());
set_pstate(ctx, CHECKED, checked.clone());
Some(checked)
}
/// Check Fold Lines from its menu item: checks with `p`, keeps the issues for the Fold Lines panel
/// and shows the panel.
pub(crate) fn check(app: &mut VectorcraftApp, p: Value) {
let ctx = app.ui_ctx.clone().unwrap_or_default();
if run_check(app, &ctx, p).is_some()
&& let Err(e) = crate::panel_docking::reveal_panel(app, ID)
{
app.status(e);
}
}
/// The last check of the active document, while the document has not changed since.
fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option<Checked> {
let checked: Checked = pstate(ctx, CHECKED);
let same = match (&checked.key, doc_key(app)) {
(Some((uid, doc)), Some((now, current))) => *uid == now && doc.ptr_eq(&current),
_ => false,
};
same.then_some(checked)
}
/// The Check button, then the last check's summary and issues (errors in the error color, warnings
/// in the warning color), each with a Select button; clicking an issue selects its objects too.
fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) {
widgets::divider(ui);
let width = ui.available_width();
if widgets::flat_button(ui, tl!("Check"), width).clicked() {
run_check(app, ui.ctx(), json!({}));
}
let Some(checked) = last_check(app, ui.ctx()) else { return };
ui.add_space(4.0);
dim_label(ui, &crate::i18n::msg(&checked.summary()));
if checked.issues.is_empty() {
dim_label(ui, tl!("No issues found."));
}
let t = crate::theme::Tokens::get(ui.ctx());
let mut select = None;
for (n, issue) in checked.issues.iter().enumerate() {
ui.horizontal(|ui| {
let can = !issue.ids.is_empty();
let picked = ui
.with_layout(Layout::right_to_left(Align::Center), |ui| {
let button = ui.add_enabled_ui(can, |ui| widgets::flat_button(ui, tl!("Select"), 56.0)).inner;
let text = egui::RichText::new(crate::i18n::msg(&issue.message)).color(if issue.error { t.error } else { t.warning });
let row =
ui.with_layout(Layout::left_to_right(Align::Center), |ui| ui.add(egui::Label::new(text).sense(Sense::click()).wrap())).inner;
button.clicked() || (row.clicked() && can)
})
.inner;
if picked {
select = Some(n);
}
});
}
if let Some(issue) = select.and_then(|n| checked.issues.get(n))
&& let Err(e) = app.run("select.set", json!({ "ids": issue.ids }))
{
app.status(e);
}
}
/// One role row: (role id, swatch name, the swatch's paint if the document has it, count).
type Row = (String, String, Option<vectorcraft_color::Paint>, u64);
@@ -103,6 +244,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
show_check(app, ui);
}
/// Role Swatches… (the dialog of `addon.packaging.setRoleSwatch`): when another role is picked, its
+134 -1
View File
@@ -1,7 +1,7 @@
use serde_json::json;
use vectorcraft_engine::Session;
use super::{ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show};
use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show};
use crate::tests_labels::painted_text;
use crate::{VectorcraftApp, menus};
@@ -125,6 +125,139 @@ fn role_swatches_shows_the_swatch_of_the_role_picked() {
assert_eq!(crate::dialogs::form::params(&d), json!({"role": "crease", "swatch": "Ink"}), "the dialog sends no __role");
}
/// An app with a square blank cut on its outline, a crease across it and a cut line that stops
/// inside it, nothing selected → (app, the cut line that stops).
fn blank() -> (VectorcraftApp, u64) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
let outline = path(&mut app, "M50 50 L250 50 L250 250 L50 250 Z");
let crease = path(&mut app, "M50 150 L250 150");
let slit = path(&mut app, "M100 50 L100 100");
app.run(SET_ROLE, json!({"role": "cut", "ids": [outline, slit]})).unwrap();
app.run(SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap();
app.run("select.none", json!({})).unwrap();
(app, slit)
}
/// Frames of the panel in one context, the pointer clicking the middle of the element that screen
/// readers name `click` (egui finds what the pointer is over from the frame before, so the move
/// gets a frame of its own) → the text the last frame painted.
fn frames(app: &mut VectorcraftApp, ctx: &egui::Context, click: Option<&str>) -> String {
ctx.enable_accesskit();
crate::theme::install_fonts(ctx);
// The context's clock runs on from its last frame: egui requires time to move forward.
let mut time = ctx.input(|i| i.time);
let mut frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.1;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 480.0));
let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
out
};
frame(app, vec![]);
let out = frame(app, vec![]);
let Some(label) = click else { return crate::tests_labels::shapes_text(&out) };
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
// A button carries its text as its name, a label as its value.
let node = nodes.iter().find(|(_, n)| n.label() == Some(label) || n.value() == Some(label));
let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds");
let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5);
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
frame(app, vec![egui::Event::PointerMoved(at)]);
frame(app, vec![button(true)]);
let out = frame(app, vec![button(false)]);
crate::tests_labels::shapes_text(&out)
}
#[test]
fn check_fold_lines_lists_its_issues_in_the_panel_until_the_document_changes() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, _) = blank();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Check Fold Lines").expect("listed");
assert_eq!(item.command.as_deref(), Some(CHECK));
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
assert!(!crate::panel_docking::showing(&app.ui, ID));
menus::invoke(&mut app, CHECK, item.params.clone());
assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens");
assert_eq!(app.ui.status, "Panels: 2, hinges: 1, errors: 1, warnings: 0");
let text = frames(&mut app, &ctx, None);
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
assert!(text.contains("Panels: 2, hinges: 1, errors: 1, warnings: 0") && text.contains("Select"), "{text}");
// Any change to the document takes the list away.
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
let text = frames(&mut app, &ctx, None);
assert!(!text.contains("A cut line ends"), "{text}");
}
#[test]
fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, slit) = blank();
let ctx = egui::Context::default();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
assert!(app.session.active().unwrap().selection.is_empty());
frames(&mut app, &ctx, Some("A cut line ends without meeting another cut line."));
let selected: Vec<u64> = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect();
assert_eq!(selected, [slit]);
let text = frames(&mut app, &ctx, None);
assert!(text.contains("A cut line ends without meeting another cut line."), "selecting keeps the list: {text}");
// A clean blank: no issues.
app.run("edit.clear", json!({})).unwrap();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("No issues found.") && text.contains("Panels: 2, hinges: 1, errors: 0, warnings: 0"), "{text}");
}
#[test]
fn issues_and_the_summary_show_in_the_interface_language() {
let (mut app, _) = blank();
let ctx = egui::Context::default();
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
let text = frames(&mut app, &ctx, Some(crate::i18n::t("Check")));
crate::i18n::set_current(crate::i18n::Lang::EN);
assert!(!text.contains("A cut line ends") && !text.contains("Panels:"), "{text}");
assert!(text.contains("Eine Schnittlinie endet, ohne auf eine andere Schnittlinie zu treffen."), "{text}");
assert!(text.contains("Felder: 2, Scharniere: 1, Fehler: 1, Warnungen: 0"), "{text}");
}
/// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`).
const ISSUE_MESSAGES: [&str; 17] = [
"No cut lines are in the selection.",
"No cut lines are in the document.",
"No cut lines are among the given objects.",
"The cut lines do not enclose an area.",
"A cut line ends without meeting another cut line.",
"A gap between cut lines was closed.",
"The fold lines are too complex to check.",
"A cut line and a crease lie on top of each other.",
"Two fold lines lie on top of each other.",
"A crease ends inside a panel.",
"A crease does not divide two panels.",
"A crease lies outside the cut outline, wholly or in part.",
"The pieces of a hinge are not on one straight line.",
"A gap between cut lines is too narrow to tell apart.",
"A cut-out area holds other fold lines or another blank.",
"A panel is not joined to the rest by a crease.",
"A fold line is on a non-printing layer.",
];
#[test]
fn every_issue_message_translates_in_every_complete_message_catalog() {
for code in [
"cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr",
"ca", "nl", "da",
] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) {
assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}");
}
}
}
#[test]
fn the_panel_without_a_document_asks_for_one() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+2 -1
View File
@@ -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);
+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;
+29 -1
View File
@@ -339,7 +339,9 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
}
let bar = egui::Rect::from_min_size(area.min, vec2(area.width(), 24.0));
// Keeps the pointer off the canvas; not focusable (`click_and_drag` is), so Tab skips it.
ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG);
// A click on it, the current object's name included, outside the back arrow, the crumbs of
// the levels above and the pattern buttons leaves isolation mode.
let background = ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG);
ui.painter().rect_filled(bar, 0.0, t.panel);
let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0));
let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click());
@@ -406,12 +408,38 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
});
}
}
// A click on the background leaves isolation mode altogether, symbol editing mode included.
// While a pattern is edited it does nothing: Save a Copy, Done and Cancel end pattern editing.
let leave = background.clicked() && nav_cmd.is_none() && pattern_cmd.is_none() && pattern_edit.is_none();
if let Some((cmd, params)) = nav_cmd {
app.run(cmd, params).ok();
}
if let Some(cmd) = pattern_cmd {
app.run(cmd, json!({})).ok();
}
if leave {
leave_isolation(app);
}
}
}
/// Runs `object.exitIsolation` until the current document is out of isolation mode. Leaving symbol
/// editing mode from a group isolated inside the symbol's art first goes back to the art, and leaving
/// the mode restores the isolation it was entered from; each of these is left in turn. It stops at
/// pattern editing, which only its own buttons end, and when a step fails or changes nothing.
fn leave_isolation(app: &mut VectorcraftApp) {
// Each step leaves one level; a document has far fewer levels than this.
const MAX_STEPS: usize = 64;
let state = |app: &VectorcraftApp| {
app.session
.active()
.map(|d| (d.isolation, d.doc.symbol_edit.as_ref().map(|e| e.layer), d.doc.mask_edit.is_some(), d.doc.pattern_edit.is_some()))
};
for _ in 0..MAX_STEPS {
let Some(before) = state(app) else { return };
if before.0.is_none() || before.3 || app.run("object.exitIsolation", json!({})).is_err() || state(app) == Some(before) {
return;
}
}
}
+149
View File
@@ -1508,6 +1508,155 @@ fn isolation_bar_navigation_and_back_button_steps_up() {
assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2)));
}
/// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press
/// at `from`, a move to `to` and a release there. `from == to` is a click.
fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0));
let press = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for events in [vec![egui::Event::PointerMoved(from)], vec![press(from, true)], vec![egui::Event::PointerMoved(to)], vec![press(to, false)]] {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| {
super::isolation_bar(app, ui, screen);
});
out.textures_delta.clear();
}
}
/// A context for `isolation_bar_gesture`.
fn isolation_bar_context() -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
egui_extras::install_image_loaders(&ctx);
ctx
}
/// A click on the isolation bar's empty space leaves nested isolation mode altogether, selects the
/// isolated object as Exit Isolation Mode does and adds no undo step. A drag across the bar does not
/// leave it.
#[test]
fn isolation_bar_background_click_exits_nested_isolation() {
use vectorcraft_doc::NodeId;
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let rect = |app: &mut crate::VectorcraftApp, x: f64| {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0));
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let g1 = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
let c = rect(&mut app, 90.0);
app.run("select.set", json!({"ids": [g1, c]})).unwrap();
app.run("object.group", json!({})).unwrap();
app.run("object.isolate", json!({"id": a})).unwrap();
let ctx = isolation_bar_context();
let empty = egui::pos2(700.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, egui::pos2(900.0, 14.0));
assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(a)), "a drag across the bar stays in isolation mode");
let steps = app.session.doc().unwrap().history.undo.len();
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert_eq!((st.isolation, st.selection.objects.clone()), (None, vec![NodeId(a)]), "the click leaves isolation mode");
assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step");
}
/// While a pattern is edited, a click on the isolation bar's empty space leaves pattern editing
/// open; the back arrow still ends it as Done does.
#[test]
fn isolation_bar_background_click_leaves_pattern_edit_open() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let f = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [f]})).unwrap();
app.run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap();
assert!(app.session.active().unwrap().doc.pattern_edit.is_some());
let ctx = isolation_bar_context();
let empty = egui::pos2(500.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open");
let back = egui::pos2(15.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, back, back);
let st = app.session.active().unwrap();
assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing");
}
/// While an opacity mask is edited, a click on the isolation bar's empty space stops editing the
/// mask as Exit Isolation Mode does: the masked object is selected again.
#[test]
fn isolation_bar_background_click_stops_mask_editing() {
use vectorcraft_doc::NodeId;
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let obj = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap();
let m = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [obj, m]})).unwrap();
app.run("transparency.makeOpacityMask", json!({})).unwrap();
app.run("transparency.editOpacityMask", json!({})).unwrap();
assert!(app.session.active().unwrap().doc.mask_edit.is_some());
let ctx = isolation_bar_context();
let empty = egui::pos2(700.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.mask_edit.is_none() && st.isolation.is_none(), "mask editing ends");
assert_eq!(st.selection.objects, vec![NodeId(obj)]);
}
/// In symbol editing mode, a click on the isolation bar's empty space leaves the mode, also while a
/// group inside the symbol's art is isolated, and the symbol keeps the art drawn while editing.
#[test]
fn isolation_bar_background_click_leaves_nested_symbol_editing() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
app.run("symbol.new", json!({"name": "Box"})).unwrap();
app.run("symbol.edit", json!({"name": "Box"})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
let b = app.run("shape.rectangle", json!({"x": 130, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let g = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("object.isolate", json!({"id": g})).unwrap();
let ctx = isolation_bar_context();
let empty = egui::pos2(700.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none(), "symbol editing mode ends");
let symbol = st.doc.symbols.iter().find(|s| s.name == "Box").expect("the symbol");
assert!(symbol.art.children().is_some_and(|c| c.len() >= 2), "the edit reached the symbol");
// Symbol editing entered while a group was isolated: the click leaves that isolation too.
let c = app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
let d = app.run("shape.rectangle", json!({"x": 250, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [c, d]})).unwrap();
let h = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("object.isolate", json!({"id": h})).unwrap();
app.run("symbol.edit", json!({"name": "Box"})).unwrap();
assert!(app.session.active().unwrap().doc.symbol_edit.is_some());
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none(), "the isolation from before symbol editing ends too");
}
/// A click on the current object's name at the end of the breadcrumbs, which is not a link, leaves
/// isolation mode as a click on the bar's empty space does.
#[test]
fn isolation_bar_click_on_the_current_name_exits() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("object.isolate", json!({"id": a})).unwrap();
let ctx = isolation_bar_context();
// The crumbs are "Layer 1 › <Path>"; the leaf's name starts after the layer crumb and separator.
let layer = app.session.active().unwrap().doc.ancestry(vectorcraft_doc::NodeId(a)).unwrap()[0];
let layer_name = app.session.active().unwrap().doc.node(layer).unwrap().display_name();
let mut start = 0.0;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let width = |s: &str| ui.painter().layout_no_wrap(s.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x;
start = 30.0 + width(&layer_name) + 6.0 + width("›") + 6.0;
});
out.textures_delta.clear();
let leaf = egui::pos2(start + 4.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, leaf, leaf);
assert_eq!(app.session.active().unwrap().isolation, None);
}
/// Tab goes to the isolation bar's back button and breadcrumbs and does not stop on the bar
/// behind them, which only keeps the pointer off the canvas.
#[test]
+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;
+27
View File
@@ -1505,6 +1505,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 Премахване на цвят
@@ -2572,6 +2574,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… Приставка…
@@ -4166,6 +4172,7 @@ imageTrace Outline Контур
to set spacing and orientation за задаване на разстояние и ориентация
: :
Isolate Selected Group Изолиране на избраната група
Isolate Selected Path Изолиране на избрания път
Release Clipping Mask Освобождаване на маска за изрязване
Make Compound Path Създаване на съставен път
Release Compound Path Освобождаване на съставен път
@@ -7090,4 +7097,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.
+27
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
@@ -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
@@ -2927,6 +2932,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
@@ -7143,4 +7150,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.
+27
View File
@@ -2045,6 +2045,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
@@ -2266,6 +2268,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
@@ -3330,6 +3333,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
@@ -7951,4 +7958,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.
+27
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
@@ -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
@@ -9748,3 +9755,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.
+27
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
@@ -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
@@ -9850,4 +9857,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.
+27
View File
@@ -1555,6 +1555,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
@@ -2618,6 +2620,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…
@@ -4224,6 +4230,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
@@ -9346,3 +9353,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.
+27
View File
@@ -1487,6 +1487,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 Αφαίρεση χρώματος
@@ -3526,6 +3528,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 Αντικείμενα κειμένου σημείου
@@ -4686,6 +4692,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}
@@ -7925,4 +7932,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.
+27
View File
@@ -1570,6 +1570,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
@@ -2661,6 +2663,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…
@@ -4311,6 +4317,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
@@ -7912,4 +7919,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.
+27
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
@@ -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
@@ -8008,4 +8015,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.
+27
View File
@@ -1559,6 +1559,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
@@ -2649,6 +2651,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…
@@ -4296,6 +4302,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
@@ -9733,4 +9740,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.
+27
View File
@@ -1859,6 +1859,7 @@
Isolate Blending બ્લેન્ડિંગ અલગ કરો
Isolate Group ગ્રૂપ અલગ કરો
Isolate Selected Group પસંદ કરેલું ગ્રૂપ અલગ કરો
Isolate Selected Path પસંદ કરેલો પાથ અલગ કરો
Isolate Selected Object પસંદ કરેલી ઑબ્જેક્ટ અલગ કરો
Isometric Bottom આઇસોમેટ્રિક નીચે
Isometric Left આઇસોમેટ્રિક ડાબે
@@ -2052,6 +2053,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 કેરેક્ટર સ્ટાઇલ લોડ કરો
@@ -3608,6 +3613,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 રંગ દૂર કરો
@@ -4847,6 +4854,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.
+27
View File
@@ -2509,6 +2509,7 @@ antiAlias Sharp शार्प
Isolate Blending ब्लेंडिंग अलग करें
Isolate Group अलग समूह
Isolate Selected Group सिलेक्टेड समूह अलग करें
Isolate Selected Path सिलेक्टेड पाथ अलग करें
Isolate Selected Object सिलेक्टेड ऑब्जेक्ट को अलग करें
Isometric Bottom आइसोमेट्रिक बॉटम
Isometric Left आइसोमेट्रिक लेफ्ट
@@ -2757,6 +2758,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 क्लिपबोर्ड में इमेज लोड करें
@@ -4688,6 +4693,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 रंग हटाएँ
@@ -9353,3 +9360,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.
+27
View File
@@ -1973,6 +1973,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
@@ -2267,6 +2269,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
@@ -3207,6 +3210,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…
@@ -9736,3 +9743,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.
+27
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
@@ -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
@@ -7105,4 +7112,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.
+27
View File
@@ -1589,6 +1589,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
@@ -2699,6 +2701,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…
@@ -4359,6 +4365,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
@@ -9380,3 +9387,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.
+27
View File
@@ -950,6 +950,7 @@ digits Malayalam マラヤーラム数字
Auto Color 自動カラー
Automatic 自動
Isolate Selected Group 選択したグループを分離
Isolate Selected Path 選択したパスを分離
Isolate Selected Object 選択したオブジェクトを分離
Exit Isolation Mode 分離モードを終了
Make Clipping Mask クリッピングマスクを作成
@@ -1960,6 +1961,8 @@ antiAlias Sharp シャープ
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 カラーを削除
@@ -2785,6 +2788,10 @@ diagnostics ui UI
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… プラグイン…
Points ポイント
@@ -9447,3 +9454,23 @@ 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. 折り線が 2 本重なっています。
@msg A crease ends inside a panel. 筋入れ線がパネルの内側で終わっています。
@msg A crease does not divide two panels. 筋入れ線が 2 つのパネルを分けていません。
@msg A crease lies outside the cut outline, wholly or in part. 筋入れ線の全体または一部がカットの輪郭の外側にあります。
@msg The pieces of a hinge are not on one straight line. ヒンジの各部分が 1 本の直線上にありません。
@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.
+27
View File
@@ -2874,6 +2874,7 @@
VectorCraft Help… VectorCraft-ის დახმარება…
Automatic ავტომატური
Isolate Selected Group მონიშნული ჯგუფის იზოლირება
Isolate Selected Path მონიშნული ტრაექტორიის იზოლირება
Exit Isolation Mode იზოლაციის რეჟიმიდან გამოსვლა
Make Clipping Mask მომჭრელი ნიღბის შექმნა
Release Clipping Mask მომჭრელი ნიღბის მოხსნა
@@ -3453,6 +3454,10 @@ lighting Light სინათლე
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 დამატება
Reflect Horizontal ჰორიზონტალურად არეკვლა
Rotate 90° CW 90°-ით შემობრუნება საათის ისრის მიმართულებით
Set 1 ნაკრები 1
@@ -4788,6 +4793,8 @@ digits Malayalam მალაიალამური
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 ფერის წაშლა
@@ -10014,4 +10021,24 @@ font-script Japanese იაპონური
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.
+27
View File
@@ -943,6 +943,7 @@ digits Malayalam 말라얄람어
Auto Color 자동 색상
Automatic 자동
Isolate Selected Group 선택한 그룹 격리
Isolate Selected Path 선택한 패스 격리
Isolate Selected Object 선택한 개체 격리
Exit Isolation Mode 격리 모드 종료
Make Clipping Mask 클리핑 마스크 만들기
@@ -1950,6 +1951,8 @@ antiAlias Sharp 날카롭게
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 색상 제거
@@ -2775,6 +2778,10 @@ diagnostics ui UI
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… 플러그인…
Points 포인트
@@ -9343,3 +9350,23 @@ 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}
Can't render this file because it is too large.
+27
View File
@@ -1394,6 +1394,7 @@ liquify-list-end {0}, {1} {0} en {1}
Auto Color Automatische kleur
Automatic Automatisch
Isolate Selected Group Geselecteerde groep isoleren
Isolate Selected Path Geselecteerd pad isoleren
Exit Isolation Mode Isolatiemodus verlaten
Make Clipping Mask Knipmasker maken
Release Clipping Mask Knipmasker vrijgeven
@@ -1997,6 +1998,10 @@ lighting Light Licht
Play Current Selection Huidige selectie afspelen
Save Actions… Acties opslaan…
Load Actions… Acties laden…
Reset Actions Acties opnieuw instellen
Replace the current actions with the default set? De huidige acties vervangen door de standaardset?
Append adds the default set after the current sets instead. Toevoegen voegt in plaats daarvan de standaardset toe na de huidige sets.
Append Toevoegen
Reflect Horizontal Horizontaal spiegelen
Rotate 90° CW 90° met de klok mee draaien
Set 1 Set 1
@@ -3354,6 +3359,8 @@ digits Malayalam Malayalam
Show smooth color wheel Vloeiend kleurenwiel tonen
Show segmented color wheel Gesegmenteerd kleurenwiel tonen
Show color bars Kleurbalken tonen
Show brightness and hue on wheel Helderheid en tint op het wiel tonen
Show saturation and hue on wheel Verzadiging en tint op het wiel tonen
Add Color Tool Gereedschap Kleur toevoegen
Remove Color Tool Gereedschap Kleur verwijderen
Remove Color Kleur verwijderen
@@ -9781,3 +9788,23 @@ breakText Glyphs Glyphs
No objects are selected. Er zijn geen objecten geselecteerd.
Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren.
Remove Fold Line Role Lijnsoort verwijderen
Check Controleren
Check Fold Lines Vouwlijnen controleren
@msg No cut lines are in the selection. De selectie bevat geen snijlijnen.
@msg No cut lines are in the document. Het document bevat geen snijlijnen.
@msg The cut lines do not enclose an area. De snijlijnen sluiten geen gebied in.
@msg A cut line ends without meeting another cut line. Een snijlijn eindigt zonder een andere snijlijn te raken.
@msg A gap between cut lines was closed. Een opening tussen snijlijnen is gesloten.
@msg The fold lines are too complex to check. De vouwlijnen zijn te complex om te controleren.
@msg A cut line and a crease lie on top of each other. Een snijlijn en een rillijn liggen over elkaar.
@msg No cut lines are among the given objects. De opgegeven objecten bevatten geen snijlijnen.
@msg Two fold lines lie on top of each other. Twee vouwlijnen liggen over elkaar.
@msg A crease ends inside a panel. Een rillijn eindigt binnen een paneel.
@msg A crease does not divide two panels. Een rillijn verdeelt geen twee panelen.
@msg A crease lies outside the cut outline, wholly or in part. Een rillijn ligt geheel of gedeeltelijk buiten de snijcontour.
@msg The pieces of a hinge are not on one straight line. De delen van een scharnier liggen niet op één rechte lijn.
@msg A gap between cut lines is too narrow to tell apart. Een opening tussen snijlijnen is te smal om te onderscheiden.
@msg A cut-out area holds other fold lines or another blank. Een uitgesneden gebied bevat andere vouwlijnen of een andere uitslag.
@msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden.
@msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings}
Can't render this file because it is too large.
+27
View File
@@ -840,6 +840,7 @@
Auto Color Kolor automatyczny
Automatic Automatycznie
Isolate Selected Group Izoluj zaznaczoną grupę
Isolate Selected Path Izoluj zaznaczoną ścieżkę
Isolate Selected Object Izoluj zaznaczony obiekt
Exit Isolation Mode Wyjdź z trybu izolacji
Make Clipping Mask Utwórz maskę przycinającą
@@ -1443,6 +1444,10 @@ lighting Light Światło
Play Current Selection Odtwórz bieżące zaznaczenie
Save Actions… Zapisz operacje…
Load Actions… Wczytaj operacje…
Reset Actions Resetuj operacje
Replace the current actions with the default set? Zastąpić bieżące operacje zestawem domyślnym?
Append adds the default set after the current sets instead. Dołącz dodaje zamiast tego zestaw domyślny po bieżących zestawach.
Append Dołącz
Reflect Horizontal Odbij w poziomie
Rotate 90° CW Obróć o 90° w prawo
Set 1 Zestaw 1
@@ -2922,6 +2927,8 @@ digits Malayalam Malajalam
Show smooth color wheel Pokaż płynne koło kolorów
Show segmented color wheel Pokaż segmentowe koło kolorów
Show color bars Pokaż paski kolorów
Show brightness and hue on wheel Pokaż jasność i barwę na kole
Show saturation and hue on wheel Pokaż nasycenie i barwę na kole
Add Color Tool Narzędzie Dodaj kolor
Remove Color Tool Narzędzie Usuń kolor
Remove Color Usuń kolor
@@ -9601,3 +9608,23 @@ breakText Glyphs Glify
No objects are selected. Nie zaznaczono żadnych obiektów.
Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia.
Remove Fold Line Role Usuń rodzaj linii
Check Sprawdź
Check Fold Lines Sprawdź linie zgięcia
@msg No cut lines are in the selection. W zaznaczeniu nie ma linii cięcia.
@msg No cut lines are in the document. W dokumencie nie ma linii cięcia.
@msg The cut lines do not enclose an area. Linie cięcia nie obejmują żadnego obszaru.
@msg A cut line ends without meeting another cut line. Linia cięcia kończy się, nie stykając się z inną linią cięcia.
@msg A gap between cut lines was closed. Zamknięto przerwę między liniami cięcia.
@msg The fold lines are too complex to check. Linie zgięcia są zbyt złożone, aby je sprawdzić.
@msg A cut line and a crease lie on top of each other. Linia cięcia i linia bigowania leżą na sobie.
@msg No cut lines are among the given objects. Wśród podanych obiektów nie ma linii cięcia.
@msg Two fold lines lie on top of each other. Dwie linie zgięcia leżą na sobie.
@msg A crease ends inside a panel. Linia bigowania kończy się wewnątrz panelu.
@msg A crease does not divide two panels. Linia bigowania nie rozdziela dwóch paneli.
@msg A crease lies outside the cut outline, wholly or in part. Linia bigowania leży całkowicie lub częściowo poza konturem cięcia.
@msg The pieces of a hinge are not on one straight line. Części zawiasu nie leżą na jednej linii prostej.
@msg A gap between cut lines is too narrow to tell apart. Przerwa między liniami cięcia jest zbyt wąska, aby ją rozróżnić.
@msg A cut-out area holds other fold lines or another blank. Wycięty obszar zawiera inne linie zgięcia lub inny wykrój.
@msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania.
@msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings}
Can't render this file because it is too large.
+27
View File
@@ -1355,6 +1355,8 @@ antiAlias Sharp Nítido
Show smooth color wheel Mostrar roda de cores contínua
Show segmented color wheel Mostrar roda de cores segmentada
Show color bars Mostrar barras de cores
Show brightness and hue on wheel Mostrar brilho e tom na roda
Show saturation and hue on wheel Mostrar saturação e tom na roda
Add Color Tool Ferramenta Adicionar cor
Remove Color Tool Ferramenta Remover cor
Remove Color Remover cor
@@ -1574,6 +1576,7 @@ antiAlias Sharp Nítido
Isolate Blending Isolar Mesclagem
Isolate Group Isolar Grupo
Isolate Selected Group Isolar Grupo Selecionado
Isolate Selected Path Isolar Caminho Selecionado
Isolate Selected Object Isolar Objeto Selecionado
Italian Italiano
Join Unir
@@ -2195,6 +2198,10 @@ antiAlias Sharp Nítido
Play Current Selection Reproduzir Seleção Atual
Save Actions… Salvar Ações…
Load Actions… Carregar Ações…
Reset Actions Redefinir Ações
Replace the current actions with the default set? Substituir as ações atuais pelo conjunto padrão?
Append adds the default set after the current sets instead. Anexar adiciona o conjunto padrão depois dos conjuntos atuais.
Append Anexar
Plug-in Info Informações do Plug-in
Plug-ins Plug-ins
Plug-in… Plug-in…
@@ -9819,3 +9826,23 @@ swatch Yellow Green Verde-amarelado
No objects are selected. Nenhum objeto selecionado.
Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra.
Remove Fold Line Role Remover Tipo de Linha
Check Verificar
Check Fold Lines Verificar Linhas de Dobra
@msg No cut lines are in the selection. Não há linhas de corte na seleção.
@msg No cut lines are in the document. Não há linhas de corte no documento.
@msg The cut lines do not enclose an area. As linhas de corte não delimitam nenhuma área.
@msg A cut line ends without meeting another cut line. Uma linha de corte termina sem encontrar outra linha de corte.
@msg A gap between cut lines was closed. Uma lacuna entre linhas de corte foi fechada.
@msg The fold lines are too complex to check. As linhas de dobra são complexas demais para verificar.
@msg A cut line and a crease lie on top of each other. Uma linha de corte e uma de vinco estão sobrepostas.
@msg No cut lines are among the given objects. Não há linhas de corte entre os objetos indicados.
@msg Two fold lines lie on top of each other. Duas linhas de dobra estão sobrepostas.
@msg A crease ends inside a panel. Uma linha de vinco termina dentro de um painel.
@msg A crease does not divide two panels. Uma linha de vinco não divide dois painéis.
@msg A crease lies outside the cut outline, wholly or in part. Uma linha de vinco está total ou parcialmente fora do contorno de corte.
@msg The pieces of a hinge are not on one straight line. As partes de uma dobradiça não estão em uma única linha reta.
@msg A gap between cut lines is too narrow to tell apart. Uma lacuna entre linhas de corte é estreita demais para ser distinguida.
@msg A cut-out area holds other fold lines or another blank. Uma área recortada contém outras linhas de dobra ou outra planificação.
@msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco.
@msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings}
Can't render this file because it is too large.
+27
View File
@@ -1580,6 +1580,8 @@ file-filter Templates Шаблоны
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 Удалить цвет
@@ -2688,6 +2690,10 @@ diagnostics ui интерфейс
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… Модуль…
@@ -4344,6 +4350,7 @@ imageTrace Outline Контур
to set spacing and orientation для задания интервала и ориентации
: :
Isolate Selected Group Изолировать выбранную группу
Isolate Selected Path Изолировать выбранный контур
Isolate Selected Object Изолировать выбранный объект
Release Clipping Mask Освободить маску обрезки
Make Compound Path Создать составной контур
@@ -9840,5 +9847,25 @@ shape Open Открытый
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 {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Can't render this file because it is too large.
+27
View File
@@ -1523,6 +1523,8 @@ font-technology Variable Variabla
Show smooth color wheel Visa steglöst färghjul
Show segmented color wheel Visa segmenterat färghjul
Show color bars Visa färgstaplar
Show brightness and hue on wheel Visa ljusstyrka och nyans på hjulet
Show saturation and hue on wheel Visa mättnad och nyans på hjulet
Add Color Tool Verktyget Lägg till färg
Remove Color Tool Verktyget Ta bort färg
Remove Color Ta bort färg
@@ -2592,6 +2594,10 @@ font-technology Variable Variabla
Play Current Selection Spela upp aktuell markering
Save Actions… Spara åtgärder…
Load Actions… Läs in åtgärder…
Reset Actions Återställ åtgärder
Replace the current actions with the default set? Vill du ersätta de aktuella åtgärderna med standarduppsättningen?
Append adds the default set after the current sets instead. Lägg till lägger i stället till standarduppsättningen efter de aktuella uppsättningarna.
Append Lägg till
Plug-in Info Information om plugin
Plug-ins Plugins
Plug-in… Plugin…
@@ -4228,6 +4234,7 @@ imageTrace Outline Kontur
to set spacing and orientation för att ange avstånd och orientering
: :
Isolate Selected Group Isolera markerad grupp
Isolate Selected Path Isolera markerad bana
Release Clipping Mask Släpp klippningsmask
Make Compound Path Skapa sammansatt bana
Release Compound Path Släpp sammansatt bana
@@ -9429,4 +9436,24 @@ digits Hindi Hindi
No objects are selected. Inga objekt är markerade.
Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer.
Remove Fold Line Role Ta bort linjetyp
Check Kontrollera
Check Fold Lines Kontrollera falslinjer
@msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen.
@msg No cut lines are in the document. Det finns inga skärlinjer i dokumentet.
@msg The cut lines do not enclose an area. Skärlinjerna omsluter inget område.
@msg A cut line ends without meeting another cut line. En skärlinje slutar utan att möta en annan skärlinje.
@msg A gap between cut lines was closed. Ett mellanrum mellan skärlinjer stängdes.
@msg The fold lines are too complex to check. Falslinjerna är för komplexa för att kontrollera.
@msg A cut line and a crease lie on top of each other. En skärlinje och en biglinje ligger ovanpå varandra.
@msg No cut lines are among the given objects. Det finns inga skärlinjer bland de angivna objekten.
@msg Two fold lines lie on top of each other. Två falslinjer ligger ovanpå varandra.
@msg A crease ends inside a panel. En biglinje slutar inuti en panel.
@msg A crease does not divide two panels. En biglinje delar inte två paneler.
@msg A crease lies outside the cut outline, wholly or in part. En biglinje ligger helt eller delvis utanför skärkonturen.
@msg The pieces of a hinge are not on one straight line. Delarna av ett gångjärn ligger inte på en rak linje.
@msg A gap between cut lines is too narrow to tell apart. Ett mellanrum mellan skärlinjer är för smalt för att skilja ut.
@msg A cut-out area holds other fold lines or another blank. Ett utskuret område innehåller andra falslinjer eller ett annat ämne.
@msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje.
@msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings}
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen
Can't render this file because it is too large.
+27
View File
@@ -1480,6 +1480,8 @@ font-technology Variable Değişken
Show smooth color wheel Kesintisiz renk tekerleğini göster
Show segmented color wheel Bölümlü renk tekerleğini göster
Show color bars Renk çubuklarını göster
Show brightness and hue on wheel Tekerlekte parlaklık ve renk tonunu göster
Show saturation and hue on wheel Tekerlekte doygunluk ve renk tonunu göster
Add Color Tool Renk Ekle aracı
Remove Color Tool Renk Kaldır aracı
Remove Color Rengi kaldır
@@ -2433,6 +2435,10 @@ shape Open Açık
Play Current Selection Geçerli Seçimi Oynat
Save Actions… Eylemleri Kaydet…
Load Actions… Eylemleri Yükle…
Reset Actions Eylemleri Sıfırla
Replace the current actions with the default set? Geçerli eylemler varsayılan setle değiştirilsin mi?
Append adds the default set after the current sets instead. Ekle bunun yerine varsayılan seti geçerli setlerin sonuna ekler.
Append Ekle
Plug-in Info Eklenti Bilgisi
Plug-ins Eklentiler
Plug-in… Eklenti…
@@ -4079,6 +4085,7 @@ imageTrace Outline Kontur
to set spacing and orientation aralığı ve yönlendirmeyi ayarlamak için
: :
Isolate Selected Group Seçili Grubu İzole Et
Isolate Selected Path Seçili Yolu İzole Et
Isolate Selected Object Seçili Nesneyi Ayır
Release Clipping Mask Kırpma Maskesini Serbest Bırakın
Make Compound Path Bileşik Yol Yap
@@ -9702,3 +9709,23 @@ breakText Glyphs Glifler
No objects are selected. Hiçbir nesne seçili değil.
Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın.
Remove Fold Line Role Çizgi Türünü Kaldır
Check Denetle
Check Fold Lines Katlama Çizgilerini Denetle
@msg No cut lines are in the selection. Seçimde kesim çizgisi yok.
@msg No cut lines are in the document. Belgede kesim çizgisi yok.
@msg The cut lines do not enclose an area. Kesim çizgileri bir alanı çevrelemiyor.
@msg A cut line ends without meeting another cut line. Bir kesim çizgisi başka bir kesim çizgisiyle buluşmadan bitiyor.
@msg A gap between cut lines was closed. Kesim çizgileri arasındaki bir boşluk kapatıldı.
@msg The fold lines are too complex to check. Katlama çizgileri denetlenemeyecek kadar karmaşık.
@msg A cut line and a crease lie on top of each other. Bir kesim çizgisi ile bir pilyaj çizgisi üst üste.
@msg No cut lines are among the given objects. Belirtilen nesneler arasında kesim çizgisi yok.
@msg Two fold lines lie on top of each other. İki katlama çizgisi üst üste.
@msg A crease ends inside a panel. Bir pilyaj çizgisi bir panelin içinde bitiyor.
@msg A crease does not divide two panels. Bir pilyaj çizgisi iki paneli ayırmıyor.
@msg A crease lies outside the cut outline, wholly or in part. Bir pilyaj çizgisi tamamen veya kısmen kesim konturunun dışında.
@msg The pieces of a hinge are not on one straight line. Bir menteşenin parçaları tek bir düz çizgi üzerinde değil.
@msg A gap between cut lines is too narrow to tell apart. Kesim çizgileri arasındaki bir boşluk ayırt edilemeyecek kadar dar.
@msg A cut-out area holds other fold lines or another blank. Kesilip çıkarılmış bir alan başka katlama çizgileri veya başka bir açınım içeriyor.
@msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil.
@msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda.
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings}
Can't render this file because it is too large.
+27
View File
@@ -1583,6 +1583,8 @@ file-filter Templates Шаблони
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 Вилучити колір
@@ -2691,6 +2693,10 @@ diagnostics ui інтерфейс
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… Модуль…
@@ -4352,6 +4358,7 @@ imageTrace Outline Контур
to set spacing and orientation для завдання інтервалу та орієнтації
: :
Isolate Selected Group Ізолювати обрану групу
Isolate Selected Path Ізолювати обраний контур
Isolate Selected Object Ізолювати обраний об’єкт
Release Clipping Mask Звільнити відсічну маску
Make Compound Path Створити складений контур
@@ -9355,3 +9362,23 @@ 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}
Can't render this file because it is too large.

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