mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 01:10:54 +01:00
Merge main into feat/bleed-coverage-warning
This commit is contained in:
commit
121db55910
536 files changed
+44750
-3654
No files matched your search
@@ -886,6 +886,9 @@ pub(crate) use buildcmds::TracePresetChanges;
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
/// The Shape Mode commands' warning when a selected open path encloses no area.
|
||||
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
|
||||
@@ -901,6 +904,10 @@ pub use brushsym::current_symbol;
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data
|
||||
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
|
||||
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ mod pen;
|
||||
mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
@@ -35,5 +36,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(select::specs());
|
||||
v.extend(shapes::specs());
|
||||
v.extend(typetools::specs());
|
||||
v.extend(units::specs());
|
||||
v
|
||||
}
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Points at Crossings",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
|
||||
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, an open end that lies within 0.001 pt of another path counting as crossing it there, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
|
||||
has_selection,
|
||||
crossings
|
||||
),
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
@@ -33,7 +35,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Trim at Crossings",
|
||||
[],
|
||||
None,
|
||||
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
|
||||
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another, or within 0.001 pt of it, marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
|
||||
has_doc,
|
||||
trim
|
||||
)]
|
||||
@@ -100,20 +102,21 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
compounds.dedup();
|
||||
let mut beside = Beside::replacing(d, &trimmed);
|
||||
let mut all = vec![];
|
||||
// The selection is read through a set and changed once at the end, so a trim of many
|
||||
// paths does not go through the selected objects once per path and per piece.
|
||||
let mut selected_ids: HashSet<NodeId> = sel.objects.iter().copied().collect();
|
||||
let mut joining: Vec<NodeId> = vec![];
|
||||
let mut gone: Vec<NodeId> = vec![];
|
||||
for (id, pieces) in plan {
|
||||
let selected = sel.contains(id);
|
||||
let selected = selected_ids.contains(&id);
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
let made = replace_with_pieces(d, &mut beside, id, pieces)?;
|
||||
// The pieces of a selected path are selected; what was not selected stays so.
|
||||
if made.is_empty() {
|
||||
sel.remove(id);
|
||||
gone.push(id);
|
||||
} else if selected {
|
||||
for n in &made {
|
||||
if !sel.contains(*n) {
|
||||
sel.add(*n);
|
||||
}
|
||||
}
|
||||
joining.extend(made.iter().copied().filter(|n| selected_ids.insert(*n)));
|
||||
}
|
||||
all.extend(made);
|
||||
}
|
||||
@@ -121,9 +124,15 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for c in compounds {
|
||||
if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) {
|
||||
d.remove(c)?;
|
||||
sel.remove(c);
|
||||
gone.push(c);
|
||||
}
|
||||
}
|
||||
sel.remove_all(gone);
|
||||
if let Some((first, rest)) = joining.split_first() {
|
||||
// `add` clears what any change to the object selection clears; the rest are new ids.
|
||||
sel.add(*first);
|
||||
sel.objects.extend_from_slice(rest);
|
||||
}
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed }))
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! one undo step, and what takes no part.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Stretches};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -420,6 +421,139 @@ fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected(
|
||||
assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection");
|
||||
}
|
||||
|
||||
/// Run the command with `p`, and check that it leaves the selection exactly as changing it one
|
||||
/// id at a time does: for each trimmed path in the plan's order, its anchors and segments let go,
|
||||
/// a path with no pieces left removed, and each piece of a selected path added; then each emptied
|
||||
/// compound path removed. Returns the selection.
|
||||
fn same_selection_as_one_id_at_a_time(s: &mut Session, p: Value) -> Selection {
|
||||
let st = s.doc().unwrap();
|
||||
let pick = super::pick(&p).unwrap();
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let plan: Vec<(NodeId, usize)> =
|
||||
plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).unwrap().into_iter().map(|t| (t.id, t.pieces.len())).collect();
|
||||
let mut compounds: Vec<NodeId> = plan
|
||||
.iter()
|
||||
.filter_map(|(id, _)| st.doc.parent_of(*id))
|
||||
.filter(|c| matches!(st.doc.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. })))
|
||||
.collect();
|
||||
compounds.dedup();
|
||||
let mut want = st.selection.clone();
|
||||
let made = ids(&s.execute(TRIM, &p).unwrap());
|
||||
assert_eq!(made.len(), plan.iter().map(|(_, n)| n).sum::<usize>());
|
||||
let mut made = made.into_iter();
|
||||
for (id, n) in plan {
|
||||
let selected = want.contains(id);
|
||||
want.anchors.remove(&id);
|
||||
want.segments.remove(&id);
|
||||
let pieces: Vec<NodeId> = made.by_ref().take(n).collect();
|
||||
if pieces.is_empty() {
|
||||
want.remove(id);
|
||||
} else if selected {
|
||||
for piece in pieces {
|
||||
if !want.contains(piece) {
|
||||
want.add(piece);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
for c in compounds {
|
||||
if st.doc.node(c).is_none() {
|
||||
want.remove(c);
|
||||
}
|
||||
}
|
||||
want.prune(&st.doc);
|
||||
assert_eq!(st.selection, want);
|
||||
st.selection.clone()
|
||||
}
|
||||
|
||||
/// Two lines across split by a rectangle, one of them selected; a selected line nothing crosses
|
||||
/// and a selected compound path of two such lines, which the rectangle removes whole; and a
|
||||
/// selected line elsewhere with an anchor and a segment direct-selected. Returns (the selected
|
||||
/// line across, the line removed whole, the compound path, the line elsewhere).
|
||||
fn trim_scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let (h, ..) = across_and_uprights(s);
|
||||
line(s, &[(0.0, 120.0), (300.0, 120.0)], false);
|
||||
let alone = line(s, &[(145.0, 200.0), (155.0, 200.0)], false);
|
||||
let c1 = line(s, &[(145.0, 170.0), (155.0, 170.0)], false);
|
||||
let c2 = line(s, &[(145.0, 180.0), (155.0, 180.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let elsewhere = line(s, &[(0.0, 250.0), (10.0, 250.0), (20.0, 250.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0, alone.0, compound.0]})).unwrap();
|
||||
s.edit("direct", |_, sel| {
|
||||
sel.anchors.insert(elsewhere, [(0, 1)].into());
|
||||
sel.anchors.insert(h, [(0, 0)].into());
|
||||
sel.segments.insert(elsewhere, [(0, 0)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(h, alone, compound, elsewhere)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives() {
|
||||
// A removed key object stops being the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, elsewhere) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(alone);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, None);
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
assert_eq!(&sel.objects[..2], [elsewhere, h]);
|
||||
assert_eq!(sel.objects.len(), 3, "{:?}", sel.objects);
|
||||
assert!(sel.anchors.contains_key(&elsewhere) && sel.segments.contains_key(&elsewhere) && !sel.anchors.contains_key(&h));
|
||||
// A key object that keeps its first piece stays the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, _) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(h);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, Some(h));
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
// Trimming only paths that are not selected leaves a targeted object targeted.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), Some(elsewhere)));
|
||||
assert!(exists(&s, h));
|
||||
// A selected path that gains a piece changes the object selection, which lets go of the target.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.len(), sel.target), (3, None));
|
||||
// So does a selected path that is removed whole.
|
||||
let mut s = session();
|
||||
let (_, alone, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, alone.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 190, 20, 20]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() {
|
||||
let mut s = session();
|
||||
@@ -648,3 +782,45 @@ fn bad_params_are_refused_and_change_nothing() {
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_ending_on_a_curve_that_was_cut_still_divides_it_there() {
|
||||
// An open egg-shaped curve, lines across it whose stubs on the left are trimmed away, so each
|
||||
// line ends on the curve, and the curve's bottom trimmed off below the last line, which cuts
|
||||
// its segments there. A click on the curve between the last two lines removes only that
|
||||
// stretch: the lines' ends on it still divide it, however the curve was cut. Twenty placements,
|
||||
// as how near a cut end lies to the curve depends on the coordinates.
|
||||
for shift in 0..20 {
|
||||
let dx = shift as f64 * 7.31;
|
||||
let mut s = session();
|
||||
let egg = json!({"anchors": [
|
||||
{"x": 160.0 + dx, "y": 40.0, "out": [110.0 + dx, 80.0]},
|
||||
{"x": 92.3 + dx, "y": 190.7, "in": [88.0 + dx, 140.0], "out": [97.0 + dx, 240.0]},
|
||||
{"x": 170.0 + dx, "y": 268.0, "in": [130.0 + dx, 265.0], "out": [210.0 + dx, 271.0]},
|
||||
{"x": 236.4 + dx, "y": 170.2, "in": [238.0 + dx, 230.0], "out": [233.0 + dx, 110.0]},
|
||||
{"x": 150.0 + dx, "y": 20.0, "in": [200.0 + dx, 40.0]}
|
||||
], "closed": false});
|
||||
let egg = NodeId(s.execute("path.create", &egg).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let ys: Vec<f64> = (0..8).map(|k| 70.0 + k as f64 * 23.17 + shift as f64 * 0.37).collect();
|
||||
let lines: Vec<NodeId> = ys.iter().map(|y| line(&mut s, &[(40.0 + dx, *y), (300.0 + dx, *y)], false)).collect();
|
||||
for y in &ys {
|
||||
assert_eq!(s.execute(TRIM, &json!({"at": [50.0 + dx, y], "tolerance": 0.5})).unwrap()["removed"], json!(1));
|
||||
}
|
||||
assert_eq!(s.execute(TRIM, &json!({"at": [170.0 + dx, 268.0], "tolerance": 0.5})).unwrap()["removed"], json!(1));
|
||||
let start = |id: NodeId| path(&s, id).subpaths[0].anchors[0].p;
|
||||
let ends: Vec<Point> = lines.iter().map(|id| start(*id)).collect();
|
||||
// Off every path but the lines: the curve's pieces.
|
||||
let off_curve = |s: &Session, p: Point| {
|
||||
stack(s).into_iter().filter(|id| !lines.contains(id)).filter_map(|id| path(s, id).nearest(p)).map(|n| n.4).fold(f64::INFINITY, f64::min)
|
||||
};
|
||||
let (a, b) = (ends[6], ends[7]);
|
||||
let click = path(&s, egg).nearest(a.midpoint(b)).unwrap().3;
|
||||
assert!(off_curve(&s, a) < 1e-3 && off_curve(&s, click) < 1e-3);
|
||||
assert_eq!(s.execute(TRIM, &json!({"at": [click.x, click.y], "tolerance": 0.5})).unwrap()["removed"], json!(1));
|
||||
assert!(off_curve(&s, click) > 0.5, "{shift}: the stretch clicked is left");
|
||||
for (k, e) in ends.iter().enumerate().take(7) {
|
||||
assert!(off_curve(&s, *e) < 1e-3, "{shift}: the curve no longer reaches line {k}'s end");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
//! UI's; the panel applies a length to the selection with `object.setBounds`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CONVERT: &str = "addon.units.convert";
|
||||
const SELECTION_SIZE: &str = "addon.units.selectionSize";
|
||||
/// The most characters of a refused value an error message shows.
|
||||
const SHOWN_CHARS: usize = 64;
|
||||
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
|
||||
const MAX_TEXT_LEN: usize = 1024;
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
|
||||
/// level of recursion per sign.
|
||||
const MAX_OPERATORS: usize = 128;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "addon.units.convert",
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
cmd!(
|
||||
query "addon.units.selectionSize",
|
||||
"Selection Size in Units",
|
||||
[],
|
||||
None,
|
||||
"{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}",
|
||||
has_selection,
|
||||
selection_size
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit,
|
||||
/// label, number, text}]}`.
|
||||
pub fn in_every_unit(pt: f64) -> Value {
|
||||
let units: Vec<Value> =
|
||||
Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect();
|
||||
json!({ "points": pt, "units": units })
|
||||
}
|
||||
|
||||
/// The unit `p` gives for a number without a suffix (points when left out; null is an error).
|
||||
fn unit_param(p: &Value) -> Result<Unit> {
|
||||
let Some(given) = p.get("unit") else { return Ok(Unit::Points) };
|
||||
let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian);
|
||||
named.ok_or_else(|| {
|
||||
let u = match given {
|
||||
Value::String(s) => clipped(s).escape_debug().to_string(),
|
||||
other => shown(other),
|
||||
};
|
||||
bad(CONVERT, format!("unknown units `{u}`"))
|
||||
})
|
||||
}
|
||||
|
||||
fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let unit = unit_param(p)?;
|
||||
let Some(v) = p.get("value").filter(|v| !v.is_null()) else {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
let pt = pt.filter(|&pt| finite_in_every_unit(pt));
|
||||
pt.map(in_every_unit).ok_or_else(|| {
|
||||
let v = shown(v);
|
||||
bad(CONVERT, format!("`value` must be a number, not {v}"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
|
||||
/// signs?
|
||||
fn readable(s: &str) -> bool {
|
||||
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
|
||||
}
|
||||
|
||||
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
|
||||
/// an array as `[…]` and an object as `{…}`.
|
||||
fn shown(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => Value::String(clipped(s)).to_string(),
|
||||
Value::Array(_) => "[…]".into(),
|
||||
Value::Object(_) => "{…}".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer.
|
||||
fn clipped(s: &str) -> String {
|
||||
match s.char_indices().nth(SHOWN_CHARS) {
|
||||
Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_size(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let measure = s.bounds_measure();
|
||||
let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) {
|
||||
Some(r) => Some(OrientedBox::aligned(r)),
|
||||
None => s.transform_box(&st.selection.objects),
|
||||
};
|
||||
let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?;
|
||||
Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) }))
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's
|
||||
//! size as the Transform panel measures it, bad params refused, and nothing in the document changed.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn convert(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.units.convert", &p).unwrap()
|
||||
}
|
||||
|
||||
/// The row of `r` for the unit with key `key`.
|
||||
fn row<'a>(r: &'a Value, key: &str) -> &'a Value {
|
||||
r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}"))
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_length_comes_back_in_every_unit_in_order() {
|
||||
let mut s = session();
|
||||
let r = convert(&mut s, json!({"value": "10mm"}));
|
||||
assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4));
|
||||
let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect();
|
||||
assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key));
|
||||
assert_eq!(row(&r, "millimeters")["number"], "10");
|
||||
assert_eq!(row(&r, "millimeters")["text"], "10 mm");
|
||||
assert_eq!(row(&r, "centimeters")["text"], "1 cm");
|
||||
assert_eq!(row(&r, "inches")["text"], "0.3937 in");
|
||||
assert_eq!(row(&r, "points")["text"], "28.346 pt");
|
||||
assert_eq!(row(&r, "q")["text"], "40 Q");
|
||||
assert_eq!(row(&r, "ha")["text"], "40 H");
|
||||
assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points");
|
||||
assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches");
|
||||
// Each row is what a field of that unit shows for the length.
|
||||
for u in Unit::EAST_ASIAN {
|
||||
let pt = 720.0 / 25.4;
|
||||
assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}");
|
||||
assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54));
|
||||
assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6));
|
||||
// A number without a unit is in `unit`, points by default.
|
||||
assert!(near(pt(&mut s, json!({"value": 12})), 12.0));
|
||||
assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54));
|
||||
assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6));
|
||||
assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0));
|
||||
// A suffix wins over `unit`.
|
||||
assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0));
|
||||
// A decimal comma reads as a point, as in the number fields.
|
||||
assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let s = session();
|
||||
s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap();
|
||||
s.check_params("addon.units.selectionSize", &json!({})).unwrap();
|
||||
for (id, p) in [
|
||||
("addon.units.convert", json!({"value": 1, "units": "mm"})),
|
||||
("addon.units.convert", json!({"value": 1, "ids": [1]})),
|
||||
("addon.units.selectionSize", json!({"ids": [1]})),
|
||||
("addon.units.selectionSize", json!({"value": 1})),
|
||||
] {
|
||||
match s.check_params(id, &p) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"),
|
||||
other => panic!("{id} {p}: expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_size_follows_preview_bounds_and_selected_anchors() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap();
|
||||
let wh = |s: &mut Session| {
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
(r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap())
|
||||
};
|
||||
assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds");
|
||||
// Use Preview Bounds: the stroke's outer half on every side.
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let (w, h) = wh(&mut s);
|
||||
assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}");
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap();
|
||||
// Two neighboring anchors selected (Direct Selection): the box around them, one edge of the
|
||||
// rectangle.
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
let (w, h) = wh(&mut s);
|
||||
assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_no_document_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0));
|
||||
let mut s = session();
|
||||
let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
convert(&mut s, json!({"value": "5mm"}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_and_units_are_refused() {
|
||||
let mut s = session();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"value": null}),
|
||||
json!({"value": "abc"}),
|
||||
json!({"value": "10 furlongs"}),
|
||||
json!({"value": "1in/0"}),
|
||||
json!({"value": "1e400"}),
|
||||
// Finite in points, too large in Q and Ha.
|
||||
json!({"value": 1.5e308}),
|
||||
json!({"value": "1.5e308"}),
|
||||
// A thousands comma is refused, as the number fields refuse it.
|
||||
json!({"value": "1,000 mm"}),
|
||||
json!({"value": "1,000.5"}),
|
||||
json!({"value": "+1,000"}),
|
||||
json!({"value": "1,000\""}),
|
||||
json!({"value": "1,000'"}),
|
||||
// A long expression is refused instead of exhausting the stack.
|
||||
json!({"value": format!("1{}", "+1".repeat(200_000))}),
|
||||
json!({"value": format!("1{}", "+1".repeat(129))}),
|
||||
json!({"value": true}),
|
||||
json!({"value": [1]}),
|
||||
json!({"value": 1, "unit": "furlongs"}),
|
||||
json!({"value": 1, "unit": 5}),
|
||||
json!({"value": 1, "unit": ["mm"]}),
|
||||
// Only an omitted `unit` is points.
|
||||
json!({"value": 1, "unit": null}),
|
||||
] {
|
||||
match s.execute("addon.units.convert", &p) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"),
|
||||
other => panic!("{p}: expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_value_or_unit_is_refused_with_a_short_message() {
|
||||
let mut s = session();
|
||||
let long = "9".repeat(100_000);
|
||||
for (p, says) in [
|
||||
(json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))),
|
||||
(json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()),
|
||||
(json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))),
|
||||
(json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()),
|
||||
(json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()),
|
||||
] {
|
||||
match s.execute("addon.units.convert", &p) {
|
||||
Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"),
|
||||
other => panic!("expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_size_is_the_transform_panels() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected");
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
|
||||
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
|
||||
assert_eq!(row(&r["width"], "inches")["text"], "1 in");
|
||||
assert_eq!(row(&r["height"], "picas")["text"], "3 p");
|
||||
// A turned object keeps its own sides, as the Transform panel's W and H show them.
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap();
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width()));
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
|
||||
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step");
|
||||
}
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
|
||||
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens,
|
||||
image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
|
||||
};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
@@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
|
||||
let zip = switch_or(p, "zip", false, C)?;
|
||||
let size = texture_size_param(p, C)?;
|
||||
let mut pixels = 0u64;
|
||||
// Every file's name, compared without case: a later file that would take one gets -2, -3…
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut files: Vec<(String, Vec<u8>)> = vec![];
|
||||
@@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let what = &a.name;
|
||||
let parts =
|
||||
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
|
||||
let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
|
||||
let images = image_maps(&pictures);
|
||||
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
|
||||
let mut stem = base.clone();
|
||||
let mut k = 1;
|
||||
loop {
|
||||
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
|
||||
let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?;
|
||||
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
|
||||
break;
|
||||
}
|
||||
k += 1;
|
||||
stem = format!("{base}-{k}");
|
||||
}
|
||||
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
|
||||
let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?;
|
||||
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
|
||||
files.extend(made);
|
||||
}
|
||||
@@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture,
|
||||
/// [`TEXTURE_SIZE`] when it is not given.
|
||||
fn texture_size_param(p: &Value, cmd: &str) -> Result<u32> {
|
||||
let key = "textureSize";
|
||||
let (lo, hi) = TEXTURE_SIZES;
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(TEXTURE_SIZE),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|n| (lo..=hi).contains(n))
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset ids of param `key`.
|
||||
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
|
||||
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
|
||||
|
||||
@@ -36,8 +36,8 @@ mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
|
||||
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
|
||||
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
@@ -169,6 +169,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
cmd!(
|
||||
"brush.objectOptions",
|
||||
"Options of Selected Object…",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
|
||||
has_doc,
|
||||
brush_object_options
|
||||
),
|
||||
cmd!(
|
||||
"object.expandBrush",
|
||||
"Expand Brush Strokes",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::{
|
||||
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
|
||||
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
// ---------- brushes ----------
|
||||
@@ -57,6 +58,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke:
|
||||
st.width = 1.0;
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
// The path's own brush settings (Options of Selected Object) go with the brush they set.
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +88,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for it in &mut n.appearance.items {
|
||||
if let AppearanceItem::Stroke(st) = it {
|
||||
st.brush = None;
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,13 +133,17 @@ fn merge(base: &mut Value, patch: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`.
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps
|
||||
/// each stroke's own settings for it; a stroke left without a brush loses them.
|
||||
fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) {
|
||||
for it in items {
|
||||
if let AppearanceItem::Stroke(st) = it
|
||||
&& st.brush.as_deref() == Some(from)
|
||||
{
|
||||
st.brush = to.map(str::to_string);
|
||||
if to.is_none() {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -494,6 +502,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths
|
||||
/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's
|
||||
/// own settings, `reset` clears them; without either, nothing changes and the settings are given.
|
||||
pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.objectOptions";
|
||||
let params = match p.get("params") {
|
||||
None | Some(Value::Null) => serde_json::Map::new(),
|
||||
Some(Value::Object(o)) => o.clone(),
|
||||
Some(_) => {
|
||||
let key = "params";
|
||||
return Err(bad(C, format!("`{key}` must be an object")));
|
||||
}
|
||||
};
|
||||
let reset = switch_or(p, "reset", false, C)?;
|
||||
if reset && !params.is_empty() {
|
||||
return Err(bad(C, "give `params` or `reset`, not both"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let lib = brush::library(d);
|
||||
let ids = brush_targets(d, &roots(s, p)?);
|
||||
// Each brushed stroke: its path, its place in the appearance, its brush and its settings now.
|
||||
let mut strokes = vec![];
|
||||
for id in &ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
for (i, it) in n.appearance.items.iter().enumerate() {
|
||||
let AppearanceItem::Stroke(st) = it else { continue };
|
||||
if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) {
|
||||
strokes.push((*id, i, b, &st.brush_options));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) };
|
||||
if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) {
|
||||
return Err(bad(C, "the selected paths are painted with brushes of different types"));
|
||||
}
|
||||
// Only a bristle brush has none.
|
||||
if first.kind.stroke_option_keys().is_empty() {
|
||||
return Err(bad(C, "a bristle brush has no options of its own on a path"));
|
||||
}
|
||||
let out: Vec<NodeId> = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect();
|
||||
// Without params or reset the settings are only given: nothing is normalized or changed.
|
||||
if !reset && params.is_empty() {
|
||||
let keys = first.kind.stroke_option_keys();
|
||||
let own: serde_json::Map<String, Value> =
|
||||
strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own }));
|
||||
}
|
||||
let mut changes = vec![];
|
||||
let mut options = None;
|
||||
for (id, i, b, own) in &strokes {
|
||||
let next = if reset {
|
||||
serde_json::Map::new()
|
||||
} else {
|
||||
// Settings saved for another type of brush are left out.
|
||||
let keys = b.kind.stroke_option_keys();
|
||||
let mut merged: serde_json::Map<String, Value> =
|
||||
own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
let was = merged.clone();
|
||||
// A colorization object changes only the fields it gives, and a null item of an
|
||||
// array keeps the stroke's own item (else the brush's).
|
||||
for (k, v) in ¶ms {
|
||||
let next = match (merged.get(k), v) {
|
||||
(Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => {
|
||||
let mut c = mine.clone();
|
||||
c.extend(fields.clone());
|
||||
Value::Object(c)
|
||||
}
|
||||
(Some(mine), _) => brush::keep_items(v, mine),
|
||||
(None, _) => v.clone(),
|
||||
};
|
||||
merged.insert(k.clone(), next);
|
||||
}
|
||||
keep_drawn_modes(b, &was, ¶ms, &mut merged);
|
||||
keep_largest_width(b, &was, ¶ms, &mut merged);
|
||||
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
|
||||
};
|
||||
options.get_or_insert_with(|| next.clone());
|
||||
if &next != *own {
|
||||
changes.push((*id, *i, next));
|
||||
}
|
||||
}
|
||||
let changed: Vec<NodeId> = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect();
|
||||
if !changes.is_empty() {
|
||||
s.edit("Options of Selected Object", |d, _| {
|
||||
for (id, i, next) in changes {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) {
|
||||
st.brush_options = next;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() }))
|
||||
}
|
||||
|
||||
/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush.
|
||||
fn drawn_modes(b: &Brush) -> Option<Vec<Value>> {
|
||||
let modes = match &b.kind {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(s.modes()),
|
||||
_ => return None,
|
||||
};
|
||||
match modes {
|
||||
Ok(Value::Array(m)) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params`
|
||||
/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`,
|
||||
/// would change. A mode the stroke leaves to its values follows them, so without this a changed
|
||||
/// variation or range would also change the mode.
|
||||
fn keep_drawn_modes(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
let given = match params.get("modes") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(m)) => m.clone(),
|
||||
// A value of the wrong kind is refused when the settings are checked.
|
||||
Some(_) => return,
|
||||
};
|
||||
let (Some(before), Some(after)) =
|
||||
(b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if before == after {
|
||||
return;
|
||||
}
|
||||
let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect();
|
||||
merged.insert("modes".into(), Value::Array(kept));
|
||||
}
|
||||
|
||||
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
|
||||
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
|
||||
/// the width, so without this a changed width would also change the largest width.
|
||||
fn keep_largest_width(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
|
||||
return;
|
||||
}
|
||||
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
|
||||
Some(BrushKind::Art(a)) => Some(a),
|
||||
_ => None,
|
||||
};
|
||||
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
|
||||
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
|
||||
// Only a width that followed the pen has a largest width, and only one that still does uses it.
|
||||
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
|
||||
merged.insert("width_max".into(), json!(before.width));
|
||||
}
|
||||
}
|
||||
|
||||
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
|
||||
/// places them; `brush.replaceArt` reads a group of that name as that tile.
|
||||
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
|
||||
|
||||
@@ -38,6 +38,7 @@ mod shape_builder;
|
||||
mod trace;
|
||||
|
||||
pub use live_paint::live_paint_gaps;
|
||||
pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation};
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
@@ -144,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -658,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
|
||||
}
|
||||
s.profile = None;
|
||||
s.brush = None;
|
||||
s.brush_options.clear();
|
||||
}
|
||||
if !starts {
|
||||
s.start_arrow = None;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
|
||||
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
|
||||
source_nodes, source_shapes, switch_or,
|
||||
PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -53,6 +53,27 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
|
||||
Ok((gid, nf, ne))
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and
|
||||
/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in
|
||||
/// isolation mode. A group or other object named like a part is one of them.
|
||||
fn others_in(g: &Node) -> impl Iterator<Item = &Arc<Node>> {
|
||||
let src = b::sources(g).map(|s| s.id);
|
||||
g.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME))))
|
||||
}
|
||||
|
||||
/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`,
|
||||
/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their
|
||||
/// order.
|
||||
fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
|
||||
parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned());
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = parts;
|
||||
}
|
||||
}
|
||||
|
||||
/// Select `ids` alone, without an undo step, when they are not selected that way already.
|
||||
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
@@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let old_parts = old.clone();
|
||||
let mut sources = source_nodes(&old);
|
||||
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
|
||||
let mut others = vec![];
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
|
||||
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
|
||||
sources.extend(source_nodes(n));
|
||||
if is_live_paint(n) {
|
||||
others.extend(others_in(n).cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
|
||||
@@ -146,8 +173,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
|
||||
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
|
||||
let mut g = old;
|
||||
set_parts(&mut g, children, roots);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = children;
|
||||
ch.extend(others);
|
||||
}
|
||||
g.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
for (pt, carried) in keep_faces {
|
||||
@@ -199,6 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
|
||||
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
|
||||
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
|
||||
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
|
||||
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
|
||||
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
|
||||
/// front: the paths drawn in it in isolation mode.
|
||||
fn drawn_in(g: &Node) -> Vec<NodeId> {
|
||||
fn open(n: &Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
|
||||
}
|
||||
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as
|
||||
/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type,
|
||||
/// images, other objects Live Paint does not take, and hidden or locked objects stay where they
|
||||
/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo
|
||||
/// step is recorded.
|
||||
pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<bool> {
|
||||
let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default();
|
||||
if drawn.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let roots: Vec<NodeId> = std::iter::once(g).chain(drawn).collect();
|
||||
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = root_ids(s, p)?;
|
||||
@@ -216,7 +276,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
|
||||
// The objects drawn in the group besides its parts are released in front of its paths.
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect();
|
||||
out.extend(srcs.iter().map(|c| c.id));
|
||||
released.put(d, *g, srcs)?;
|
||||
}
|
||||
@@ -245,10 +306,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
e.trace = None;
|
||||
e.live_paint_gaps = None;
|
||||
}
|
||||
// Objects drawn in the group ([`others_in`]) stay, whatever they are named.
|
||||
let src = b::sources(n).map(|c| c.id);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| match c.name.as_deref() {
|
||||
Some(SOURCES_NAME) => false,
|
||||
Some(FACE_NAME | EDGE_NAME) => draws(c),
|
||||
_ if Some(c.id) == src => false,
|
||||
Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c),
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
@@ -354,9 +417,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The faces change only with what paint stops at, or with new paths.
|
||||
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
|
||||
let (children, _, _) = build_children(d, sources, options.max_gap())?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
set_parts(&mut n, children, &[]);
|
||||
repaint_from(&mut n, &old);
|
||||
}
|
||||
n.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
|
||||
@@ -209,7 +209,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Metafile into Clipboard",
|
||||
[],
|
||||
None,
|
||||
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste",
|
||||
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste",
|
||||
has_doc,
|
||||
import_emf
|
||||
),
|
||||
|
||||
@@ -579,6 +579,11 @@ impl SwatchChoices {
|
||||
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
|
||||
}
|
||||
}
|
||||
/// Add for every conflict: each pasted swatch whose name the document gives another color
|
||||
/// comes in renamed.
|
||||
pub(crate) fn add_all() -> Self {
|
||||
Self { all: SwatchChoice::Add, by_name: BTreeMap::new() }
|
||||
}
|
||||
fn of(&self, name: &str) -> SwatchChoice {
|
||||
self.by_name.get(name).copied().unwrap_or(self.all)
|
||||
}
|
||||
|
||||
@@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof
|
||||
}
|
||||
|
||||
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
|
||||
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
|
||||
/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings
|
||||
/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps
|
||||
/// ([`map_graph_colors`]) and the art of every opacity mask.
|
||||
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
map_effect_colors(&mut n.appearance, f);
|
||||
map_stroke_brush_keys(&mut n.appearance, f);
|
||||
if let Some(e) = n.extras_if_any() {
|
||||
if let Some(g) = e.graph.as_deref_mut() {
|
||||
map_graph_colors(g, f);
|
||||
@@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a`
|
||||
/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key
|
||||
/// that does not read is left as it is.
|
||||
///
|
||||
/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options
|
||||
fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for it in &mut a.items {
|
||||
let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue };
|
||||
let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue };
|
||||
let Some(key) = c.get("key").and_then(|k| serde_json::from_value::<Color>(k.clone()).ok()) else { continue };
|
||||
let n = f(&key, None);
|
||||
if n != key {
|
||||
c.insert("key".into(), json!(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's
|
||||
/// colorization matches it with.
|
||||
fn matches_key(c: &Color, key: &Color) -> bool {
|
||||
|
||||
+129
-22
@@ -53,12 +53,29 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
|
||||
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
|
||||
cmd!(
|
||||
"shape.spiral",
|
||||
"Spiral",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius, decay=80 (%), segments=10, clockwise?, rotation?: deg clockwise about (cx, cy)} (0: outer end at (cx + radius, cy)) → {id}",
|
||||
has_doc,
|
||||
spiral
|
||||
),
|
||||
cmd!(
|
||||
"shape.arc",
|
||||
"Arc",
|
||||
@@ -116,13 +133,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Insert a new object at the top of the insertion parent with the current paint and new-art
|
||||
/// template; select it.
|
||||
pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option<String>) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
add_look(s, label, kind, look, name)
|
||||
}
|
||||
|
||||
/// Insert a new object looking like `look` (drawing modes apply); select it.
|
||||
pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>) -> Result<Value> {
|
||||
insert_look(s, label, kind, look, name, true)
|
||||
@@ -131,14 +141,22 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr
|
||||
/// [`add_look`] that selects the new object only when `select` is set; otherwise the selection
|
||||
/// stays as it was.
|
||||
pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>, select: bool) -> Result<Value> {
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0)
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0, true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
|
||||
/// Insert a new object at the top of the insertion parent with the current paint and new-art
|
||||
/// template, made turned by a `rotation` param (degrees, clockwise on the page), and select it:
|
||||
/// its bounding box turns with it, as after the Rotate tool.
|
||||
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation))
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object whose geometry must stay where it was computed: it is not
|
||||
/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on.
|
||||
fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, 0.0, false)
|
||||
}
|
||||
|
||||
/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it)
|
||||
@@ -162,8 +180,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or
|
||||
/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on.
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new
|
||||
/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is
|
||||
/// on.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn insert_look_turned(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
@@ -172,6 +192,7 @@ fn insert_look_turned(
|
||||
name: Option<String>,
|
||||
select: bool,
|
||||
bbox_angle: f64,
|
||||
align: bool,
|
||||
) -> Result<Value> {
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let mode = s.draw_mode;
|
||||
@@ -181,7 +202,9 @@ fn insert_look_turned(
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
look.apply(d, &mut n);
|
||||
super::object::align_new_object(d, &mut n);
|
||||
if align {
|
||||
super::object::align_new_object(d, &mut n);
|
||||
}
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let mut into = None;
|
||||
@@ -300,7 +323,7 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
|
||||
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
|
||||
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
|
||||
/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog
|
||||
/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at
|
||||
/// placed at the click; a polygon, star or spiral turns its base orientation about its centre. The params as they are at
|
||||
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
|
||||
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
|
||||
let base = s.prefs.constrain_angle;
|
||||
@@ -316,7 +339,7 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
|
||||
o.insert("y".into(), json!(c.y - h / 2.0));
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
"shape.polygon" | "shape.star" => {
|
||||
"shape.polygon" | "shape.star" | "shape.spiral" => {
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
|
||||
@@ -390,6 +413,71 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
|
||||
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
|
||||
};
|
||||
let [a, b, c] = points;
|
||||
let (center, radius) = shapes::circle_through(a, b, c)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
|
||||
fn three_points(v: &Value) -> Option<[Point; 3]> {
|
||||
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
};
|
||||
match v.as_array().map(Vec::as_slice) {
|
||||
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions of the selected anchor points, when there are exactly three. They are counted as
|
||||
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
|
||||
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
|
||||
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
|
||||
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
|
||||
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
|
||||
let st = s.doc()?;
|
||||
if st.selection.segments.values().any(|set| !set.is_empty()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut points = Vec::with_capacity(4);
|
||||
for id in &st.selection.objects {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) };
|
||||
match st.selection.anchors.get(id) {
|
||||
Some(set) => {
|
||||
for &(si, ai) in set.iter().take(4) {
|
||||
let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) };
|
||||
points.push(a.p);
|
||||
}
|
||||
}
|
||||
None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)),
|
||||
}
|
||||
if points.len() > 3 {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(match points.as_slice() {
|
||||
&[a, b, c] => Some([a, b, c]),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
@@ -479,7 +567,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// The generator's state is odd (never 0).
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
@@ -494,7 +582,13 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
@@ -581,6 +675,10 @@ fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.spiral")? } else { 0.0 };
|
||||
if !rotation.is_finite() {
|
||||
return Err(bad("shape.spiral", "rotation must be finite"));
|
||||
}
|
||||
let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?);
|
||||
let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32;
|
||||
let path = shapes::spiral(
|
||||
@@ -590,7 +688,15 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
segments,
|
||||
switch_or(p, "clockwise", true, "shape.spiral")?,
|
||||
);
|
||||
add_art(s, "Spiral", path_kind(path, None), None)
|
||||
// The outer end turns clockwise from (cx + radius, cy) about the center; 0 and whole turns
|
||||
// leave the path as it is, and quarter turns are exact.
|
||||
let path = if bbox_turn(rotation) == 0.0 {
|
||||
path
|
||||
} else {
|
||||
let c = c.to_vec2();
|
||||
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
|
||||
};
|
||||
add_art_turned(s, "Spiral", path_kind(path, None), constrained_turn(s, rotation))
|
||||
}
|
||||
|
||||
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -651,7 +757,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
@@ -831,7 +937,8 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?;
|
||||
let made =
|
||||
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?;
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
(entry, (name, format!("{}, {detail}", kind.label())))
|
||||
}
|
||||
|
||||
/// The artboards the Artboard tool has selected while it is the current tool, in artboard order,
|
||||
/// with the index of its active artboard; none with another tool or when it has none of the
|
||||
/// document's artboards selected. Indices the document does not have are left out.
|
||||
fn artboard_tool_selection(s: &Session) -> Option<(Vec<usize>, usize)> {
|
||||
if s.tool_id() != "artboard" {
|
||||
return None;
|
||||
}
|
||||
let n = s.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let t = s.tool_options_of("artboard");
|
||||
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let mut picked: Vec<usize> = t["selected"].as_array().into_iter().flatten().filter_map(index).collect();
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
let first = *picked.first()?;
|
||||
let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first);
|
||||
Some((picked, active))
|
||||
}
|
||||
|
||||
/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the
|
||||
/// current tool: their `selectedArtboards` entries (in the document's units), and for each its
|
||||
/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of
|
||||
/// artboard `active`.
|
||||
fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec<Value>, Vec<(String, String)>) {
|
||||
let (u, per) = (d.units, d.units.points());
|
||||
let origin = d.ruler_origin_for(active);
|
||||
let mut entries = vec![];
|
||||
let mut rows = vec![];
|
||||
for &i in picked {
|
||||
let Some(a) = d.artboards.get(i) else { continue };
|
||||
let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y);
|
||||
entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per }));
|
||||
rows.extend([
|
||||
("Artboard".to_string(), a.name.clone()),
|
||||
("Width".into(), u.format(w)),
|
||||
("Height".into(), u.format(h)),
|
||||
("X".into(), u.format(x)),
|
||||
("Y".into(), u.format(y)),
|
||||
]);
|
||||
}
|
||||
(entries, rows)
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
|
||||
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
|
||||
/// stroked with a spot color, with a pattern and with a gradient.
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
|
||||
/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows
|
||||
/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
|
||||
/// pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
selected_artboards: &[(String, String)],
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
font_details: &[(String, String)],
|
||||
images: &[ImageRow],
|
||||
@@ -215,7 +259,19 @@ fn sections(
|
||||
rows.extend(
|
||||
d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))),
|
||||
);
|
||||
rows.extend(selected_artboards.iter().cloned());
|
||||
rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi)));
|
||||
let setup = &d.setup;
|
||||
let colors = match setup.grid_colors_name() {
|
||||
"Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "),
|
||||
name => name.to_string(),
|
||||
};
|
||||
rows.extend([
|
||||
("Grid Size".to_string(), setup.grid_size.label().to_string()),
|
||||
("Grid Colors".into(), colors),
|
||||
("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()),
|
||||
("Flattener Preset".into(), setup.flattener().to_string()),
|
||||
]);
|
||||
let counts = [
|
||||
("Swatches", "swatches"),
|
||||
("Character Styles", "characterStyles"),
|
||||
@@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some("text") => true,
|
||||
Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))),
|
||||
};
|
||||
let artboard_tool = artboard_tool_selection(s);
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
@@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default();
|
||||
out["document"]["selectedArtboards"] = json!(selected_entries);
|
||||
let sections = sections(
|
||||
d,
|
||||
&out,
|
||||
&selected_rows,
|
||||
&fonts,
|
||||
&font_rows,
|
||||
&image_rows,
|
||||
&brush_rows,
|
||||
&repeat_rows,
|
||||
&spot_rows,
|
||||
&pattern_rows,
|
||||
&gradient_rows,
|
||||
category,
|
||||
);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value {
|
||||
"unitId": d.units.key(),
|
||||
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
|
||||
"rasterEffectsPpi": d.raster_effects_ppi,
|
||||
"transparency": {
|
||||
"gridSize": d.setup.grid_size.id(),
|
||||
"gridColors": d.setup.grid_colors.map(|c| c.to_hex()),
|
||||
"gridColorsName": d.setup.grid_colors_name(),
|
||||
"simulatePaper": d.setup.simulate_paper,
|
||||
"flattenerPreset": d.setup.flattener(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -875,6 +954,101 @@ mod tests {
|
||||
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
|
||||
}
|
||||
|
||||
/// The Document category's rows from `info`, as (label, value) pairs.
|
||||
fn document_rows(i: &Value) -> Vec<(String, String)> {
|
||||
let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap();
|
||||
doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect()
|
||||
}
|
||||
|
||||
/// Document lists File › Document Setup's transparency settings: the grid's size and colors
|
||||
/// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset.
|
||||
#[test]
|
||||
fn info_lists_the_transparency_settings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let t = &i["document"]["transparency"];
|
||||
assert_eq!(
|
||||
(t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()),
|
||||
(json!("medium"), json!("Light"), json!(false), json!("Medium Resolution"))
|
||||
);
|
||||
let rows = document_rows(&i);
|
||||
let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap();
|
||||
let expected =
|
||||
[("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")];
|
||||
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
s.execute(
|
||||
"document.setup",
|
||||
&json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}),
|
||||
)
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"]));
|
||||
assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom");
|
||||
let rows = document_rows(&i);
|
||||
let expected =
|
||||
[("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")];
|
||||
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}");
|
||||
}
|
||||
|
||||
/// While the Artboard tool is the current tool, Document lists each artboard it has selected
|
||||
/// after the artboards: its name, width, height and the X and Y of its top-left corner from the
|
||||
/// ruler origin of the tool's active artboard. With another tool it lists none.
|
||||
#[test]
|
||||
fn info_lists_the_artboards_the_artboard_tool_selected() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap();
|
||||
let before = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(before["document"]["selectedArtboards"], json!([]));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([2, 1, 7]));
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// Artboard 2 is active: positions are measured from its top-left corner.
|
||||
assert_eq!(
|
||||
i["document"]["selectedArtboards"],
|
||||
json!([
|
||||
{"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0},
|
||||
{"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0},
|
||||
])
|
||||
);
|
||||
let rows = document_rows(&i);
|
||||
let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4;
|
||||
let expected = [
|
||||
("Artboard", "Artboard 2"),
|
||||
("Width", "60 pt"),
|
||||
("Height", "80 pt"),
|
||||
("X", "-250 pt"),
|
||||
("Y", "30 pt"),
|
||||
("Artboard", "Back"),
|
||||
("Width", "100 pt"),
|
||||
("Height", "50 pt"),
|
||||
("X", "0 pt"),
|
||||
("Y", "0 pt"),
|
||||
("Raster Effects", "72 ppi"),
|
||||
];
|
||||
assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
// The rows follow the document's units and its ruler origin.
|
||||
s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap();
|
||||
s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap();
|
||||
s.set_tool_option("selected", &json!([2]));
|
||||
let i = s.execute("document.info", &json!({"category": "document"})).unwrap();
|
||||
let entry = &i["document"]["selectedArtboards"];
|
||||
assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2)));
|
||||
assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}");
|
||||
let rows = document_rows(&i);
|
||||
assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}");
|
||||
// Another tool: no artboard rows.
|
||||
s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(i["document"]["selectedArtboards"], json!([]));
|
||||
assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i));
|
||||
}
|
||||
|
||||
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
|
||||
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
|
||||
#[test]
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -495,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let total: usize = items.iter().map(|x| x.1.len()).sum();
|
||||
s.select(|_, sel| {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| select_anchors(sel, items))?;
|
||||
Ok(json!({ "anchors": total }))
|
||||
}
|
||||
|
||||
/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors
|
||||
/// listed with each path. A path listed twice keeps its first place and its last anchor set.
|
||||
fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.save";
|
||||
let st = s.doc()?;
|
||||
@@ -1026,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({ "closed": n }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The selection that Select ▸ Object ▸ Direction Handles builds.
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{NodeId, Selection, SymbolPart};
|
||||
|
||||
use super::select_anchors;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, as one left by earlier selecting.
|
||||
fn busy() -> Selection {
|
||||
let mut sel = Selection::default();
|
||||
sel.set([NodeId(90), NodeId(91)]);
|
||||
sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)]));
|
||||
sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)]));
|
||||
sel.key = Some(NodeId(91));
|
||||
sel.target = Some(NodeId(92));
|
||||
sel.slices = vec![NodeId(93)];
|
||||
sel.guides = vec![NodeId(94)];
|
||||
sel.key_guide = Some(NodeId(94));
|
||||
sel.key_anchor = Some((NodeId(90), (0, 0)));
|
||||
sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] });
|
||||
sel.on_path_member = Some(NodeId(96));
|
||||
sel.new_art = Arc::new(HashSet::from([NodeId(97)]));
|
||||
sel
|
||||
}
|
||||
|
||||
fn refs(n: usize) -> BTreeSet<(usize, usize)> {
|
||||
(0..n).map(|i| (0, i)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_anchors_gives_the_selection_one_by_one_selecting_gives() {
|
||||
let cases: Vec<Items> = vec![
|
||||
vec![],
|
||||
vec![(NodeId(1), refs(4))],
|
||||
(1..=500).map(|i| (NodeId(i), refs(4))).collect(),
|
||||
// A path listed again keeps its first place and its last anchors.
|
||||
vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))],
|
||||
];
|
||||
for items in cases {
|
||||
for start in [Selection::default(), busy()] {
|
||||
let (mut want, mut got) = (start.clone(), start);
|
||||
one_by_one(&mut want, items.clone());
|
||||
select_anchors(&mut got, items.clone());
|
||||
assert_eq!(got, want, "{items:?}");
|
||||
}
|
||||
}
|
||||
let mut got = busy();
|
||||
select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]);
|
||||
assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]);
|
||||
assert_eq!(got.anchors[&NodeId(3)], refs(2));
|
||||
assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty());
|
||||
assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None));
|
||||
assert!(got.symbol_part.is_none());
|
||||
assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone");
|
||||
}
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Path Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes",
|
||||
has_selection,
|
||||
erase_segments
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -522,13 +522,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// The Path Eraser's band width, in points (VectorCraft's own range).
|
||||
const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0);
|
||||
|
||||
pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseSegments";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let w = number_or(p, "width", 8.0, C)?;
|
||||
if !(w.is_finite() && w > 0.0) {
|
||||
return Err(bad(C, "width must be positive"));
|
||||
}
|
||||
let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut plan = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) {
|
||||
|
||||
@@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError {
|
||||
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
|
||||
}
|
||||
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`.
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another
|
||||
/// brush (Options of Selected Object) are cleared.
|
||||
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
if st.brush.as_deref() != Some(name) {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
@@ -200,14 +204,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("pencil")) => false,
|
||||
Some(Some("brush")) => true,
|
||||
Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")),
|
||||
};
|
||||
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("end")) => false,
|
||||
Some(Some("start")) => true,
|
||||
Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")),
|
||||
};
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let target = brush_target(&s.doc()?.doc, id);
|
||||
@@ -488,12 +500,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
}
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !angle.is_finite() || !roundness.is_finite() {
|
||||
return Err(bad(C, "angle and roundness must be finite"));
|
||||
if !(0.0..=100.0).contains(&roundness) {
|
||||
return Err(bad(C, "`roundness` must be from 0 to 100%"));
|
||||
}
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?),
|
||||
};
|
||||
if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) {
|
||||
return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt"));
|
||||
}
|
||||
let angle = angle.clamp(-180.0, 180.0);
|
||||
let roundness = roundness.clamp(0.0, 100.0);
|
||||
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
|
||||
let squash = tip.inverse();
|
||||
// Width profiles use distance along the spine, so measure pressure on the same squashed
|
||||
@@ -515,13 +538,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
|
||||
};
|
||||
let spine = |tol: Option<f64>| {
|
||||
let path = match tol {
|
||||
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
|
||||
|
||||
@@ -399,9 +399,7 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. });
|
||||
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
|
||||
let found: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
super::select::select_where(s, "document.find", p, |d, n| {
|
||||
found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
})
|
||||
super::select::select_where(s, "document.find", p, |_, n, parent| found.contains(&n.id) && (members || !parent.is_some_and(compound)))
|
||||
}
|
||||
|
||||
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
|
||||
|
||||
@@ -1040,7 +1040,8 @@ impl RasterBudget {
|
||||
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
/// the member's new id. `Err` when such a member still holds a random Transform effect after the
|
||||
/// raster budget left part of it as it is: its new ids would give that effect another seed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
@@ -1051,7 +1052,7 @@ fn expand_pieces(
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
) -> std::result::Result<std::collections::HashMap<NodeId, Vec<Listed>>, OverBudget> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = std::collections::HashMap::new();
|
||||
@@ -1065,7 +1066,12 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
let left = raster.left;
|
||||
let expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
return Err(OverBudget);
|
||||
}
|
||||
listed = Some(expanded);
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1086,7 +1092,7 @@ fn expand_pieces(
|
||||
expanded.insert(c.id, listed);
|
||||
}
|
||||
}
|
||||
expanded
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
|
||||
@@ -1301,6 +1307,19 @@ fn carries_copies(n: &Node) -> bool {
|
||||
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
|
||||
}
|
||||
|
||||
/// Does `n`, something in it, or the art of the symbol it places when a color adjustment makes it
|
||||
/// that art, hold a random Transform effect ([`has_seeded`])? The raster budget can then leave `n`
|
||||
/// as it is after part of it expanded ([`expand_pieces`], Crop Marks).
|
||||
fn holds_seeded(d: &Document, n: &Node) -> bool {
|
||||
has_seeded(n)
|
||||
|| match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(n) => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| has_seeded(&s.art))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
@@ -1331,12 +1350,22 @@ fn expanded_node(
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment and the expansions of the copies
|
||||
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
|
||||
// recolored copies and the images those add then go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
|
||||
// ([`copies_carrying_raster`]) and of the members that hold a random Transform effect, when the
|
||||
// raster budget may yet leave `n` as it is: the recolored copies and the images those add then
|
||||
// go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n) || holds_seeded(d, &n))
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
// What the raster budget had left before those expansions: it gets back what they took.
|
||||
let budget_before = (raster.images, raster.pixels);
|
||||
// `n` stays as it is: `out` lists nothing of it, and the document and the raster budget lose
|
||||
// what expanding it added and took.
|
||||
let leave = |d: &mut Document, out: &mut Vec<Listed>, raster: &mut RasterBudget| {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = &images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
};
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1352,14 +1381,21 @@ fn expanded_node(
|
||||
let container = is_container(&n);
|
||||
// Crop Marks: the object and its marks become a group. The object expands on its own first,
|
||||
// with `id`: the canvas draws it with that id, which Random in a Transform effect takes its
|
||||
// seed from. Then the object and the marks get ids of their own.
|
||||
// seed from. Then the object and the marks get ids of their own. When the raster budget leaves
|
||||
// a random Transform effect in the object, `n` stays as it is: new ids would give that effect
|
||||
// another seed.
|
||||
if let Some(mut m) = effects::crop_marks_art(&n) {
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = vec![];
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
let left = raster.left;
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1390,16 +1426,13 @@ fn expanded_node(
|
||||
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
|
||||
// so does a group or layer whose copies keep a random Transform effect the budget left.
|
||||
// so does a group or layer whose copies or members keep a random Transform effect the budget
|
||||
// left.
|
||||
let Ok(image) = copies.and_then(|copied| {
|
||||
changed |= copied;
|
||||
raster_image(d, &n, raster)
|
||||
}) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
@@ -1413,18 +1446,20 @@ fn expanded_node(
|
||||
image => {
|
||||
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
|
||||
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok::<_, OverBudget>(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
|
||||
m
|
||||
})
|
||||
effects::evaluate_container(Some(&*d), &v)
|
||||
.map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)?);
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !effects::has_transform_art(&v)
|
||||
&& !effects::has_transform_copies(&v)
|
||||
{
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else {
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them, each copy an object of its own, or changes their fills and strokes): through
|
||||
@@ -1440,12 +1475,18 @@ fn expanded_node(
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
outlined
|
||||
.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster)?;
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let Ok(m) = m else {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
|
||||
// expands in turn, to an image.
|
||||
|
||||
@@ -1189,3 +1189,90 @@ fn copies_the_raster_budget_leaves_keep_their_random_moves() {
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose Transform effect copies its symbol instance, which has a drop shadow and a random
|
||||
/// Transform effect that takes its seed from the instance's id: each copy's instance has that id.
|
||||
/// When the raster budget has no image left for a copy's shadow, with none left or with one for the
|
||||
/// first copy's, the group stays as it is: the copies keep the ids their random moves are drawn
|
||||
/// with, the group draws as before, and the document holds no image the first copy's expansion
|
||||
/// made, nor the budget its charge. With the whole budget, the group expands and each object gets
|
||||
/// an id of its own.
|
||||
#[test]
|
||||
fn a_member_the_raster_budget_leaves_keeps_its_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
for images in [0, 1, 1_024] {
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(g).cloned().unwrap();
|
||||
assert!(effects::outer_effects(&before).len() == before.appearance.effects.len(), "the copies carry no shadow of the group's");
|
||||
let art = effects::evaluate_container(Some(&d), &before).unwrap();
|
||||
let mut instances = 0;
|
||||
art.walk(&mut |n| instances += usize::from(n.id == id && super::has_seeded(n)));
|
||||
assert!(instances >= 2, "{images}: each copy's instance has the id and its random effect: {instances}");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
|
||||
if images < 2 {
|
||||
assert!(budget.left > 0, "{images}: a shadow is left");
|
||||
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
|
||||
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
|
||||
assert!(draw(&d) == drawn, "{images}: the group draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
} else {
|
||||
assert_eq!(budget.left, 0, "no shadow is left");
|
||||
assert!(!out.is_empty(), "the group expands");
|
||||
let (mut ids, mut count, mut seeded) = (std::collections::HashSet::new(), 0, false);
|
||||
d.node(g).unwrap().walk(&mut |n| {
|
||||
ids.insert(n.id);
|
||||
count += 1;
|
||||
seeded |= super::has_seeded(n);
|
||||
});
|
||||
assert_eq!(ids.len(), count, "each object has an id of its own");
|
||||
assert!(!seeded, "no random Transform effect is left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object with Crop Marks, a drop shadow and a random Transform effect that takes its seed from
|
||||
/// the object's id stays as it is when the raster budget has no image left for its shadow: the
|
||||
/// object keeps its id and its random move, and draws as before.
|
||||
#[test]
|
||||
fn crop_marks_the_raster_budget_leaves_keep_their_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "cropMarks", "params": {}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(id).cloned().unwrap();
|
||||
assert!(effects::crop_marks_art(&before).is_some(), "the object has crop marks");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, id, &[], &mut out, &mut budget);
|
||||
assert!(budget.left > 0, "the shadow is left");
|
||||
assert!(out.is_empty(), "nothing expands: {out:?}");
|
||||
assert_eq!(d.node(id), Some(&before), "the object stays as it is");
|
||||
assert!(draw(&d) == drawn, "the object draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (0, u64::MAX), "the budget is as it was");
|
||||
}
|
||||
@@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>(
|
||||
std::borrow::Cow::Owned(def)
|
||||
}
|
||||
|
||||
/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or
|
||||
/// scatter brush with Random variation, or a bristle brush?
|
||||
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool {
|
||||
/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different
|
||||
/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle
|
||||
/// brush?
|
||||
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map<String, Value>) -> bool {
|
||||
use vectorcraft_brush::{BrushKind, Variation};
|
||||
brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind {
|
||||
let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false };
|
||||
let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() };
|
||||
let b = edited.as_ref().unwrap_or(brush);
|
||||
match &b.kind {
|
||||
BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random),
|
||||
BrushKind::Scatter(s) => s.modes().contains(&Variation::Random),
|
||||
BrushKind::Bristle(_) => true,
|
||||
BrushKind::Art(_) | BrushKind::Pattern(_) => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])?
|
||||
fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool {
|
||||
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b));
|
||||
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| {
|
||||
st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options))
|
||||
};
|
||||
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st)))
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
@@ -87,8 +87,10 @@ pub use load::{
|
||||
};
|
||||
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
|
||||
pub use load::{losses_summary, overwrite_losses};
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
|
||||
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
#[cfg(test)]
|
||||
pub(crate) use mesh3d::MAX_TEXTURE_PIXELS;
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label};
|
||||
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
@@ -131,7 +133,7 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{check_images_in, check_scripts_of};
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
|
||||
@@ -171,13 +171,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
/// The error for a file that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in
|
||||
/// force and the file would name a linked image's file outside them (a relative path taken from
|
||||
/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it
|
||||
/// carries the native document ([`check_native_images`]). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
@@ -193,9 +194,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(format, "svg" | "svgz") {
|
||||
return check_native_images(cmd, format, d, base, p);
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
|
||||
// layers kept and SVG 1.1: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
|
||||
@@ -222,6 +226,38 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
|
||||
/// always, unless read roots are in force, the file carries the native document (a native file or
|
||||
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
|
||||
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
|
||||
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
|
||||
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
|
||||
/// read). The error names no file or folder.
|
||||
pub(crate) fn check_native_images(
|
||||
cmd: &str,
|
||||
format: &str,
|
||||
d: &vectorcraft_doc::Document,
|
||||
base: crate::cmd::links::LinkBase,
|
||||
p: &Value,
|
||||
) -> Result<()> {
|
||||
let carried =
|
||||
crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len());
|
||||
if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// `doc` as a file written for the request being served carries it: without an Export for Screens
|
||||
/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The
|
||||
/// open document keeps it.
|
||||
pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return std::borrow::Cow::Borrowed(doc);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
std::borrow::Cow::Owned(kept)
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -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; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), 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
Line truncated
|
||||
"{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; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), 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; webp 0–100 with lossless: false), …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 t
Line truncated
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -241,7 +241,8 @@ struct RasterOptions {
|
||||
width: Option<f64>,
|
||||
/// The height of each file in pixels (wins over `ppi` and `scale`).
|
||||
height: Option<f64>,
|
||||
quality: Option<u8>,
|
||||
/// JPEG and lossy WebP quality, read by [`RasterOptions::quality`].
|
||||
quality: Option<Value>,
|
||||
background: Option<Value>,
|
||||
anti_alias: Option<String>,
|
||||
interlaced: Option<bool>,
|
||||
@@ -281,6 +282,19 @@ fn clamped_ppi(ppi: f64) -> f64 {
|
||||
}
|
||||
|
||||
impl RasterOptions {
|
||||
/// `quality` as given: `None` when absent or null, else a whole number 0–255 (JPEG caps it at
|
||||
/// 100; WebP refuses more than 100), or an error naming it.
|
||||
fn quality(&self) -> Result<Option<u8>> {
|
||||
match &self.quality {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|q| u8::try_from(q).ok())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(C, format!("quality must be a whole number from 0 to 100, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -311,7 +325,8 @@ impl RasterOptions {
|
||||
},
|
||||
anti_alias: self.anti_alias.as_deref().map(anti_alias).transpose().map_err(|e| bad(C, e))?.unwrap_or_default(),
|
||||
interlaced: self.interlaced.unwrap_or(false),
|
||||
quality: self.quality.unwrap_or(90).min(100),
|
||||
quality: self.quality()?.unwrap_or(90).min(100),
|
||||
webp_lossless: self.lossless.unwrap_or(true),
|
||||
jpeg: JpegOptions {
|
||||
color_model,
|
||||
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
|
||||
@@ -1136,6 +1151,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"psd" => RasterFormat::Psd,
|
||||
_ => RasterFormat::WebP,
|
||||
};
|
||||
if format == RasterFormat::WebP
|
||||
&& let Some(q) = o.quality()?.filter(|q| *q > 100)
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
@@ -1182,9 +1202,6 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
if format == RasterFormat::WebP && o.lossless == Some(false) {
|
||||
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
}
|
||||
return Ok(enc);
|
||||
}
|
||||
_ => return Err(bad(C, format!("no encoder for {} yet", f.label))),
|
||||
|
||||
@@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
|
||||
}
|
||||
|
||||
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
|
||||
/// several artboards), with linked images whole when `include_linked`.
|
||||
/// several artboards), with linked images whole when `include_linked`, and without an Export for
|
||||
/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]).
|
||||
fn native(doc: &Document, board: Option<usize>, include_linked: bool) -> Vec<u8> {
|
||||
let doc = &*super::access::with_readable_settings_folder(doc);
|
||||
let several = board.filter(|_| doc.artboards.len() > 1);
|
||||
if several.is_none() && !include_linked {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
|
||||
@@ -211,17 +211,11 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
|
||||
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
|
||||
/// the next artboard of the same document.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
|
||||
fn kept(
|
||||
n: &Arc<Node>,
|
||||
doc: &Document,
|
||||
symbols: &SymbolBoxes,
|
||||
rect: vectorcraft_geom::Rect,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
) -> Option<Arc<Node>> {
|
||||
fn kept(n: &Arc<Node>, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option<Arc<Node>> {
|
||||
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
|
||||
let mut layer = Node::clone(n);
|
||||
let children = layer.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
|
||||
return Some(Arc::new(layer));
|
||||
}
|
||||
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
|
||||
@@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
|
||||
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
|
||||
let mut group = Node::clone(n);
|
||||
let children = group.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
|
||||
return (!children.is_empty()).then(|| Arc::new(group));
|
||||
}
|
||||
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
// Measured in boxes of its own, which find symbols through the same index.
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over);
|
||||
let reach = vectorcraft_brush::reach_within(n);
|
||||
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
|
||||
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -206,11 +206,15 @@ const LOSSLESS: FormatOption = FormatOption {
|
||||
name: "lossless",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
|
||||
description: "lossless WebP (every pixel kept exactly); false writes lossy WebP at quality: a smaller file that loses some detail",
|
||||
};
|
||||
|
||||
const WEBP_QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
|
||||
const WEBP_QUALITY: FormatOption = FormatOption {
|
||||
name: "quality",
|
||||
ty: "integer",
|
||||
default: "90",
|
||||
description: "lossy WebP quality 0–100 (with lossless false; higher keeps more detail in a larger file; more than 100 is refused)",
|
||||
};
|
||||
|
||||
/// The options of the palette formats (PNG-8, GIF).
|
||||
const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
@@ -834,13 +838,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
|
||||
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
|
||||
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
|
||||
/// match the default filter) still list `.ase` and the other library extensions; then the same
|
||||
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
|
||||
/// filters as [`builtin_open_filters`], without a second filter of that label, so a document
|
||||
/// can be picked for its swatches or graphic styles.
|
||||
pub fn library_open_filters(
|
||||
library_label: &'static str,
|
||||
library_exts: &'static [&'static str],
|
||||
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
|
||||
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label))
|
||||
}
|
||||
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
|
||||
@@ -60,8 +60,7 @@ impl Loaded {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG
|
||||
/// (what browsers, PDF and SVG viewers show).
|
||||
/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats.
|
||||
#[derive(Clone)]
|
||||
pub struct RasterImage {
|
||||
/// Content key for `Document::images` (identical files share one blob).
|
||||
@@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
|
||||
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
|
||||
/// settings' CMYK, whichever of their extra channels is the alpha
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
|
||||
/// merged image is read ([`psdread`]).
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain
|
||||
/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits;
|
||||
/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]).
|
||||
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
|
||||
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
|
||||
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
|
||||
@@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
|
||||
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
|
||||
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
|
||||
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
|
||||
/// names ([`png_with_clip`]).
|
||||
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
|
||||
/// clipping path ([`image_clip`]).
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? {
|
||||
native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32));
|
||||
let clip = psdread::clipping_path(bytes).and_then(|path| {
|
||||
let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?;
|
||||
native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}")));
|
||||
Some((path, vectorcraft_geom::FillRule::EvenOdd))
|
||||
});
|
||||
let data =
|
||||
craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?;
|
||||
let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?;
|
||||
img.clip = clip;
|
||||
return Ok(img);
|
||||
}
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
|
||||
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
|
||||
@@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget.
|
||||
pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData> {
|
||||
if blob.mime == "image/png" {
|
||||
return png_clip(&blob.bytes);
|
||||
}
|
||||
if blob.mime != "image/tiff" {
|
||||
return None;
|
||||
}
|
||||
use tiff::tags::{Tag, Type, ValueBuffer};
|
||||
let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?;
|
||||
let mut ifd = d.image_ifd();
|
||||
let entry = ifd.find_entry(Tag::ImageDescription)?;
|
||||
if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 {
|
||||
return None;
|
||||
}
|
||||
let mut buf = ValueBuffer::empty(Type::ASCII);
|
||||
ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??;
|
||||
let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?;
|
||||
let json = json.strip_suffix(b"\0").unwrap_or(json);
|
||||
if json.len() > MAX_PNG_CLIP {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
|
||||
@@ -9,13 +9,24 @@
|
||||
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
|
||||
//! an open solid or a turned plane is seen from both sides.
|
||||
//!
|
||||
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
|
||||
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
|
||||
//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it
|
||||
//! after the layer, and OBJ and USDA name PNG files written beside them (`<name>-texture-1.png`…).
|
||||
//!
|
||||
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>;
|
||||
//! textures: <https://openusd.org/release/spec_usdpreviewsurface.html>), OBJ and MTL
|
||||
//! <https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_render::effects::SolidMesh;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_render::effects::{MeshGraphics, SolidMesh};
|
||||
|
||||
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
|
||||
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
@@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
pub const DEFAULT_FORMAT_3D: &str = "usda";
|
||||
/// The meters in a point (1/72 inch).
|
||||
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
|
||||
/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another
|
||||
/// size, and the sizes it takes.
|
||||
pub(crate) const TEXTURE_SIZE: u32 = 1024;
|
||||
pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096);
|
||||
/// The most texture pixels one export draws, all its assets together.
|
||||
pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096;
|
||||
|
||||
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
|
||||
pub fn format_3d_label(format: &str) -> &'static str {
|
||||
@@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
|
||||
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
|
||||
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
|
||||
fn texture_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
|
||||
/// [`texture_name`] names the texture.
|
||||
fn opacity_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
|
||||
fn texture_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
|
||||
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
|
||||
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
|
||||
/// theirs.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
|
||||
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
|
||||
for (k, map) in images.iter().enumerate() {
|
||||
names.push(texture_name(stem, k));
|
||||
if maps && *map {
|
||||
names.push(opacity_name(stem, k));
|
||||
}
|
||||
}
|
||||
names
|
||||
};
|
||||
match format {
|
||||
"obj" => {
|
||||
let stem = obj_stem(stem);
|
||||
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
|
||||
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
|
||||
}
|
||||
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
|
||||
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
_ => {
|
||||
let key = "format";
|
||||
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
|
||||
@@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, S
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
|
||||
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
|
||||
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Texture {
|
||||
pub png: Arc<Vec<u8>>,
|
||||
pub opacity: Option<Arc<Vec<u8>>>,
|
||||
pub uv: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// A distinct picture of a 3D object: the PNG and its opacity map.
|
||||
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
|
||||
|
||||
/// The distinct pictures of `textures` in order of first use, and the index among them of each
|
||||
/// part's (`None` for a part without one).
|
||||
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
|
||||
let mut out: Vec<Picture> = vec![];
|
||||
let index = (0..parts)
|
||||
.map(|k| {
|
||||
let t = textures.get(k)?.as_ref()?;
|
||||
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
|
||||
out.push((t.png.clone(), t.opacity.clone()));
|
||||
out.len() - 1
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
|
||||
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
|
||||
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
|
||||
}
|
||||
|
||||
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
|
||||
/// OBJ with its MTL after it.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let names = mesh_file_names(stem, format)?;
|
||||
let bytes = match format {
|
||||
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
|
||||
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let (images, image) = images(parts.len(), textures);
|
||||
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
|
||||
let names = mesh_file_names(stem, format, &maps)?;
|
||||
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
|
||||
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
|
||||
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
|
||||
let bytes: Vec<Vec<u8>> = match format {
|
||||
"obj" => {
|
||||
let (obj, mtl) = obj(&obj_stem(stem), parts);
|
||||
vec![obj.into_bytes(), mtl.into_bytes()]
|
||||
let stem = obj_stem(stem);
|
||||
let (obj, mtl) = obj(&stem, &scene);
|
||||
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
|
||||
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
|
||||
}
|
||||
"gltf" => vec![gltf(stem, &scene).into_bytes()],
|
||||
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
|
||||
_ => {
|
||||
let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())];
|
||||
members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png)));
|
||||
vec![super::zip::store_aligned(&members, 64)?]
|
||||
}
|
||||
"gltf" => vec![gltf(stem, parts).into_bytes()],
|
||||
"usda" => vec![usda(stem, parts).into_bytes()],
|
||||
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
|
||||
};
|
||||
Ok(names.into_iter().zip(bytes).collect())
|
||||
}
|
||||
|
||||
/// The distinct colors of `parts` in order, and each part's index among them.
|
||||
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
|
||||
let mut colors: Vec<[f32; 4]> = vec![];
|
||||
let index = parts
|
||||
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
|
||||
/// `maps` says for each picture whether it has an opacity map.
|
||||
struct Scene<'a> {
|
||||
parts: &'a [SolidMesh],
|
||||
textures: &'a [Option<Texture>],
|
||||
image: &'a [Option<usize>],
|
||||
pictures: &'a [Arc<Vec<u8>>],
|
||||
maps: &'a [bool],
|
||||
}
|
||||
|
||||
impl Scene<'_> {
|
||||
/// Part `k`'s texture coordinates and picture, when it has a picture.
|
||||
fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> {
|
||||
let t = self.textures.get(k)?.as_ref()?;
|
||||
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// A material: a color, with a picture that replaces its red, green and blue.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct Material {
|
||||
color: [f32; 4],
|
||||
image: Option<usize>,
|
||||
}
|
||||
|
||||
/// The distinct materials of `scene`'s parts in order, and each part's index among them.
|
||||
fn materials(scene: &Scene) -> (Vec<Material>, Vec<usize>) {
|
||||
let mut out: Vec<Material> = vec![];
|
||||
let index = scene
|
||||
.parts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
|
||||
colors.push(p.color);
|
||||
colors.len() - 1
|
||||
.enumerate()
|
||||
.map(|(k, p)| {
|
||||
let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) };
|
||||
out.iter().position(|c| *c == m).unwrap_or_else(|| {
|
||||
out.push(m);
|
||||
out.len() - 1
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(colors, index)
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// An sRGB channel (0..1) as linear light.
|
||||
@@ -96,8 +217,9 @@ fn num(v: f64) -> String {
|
||||
format!("{v}")
|
||||
}
|
||||
|
||||
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let (colors, material) = materials(parts);
|
||||
fn obj(stem: &str, scene: &Scene) -> (String, String) {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let mut o = String::new();
|
||||
let _ = writeln!(o, "mtllib {stem}.mtl");
|
||||
let _ = writeln!(o, "o {stem}");
|
||||
@@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
|
||||
}
|
||||
}
|
||||
// OBJ's texture coordinates run up from the picture's bottom.
|
||||
for k in 0..parts.len() {
|
||||
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
|
||||
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
|
||||
}
|
||||
}
|
||||
for p in parts {
|
||||
for n in &p.mesh.normals {
|
||||
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
|
||||
}
|
||||
}
|
||||
let mut base = 1usize;
|
||||
let (mut base, mut uv_base) = (1usize, 1usize);
|
||||
for (k, p) in parts.iter().enumerate() {
|
||||
let _ = writeln!(o, "g Solid_{}", k + 1);
|
||||
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
|
||||
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
|
||||
for t in &p.mesh.triangles {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
if textured {
|
||||
let [a, b, c] = t.map(|i| i as usize);
|
||||
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
|
||||
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
|
||||
} else {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
}
|
||||
}
|
||||
base += p.mesh.positions.len();
|
||||
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
|
||||
}
|
||||
let mut m = String::new();
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
for (k, mat) in materials.iter().enumerate() {
|
||||
let c = mat.color;
|
||||
let _ = writeln!(m, "newmtl Material_{}", k + 1);
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
|
||||
match mat.image {
|
||||
// The picture holds the color; Kd multiplies it.
|
||||
Some(_) => {
|
||||
let _ = writeln!(m, "Kd 1 1 1");
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
}
|
||||
}
|
||||
// A picture's opacity map holds the opacity, as gray levels.
|
||||
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
|
||||
let _ = writeln!(m, "illum 1");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
|
||||
if scene.maps.get(i).copied().unwrap_or(false) {
|
||||
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
(o, m)
|
||||
}
|
||||
|
||||
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
fn gltf(stem: &str, scene: &Scene) -> String {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let mut buffer: Vec<u8> = vec![];
|
||||
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
|
||||
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
|
||||
@@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
}));
|
||||
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
|
||||
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
|
||||
primitives.push(json!({
|
||||
let mut primitive = json!({
|
||||
"attributes": { "POSITION": at, "NORMAL": at + 1 },
|
||||
"indices": at + 2,
|
||||
"material": material.get(k).copied().unwrap_or(0),
|
||||
}));
|
||||
});
|
||||
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
|
||||
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
|
||||
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
|
||||
let coords = view(&mut buffer, bytes, 34962);
|
||||
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
|
||||
accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" }));
|
||||
}
|
||||
primitives.push(primitive);
|
||||
}
|
||||
let materials: Vec<Value> = colors
|
||||
let materials: Vec<Value> = materials
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, c)| {
|
||||
.map(|(k, mat)| {
|
||||
let c = mat.color;
|
||||
let mut m = json!({
|
||||
"name": format!("Material_{}", k + 1),
|
||||
"pbrMetallicRoughness": {
|
||||
@@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
},
|
||||
"doubleSided": true,
|
||||
});
|
||||
if let Some(i) = mat.image {
|
||||
// The picture holds the color and the opacity; the factor multiplies them.
|
||||
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
|
||||
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
|
||||
}
|
||||
if c[3] < 1.0 {
|
||||
m["alphaMode"] = json!("BLEND");
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let doc = json!({
|
||||
let mut doc = json!({
|
||||
"asset": { "version": "2.0", "generator": "VectorCraft" },
|
||||
"scene": 0,
|
||||
"scenes": [{ "nodes": [0] }],
|
||||
@@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
"bufferViews": views,
|
||||
"accessors": accessors,
|
||||
});
|
||||
if !scene.pictures.is_empty() {
|
||||
// Linear filtering, mipmaps, and coordinates held at the picture's edge.
|
||||
doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]);
|
||||
doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect());
|
||||
doc["images"] = Value::Array(
|
||||
scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(),
|
||||
);
|
||||
}
|
||||
serde_json::to_string_pretty(&doc).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
fn usda(stem: &str, scene: &Scene) -> String {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let root = prim_name(stem);
|
||||
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
|
||||
let list = |items: Vec<String>| items.join(", ");
|
||||
@@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
linear(c[2])
|
||||
);
|
||||
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
|
||||
// USD's texture coordinates run up from the picture's bottom.
|
||||
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
|
||||
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
|
||||
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
|
||||
}
|
||||
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
|
||||
}
|
||||
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
let m = k + 1;
|
||||
for (k, mat) in materials.iter().enumerate() {
|
||||
let (m, c) = (k + 1, mat.color);
|
||||
let at = format!("/{root}/Materials/Material_{m}");
|
||||
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
match mat.image {
|
||||
// The picture holds the color, and the opacity when the face is not opaque.
|
||||
Some(_) => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
|
||||
} else {
|
||||
let _ = writeln!(u, " float inputs:opacity = 1");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(u, " float inputs:roughness = 1");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(u, "\n def Shader \"Texture\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\"");
|
||||
let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i));
|
||||
let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>");
|
||||
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
|
||||
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
|
||||
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
|
||||
let _ = writeln!(u, " float3 outputs:rgb");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float outputs:a");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
|
||||
let _ = writeln!(u, " string inputs:varname = \"st\"");
|
||||
let _ = writeln!(u, " float2 outputs:result\n }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}\n}}");
|
||||
u
|
||||
}
|
||||
|
||||
/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order
|
||||
/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its
|
||||
/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]),
|
||||
/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with
|
||||
/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so
|
||||
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
|
||||
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
|
||||
let mut renderer: Option<vectorcraft_render::Renderer> = None;
|
||||
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
|
||||
// (`None`: nothing drawn).
|
||||
let mut drawn: Vec<Drawn> = vec![];
|
||||
let mut out = vec![];
|
||||
for part in parts {
|
||||
let Some(g) = &part.graphics else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let Some(frame) = texture_frame(g) else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let scale = f64::from(size) / frame.width().max(frame.height());
|
||||
let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size);
|
||||
let (w, h) = (fit(frame.width()), fit(frame.height()));
|
||||
let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g));
|
||||
let png = match drawn.iter().find(same) {
|
||||
Some((_, _, png)) => png.clone(),
|
||||
None => {
|
||||
let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? {
|
||||
None => None,
|
||||
Some(art) => {
|
||||
*pixels = pixels.saturating_add(u64::from(w) * u64::from(h));
|
||||
if *pixels > MAX_TEXTURE_PIXELS {
|
||||
return Err(format!(
|
||||
"the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})"
|
||||
));
|
||||
}
|
||||
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
|
||||
Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?)
|
||||
}
|
||||
};
|
||||
drawn.push((part, frame, png.clone()));
|
||||
png
|
||||
}
|
||||
};
|
||||
out.push(png.map(|(png, opacity)| {
|
||||
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
|
||||
Texture { png, opacity, uv }
|
||||
}));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an
|
||||
/// area and whose graphics draw something? Nothing is rendered.
|
||||
pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool {
|
||||
parts.iter().any(|p| {
|
||||
p.graphics
|
||||
.as_ref()
|
||||
.is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_))))
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when
|
||||
/// they span an area.
|
||||
fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
|
||||
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
|
||||
}
|
||||
|
||||
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
|
||||
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
|
||||
|
||||
/// Do `a` and `b` draw the same graphics on their face?
|
||||
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
|
||||
a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object
|
||||
}
|
||||
|
||||
/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at
|
||||
/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on
|
||||
/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at
|
||||
/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole
|
||||
/// picture.
|
||||
fn picture(
|
||||
doc: &Document,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
(color, face, object): ([f32; 4], f32, f32),
|
||||
mut art: Node,
|
||||
(frame, scale): (Rect, f64),
|
||||
(w, h): (u32, u32),
|
||||
) -> Result<Picture, String> {
|
||||
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
|
||||
let reach = 2.0 / scale;
|
||||
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
|
||||
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
|
||||
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let object = unit(object);
|
||||
ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 };
|
||||
art.opacity *= unit(face);
|
||||
let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]);
|
||||
group.opacity = object;
|
||||
let group = Arc::new(group);
|
||||
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
|
||||
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
|
||||
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
|
||||
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
|
||||
let opacity = if alpha.iter().all(|a| *a == 255) {
|
||||
None
|
||||
} else {
|
||||
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
|
||||
let mut png = vec![];
|
||||
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
|
||||
Some(Arc::new(png))
|
||||
};
|
||||
Ok((Arc::new(drawn.to_png()?), opacity))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -7,7 +7,7 @@ use super::*;
|
||||
fn square(color: [f32; 4]) -> SolidMesh {
|
||||
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
|
||||
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
|
||||
SolidMesh { mesh, color }
|
||||
SolidMesh::plain(mesh, color)
|
||||
}
|
||||
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
@@ -18,9 +18,14 @@ fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
|
||||
String::from_utf8(bytes.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// [`mesh_files`] without textures.
|
||||
fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
mesh_files(stem, format, parts, &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
let obj = text(&files, "Box.obj");
|
||||
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
|
||||
@@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
|
||||
#[test]
|
||||
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
|
||||
assert_eq!(g["asset"]["version"], "2.0");
|
||||
let uri = g["buffers"][0]["uri"].as_str().unwrap();
|
||||
@@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
|
||||
assert!(g["materials"][0].get("alphaMode").is_none());
|
||||
assert_eq!(g["materials"][0]["doubleSided"], true);
|
||||
// Without graphics there are no textures.
|
||||
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let u = text(&files, "My Box.usda");
|
||||
assert!(u.starts_with("#usda 1.0\n"));
|
||||
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
|
||||
@@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
// sRGB 0.5 is about 0.214 linear.
|
||||
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let files = plain_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let (name, zip) = &files[0];
|
||||
assert_eq!(name, "Box.usdz");
|
||||
// The local header: 30 bytes, the name, then the extra field.
|
||||
@@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
assert_eq!(u16_at(8), 0, "stored, not deflated");
|
||||
let start = 30 + u16_at(26) + u16_at(28);
|
||||
assert_eq!(start % 64, 0);
|
||||
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
|
||||
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
|
||||
@@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
|
||||
#[test]
|
||||
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
|
||||
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
|
||||
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
|
||||
let mut part = square(RED);
|
||||
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
|
||||
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
|
||||
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
|
||||
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
assert!(usda.contains("(20000001, 0, 0)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_format_is_refused() {
|
||||
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "").is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "", &[]).is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() {
|
||||
assert_eq!(prim_name(""), "_");
|
||||
assert_eq!(prim_name("é/x"), "__x");
|
||||
}
|
||||
|
||||
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
|
||||
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
|
||||
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
|
||||
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
|
||||
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
|
||||
let png = b"\x89PNG picture".to_vec();
|
||||
let (parts, pictures) = textured(&png);
|
||||
// OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG
|
||||
// written beside it, with its name in one word.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
|
||||
assert_eq!(files[2].1, png);
|
||||
let obj = text(&files, "My_Box.obj");
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
|
||||
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
|
||||
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
|
||||
assert_eq!(mtl.matches("map_Kd").count(), 1);
|
||||
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
|
||||
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
|
||||
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
|
||||
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
|
||||
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
|
||||
let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
|
||||
let at = view["byteOffset"].as_u64().unwrap() as usize;
|
||||
let first: Vec<f32> = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect();
|
||||
assert_eq!(first, [0.0, 1.0]);
|
||||
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
|
||||
assert_eq!(g["textures"][0]["source"], 0);
|
||||
assert_eq!(g["samplers"][0]["wrapS"], 33071);
|
||||
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
|
||||
assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png);
|
||||
// USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it.
|
||||
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
|
||||
let u = text(&files, "Box.usda");
|
||||
assert_eq!(u.matches("primvars:st").count(), 1);
|
||||
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
|
||||
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
|
||||
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
|
||||
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
|
||||
assert!(u.contains("string inputs:varname = \"st\""));
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
// USDZ: the layer first, then the picture, each on a 64-byte boundary.
|
||||
let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1;
|
||||
let archive = super::super::zip::Archive::open(&zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u)));
|
||||
assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone()));
|
||||
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
|
||||
let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize;
|
||||
let first = 30 + u16_at(26) + u16_at(28);
|
||||
let second = first + u32_at(18);
|
||||
assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second");
|
||||
let data = second + 30 + u16_at(second + 26) + u16_at(second + 28);
|
||||
assert_eq!((first % 64, data % 64), (0, 0));
|
||||
assert_eq!(&zip[data..data + png.len()], png.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
|
||||
let (parts, mut pictures) = textured(b"picture");
|
||||
if let Some(t) = pictures[1].as_mut() {
|
||||
t.opacity = Some(Arc::new(b"gray".to_vec()));
|
||||
}
|
||||
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
|
||||
assert_eq!(files[3].1, b"gray");
|
||||
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let material = &g["materials"][1];
|
||||
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
|
||||
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
|
||||
let u = text(&usda, "Box.usda");
|
||||
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
|
||||
// An opaque textured face reads no opacity from its picture.
|
||||
let (_, plain) = textured(b"picture");
|
||||
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
|
||||
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
|
||||
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
|
||||
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
|
||||
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_sharing_a_picture_write_it_once() {
|
||||
let (mut parts, mut pictures) = textured(b"one");
|
||||
parts.push(square(BLUE));
|
||||
pictures.push(pictures[1].clone());
|
||||
assert_eq!(image_maps(&pictures), [false]);
|
||||
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.len(), 3);
|
||||
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
|
||||
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
|
||||
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
|
||||
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
|
||||
}
|
||||
@@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
// Without an Export for Screens folder outside the read roots.
|
||||
let native = super::access::with_readable_settings_folder(&native);
|
||||
so.pretty = so.pretty_fits(&native);
|
||||
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
@@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result<V
|
||||
} else {
|
||||
Cow::Borrowed(doc)
|
||||
};
|
||||
// Without an Export for Screens folder outside the read roots.
|
||||
let native = super::access::with_readable_settings_folder(&native);
|
||||
vectorcraft_format::save_with(&native, so).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
@@ -525,7 +525,8 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i
|
||||
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(doc);
|
||||
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
|
||||
let native = || Ok(vectorcraft_format::save(doc, false));
|
||||
// The editing data leaves out an Export for Screens folder outside the read roots.
|
||||
let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false));
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, true, native, || Ok(None))?;
|
||||
notes.extend(drawn);
|
||||
if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None {
|
||||
@@ -614,9 +615,13 @@ fn encode_carrying_at(
|
||||
}
|
||||
let (flat, flattened) = flatten_for(cmd, doc, set, p)?;
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
if flattened {
|
||||
if let Some(o) = flattened {
|
||||
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
|
||||
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
|
||||
let line_ppi = o.line_art_ppi.round() as u32;
|
||||
let grad_ppi = o.gradient_ppi.round() as u32;
|
||||
notes.push(Note::loss(format!(
|
||||
"transparency is flattened into opaque art and images ({kind} files have none) at {line_ppi} ppi line art and text, {grad_ppi} ppi gradients and meshes: see the flattener preset"
|
||||
)));
|
||||
}
|
||||
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
notes.extend(r.warnings.into_iter().map(Note::loss));
|
||||
@@ -635,9 +640,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
|
||||
/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
|
||||
/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is)
|
||||
/// and whether its transparency was flattened.
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, bool)> {
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, Option<FlattenOptions>)> {
|
||||
if !set.pdf13() {
|
||||
return Ok((None, false));
|
||||
return Ok((None, None));
|
||||
}
|
||||
let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) };
|
||||
let shown = printed.map(|layers| {
|
||||
@@ -653,8 +658,8 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
|
||||
// its art: it is clipped to its regions (opaque inside them).
|
||||
o.clip_complex_regions = true;
|
||||
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
|
||||
Some(flat) => (Some(flat), true),
|
||||
None => (shown, false),
|
||||
Some(flat) => (Some(flat), Some(o)),
|
||||
None => (shown, None),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -697,6 +702,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = &*expanded;
|
||||
let st = s.doc()?;
|
||||
super::check_linked_scripts(C, "pdf", st, p)?;
|
||||
super::check_linked_images(C, "pdf", st, &st.doc, p)?;
|
||||
let display_doc_title = super::has_own_title(&st.doc);
|
||||
let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf");
|
||||
let mut q = p.clone();
|
||||
|
||||
@@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes,
|
||||
/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`.
|
||||
pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result<Option<craft_image_codecs::Image>, String> {
|
||||
use craft_image_codecs::{ChannelLayout, Image, SampleType};
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r)?;
|
||||
if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let pixels = u64::from(h.width) * u64::from(h.height);
|
||||
if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS {
|
||||
return Ok(None);
|
||||
}
|
||||
let sample_bytes = usize::from(h.depth / 8);
|
||||
let samples = pixels * 4 * sample_bytes as u64;
|
||||
let icc = resources(h.resources, false)
|
||||
.find(|(id, _, _)| *id == 1039)
|
||||
.map(|(_, _, data)| data)
|
||||
.filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK"));
|
||||
if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc {
|
||||
return Ok(None);
|
||||
}
|
||||
let count = pixels as usize;
|
||||
let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?;
|
||||
let mut out = Vec::with_capacity(samples as usize);
|
||||
for i in 0..count {
|
||||
for channel in 0..4 {
|
||||
let at = (channel * count + i) * sample_bytes;
|
||||
if h.depth == 8 {
|
||||
out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?);
|
||||
} else {
|
||||
let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?;
|
||||
out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 };
|
||||
let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?;
|
||||
image.icc = icc.map(<[u8]>::to_vec);
|
||||
Ok(Some(image))
|
||||
}
|
||||
|
||||
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
|
||||
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
|
||||
/// `max_alloc` bytes.
|
||||
|
||||
@@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// Other formats are checked below, with the options the encoder reads.
|
||||
if is_svg(plan.format) {
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
}
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -941,6 +944,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
_ => std::borrow::Cow::Borrowed(¶ms),
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
}
|
||||
|
||||
|
||||
@@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
|
||||
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
|
||||
}
|
||||
|
||||
/// The document the file of `item` that row `r` writes carries when it carries one
|
||||
/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a
|
||||
/// native, `.ai` or EPS row ([`board_document`]), else the item's document.
|
||||
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> {
|
||||
match (&item.every_artboard, r.format.id, single) {
|
||||
(Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all),
|
||||
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)),
|
||||
_ => std::borrow::Cow::Borrowed(&*item.doc),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with
|
||||
/// its background color and the art on it, as Save's separateArtboards writes it (#3868).
|
||||
fn board_document(item: &Item) -> Document {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
d
|
||||
}
|
||||
|
||||
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
@@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// The native document the files of the other rows carry, each document looked through once.
|
||||
if crate::file_access::current().is_some() {
|
||||
let mut looked: HashSet<(usize, bool, Option<usize>)> = HashSet::new();
|
||||
for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) {
|
||||
// A single-file PDF carries the first item's document alone, as the writer writes it.
|
||||
let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0));
|
||||
for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) {
|
||||
let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none();
|
||||
let board = item.artboard.filter(|_| !all && r.whole_document());
|
||||
if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board))
|
||||
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base)
|
||||
{
|
||||
return Err(bad(C, super::access::IMAGE_OUTSIDE));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
@@ -1322,8 +1361,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
// A whole-document copy of an artboard, for the formats that write documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<usize, Arc<Document>> = std::collections::HashMap::new();
|
||||
// A whole-document copy of an artboard of an item's document, for the formats that write
|
||||
// documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<(usize, usize), Arc<Document>> = std::collections::HashMap::new();
|
||||
let mut files = 0u64;
|
||||
// One step per item and row, the files a name collision skips included.
|
||||
let steps = (items.len() * rows.len()) as u64;
|
||||
@@ -1362,19 +1402,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
write(pdf_doc.unwrap_or(all), "pdf", &options)?
|
||||
} else if r.whole_document() && item.artboard.is_some() {
|
||||
let b = item.artboard.unwrap_or(0);
|
||||
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
|
||||
let d = board_docs
|
||||
.entry(b)
|
||||
.or_insert_with(|| {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
// It keeps its background color.
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
Arc::new(d)
|
||||
})
|
||||
.clone();
|
||||
let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone();
|
||||
let mut options = r.options_for(item.region, None)?;
|
||||
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
|
||||
if r.format.id == "eps" {
|
||||
|
||||
@@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
vectorcraft_format::save(&kept, false)
|
||||
vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
|
||||
@@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load
|
||||
/// as a library, and it is the only filter of that label.
|
||||
#[test]
|
||||
fn the_swatch_library_filter_lists_ai_and_eps_files() {
|
||||
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect();
|
||||
for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] {
|
||||
assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]);
|
||||
}
|
||||
assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}");
|
||||
// File › Open still opens a `.ai` as a document, not as a swatch library.
|
||||
assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai"));
|
||||
}
|
||||
|
||||
/// The extensions usage texts list for export: one per writable format, each picking that format
|
||||
/// (`.png` picks PNG; PNG-8 is asked for by `format`).
|
||||
#[test]
|
||||
|
||||
@@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
|
||||
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
|
||||
}
|
||||
|
||||
/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the
|
||||
/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with
|
||||
/// `square` (a color operator), a color the palette doesn't list.
|
||||
fn textures_library(square: &str) -> Vec<u8> {
|
||||
let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n");
|
||||
let gradient =
|
||||
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
|
||||
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\
|
||||
1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n";
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}"));
|
||||
ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")
|
||||
}
|
||||
|
||||
/// `swatch.library.load` of `file` named `name` → its library id.
|
||||
fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value {
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name});
|
||||
s.execute("swatch.library.load", &p).unwrap()["library"].clone()
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its
|
||||
/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's
|
||||
/// tile and art in the document, in the library's color group, not the pattern's colors.
|
||||
#[test]
|
||||
fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() {
|
||||
let mut s = Session::new();
|
||||
let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k"));
|
||||
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
|
||||
let kinds: Vec<(&str, &str, Option<&str>)> =
|
||||
lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect();
|
||||
assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}");
|
||||
assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}");
|
||||
// The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own.
|
||||
let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap();
|
||||
let tiles = library.iter().find(|w| w.name == "Tiles").unwrap();
|
||||
assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some()));
|
||||
assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none());
|
||||
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap();
|
||||
assert_eq!(r["added"], json!(["Tiles"]), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let dots = doc.pattern("Dots").expect("the pattern comes with its swatch");
|
||||
assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0));
|
||||
assert_eq!(dots.art.len(), 1, "{:?}", dots.art);
|
||||
let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too");
|
||||
let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect();
|
||||
assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}");
|
||||
// Added again, the swatch the document has is used.
|
||||
let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
|
||||
assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}");
|
||||
}
|
||||
|
||||
/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list
|
||||
/// still comes in with that color in its art.
|
||||
#[test]
|
||||
fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() {
|
||||
let mut s = Session::new();
|
||||
let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k"));
|
||||
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
|
||||
let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}");
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let art = &doc.pattern("Dots").unwrap().art;
|
||||
let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color());
|
||||
assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}");
|
||||
// Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is
|
||||
// refused, writes nothing and leaves the library loaded.
|
||||
let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id()));
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string();
|
||||
assert!(e.contains("`textures` has pattern swatches"), "{e}");
|
||||
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written");
|
||||
assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as
|
||||
/// swatch libraries with a message, not listed as the default swatches or as an empty library. A
|
||||
/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file
|
||||
/// with no swatches loads as an empty library.
|
||||
#[test]
|
||||
fn swatch_library_documents_without_swatches_or_damaged_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.edit("Clear", |d, _| {
|
||||
d.swatches.clear();
|
||||
d.swatch_groups.clear();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
|
||||
let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}");
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0))));
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"});
|
||||
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`art.ai` has no swatches of its own"), "{e}");
|
||||
let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"});
|
||||
assert!(s.execute("swatch.library.load", &damaged).is_err());
|
||||
let list = s.execute("swatch.library.list", &json!({})).unwrap();
|
||||
assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}");
|
||||
// A library file without swatches still loads, as an empty library.
|
||||
let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap();
|
||||
assert_eq!(r["count"], json!(0), "{r}");
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
|
||||
/// library the styles of its list, in the list's order, not the default styles; the file opens with
|
||||
/// them too.
|
||||
|
||||
@@ -135,26 +135,25 @@ fn formats_list_use_artboards() {
|
||||
assert!(opts("vectorcraft").get("useArtboards").is_none());
|
||||
}
|
||||
|
||||
/// An export's reply gives what the file loses before its notes on the options, whatever order
|
||||
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
|
||||
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
|
||||
/// order.
|
||||
/// An export's reply gives what the file loses before its notes on the options: the type the
|
||||
/// export drew in the fallback font comes before the note on an option WebP doesn't read. With
|
||||
/// only notes on the options, they keep their order.
|
||||
#[test]
|
||||
fn what_the_file_loses_comes_before_a_note_on_the_options() {
|
||||
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
|
||||
let unused = "`interlaced` was not used: WebP files don't read it";
|
||||
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
|
||||
};
|
||||
let mut s = session(60.0, 40.0, 1);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "interlaced": true})), [unused]);
|
||||
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
|
||||
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
|
||||
let w = warnings(&mut s, json!({"format": "webp", "interlaced": true}));
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
|
||||
assert_eq!(w[1], lossy);
|
||||
assert_eq!(w[1], unused);
|
||||
// document.serialize gives them in the same order.
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "interlaced": true})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(w));
|
||||
}
|
||||
|
||||
|
||||
@@ -1050,3 +1050,78 @@ fn flattening_keeps_the_group_in_the_clipping_layer_when_the_layer_below_differs
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// #6861: Layer opacity, blend modes, sublayers with transparency, and empty transparent layers:
|
||||
/// PDF/X-1a, PDF/X-3, and PDF 1.3 automatically flatten and reduce transparency without failing,
|
||||
/// and the output contains no transparency dictionary or soft mask.
|
||||
#[test]
|
||||
fn pdfx_flattens_layer_and_sublayer_transparency() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200, "colorMode": "cmyk"}));
|
||||
|
||||
// Bottom layer: base artwork
|
||||
let _layer1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}}));
|
||||
|
||||
// Middle layer with 50% opacity and Multiply blend mode
|
||||
let layer2 = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 1.0, "y": 0.0, "k": 0.0}}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer2], "opacity": 50, "blendMode": "multiply"}));
|
||||
|
||||
// Sublayer inside layer2 with 70% opacity
|
||||
let sublayer = run(&mut s, "layer.newSublayer", json!({"parent": layer2}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 60, "y": 60, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 0.0, "y": 1.0, "k": 0.0}}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [sublayer], "opacity": 70}));
|
||||
|
||||
// Empty layer with opacity (must not leave /CA or /ca in output)
|
||||
let empty_layer = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "transparency.set", json!({"ids": [empty_layer], "opacity": 40}));
|
||||
|
||||
for standard in ["pdfX1a", "pdfX3"] {
|
||||
let (text, warnings) = pdf(&mut s, json!({"standard": standard}));
|
||||
assert!(text.starts_with("%PDF-1.3"), "{standard}");
|
||||
assert!(warnings.iter().any(|w| w.contains("flattened")), "{standard}: expected flattening warning");
|
||||
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
|
||||
assert!(!text.contains(no), "{standard}: forbidden token '{no}' found in text:\n{text}");
|
||||
}
|
||||
// Verify it can be imported back and renders artwork
|
||||
let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let imported = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert!(!imported.layers.is_empty());
|
||||
let rendered = drawn(&imported);
|
||||
let non_white = rendered.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().any(|c| *c < 240)).count();
|
||||
assert!(non_white > 1000, "{standard}: flattened artwork failed to render, only {non_white} pixels");
|
||||
}
|
||||
|
||||
// PDF 1.3 export with compatibility: 1.3
|
||||
let (text, warnings) = pdf(&mut s, json!({"compatibility": "1.3", "preserveEditing": false}));
|
||||
assert!(text.starts_with("%PDF-1.3"));
|
||||
assert!(warnings.iter().any(|w| w.contains("flattened")));
|
||||
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
|
||||
assert!(!text.contains(no), "PDF 1.3: forbidden token '{no}' found in text");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_outlining_does_not_wrap_layer_transparency_into_groups() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let layer1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer1], "opacity": 60}));
|
||||
|
||||
let o = crate::cmd::FlattenOptions { text_to_outlines: true, ..Default::default() };
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let flattened = crate::cmd::flatten::flatten_expanded(&doc, &o).unwrap();
|
||||
let resulting_doc = flattened.as_ref().unwrap_or(&doc);
|
||||
assert_eq!(resulting_doc.layers.len(), 1);
|
||||
let l = &resulting_doc.layers[0];
|
||||
assert_eq!(l.opacity, 0.6);
|
||||
assert!(!matches!(l.children().unwrap()[0].kind, vectorcraft_doc::NodeKind::Group { .. }));
|
||||
}
|
||||
@@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() {
|
||||
assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_place_keeps_the_native_ink_samples() {
|
||||
let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]]));
|
||||
let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)});
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap();
|
||||
let info = s.execute("file.place.info", &p).unwrap();
|
||||
assert_eq!(info["colorMode"], "CMYK");
|
||||
let placed = s.execute("file.place", &p).unwrap();
|
||||
let id = NodeId(placed["ids"][0].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") };
|
||||
let blob = d.images.get(&im.key).unwrap();
|
||||
assert!(blob.is_cmyk());
|
||||
assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() {
|
||||
let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]]));
|
||||
assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none());
|
||||
assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]);
|
||||
assert!(decode(&bytes, 1, naive).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_depth_and_compression_preserve_exact_samples() {
|
||||
for version in [1, 2] {
|
||||
for depth in [8, 16] {
|
||||
let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] };
|
||||
let planes: Vec<Vec<u8>> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect();
|
||||
let uncompressed = planes.concat();
|
||||
for method in 0..=3u16 {
|
||||
let mut data = method.to_be_bytes().to_vec();
|
||||
match method {
|
||||
0 => data.extend(&uncompressed),
|
||||
1 => {
|
||||
for p in &planes {
|
||||
let count = (p.len() + 1) as u32;
|
||||
if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) }
|
||||
}
|
||||
for p in &planes {
|
||||
data.push((p.len() - 1) as u8);
|
||||
data.extend(p);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// One sample per row has the same bytes with or without prediction.
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut z, &uncompressed).unwrap();
|
||||
data.extend(z.finish().unwrap());
|
||||
}
|
||||
}
|
||||
let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data);
|
||||
let img = raster_image(&bytes).unwrap();
|
||||
assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}");
|
||||
assert_eq!(img.blob.is_cmyk16(), depth == 16);
|
||||
let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap();
|
||||
let expected: Vec<u8> =
|
||||
values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect();
|
||||
assert_eq!(decoded.data(), expected);
|
||||
assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none());
|
||||
assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]];
|
||||
let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes));
|
||||
assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency");
|
||||
let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes));
|
||||
let img = raster_image(&alpha).unwrap();
|
||||
assert!(!img.blob.is_cmyk());
|
||||
assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() {
|
||||
let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap();
|
||||
let mut res = Vec::new();
|
||||
res.extend((144u32 << 16).to_be_bytes());
|
||||
res.extend([0, 1, 0, 1]);
|
||||
res.extend((144u32 << 16).to_be_bytes());
|
||||
res.extend([0, 1, 0, 1]);
|
||||
let make = |clip: &[u8], ink: u8| {
|
||||
let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat();
|
||||
psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]]))
|
||||
};
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links");
|
||||
let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64));
|
||||
let square = write_file(&dir, "square.psd", &make(&square_resources(), 96));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap();
|
||||
assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK");
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = r["image"].as_u64().unwrap();
|
||||
assert_eq!(r["width"], 1.0);
|
||||
assert_eq!(r["height"], 0.5);
|
||||
let check = |s: &mut Session, ink, linked| {
|
||||
let info = s.execute("links.info", &json!({"id": id})).unwrap();
|
||||
assert_eq!(info["colorMode"], "CMYK");
|
||||
assert_eq!(info["linked"], linked);
|
||||
assert_eq!(info["ppi"], json!([144.0, 144.0]));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") };
|
||||
let blob = d.images.get(&im.key).unwrap();
|
||||
assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]);
|
||||
assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref()));
|
||||
assert_eq!(
|
||||
super::load::image_clip(blob),
|
||||
Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap())
|
||||
);
|
||||
};
|
||||
check(&mut s, 64, true);
|
||||
let triangle = clip_group(&s.doc().unwrap().doc, group);
|
||||
s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap();
|
||||
check(&mut s, 96, true);
|
||||
assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0);
|
||||
std::fs::write(&square, make(&triangle_resources(), 64)).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [id]})).unwrap();
|
||||
check(&mut s, 64, true);
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle);
|
||||
s.execute("links.embed", &json!({"ids": [id]})).unwrap();
|
||||
check(&mut s, 64, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() {
|
||||
// Half-transparent red, stored on white: (255, 127, 127) with alpha 128.
|
||||
|
||||
@@ -546,20 +546,19 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
|
||||
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
|
||||
}
|
||||
|
||||
/// What a later file loses comes before a note on the options that an earlier file gave: the
|
||||
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
|
||||
/// fit.
|
||||
/// What a later file loses comes before a note on the options: the second artboard's WebP says
|
||||
/// its type doesn't fit, before the note on the row's option that WebP doesn't read.
|
||||
#[test]
|
||||
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
|
||||
let mut s = session(2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect;
|
||||
let area = json!({"width": 30, "height": 8});
|
||||
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "interlaced": true}]}));
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("`formats[0].interlaced` was not used"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1491,3 +1490,25 @@ fn an_export_preset_adds_no_notes() {
|
||||
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art:
|
||||
/// every piece's file holds its own artboard, named after it, not the first piece's.
|
||||
#[test]
|
||||
fn each_piece_writes_its_own_native_document() {
|
||||
let mut s = session(1);
|
||||
s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let ids: Vec<u64> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
let mut assets = vec![];
|
||||
for (id, name) in ids.iter().zip(["Square", "Circle"]) {
|
||||
assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap());
|
||||
}
|
||||
let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]}));
|
||||
let written = files(&r);
|
||||
assert_eq!(written.len(), 4, "{r}");
|
||||
for (name, bytes) in written {
|
||||
let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes };
|
||||
let doc = vectorcraft_format::load(&native).unwrap();
|
||||
let board = doc.artboards[0].name.clone();
|
||||
assert!(name.contains(&board), "{name} holds the artboard {board}");
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a
|
||||
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
|
||||
}
|
||||
|
||||
/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found
|
||||
/// reading the symbol list once, and keeps the instances over it.
|
||||
#[test]
|
||||
fn art_over_an_artboard_reads_the_symbol_list_once() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let square = |d: &mut Document, side: f64| {
|
||||
let r = vectorcraft_geom::Rect::new(-side, -side, side, side);
|
||||
let ap =
|
||||
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap))
|
||||
};
|
||||
for i in 0..2000 {
|
||||
let art = square(&mut d, 0.5);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art });
|
||||
}
|
||||
let art = square(&mut d, 2.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art });
|
||||
let layer = d.layers[0].id;
|
||||
// Twenty rows of 15: the first ten over the artboard, the rest below it.
|
||||
let ids: Vec<_> = (0..300)
|
||||
.map(|i| {
|
||||
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0));
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "stylize.dropShadow".into(),
|
||||
params: json!({"x": 1, "y": 1, "blur": 0}),
|
||||
visible: true,
|
||||
});
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
|
||||
assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150);
|
||||
}
|
||||
|
||||
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
|
||||
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
|
||||
/// Document keep the document's.
|
||||
|
||||
@@ -53,41 +53,115 @@ fn text_export_writes_the_stories_in_stacking_order() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The chunk types of RIFF WebP file `file`, in order.
|
||||
fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
|
||||
assert_eq!((&file[..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..]));
|
||||
let mut chunks = Vec::new();
|
||||
let mut at = 12;
|
||||
while at + 8 <= file.len() {
|
||||
let len = u32::from_le_bytes([file[at + 4], file[at + 5], file[at + 6], file[at + 7]]) as usize;
|
||||
chunks.push([file[at], file[at + 1], file[at + 2], file[at + 3]]);
|
||||
at += 8 + len + len % 2;
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
/// The size and straight RGBA pixels of image file `file`.
|
||||
fn rgba(file: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
let (w, h) = img.dimensions();
|
||||
(w, h, img.to_rgba8())
|
||||
}
|
||||
|
||||
/// A 120 × 80 pt document filled with a grid of rectangles in 96 colors.
|
||||
fn varied_art() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 120, "height": 80})).unwrap();
|
||||
for row in 0..8 {
|
||||
for col in 0..12 {
|
||||
s.execute("shape.rectangle", &json!({"x": col * 10, "y": row * 10, "width": 10, "height": 10})).unwrap();
|
||||
let color = format!("#{:02x}{:02x}{:02x}", col * 21, row * 32, (col * 7 + row * 23) % 256);
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() {
|
||||
fn webp_is_lossless_by_default_and_lossy_when_asked() {
|
||||
let mut s = varied_art();
|
||||
let export = |s: &mut Session, p: Value| -> (Vec<u8>, Value) {
|
||||
let r = s.execute("document.export", &merge(json!({"format": "webp", "background": "white"}), p)).unwrap();
|
||||
(b64(&r), r["warnings"].clone())
|
||||
};
|
||||
let (lossless, warnings) = export(&mut s, json!({}));
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
assert_eq!(warnings, json!([]));
|
||||
// Quality doesn't change a lossless file.
|
||||
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
|
||||
|
||||
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
|
||||
assert_eq!(warnings, json!([]), "no note: the file is lossy");
|
||||
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
|
||||
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
assert_eq!((w, h), (120, 80));
|
||||
let diff: u64 = exact.iter().zip(&near).map(|(a, b)| u64::from(a.abs_diff(*b))).sum();
|
||||
let mean = diff as f64 / exact.len() as f64;
|
||||
assert!(mean <= 4.0, "mean difference {mean}");
|
||||
// Lower quality, smaller file.
|
||||
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
|
||||
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
|
||||
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
|
||||
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
|
||||
for q in [0, 100] {
|
||||
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossy_webp_keeps_translucent_pixels() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 30, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "webp"})).unwrap();
|
||||
let file = b64(&r);
|
||||
assert_eq!((&file[..4], &file[8..12], &file[12..16]), (&b"RIFF"[..], &b"WEBP"[..], &b"VP8L"[..]), "lossless bitstream");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap();
|
||||
assert_eq!(&b64(&r)[12..16], b"VP8L");
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}");
|
||||
assert_eq!(
|
||||
craft_image_codecs::decode(&b64(&r))
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8()
|
||||
.get_pixel(29, 19)
|
||||
.0,
|
||||
[0, 0, 0, 255]
|
||||
);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
|
||||
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
|
||||
let i = 4 * (y * w + x) as usize;
|
||||
[px[i], px[i + 1], px[i + 2], px[i + 3]]
|
||||
};
|
||||
// The alpha is written exactly: half covered under the rectangle, clear past it.
|
||||
let alphas = |px: &[u8]| px.chunks(4).map(|p| p[3]).collect::<Vec<u8>>();
|
||||
assert_eq!(alphas(&near), alphas(&exact));
|
||||
assert!((120..=135).contains(&at(&near, 5, 5)[3]), "{:?}", at(&near, 5, 5));
|
||||
assert_eq!(at(&near, 28, 10)[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_quality_out_of_its_range_is_refused() {
|
||||
let mut s = varied_art();
|
||||
for q in [json!(101), json!(255), json!(256), json!(-1), json!(60.5), json!("high"), json!(true)] {
|
||||
let p = json!({"format": "webp", "lossless": false, "quality": q});
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("quality"), "{q}: {e}");
|
||||
// In Export for Screens too, in a row or in the format's settings.
|
||||
let row = json!({"formats": [{"format": "webp", "lossless": false, "quality": q}]});
|
||||
assert!(s.execute("document.exportForScreens", &row).is_err(), "{q}");
|
||||
let settings = json!({"formats": [{"format": "webp"}], "settings": {"webp": {"lossless": false, "quality": q}}});
|
||||
assert!(s.execute("document.exportForScreens", &settings).is_err(), "{q}");
|
||||
}
|
||||
// A lossless file refuses it as well: the value is not a WebP quality.
|
||||
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
|
||||
let file = b64(&r["files"][0]);
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,8 +5,8 @@ use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
Knockout, MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes,
|
||||
planes_cmyk, po, separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
// ---------- plan ----------
|
||||
@@ -756,27 +756,140 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt
|
||||
Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded))
|
||||
}
|
||||
|
||||
fn has_layer_container_transparency(n: &Node) -> bool {
|
||||
!n.has_default_transparency() || n.children().into_iter().flatten().any(|c| c.is_layer() && has_layer_container_transparency(c))
|
||||
}
|
||||
|
||||
/// [`flatten_document`] for `doc` whose pattern tile images were expanded already
|
||||
/// ([`expand_transparent_tile_images`]).
|
||||
pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
|
||||
let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints;
|
||||
if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut roots = vec![];
|
||||
for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(doc, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
let needs_flatten = outlining
|
||||
|| doc.layers.iter().any(|l| {
|
||||
(o.no_transparency.is_some() && has_layer_container_transparency(l)) || o.shows_transparency(doc, l) || o.draws_see_through_image(l)
|
||||
});
|
||||
if !needs_flatten {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
let changed = o.no_transparency.is_some() && normalize_layer_transparency(&mut d, o);
|
||||
let mut roots = vec![];
|
||||
for l in d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(&d, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
if changed {
|
||||
if o.no_transparency.is_some() {
|
||||
for l in &mut d.layers {
|
||||
sanitize_container_transparency(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
return Ok(Some(d));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?;
|
||||
if o.no_transparency.is_some() {
|
||||
for l in &mut d.layers {
|
||||
sanitize_container_transparency(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
Ok(Some(d))
|
||||
}
|
||||
|
||||
/// Flatten and normalize container-level transparency (on layers and sublayers) into groups
|
||||
/// so that the flattener's plan includes them and leaves no container transparency behind.
|
||||
fn normalize_layer_transparency(d: &mut Document, o: &FlattenOptions) -> bool {
|
||||
if o.no_transparency.is_none() {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut layers = std::mem::take(&mut d.layers);
|
||||
for l in &mut layers {
|
||||
changed |= normalize_node_transparency(d, Arc::make_mut(l));
|
||||
}
|
||||
d.layers = layers;
|
||||
changed
|
||||
}
|
||||
|
||||
fn clear_transparency(n: &mut Node) {
|
||||
n.opacity = 1.0;
|
||||
n.blend = BlendMode::Normal;
|
||||
n.isolate = false;
|
||||
n.knockout = Knockout::Neutral;
|
||||
n.knockout_shape = false;
|
||||
n.extras_mut().mask = None;
|
||||
n.appearance = Appearance::default().into();
|
||||
}
|
||||
|
||||
fn normalize_node_transparency(d: &mut Document, n: &mut Node) -> bool {
|
||||
let mut changed = false;
|
||||
let is_layer = n.is_layer();
|
||||
let clips = n.clips();
|
||||
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.is_layer() {
|
||||
changed |= normalize_node_transparency(d, Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let has_transparency = !n.has_default_transparency() || n.shows_own_transparency();
|
||||
|
||||
if is_layer && has_transparency {
|
||||
let children = n.children().map_or(&[][..], Vec::as_slice);
|
||||
let (guides, art): (Vec<_>, Vec<_>) = children.iter().cloned().partition(|c| c.is_ruler_guide());
|
||||
|
||||
if art.is_empty() {
|
||||
clear_transparency(n);
|
||||
n.set_clips(false);
|
||||
changed = true;
|
||||
} else {
|
||||
let mut g = Node::group(d.alloc_id(), art);
|
||||
if clips {
|
||||
g.set_clips(true);
|
||||
}
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
g.isolate = n.isolate;
|
||||
g.knockout = n.knockout;
|
||||
g.knockout_shape = n.knockout_shape;
|
||||
g.appearance = n.appearance.clone();
|
||||
g.extras_mut().mask = n.extras_mut().mask.take();
|
||||
|
||||
n.set_clips(false);
|
||||
clear_transparency(n);
|
||||
|
||||
let mut new_children = vec![Arc::new(g)];
|
||||
new_children.extend(guides);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = new_children;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
} else if is_layer && !n.visible {
|
||||
clear_transparency(n);
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn sanitize_container_transparency(n: &mut Node) {
|
||||
if n.is_container() {
|
||||
clear_transparency(n);
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.is_container() {
|
||||
sanitize_container_transparency(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- apply ----------
|
||||
|
||||
pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o: &FlattenOptions) -> Result<(Vec<NodeId>, usize, usize)> {
|
||||
|
||||
@@ -247,10 +247,11 @@ impl Resources {
|
||||
fn expand(&mut self, d: &Document) {
|
||||
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
|
||||
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
|
||||
let boxes = d.symbol_boxes();
|
||||
while !symbols.is_empty() || !patterns.is_empty() {
|
||||
let mut more = Resources::default();
|
||||
for name in symbols.drain(..) {
|
||||
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
|
||||
if let Some(sym) = boxes.symbol(&name) {
|
||||
more.add(&sym.art);
|
||||
}
|
||||
}
|
||||
@@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
|
||||
/// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's
|
||||
/// resources).
|
||||
pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) {
|
||||
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
|
||||
let mut walk = Printed::new(d);
|
||||
for l in layers {
|
||||
walk.node(l, Some(areas));
|
||||
}
|
||||
@@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -
|
||||
/// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on
|
||||
/// a template layer.
|
||||
pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: Option<&[Rect]>) -> Option<String> {
|
||||
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
|
||||
let mut walk = Printed::new(d);
|
||||
for l in layers {
|
||||
walk.node(l, areas);
|
||||
}
|
||||
@@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
|
||||
/// The walk of [`printed_type`].
|
||||
struct Printed<'a> {
|
||||
d: &'a Document,
|
||||
/// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]).
|
||||
boxes: vectorcraft_doc::SymbolBoxes<'a>,
|
||||
/// Whether the walk is among the objects of the document, not in art drawn for one.
|
||||
own: bool,
|
||||
fonts: BTreeSet<UsedFont>,
|
||||
@@ -544,7 +548,13 @@ struct Printed<'a> {
|
||||
patterns: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Printed<'_> {
|
||||
impl<'a> Printed<'a> {
|
||||
/// A walk of `d` among its own objects, nothing found yet.
|
||||
fn new(d: &'a Document) -> Self {
|
||||
let boxes = d.symbol_boxes();
|
||||
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
|
||||
}
|
||||
|
||||
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
|
||||
/// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the
|
||||
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
|
||||
@@ -625,7 +635,7 @@ impl Printed<'_> {
|
||||
let clipped = match (clip, areas) {
|
||||
(false, _) => None,
|
||||
(true, Some(a)) => Some(self.clip(n, a)),
|
||||
(true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]),
|
||||
(true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]),
|
||||
};
|
||||
for c in children {
|
||||
self.node(c, clipped.as_deref().or(areas));
|
||||
@@ -641,9 +651,8 @@ impl Printed<'_> {
|
||||
|
||||
/// Adds the fonts of symbol `name`'s art, the first time it is shown.
|
||||
fn symbol(&mut self, name: &str) {
|
||||
let d = self.d;
|
||||
if self.symbols.insert(name.to_string())
|
||||
&& let Some(s) = d.symbols.iter().find(|s| s.name == name)
|
||||
&& let Some(s) = self.boxes.symbol(name)
|
||||
{
|
||||
self.art(&s.art);
|
||||
}
|
||||
@@ -660,12 +669,13 @@ impl Printed<'_> {
|
||||
|
||||
/// Whether what `n` paints, its effects applied, meets one of `areas`.
|
||||
fn meets(&self, n: &Node, areas: &[Rect]) -> bool {
|
||||
vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
|
||||
vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n)
|
||||
.is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
|
||||
}
|
||||
|
||||
/// The parts of `areas` inside the bounds of clip group `n` (its clipping path's).
|
||||
fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> {
|
||||
let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() };
|
||||
let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() };
|
||||
areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect()
|
||||
}
|
||||
}
|
||||
@@ -2378,4 +2388,40 @@ mod dirty_tests {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().is_dirty(), "back to the saved state");
|
||||
}
|
||||
|
||||
/// The walk Print and the exports make over 300 instances with drop shadows, among 2,000
|
||||
/// symbols, reads the symbol list once to find their symbols.
|
||||
#[test]
|
||||
fn printed_type_reads_the_symbol_list_once() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
for i in 0..2000 {
|
||||
let art = Node::path(
|
||||
d.alloc_id(),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)),
|
||||
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0),
|
||||
);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
|
||||
}
|
||||
let art = Node::path(
|
||||
d.alloc_id(),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..300 {
|
||||
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0));
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "stylize.dropShadow".into(),
|
||||
params: json!({"x": 1, "y": 1, "blur": 0}),
|
||||
visible: true,
|
||||
});
|
||||
d.insert(Some(l), usize::MAX, n).unwrap();
|
||||
}
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]);
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
|
||||
}
|
||||
}
|
||||
@@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
arrow_scale,
|
||||
profile,
|
||||
brush,
|
||||
brush_options,
|
||||
opacity,
|
||||
blend,
|
||||
visible,
|
||||
@@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
bearing: _,
|
||||
rotation: _,
|
||||
} = m;
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
// A stroke's own brush settings go with the brush they set: a new brush takes the model's.
|
||||
if a.brush != b.brush {
|
||||
n.brush_options = brush_options.clone();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values};
|
||||
#[cfg(test)]
|
||||
use columns::{fill_totals, total_text};
|
||||
pub use commands::specs;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
|
||||
@@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
|
||||
g.to_csv()
|
||||
}
|
||||
|
||||
// ---------- graph data files ----------
|
||||
|
||||
/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns
|
||||
/// read, 1 MB (1,048,576 bytes).
|
||||
pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20;
|
||||
|
||||
/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels
|
||||
/// before its series; a cell's longest text.
|
||||
const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1;
|
||||
const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1;
|
||||
const SHEET_CELL: usize = 256;
|
||||
|
||||
/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode
|
||||
/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives
|
||||
/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one.
|
||||
/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired
|
||||
/// surrogate reads as U+FFFD.
|
||||
pub fn graph_data_text(bytes: &[u8]) -> String {
|
||||
let utf16 = |rest: &[u8], le: bool| {
|
||||
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
};
|
||||
match bytes {
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
_ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() {
|
||||
Some(le) => utf16(bytes, le),
|
||||
None => String::from_utf8_lossy(bytes).into_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256
|
||||
/// characters.
|
||||
pub fn graph_cell_text(s: &str) -> String {
|
||||
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect()
|
||||
}
|
||||
|
||||
/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds
|
||||
/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file
|
||||
/// stays whole), at most a graph's rows and columns.
|
||||
pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> {
|
||||
let sep = if text.contains('\t') { '\t' } else { ',' };
|
||||
text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect()
|
||||
}
|
||||
|
||||
/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the
|
||||
/// first column the category labels (none when all are blank), and the other cells the values (a
|
||||
/// blank cell, or text that isn't a number, has none), without the empty rows and columns past
|
||||
/// the data.
|
||||
pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value {
|
||||
let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default();
|
||||
let filled = |s: &String| !s.trim().is_empty();
|
||||
// At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by
|
||||
// automation is any size, and the values are their product.
|
||||
let grid = &grid[..grid.len().min(SHEET_ROWS)];
|
||||
let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
|
||||
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
|
||||
let label = |s: &str| {
|
||||
let s = s.trim();
|
||||
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
|
||||
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
|
||||
};
|
||||
// Series labels up to the last one given (none when all are blank).
|
||||
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect();
|
||||
while series.last().is_some_and(String::is_empty) {
|
||||
series.pop();
|
||||
}
|
||||
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect();
|
||||
if categories.iter().all(String::is_empty) {
|
||||
categories.clear();
|
||||
}
|
||||
let values: Vec<Vec<Value>> = (1..rows)
|
||||
.map(|r| {
|
||||
(1..cols)
|
||||
.map(|c| {
|
||||
let t = cell(r, c);
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
json!({ "series": series, "categories": categories, "rows": values })
|
||||
}
|
||||
|
||||
/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph
|
||||
/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the
|
||||
/// value gives a graph the data that Import Data and Apply give it.
|
||||
pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> {
|
||||
let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes)));
|
||||
let mut spec = GraphSpec::default();
|
||||
apply_data(&mut spec, &data, "dataset.import")?;
|
||||
Ok(spec.to_csv())
|
||||
}
|
||||
|
||||
/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
|
||||
/// `csv` does. Data the graph already holds leaves the graph as it is.
|
||||
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
|
||||
@@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool
|
||||
if let Some(csv) = csv {
|
||||
let (s, c, r) = parse_csv(csv);
|
||||
g.series = s;
|
||||
// Series labels up to the last one given, as Graph Data's sheet keeps them
|
||||
// ([`graph_data_from_grid`]): `to_csv` writes a blank label for each series without one.
|
||||
while g.series.last().is_some_and(String::is_empty) {
|
||||
g.series.pop();
|
||||
}
|
||||
g.categories = c;
|
||||
g.set_cells(r);
|
||||
changed = true;
|
||||
|
||||
@@ -47,18 +47,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let len = edit::runs_len(&t.runs);
|
||||
let from_tool = editing == Some(id);
|
||||
let (a, b) = match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
// Where the graphic goes in text `len` bytes long.
|
||||
let range = |len: usize| -> Result<(usize, usize)> {
|
||||
Ok(match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
})
|
||||
};
|
||||
let (mut a, mut b) = range(len)?;
|
||||
let symbol = match str_param(p, "symbol") {
|
||||
Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(),
|
||||
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
|
||||
@@ -76,11 +80,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?,
|
||||
};
|
||||
// A typing session ends first: the insertion is a step of its own.
|
||||
// A typing session ends first: the insertion is a step of its own. Typing that Real-time
|
||||
// Drawing off left unapplied is applied first, and the caret is read in the typed text.
|
||||
let typing = tool.get("typing").and_then(Value::as_bool) == Some(true);
|
||||
if typing && from_tool {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
super::settle_interaction(s)?;
|
||||
let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else {
|
||||
return Err(bad(C, format!("node {} is not text", id.0)));
|
||||
};
|
||||
(a, b) = range(edit::runs_len(&t.runs))?;
|
||||
}
|
||||
let caret = s.edit("Insert Inline Symbol", |d, _| {
|
||||
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
|
||||
|
||||
@@ -36,7 +36,7 @@ use vectorcraft_doc::{
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
|
||||
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)",
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
has_doc,
|
||||
unembed
|
||||
),
|
||||
@@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule);
|
||||
|
||||
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
|
||||
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
|
||||
/// file's ([`fileio::png_clip`]).
|
||||
/// file's ([`fileio::image_clip`]).
|
||||
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
|
||||
if let Some(path) = blob.separated_clip() {
|
||||
return Some((path, FillRule::NonZero));
|
||||
}
|
||||
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
|
||||
fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd))
|
||||
}
|
||||
|
||||
/// What happens to the clip of an object a link update remakes.
|
||||
@@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
|
||||
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't
|
||||
/// name).
|
||||
fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str {
|
||||
fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"))
|
||||
}
|
||||
|
||||
/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is
|
||||
/// stored in that format, else converted.
|
||||
fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime);
|
||||
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
|
||||
}
|
||||
|
||||
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
|
||||
// `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too.
|
||||
super::params::check_exclusive_keys(C, p)?;
|
||||
let ids = ids_param(p, "ids", C)?;
|
||||
if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) {
|
||||
return unembed_to_folder(s, p, ids);
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let id = image_param(st, &doc, p, C)?;
|
||||
// `ids` of one image is `id`.
|
||||
let id = match ids.as_deref() {
|
||||
Some(&[id]) => id,
|
||||
_ => image_param(st, &doc, p, C)?,
|
||||
};
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
@@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"));
|
||||
let stored = stored_extension(blob);
|
||||
let path = str_param(p, "path");
|
||||
let ext = match path.map(fileio::extension) {
|
||||
Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e,
|
||||
Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))),
|
||||
_ => stored.to_string(),
|
||||
};
|
||||
let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime);
|
||||
let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? };
|
||||
let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?;
|
||||
let Some(path) = path else {
|
||||
let name = n.display_name();
|
||||
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
|
||||
@@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the
|
||||
/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of
|
||||
/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it
|
||||
/// are removed and the document does not change.
|
||||
fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?;
|
||||
let ids = match ids {
|
||||
Some(ids) => Some(ids),
|
||||
None => object_param(p, "id", C)?.map(|id| vec![id]),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none()));
|
||||
let mut seen = BTreeSet::new();
|
||||
if !ids.iter().all(|id| seen.insert(id.0)) {
|
||||
return Err(bad(C, "`ids` names an object twice"));
|
||||
}
|
||||
let (mut embedded, mut skipped) = (vec![], vec![]);
|
||||
for &id in &ids {
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
match (embedded.is_empty(), skipped.first()) {
|
||||
(true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))),
|
||||
(true, None) => return Err(bad(C, "select an image")),
|
||||
_ => {}
|
||||
}
|
||||
let dir = absolute_path(folder);
|
||||
writable_folder(&dir)?;
|
||||
// One image at a time: its bytes are read before its file is written, so pixels that can't be
|
||||
// read leave no file behind.
|
||||
let mut written: Vec<String> = vec![];
|
||||
let mut reads = Vec::with_capacity(embedded.len());
|
||||
let wrote = embedded.iter().try_for_each(|(id, name, blob)| {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let ext = stored_extension(blob);
|
||||
let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?;
|
||||
let name = format!("{}.{ext}", unembed_stem(name));
|
||||
let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?;
|
||||
let path = write_numbered(&dir, &name, &bytes)?;
|
||||
written.push(path.clone());
|
||||
reads.push((*id, (link_info(&path, &bytes), img)));
|
||||
Ok(())
|
||||
});
|
||||
let remove_written = |written: &[String]| {
|
||||
for path in written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
};
|
||||
if let Err(e) = wrote {
|
||||
remove_written(&written);
|
||||
return Err(e);
|
||||
}
|
||||
drop(doc);
|
||||
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
|
||||
let edited = s.edit("Unembed", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None)))
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) }))
|
||||
}
|
||||
|
||||
/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without
|
||||
/// a folder part or extension, each character a file name can't hold on some system
|
||||
/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and
|
||||
/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a
|
||||
/// device (`CON`, `NUL`, `COM1` …) gets `_` after it.
|
||||
fn unembed_stem(name: &str) -> String {
|
||||
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
|
||||
let stem = match base.rfind('.') {
|
||||
Some(i) if i > 0 => &base[..i],
|
||||
_ => base,
|
||||
};
|
||||
let mut clean = String::new();
|
||||
for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) {
|
||||
if clean.len() + c.len_utf8() > 150 {
|
||||
break;
|
||||
}
|
||||
clean.push(c);
|
||||
}
|
||||
let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']);
|
||||
if clean.is_empty() {
|
||||
return "Image".to_string();
|
||||
}
|
||||
let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9')));
|
||||
if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") {
|
||||
format!("{clean}_")
|
||||
} else {
|
||||
clean.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn writable_folder(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)?;
|
||||
if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) {
|
||||
return Err(EngineError::Other(format!("{path} is not a folder")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`,
|
||||
/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result<String> {
|
||||
use std::io::Write as _;
|
||||
let create = |to: &Path| {
|
||||
crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
vectorcraft_format::write_new_with(to, |f| f.write_all(bytes))
|
||||
};
|
||||
match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) {
|
||||
Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()),
|
||||
Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))),
|
||||
Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The web has no folders to write to.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn writable_folder(_: &str) -> Result<()> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result<String> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
/// Placement Options as `{preserve, align, clip}`.
|
||||
fn placement_json(o: PlacementOptions) -> Value {
|
||||
json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip })
|
||||
@@ -2901,4 +3064,28 @@ mod tests {
|
||||
let c = read();
|
||||
assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() {
|
||||
for (name, stem) in [
|
||||
("photo.png", "photo"),
|
||||
("Image", "Image"),
|
||||
("../../etc/passwd", "passwd"),
|
||||
("C:\\art\\logo.tif", "logo"),
|
||||
("a:b*c?d\"e<f>g|h", "a_b_c_d_e_f_g_h"),
|
||||
("tab\there", "tab_here"),
|
||||
(" name. .png", "name"),
|
||||
("..", "Image"),
|
||||
("", "Image"),
|
||||
(".hidden", ".hidden"),
|
||||
("CON.png", "CON_"),
|
||||
("lpt1", "lpt1_"),
|
||||
("COM0", "COM0"),
|
||||
("console", "console"),
|
||||
] {
|
||||
assert_eq!(unembed_stem(name), stem, "{name:?}");
|
||||
}
|
||||
let long = unembed_stem(&"é".repeat(200));
|
||||
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => defaults,
|
||||
};
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let orientation = orientation_param(p, C, cur.orientation)?;
|
||||
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
|
||||
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
|
||||
@@ -364,29 +364,91 @@ fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
|
||||
|
||||
pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.options";
|
||||
let Some((_, cur, _)) = selected_spec(s) else {
|
||||
let id = crate::cmd::object_param(p, "id", C)?;
|
||||
let target = match id {
|
||||
Some(id) => {
|
||||
let doc = &s.doc()?.doc;
|
||||
match doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { .. }) if !doc.is_editable(id) => return Err(bad(C, "the object is hidden or locked")),
|
||||
Some(NodeKind::Blend { spec, children }) => Some((id, (**spec).clone(), children.iter().map(|c| c.id).collect())),
|
||||
_ => return Err(bad(C, "not a blend")),
|
||||
}
|
||||
}
|
||||
None => selected_spec(s),
|
||||
};
|
||||
let Some((_, cur, _)) = target else {
|
||||
if ["easingType", "ramp", "colorShift"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad(C, "select a blend to set easing or color shift"));
|
||||
}
|
||||
// Nothing to set them on: the options new blends start with (easing is per blend).
|
||||
let d = s.prefs.blend_options.unwrap_or_default();
|
||||
let spacing = spacing_param(p, C, d.spacing)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
|
||||
let orientation = orientation_param(p, C, d.orientation)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation, ..d });
|
||||
return Ok(json!({ "defaults": true }));
|
||||
};
|
||||
if gives_easing(p) && any_without_spine(s) {
|
||||
let no_spine = if id.is_some() { cur.no_spine } else { any_without_spine(s) };
|
||||
if gives_easing(p) && no_spine {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
// Every value is checked before anything changes. Each blend then takes only the values that
|
||||
// were given and keeps its own for the rest, so editing several blends does not copy the first
|
||||
// one's options onto the others.
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
let has_count = given("value") || given("steps") || given("distance");
|
||||
let has_spacing = given("spacing") || has_count || p.get("smooth").and_then(Value::as_bool) == Some(true);
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let orientation = orientation_param(p, C, cur.orientation)?;
|
||||
let ease = ease_param(p, C, cur.ease)?;
|
||||
let color_shift = percent_param(p, C, "colorShift", cur.color_shift, -100.0)?;
|
||||
edit_blends(s, "Blend Options", |_, spec| {
|
||||
spec.spacing = spacing;
|
||||
spec.orientation = orientation;
|
||||
spec.ease = ease;
|
||||
spec.color_shift = color_shift;
|
||||
})
|
||||
let (has_orientation, has_kind, has_ramp, has_shift) = (given("orientation"), given("easingType"), given("ramp"), given("colorShift"));
|
||||
let set = |spec: &mut BlendSpec| {
|
||||
// A spacing mode without a count keeps the count of a blend already in that mode.
|
||||
let same_mode = std::mem::discriminant(&spacing) == std::mem::discriminant(&spec.spacing);
|
||||
if has_spacing && (has_count || !same_mode) {
|
||||
spec.spacing = spacing;
|
||||
}
|
||||
if has_orientation {
|
||||
spec.orientation = orientation;
|
||||
}
|
||||
if has_kind {
|
||||
spec.ease.kind = ease.kind;
|
||||
}
|
||||
if has_ramp {
|
||||
spec.ease.ramp = ease.ramp;
|
||||
}
|
||||
if has_shift {
|
||||
spec.color_shift = color_shift;
|
||||
}
|
||||
};
|
||||
let targets = match id {
|
||||
Some(id) => vec![id],
|
||||
None => selected_of(s, is_blend),
|
||||
};
|
||||
let doc = &s.doc()?.doc;
|
||||
let changes = |b: &NodeId| match doc.node(*b).map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => {
|
||||
let mut next = (**spec).clone();
|
||||
set(&mut next);
|
||||
next != **spec
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !targets.iter().any(changes) {
|
||||
return ok();
|
||||
}
|
||||
match id {
|
||||
Some(id) => {
|
||||
s.edit("Blend Options", |d, _| {
|
||||
if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
set(spec);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
None => edit_blends(s, "Blend Options", |_, spec| set(spec)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn blend_set_easing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blend Options…",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends; easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (omitted ones keep their value; out of range is an error); with no blend selected, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
|
||||
"{id?: id, spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends (or of the blend `id` alone; a hidden or locked one is an error); easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (each blend keeps its own value for every option omitted; out of range is an error and changes nothing; no undo step when nothing changes); with no blend selected and no `id`, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
|
||||
always,
|
||||
blend_options
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::mesh::whole;
|
||||
use super::{
|
||||
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
|
||||
bad, check_numbers, has_selection, json, named_ids, selected_roots, str_param, switch_or,
|
||||
bad, check_numbers, has_selection, json, named_ids, selected_roots, switch_or, text_param,
|
||||
};
|
||||
|
||||
pub(super) fn ids_json(ids: &[NodeId]) -> Value {
|
||||
@@ -128,8 +128,11 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
|
||||
let smooth = switch_or(p, "smooth", false, cmd)?;
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
let steps = |k: &str, n: f64| whole(n, k, cmd).map(|n| BlendSpacing::Steps(n as u32));
|
||||
let mode = str_param(p, "spacing");
|
||||
let mode = text_param(p, "spacing", cmd)?;
|
||||
let value = num("value");
|
||||
if mode.is_none() && value.is_some() {
|
||||
return Err(bad(cmd, "`value` needs `spacing` (steps|distance)"));
|
||||
}
|
||||
let sp = match mode {
|
||||
Some("smooth") | Some("smoothColor") => BlendSpacing::SmoothColor,
|
||||
Some("steps") => match value {
|
||||
@@ -157,11 +160,15 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn orientation_param(p: &Value, current: BlendOrientation) -> BlendOrientation {
|
||||
match str_param(p, "orientation") {
|
||||
Some("path") | Some("alignToPath") => BlendOrientation::AlignToPath,
|
||||
Some("page") | Some("alignToPage") => BlendOrientation::AlignToPage,
|
||||
_ => current,
|
||||
/// `orientation`: `page` or `path`; missing or null keeps `current`, and any other value is an error.
|
||||
pub(super) fn orientation_param(p: &Value, cmd: &str, current: BlendOrientation) -> Result<BlendOrientation> {
|
||||
match p.get("orientation").filter(|v| !v.is_null()) {
|
||||
None => Ok(current),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("path") | Some("alignToPath") => Ok(BlendOrientation::AlignToPath),
|
||||
Some("page") | Some("alignToPage") => Ok(BlendOrientation::AlignToPage),
|
||||
_ => Err(bad(cmd, "orientation must be page or path")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset
|
||||
//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and
|
||||
//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
|
||||
//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks,
|
||||
//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
|
||||
|
||||
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
|
||||
has_selection, switch_or,
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc,
|
||||
has_selected_member, has_selection, switch_or,
|
||||
};
|
||||
|
||||
/// Session-level (not saved) state owned by the menu commands.
|
||||
@@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
reset_bounding_box
|
||||
),
|
||||
cmd!(
|
||||
"object.rotateBoundingBox",
|
||||
"Rotate Bounding Box…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}",
|
||||
has_selection,
|
||||
rotate_bounding_box
|
||||
),
|
||||
cmd!(
|
||||
"object.rasterize",
|
||||
"Rasterize…",
|
||||
@@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
|
||||
// ---------- Reset Bounding Box ----------
|
||||
|
||||
/// Squares each selected object and every object inside it: the children of groups, compound paths,
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A
|
||||
/// path of a compound path selected on its own is squared alone, as the transforms move it alone.
|
||||
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut changed = 0;
|
||||
let squared: Vec<(NodeId, Node)> = ids
|
||||
@@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
// ---------- Rotate Bounding Box ----------
|
||||
|
||||
/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle`
|
||||
/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box
|
||||
/// turns by what takes it there, and so do the boxes of the objects inside it (the children of
|
||||
/// groups and the art of linked opacity masks), which keep their angle relative to it.
|
||||
fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.rotateBoundingBox";
|
||||
// A JSON number is always finite.
|
||||
let angle = f64_req(p, "angle", C)?;
|
||||
let absolute = switch_or(p, "absolute", false, C)?;
|
||||
// The same objects the transforms move: a path of a compound path selected on its own turns
|
||||
// its own box. Layers are left out, as they have no box.
|
||||
let owners = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let start = if absolute { 0.0 } else { d.bbox_angle(&owners) };
|
||||
// An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it.
|
||||
let target = match vectorcraft_geom::normalize_deg(start + angle) {
|
||||
a if a.abs() <= BOX_EPS_DEG => 0.0,
|
||||
a => a,
|
||||
};
|
||||
let mut changed = 0;
|
||||
let turned: Vec<(NodeId, Node)> = owners
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let n = d.node(*id)?;
|
||||
let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle);
|
||||
(by.abs() > BOX_EPS_DEG).then(|| {
|
||||
let mut c = n.clone();
|
||||
c.turn_boxes(by);
|
||||
// The selected object's box is set to the target itself, so repeated turns add no
|
||||
// rounding error to it.
|
||||
c.bbox_angle = target;
|
||||
changed += boxes(&c);
|
||||
(*id, c)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !turned.is_empty() {
|
||||
s.edit("Rotate Bounding Box", |d, _| {
|
||||
for (id, n) in turned {
|
||||
if let Some(slot) = d.node_mut(id) {
|
||||
*slot = n;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "angle": target, "changed": changed }))
|
||||
}
|
||||
|
||||
/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them.
|
||||
const BOX_EPS_DEG: f64 = 1e-6;
|
||||
|
||||
/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children
|
||||
/// and the art of a linked opacity mask, layers left out.
|
||||
fn boxes(n: &Node) -> usize {
|
||||
let own = usize::from(!n.is_layer());
|
||||
let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum();
|
||||
let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art));
|
||||
own + children + mask
|
||||
}
|
||||
|
||||
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
|
||||
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
|
||||
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
|
||||
|
||||
@@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& prev != isolation
|
||||
{
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
add_drawn_live_paint(s, prev, Some(isolation))?;
|
||||
let st = s.doc_mut()?;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, prev);
|
||||
}
|
||||
@@ -369,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
|
||||
/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one
|
||||
/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is
|
||||
/// inside it; → the group when paths were added.
|
||||
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) };
|
||||
if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g))
|
||||
}
|
||||
|
||||
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
|
||||
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
|
||||
@@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer)))
|
||||
{
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner);
|
||||
let st = s.doc_mut()?;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, inner);
|
||||
st.isolation = Some(layer);
|
||||
st.selection.set([inner]);
|
||||
st.selection.set([left]);
|
||||
st.revision += 1;
|
||||
return ok();
|
||||
}
|
||||
@@ -396,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
if let Some(leave_mode) = leave_mode {
|
||||
if let Some(i) = st.isolation {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
add_drawn_live_paint(s, i, None)?;
|
||||
crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i);
|
||||
}
|
||||
leave_mode(s, p)?;
|
||||
@@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let prev = s.active().and_then(|d| d.isolation);
|
||||
if let Some(i) = prev {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
|
||||
let st = s.doc_mut()?;
|
||||
st.isolation = None;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, i);
|
||||
let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i);
|
||||
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
|
||||
st.selection.set([target]);
|
||||
// A guide path isolated while Lock Guides is on isn't selected (#1534).
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
|
||||
@@ -56,6 +56,7 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res
|
||||
/// direct-selected anchors are what changes ([`Bounds::Anchors`]).
|
||||
fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchors: bool) -> Result<Bounds> {
|
||||
check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?;
|
||||
let refi = reference_index(p)?;
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
@@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1];
|
||||
let (m, all) = (margins(vs), margins(v));
|
||||
let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]];
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
|
||||
let rp = vectorcraft_geom::reference_point(v, refi);
|
||||
let (w, h) = wanted_size(p, v);
|
||||
// The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is
|
||||
@@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) {
|
||||
/// `b`, the box around the anchors (and the objects selected whole) square to the page, and only
|
||||
/// the anchors, their handles with them, and those objects move or scale.
|
||||
fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> Result<Value> {
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
|
||||
let refi = reference_index(p)?;
|
||||
let rp = vectorcraft_geom::reference_point(b, refi);
|
||||
let (w, h) = wanted_size(p, b);
|
||||
// A single anchor, or anchors in a line, have no size to scale on that side.
|
||||
@@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> R
|
||||
apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true)
|
||||
}
|
||||
|
||||
fn reference_index(p: &Value) -> Result<usize> {
|
||||
let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?;
|
||||
if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 {
|
||||
return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number"));
|
||||
}
|
||||
Ok(reference.min(8.0) as usize)
|
||||
}
|
||||
|
||||
/// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with
|
||||
/// symbol instances measured without the strokes in their art
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]).
|
||||
|
||||
@@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
crate::cmd::maskedit::outside_mask_editing,
|
||||
isolate
|
||||
),
|
||||
cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation),
|
||||
cmd!(
|
||||
"object.exitIsolation",
|
||||
"Exit Isolation Mode",
|
||||
[],
|
||||
None,
|
||||
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
|
||||
has_doc,
|
||||
exit_isolation
|
||||
),
|
||||
cmd!(
|
||||
"object.setProps",
|
||||
"Object Properties",
|
||||
@@ -287,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
|
||||
@@ -137,6 +137,24 @@ fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for a linked file the package would copy with an Export for Screens folder outside
|
||||
/// the read roots in the native document it is or carries.
|
||||
const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots";
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when
|
||||
/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder
|
||||
/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not
|
||||
/// rewritten, would name it. The error names no file or folder.
|
||||
fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
@@ -153,6 +171,20 @@ fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTre
|
||||
fonts
|
||||
}
|
||||
|
||||
/// The document whose links are copied beside the placed file `name` (`bytes`), which is copied
|
||||
/// as it is: a `.ai` file's editing data ([`super::place::document::editing_data`]), or the native
|
||||
/// document an EPS or PostScript file carries, which placing it reads. `None` for other files and
|
||||
/// for data that can't be read.
|
||||
fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if let Some(doc) = super::place::document::editing_data(name, bytes) {
|
||||
return Some(doc);
|
||||
}
|
||||
if !super::place::document::is_postscript(bytes) {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_format::load(&vectorcraft_eps::native(bytes)?).ok()
|
||||
}
|
||||
|
||||
/// Collect dependencies depth-first so nested VectorCraft files are rewritten before
|
||||
/// their parents: each parent can record the final hash of the rewritten child.
|
||||
/// Cycles, excessive nesting, and unreadable children are reported, not fatal.
|
||||
@@ -200,7 +232,7 @@ impl<'a> Collector<'a> {
|
||||
self.warnings.push(message);
|
||||
}
|
||||
|
||||
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
|
||||
/// Warns when a file that placed `.ai` or EPS file `source` links (`name`) was copied as `copy`: the
|
||||
/// copy of `source` finds it only by its name, beside it.
|
||||
/// `path` is the link's path as the warning names it.
|
||||
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
|
||||
@@ -213,8 +245,8 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` file's editing data,
|
||||
/// whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
|
||||
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` or EPS file's editing
|
||||
/// data, whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
|
||||
/// document whose links (with the same paths as `doc`'s) are looked for, and where from, when
|
||||
/// not `doc` from `source`.
|
||||
fn collect(
|
||||
@@ -311,12 +343,13 @@ impl<'a> Collector<'a> {
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
|
||||
}
|
||||
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
|
||||
// read from its editing data links are copied beside it.
|
||||
// A placed PDF, .ai or EPS file is copied as it is, as an image is; the files a .ai
|
||||
// file read from its editing data, or an EPS file read from the native document it
|
||||
// carries, links are copied beside it.
|
||||
let pages = placed.get(&file.path);
|
||||
let placed_file = pages.is_some();
|
||||
check_carried_scripts(&file.name, &bytes, found_path)?;
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if placed_file && let Some(mut art) = editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
@@ -348,6 +381,7 @@ impl<'a> Collector<'a> {
|
||||
options.profiles = saved.profiles;
|
||||
options.compress = compressed;
|
||||
options.include_linked = include_linked;
|
||||
let nested = super::fileio::with_readable_settings_folder(&nested);
|
||||
match vectorcraft_format::save_with(&nested, &options) {
|
||||
Ok(rewritten) => bytes = rewritten,
|
||||
Err(e) => self.warn(
|
||||
@@ -366,6 +400,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
check_carried_folder(&file.name, &bytes)?;
|
||||
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
|
||||
self.copies.insert(found_path.to_string(), copy.clone());
|
||||
local.insert(file.path.clone(), copy);
|
||||
@@ -505,7 +540,9 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
}
|
||||
let root = folder.map(|f| Path::new(f).join(&name));
|
||||
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
|
||||
// The package's document leaves out an Export for Screens folder outside the read roots.
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
|
||||
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
|
||||
}
|
||||
|
||||
@@ -67,14 +67,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent
Line truncated
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification
Line truncated
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
cmd!(
|
||||
"text.convertListToText",
|
||||
"Convert to Text",
|
||||
[],
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
|
||||
has_doc,
|
||||
@@ -482,6 +482,66 @@ fn list_level_param(p: &Value, cmd: &str) -> Result<Option<u8>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to
|
||||
/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`,
|
||||
/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before.
|
||||
/// None without either; giving both is an error.
|
||||
fn list_start_param(p: &Value, cmd: &str) -> Result<Option<Option<u32>>> {
|
||||
let (key, other) = ("startNumber", "restartNumbering");
|
||||
let start = p.get(key).filter(|v| !v.is_null());
|
||||
let restart = p.get(other).filter(|v| !v.is_null());
|
||||
if start.is_some() && restart.is_some() {
|
||||
return Err(bad(cmd, format!("give `{key}` or `{other}`, not both")));
|
||||
}
|
||||
if let Some(v) = start {
|
||||
let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START);
|
||||
return match v.as_f64() {
|
||||
Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))),
|
||||
Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))),
|
||||
None => Err(bad(cmd, format!("`{key}` must be a whole number"))),
|
||||
};
|
||||
}
|
||||
// `check_switches` has already refused a value that is not true or false.
|
||||
Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1)))
|
||||
}
|
||||
|
||||
/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices;
|
||||
/// None: every paragraph), so they count on from the paragraph before. A first paragraph that
|
||||
/// continues from the frame before ([`TextObject::first_para_continues`]) keeps its number: its
|
||||
/// item begins in that frame.
|
||||
///
|
||||
/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues
|
||||
fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option<std::ops::Range<usize>>) {
|
||||
let mut paras = paras.unwrap_or(0..t.paragraph_count());
|
||||
if paras.start == 0 && t.first_para_continues {
|
||||
paras.start = 1;
|
||||
}
|
||||
if paras.is_empty() {
|
||||
return;
|
||||
}
|
||||
t.edit_paras(Some(paras), |p| {
|
||||
if let Some(l) = p.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph
|
||||
/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go.
|
||||
/// A first paragraph that continues from the frame before ([`TextObject::first_para_continues`]) is
|
||||
/// skipped: its item begins in that frame.
|
||||
///
|
||||
/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues
|
||||
fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option<std::ops::Range<usize>>) -> (Option<usize>, Option<usize>) {
|
||||
let paras = paras.unwrap_or(0..t.paragraph_count());
|
||||
let text = t.plain_text();
|
||||
let pieces: Vec<&str> = text.split('\n').collect();
|
||||
let mut numbered = paras.filter(|&i| !(i == 0 && t.first_para_continues) && t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable();
|
||||
let first = numbered.peek().copied();
|
||||
let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty()));
|
||||
(with_text, first)
|
||||
}
|
||||
|
||||
/// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap
|
||||
/// (in the type's own units), Scale and Alignment.
|
||||
fn set_warichu(
|
||||
@@ -523,6 +583,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"koreanLineBreakAnywhere",
|
||||
"bunriKinshi",
|
||||
"kurikaeshiMojiShori",
|
||||
"restartNumbering",
|
||||
],
|
||||
C,
|
||||
)?;
|
||||
@@ -582,6 +643,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"number",
|
||||
"listAlign",
|
||||
"listLevel",
|
||||
"startNumber",
|
||||
"restartNumbering",
|
||||
"hyphenate",
|
||||
"wordsLongerThan",
|
||||
"afterFirst",
|
||||
@@ -762,6 +825,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left });
|
||||
// …and `listLevel` the level of every list paragraph, 1 to 9.
|
||||
let list_level = list_level_param(p, C)?;
|
||||
// …and `startNumber` or `restartNumbering` the number of the first numbered paragraph.
|
||||
let list_start = list_start_param(p, C)?;
|
||||
let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some();
|
||||
let spacing = |k: &str| spacing_param(p, k, C);
|
||||
let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?);
|
||||
@@ -885,9 +950,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A numbered list for list "number", or without `list` for a number style.
|
||||
let numbered = list == Some("number") || (list.is_none() && number.is_some());
|
||||
// The list's other settings (the marker's alignment) stay as they were.
|
||||
// A paragraph made bulleted keeps no number of its own.
|
||||
para.list = on.then(|| vectorcraft_doc::text::ParaList {
|
||||
bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(),
|
||||
number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()),
|
||||
start: had.and_then(|l| l.start).filter(|_| numbered),
|
||||
..had.unwrap_or_default()
|
||||
});
|
||||
// A paragraph that joins a list with no left or first-line indent gets a
|
||||
@@ -912,6 +979,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &mut doc;
|
||||
// The paragraph change, for the graph labels to keep.
|
||||
let mut para_change = None;
|
||||
// Where the number `startNumber` or `restartNumbering` gives goes: the first numbered
|
||||
// paragraph with text the call touches, through every target, else the first numbered one.
|
||||
let (mut start_with_text, mut start_first) = (None, None);
|
||||
let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"));
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
@@ -1021,14 +1091,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
para.composer = v;
|
||||
}
|
||||
};
|
||||
t.edit_paras(span, |para| paras(para, &mut out_of_order));
|
||||
t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order));
|
||||
if let Some(name) = out_of_order {
|
||||
return Err(out_of_order_error(name));
|
||||
}
|
||||
match list_start {
|
||||
Some(None) => clear_list_start(t, span),
|
||||
Some(Some(_)) if start_with_text.is_none() => {
|
||||
let (with_text, first) = list_start_candidates(t, span);
|
||||
start_with_text = with_text.map(|i| (*id, i));
|
||||
start_first = start_first.or(first.map(|i| (*id, i)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
super::typecmd::refresh_bounds(t);
|
||||
changed |= *t != before;
|
||||
para_change = Some(paras);
|
||||
}
|
||||
if let Some(Some(n)) = list_start
|
||||
&& let Some((id, i)) = start_with_text.or(start_first)
|
||||
&& let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind)
|
||||
{
|
||||
let before = t.clone();
|
||||
t.edit_paras(Some(i..i + 1), |p| {
|
||||
if let Some(l) = p.list.as_mut() {
|
||||
l.start = Some(n);
|
||||
}
|
||||
});
|
||||
super::typecmd::refresh_bounds(t);
|
||||
changed |= *t != before;
|
||||
}
|
||||
// Graph labels keep a change made to all of their text through the graph being drawn again.
|
||||
if range.is_none() {
|
||||
let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0));
|
||||
@@ -1276,7 +1368,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool {
|
||||
|
||||
/// The frames of the story that type object `id` belongs to (its thread in thread order, else `id`
|
||||
/// alone), each with the length of its text in bytes.
|
||||
fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
|
||||
pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let d = &st.doc;
|
||||
let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]);
|
||||
@@ -1314,6 +1406,16 @@ fn move_editing_selection(
|
||||
at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>()
|
||||
};
|
||||
let (anchor, caret) = (story(anchor), story(caret));
|
||||
select_story_range(s, id, anchor, caret)
|
||||
}
|
||||
|
||||
/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that
|
||||
/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there,
|
||||
/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the
|
||||
/// selection when it was not selected.
|
||||
pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> {
|
||||
let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>();
|
||||
let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n);
|
||||
let after = story_frames(s, id);
|
||||
let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret);
|
||||
let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) };
|
||||
|
||||
@@ -258,11 +258,16 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
|
||||
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
|
||||
/// neither null, is a parameter error ([`check_exclusive_keys`]).
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
|
||||
("addon.pathtools.cornerSet", "items", "ids"),
|
||||
("addon.pathtools.cornerRemove", "items", "ids"),
|
||||
("links.unembed", "id", "ids"),
|
||||
("links.unembed", "path", "folder"),
|
||||
];
|
||||
|
||||
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
|
||||
/// error naming the pair.
|
||||
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
|
||||
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
|
||||
if given(key).is_some() && given(other).is_some() {
|
||||
@@ -649,6 +654,7 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"transparency.setOpacityMask",
|
||||
"transparency.unlinkOpacityMask",
|
||||
"type.pathOptions",
|
||||
"webExport.optimizeToFileSize",
|
||||
"webExport.presets.save",
|
||||
"webExport.settings",
|
||||
];
|
||||
@@ -663,18 +669,28 @@ fn pdf_option_tree() -> Value {
|
||||
tree
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`),
|
||||
/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each
|
||||
/// is one value of the message, so a catalog can match the message and translate it.
|
||||
fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError {
|
||||
bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?"))
|
||||
}
|
||||
|
||||
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
|
||||
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
match (schema.get(key), value) {
|
||||
(None, _) => {
|
||||
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
|
||||
let why = match nearest(key, &keys) {
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
let key = shown_key(key);
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
let near = nearest(key, &keys);
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => {
|
||||
let (object, keys) = (within.trim_end_matches('.'), keys.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
_ => {}
|
||||
@@ -691,14 +707,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
return Err(bad(
|
||||
id,
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
|
||||
None => format!("unknown parameter `{within}{key}`; {why_not}"),
|
||||
},
|
||||
));
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => bad(id, format!("unknown parameter `{key}`; {why_not}")),
|
||||
});
|
||||
}
|
||||
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
|
||||
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
|
||||
@@ -797,12 +810,15 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
|
||||
let formats = screen_formats();
|
||||
for (format, options) in settings {
|
||||
if !formats.contains(&format.as_str()) {
|
||||
let why = match nearest(format, &formats) {
|
||||
Some(near) => format!("did you mean `{within}settings.{near}`?"),
|
||||
None => format!("`{within}settings` takes: {}", formats.join(", ")),
|
||||
};
|
||||
let format = shown_key(format);
|
||||
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
|
||||
let near = nearest(format, &formats);
|
||||
let key = format!("{within}settings.{}", shown_key(format));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}settings.{near}")),
|
||||
None => {
|
||||
let (object, keys) = (format!("{within}settings"), formats.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Value::Object(options) = options {
|
||||
check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?;
|
||||
|
||||
@@ -1874,20 +1874,85 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
cut.finish(d)?;
|
||||
// Each cut leaves one of its two coincident anchors selected, so a drag pulls the ends apart.
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(id);
|
||||
sel.anchors.entry(id).or_default().insert(a);
|
||||
}
|
||||
select_cut_ends(sel, &picked);
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(super::draw2::ids_json(&ids))
|
||||
}
|
||||
|
||||
/// Replaces the selection with the anchors in `picked`: each id once, in the order it first
|
||||
/// appears, with every anchor listed for it. An empty `picked` clears the selection.
|
||||
fn select_cut_ends(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `select_cut_ends` by clearing the selection and adding each id in turn, kept as the
|
||||
/// reference the one-call version must match.
|
||||
fn select_cut_ends_one_by_one(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, the art made since the last deselect included.
|
||||
fn busy_selection() -> Selection {
|
||||
Selection {
|
||||
objects: vec![NodeId(90), NodeId(91)],
|
||||
anchors: [(NodeId(90), [(0, 3)].into())].into(),
|
||||
segments: [(NodeId(91), [(0, 1)].into())].into(),
|
||||
key: Some(NodeId(90)),
|
||||
target: Some(NodeId(91)),
|
||||
slices: vec![NodeId(92)],
|
||||
guides: vec![NodeId(93)],
|
||||
key_guide: Some(NodeId(93)),
|
||||
key_anchor: Some((NodeId(90), (0, 3))),
|
||||
symbol_part: Some(vectorcraft_doc::SymbolPart { instance: NodeId(94), path: vec![0, 2] }),
|
||||
on_path_member: Some(NodeId(95)),
|
||||
new_art: Arc::new([NodeId(90), NodeId(97)].into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cut ends of open paths, of an opened closed path, of a path of several subpaths (one id
|
||||
/// with several anchors, first seen before other ids), long lists and an empty one give the
|
||||
/// same selection, every field, as clearing it and adding each id in turn.
|
||||
#[test]
|
||||
fn selecting_cut_ends_matches_adding_them_one_by_one() {
|
||||
let n = NodeId;
|
||||
let mut cases: Vec<Vec<(NodeId, (usize, usize))>> = vec![
|
||||
vec![],
|
||||
vec![(n(1), (0, 0)), (n(2), (0, 0))],
|
||||
vec![(n(5), (0, 0))],
|
||||
vec![(n(7), (0, 0)), (n(3), (1, 0)), (n(8), (0, 0)), (n(3), (2, 0)), (n(7), (0, 0)), (n(3), (0, 0))],
|
||||
];
|
||||
let mut rng = Lcg(11);
|
||||
for len in [50, 2_000] {
|
||||
cases.push((0..len).map(|_| (n(rng.below(300) + 1), (rng.below(4) as usize, 0))).collect());
|
||||
}
|
||||
for picked in &cases {
|
||||
for start in [Selection::default(), busy_selection()] {
|
||||
let (mut ours, mut theirs) = (start.clone(), start.clone());
|
||||
select_cut_ends(&mut ours, picked);
|
||||
select_cut_ends_one_by_one(&mut theirs, picked);
|
||||
assert_eq!(ours, theirs, "{picked:?}");
|
||||
assert_eq!(ours.new_art, start.new_art);
|
||||
}
|
||||
}
|
||||
let mut sel = busy_selection();
|
||||
select_cut_ends(&mut sel, &cases[3]);
|
||||
assert_eq!(sel.objects, [n(7), n(3), n(8)]);
|
||||
assert_eq!(sel.anchors[&n(3)].iter().collect::<Vec<_>>(), [&(0, 0), &(1, 0), &(2, 0)]);
|
||||
assert_eq!((sel.anchors.len(), sel.key, sel.target, sel.symbol_part.is_some()), (3, None, None, false));
|
||||
}
|
||||
|
||||
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
|
||||
/// reference the one-pass version must match.
|
||||
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unite",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Unite)
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Minus Front",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusFront)
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Intersect",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Intersect)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Exclude",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Exclude)
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Minus Back",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusBack)
|
||||
),
|
||||
@@ -285,6 +285,37 @@ impl Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds
|
||||
/// a line or another open path that encloses no area once closed, and so does not change the result's
|
||||
/// shape (the result still takes its paint from the frontmost object, as without the warning).
|
||||
pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first";
|
||||
|
||||
/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd
|
||||
/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed
|
||||
/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it.
|
||||
fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool {
|
||||
path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
|
||||
// A point or a straight two-anchor line needs no area measurement.
|
||||
if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) {
|
||||
return true;
|
||||
}
|
||||
let mut closed = sp.clone();
|
||||
closed.closed = true;
|
||||
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where the
|
||||
// signed area is not zero (a contour traced twice).
|
||||
!(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0
|
||||
})
|
||||
}
|
||||
|
||||
/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it.
|
||||
fn closed_area(path: &PathData, rule: FillRule) -> f64 {
|
||||
let mut closed = path.clone();
|
||||
for sp in &mut closed.subpaths {
|
||||
sp.closed = true;
|
||||
}
|
||||
po::area(&closed, rule)
|
||||
}
|
||||
|
||||
/// All subpaths of a path or compound path node, in document coordinates, with its fill rule.
|
||||
pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
match &n.kind {
|
||||
@@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
|
||||
let label = pf_label(op);
|
||||
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let (ids, no_area) = s.edit(label, |d, sel| {
|
||||
// Build the stack (back → front); names are separate from paint/style identity.
|
||||
let mut no_area = false;
|
||||
let mut styles: Vec<Style> = vec![];
|
||||
let mut shapes: Vec<po::Shape> = vec![];
|
||||
let mut names: Vec<Option<String>> = vec![];
|
||||
@@ -759,6 +791,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
continue;
|
||||
};
|
||||
let top = *top;
|
||||
no_area = no_area || parts.iter().any(|(_, p, r)| has_open_subpath_without_area(p, *r));
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
|
||||
push(
|
||||
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
|
||||
@@ -771,6 +804,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
} else {
|
||||
for (l, clip) in &lv {
|
||||
if let Some((p, r)) = node_path(l) {
|
||||
no_area = no_area || (shape_mode && has_open_subpath_without_area(&p, r));
|
||||
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
|
||||
}
|
||||
}
|
||||
@@ -798,6 +832,21 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if results.iter().all(|r| r.path.is_empty()) {
|
||||
// The lines left the result empty when the other shapes give a result without them, or
|
||||
// when nothing else is selected. A closed shape without area stays among the others.
|
||||
let lines_emptied = no_area && {
|
||||
let kept: Vec<po::Shape> = shapes
|
||||
.iter()
|
||||
.filter(|s| closed_area(&s.path, s.rule) > 0.0 || !has_open_subpath_without_area(&s.path, s.rule))
|
||||
.cloned()
|
||||
.collect();
|
||||
kept.is_empty() || po::pathfinder_with(op, &kept, options.precision).iter().any(|r| !r.path.is_empty())
|
||||
};
|
||||
if lines_emptied {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first"
|
||||
)));
|
||||
}
|
||||
return Err(EngineError::Other(format!("{label} produced an empty result")));
|
||||
}
|
||||
let new_node = if shape_mode {
|
||||
@@ -833,9 +882,13 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
};
|
||||
let nid = d.wrap(&roots, |_| new_node)?;
|
||||
sel.set([nid]);
|
||||
Ok(vec![nid])
|
||||
Ok((vec![nid], no_area))
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
let mut out = ids_json(&ids);
|
||||
if no_area {
|
||||
out["warning"] = json!(SHAPE_MODE_OPEN_PATH_NO_AREA);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Trap ----------
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::Result;
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::clipboard::resources::{Imported, SwatchChoices};
|
||||
use super::swatchlib::LibraryInfo;
|
||||
|
||||
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
|
||||
@@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
|
||||
|
||||
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
|
||||
/// painted with it does: the same pattern there already is used, and a name another pattern or
|
||||
/// swatch has gets a number → the pattern's name in `d`.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
|
||||
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
|
||||
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
|
||||
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
|
||||
/// to Swatches adds such a color, so that the pattern keeps the library's colors.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
|
||||
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
|
||||
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
|
||||
let from = |to: &str| {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
|
||||
renamed.unwrap_or(to).to_string()
|
||||
};
|
||||
let added = d
|
||||
.swatches_iter()
|
||||
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
|
||||
.map(|w| (from(&w.name), w.name.clone()))
|
||||
.collect();
|
||||
Ok((imported_name(&imported, name), added))
|
||||
}
|
||||
|
||||
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
|
||||
fn gather(lib: &Document, name: &str) -> Clipboard {
|
||||
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
|
||||
Clipboard::gather(lib, vec![user])
|
||||
}
|
||||
|
||||
/// The name pattern `name` has in the document `imported` went into.
|
||||
fn imported_name(imported: &Imported, name: &str) -> String {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
|
||||
Ok(renamed.unwrap_or(name).to_string())
|
||||
renamed.unwrap_or(name).to_string()
|
||||
}
|
||||
|
||||
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
|
||||
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
|
||||
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
|
||||
/// with, is imported into a copy of `d`, so that those resources are compared too.
|
||||
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
|
||||
let gathered = gather(lib, name);
|
||||
let only_pattern = gathered.patterns.len() == 1
|
||||
&& gathered.symbols.is_empty()
|
||||
&& gathered.swatches.is_empty()
|
||||
&& gathered.graphic_styles.is_empty()
|
||||
&& gathered.char_styles.is_empty()
|
||||
&& gathered.para_styles.is_empty()
|
||||
&& gathered.brushes.is_empty()
|
||||
&& gathered.images.is_empty();
|
||||
if only_pattern {
|
||||
return existing_pattern(d, lib, name);
|
||||
}
|
||||
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
|
||||
// options and as many art objects; without one, the document is not copied.
|
||||
let def = lib.pattern(name)?;
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let copy = |n: &str| {
|
||||
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
|
||||
return None;
|
||||
}
|
||||
let mut probe = d.clone();
|
||||
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
|
||||
(imported.added == 0).then(|| imported_name(&imported, name))
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
@@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Placed File Info",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
always,
|
||||
info
|
||||
),
|
||||
|
||||
@@ -84,6 +84,8 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.shapes.star",
|
||||
"addon.type.releasePath",
|
||||
"addon.type.textTweaker",
|
||||
"addon.units.convert",
|
||||
"addon.units.selectionSize",
|
||||
"appearance.addEffect",
|
||||
"appearance.addFill",
|
||||
"appearance.addStroke",
|
||||
@@ -124,6 +126,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"brush.list",
|
||||
"brush.move",
|
||||
"brush.new",
|
||||
"brush.objectOptions",
|
||||
"brush.options",
|
||||
"brush.placeArt",
|
||||
"brush.remove",
|
||||
@@ -366,6 +369,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.repeat.release",
|
||||
"object.resetBoundingBox",
|
||||
"object.rotate",
|
||||
"object.rotateBoundingBox",
|
||||
"object.scale",
|
||||
"object.setBounds",
|
||||
"object.setLiveShape",
|
||||
@@ -548,6 +552,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.toggle",
|
||||
"select.update",
|
||||
"shape.arc",
|
||||
"shape.circleThroughPoints",
|
||||
"shape.ellipse",
|
||||
"shape.flare",
|
||||
"shape.line",
|
||||
|
||||
@@ -368,6 +368,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool),
|
||||
p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool),
|
||||
p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)),
|
||||
// Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013).
|
||||
p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool),
|
||||
p!("historyStates", "Performance", "", "History States", int(5, 1000)),
|
||||
p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool),
|
||||
p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Preview",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
@@ -82,11 +82,38 @@ pub(crate) fn settings_over(cmd: &str, mut v: Value, p: &Value) -> Result<PrintS
|
||||
Some(over @ Value::Object(_)) => merge(&mut v, over),
|
||||
Some(_) => return Err(bad(cmd, "settings must be an object")),
|
||||
}
|
||||
link_scale(cmd, &mut v, p.get("settings").and_then(|s| s.get("scale")).filter(|s| s.is_object()))?;
|
||||
let set = PrintSettings::deserialize(&v).map_err(|e| bad(cmd, format!("print settings: {e}")))?;
|
||||
set.check().map_err(|e| pdf_error(cmd, e))?;
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// Keep the custom scale's width and height equal in the merged settings `v` while `scale.linked`
|
||||
/// is on, after `over` (the request's `scale`) was merged in: the one side the request gives sets
|
||||
/// the other, and otherwise the height takes the width (as turning the link on does). A request
|
||||
/// that gives a different width and height without a `linked` key turns the link off; with
|
||||
/// `linked: true`, or with `linked: null` over a linked scale, it is refused.
|
||||
fn link_scale(cmd: &str, v: &mut Value, over: Option<&Value>) -> Result<()> {
|
||||
let given = |k: &str| over.and_then(|o| o.get(k)).filter(|x| !x.is_null());
|
||||
let (width, height) = (given("width").cloned(), given("height").cloned());
|
||||
let apart = matches!((&width, &height), (Some(w), Some(h)) if w.as_f64() != h.as_f64());
|
||||
let Some(scale) = v.get_mut("scale").and_then(Value::as_object_mut) else { return Ok(()) };
|
||||
if apart && over.and_then(|o| o.get("linked")).is_none() {
|
||||
scale.insert("linked".into(), Value::Bool(false));
|
||||
}
|
||||
if scale.get("linked") != Some(&Value::Bool(true)) {
|
||||
return Ok(());
|
||||
}
|
||||
if apart {
|
||||
return Err(bad(cmd, "scale: give one percentage, or the same width and height, while scale.linked is on (linked: false scales them apart)"));
|
||||
}
|
||||
let (from, to) = if width.is_none() && height.is_some() { ("height", "width") } else { ("width", "height") };
|
||||
if let Some(value) = scale.get(from).cloned() {
|
||||
scale.insert(to.into(), value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn to_json(set: &PrintSettings) -> Result<Value> {
|
||||
serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
@@ -378,11 +378,12 @@ pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool)
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
/// that is its only visible raster effect and is its own (not a fill's or a stroke's): made of `n`
|
||||
/// without that effect and without its transparency, which stays on the object. When Transform
|
||||
/// effects after the Rasterize effect move its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
/// effects after the Rasterize effect move or copy its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them once and placed by each of their maps, as the canvas
|
||||
/// draws it: with copies, a group of the placements with the lowest first. `None` otherwise, when
|
||||
/// those Transform effects flatten every placement, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let (whole, r, maps) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -395,33 +396,58 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
match maps.as_deref() {
|
||||
None => Some(image),
|
||||
Some([map]) => {
|
||||
image.transform(*map, false);
|
||||
Some(image)
|
||||
}
|
||||
Some(maps) => {
|
||||
// Each placement is an object of its own on the one image's pixels.
|
||||
let placed: Vec<Arc<Node>> = maps
|
||||
.iter()
|
||||
.map(|map| {
|
||||
let mut copy = d.reid(&image);
|
||||
copy.transform(*map, false);
|
||||
Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
Some(Node::group(d.alloc_id(), placed))
|
||||
}
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
/// that move or copy the image, without the Rasterize effect and without its transparency; that
|
||||
/// effect's options; and the maps those Transform effects place the image by, the lowest first,
|
||||
/// without those that flatten it. `None` when `n` has another raster effect, when the Rasterize
|
||||
/// effect is not its own, or when those Transform effects flatten every placement.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Vec<Affine>>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let (stage, maps) = match vectorcraft_render::rasterize_stage(d, n) {
|
||||
Some((stage, maps)) => {
|
||||
let maps: Vec<Affine> = maps.into_iter().filter(|m| places(*m)).collect();
|
||||
if maps.is_empty() {
|
||||
return None;
|
||||
}
|
||||
(Some(stage), Some(maps))
|
||||
}
|
||||
None => (None, None),
|
||||
};
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
Some((whole, r, maps))
|
||||
}
|
||||
|
||||
/// Does `map`, one of those a Rasterize image is placed by ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// place it? Not when it flattens it to a line or a point: the canvas draws nothing there.
|
||||
fn places(map: Affine) -> bool {
|
||||
let det = map.determinant();
|
||||
det.is_finite() && det.abs() > 1e-12
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
@@ -658,27 +684,32 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport)
|
||||
.then(|| nodes.iter().map(|n| walk(out, n, report).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
|
||||
}
|
||||
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it
|
||||
/// ([`vectorcraft_render::rasterize_stage`]): the image is made of the art before those Transform
|
||||
/// effects and moved by them, as the canvas draws it, which baking the geometry effects first would
|
||||
/// lose. A map that flattens the image leaves an empty group, as the canvas draws nothing. Inside
|
||||
/// groups, layers and opacity masks, the members are looked at the same way. `None` when nothing in
|
||||
/// `n` changes; hidden objects and template layers stay as they are.
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it, or as a
|
||||
/// group of that image's placements when they copy it ([`vectorcraft_render::rasterize_stage`]):
|
||||
/// the image is made of the art before those Transform effects and placed by them, as the canvas
|
||||
/// draws it, which baking the geometry effects first would lose. Maps that flatten every placement
|
||||
/// leave an empty group, as the canvas draws nothing. Inside groups, layers and opacity masks, the
|
||||
/// members are looked at the same way. `None` when nothing in `n` changes; hidden objects and
|
||||
/// template layers stay as they are.
|
||||
fn staged(out: &mut Document, n: &Node, report: &mut FlattenReport) -> Option<Node> {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, map)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
if let Some((_, maps)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
let mut v = n.clone();
|
||||
strip_raster(&mut v, false);
|
||||
let det = map.determinant();
|
||||
if !(det.is_finite() && det.abs() > 1e-12) {
|
||||
if !maps.iter().any(|m| places(*m)) {
|
||||
v.appearance = Default::default();
|
||||
v.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
return Some(v);
|
||||
}
|
||||
let image = raster_image(out, n, false, false)?;
|
||||
report.record(n, &image);
|
||||
// The placements share one image: its resolution is the first one's.
|
||||
let first = match &image.kind {
|
||||
NodeKind::Group { children, clip: false } => children.first().map_or(&image, |c| &**c),
|
||||
_ => &image,
|
||||
};
|
||||
report.record(n, first);
|
||||
let mut m = replace_with_image(v, image);
|
||||
staged_mask(out, &mut m, report);
|
||||
return Some(m);
|
||||
|
||||
@@ -66,11 +66,13 @@ impl FlattenReport {
|
||||
lowest
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let name = r.name.map(|name| format!(" ({name})")).unwrap_or_default();
|
||||
format!(
|
||||
"raster effects on object {}{name}: requested {:.1} ppi, achieved {:.1} ppi due to the 64 million pixel cap",
|
||||
r.id.0, self.requested_ppi, r.achieved_ppi
|
||||
)
|
||||
// The id and the name are one value of the message, so a catalog can match it.
|
||||
let object = match r.name {
|
||||
Some(name) => format!("{} ({name})", r.id.0),
|
||||
None => r.id.0.to_string(),
|
||||
};
|
||||
let (requested, achieved) = (self.requested_ppi, r.achieved_ppi);
|
||||
format!("raster effects on object {object}: requested {requested:.1} ppi, achieved {achieved:.1} ppi due to the 64 million pixel cap")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -127,4 +129,23 @@ mod tests {
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains(&format!("object {}", original.id.0)), "{:?}", warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warning_names_the_object_by_its_id_and_its_name() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.raster_effects_ppi = 300.0;
|
||||
let mut named = Node::group(NodeId(7), vec![]);
|
||||
named.name = Some("Logo".into());
|
||||
let unnamed = Node::group(NodeId(8), vec![]);
|
||||
let mut report = FlattenReport::new(Which::All, &doc);
|
||||
report.record(&named, &image(72.0));
|
||||
report.record(&unnamed, &image(150.0));
|
||||
assert_eq!(
|
||||
report.warnings(),
|
||||
[
|
||||
"raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap",
|
||||
"raster effects on object 8: requested 300.0 ppi, achieved 150.0 ppi due to the 64 million pixel cap",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
// A null in groupColors removes the group's swatch at its place.
|
||||
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
|
||||
// at its place its color, without the Global Adjust.
|
||||
let own: Vec<Option<Color>> = match group {
|
||||
Some(g) => {
|
||||
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
.enumerate()
|
||||
.map(|(i, v)| match v {
|
||||
Value::Null => Ok(None),
|
||||
// Past the group's swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => match own.get(i) {
|
||||
Some(Some(c)) => Ok(Some(*c)),
|
||||
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
|
||||
None => Ok(None),
|
||||
},
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Select menu.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -308,24 +308,30 @@ pub(crate) fn selectable(d: &Document, iso: Option<NodeId>) -> Vec<NodeId> {
|
||||
/// them, leaving out every hidden or locked object with what it holds. `f` returns whether to
|
||||
/// visit the objects inside the one it is given.
|
||||
pub(crate) fn walk_selectable(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if n.visible && !n.locked && f(n) {
|
||||
walk_selectable_in(d, iso, |n, _| f(n));
|
||||
}
|
||||
|
||||
/// [`walk_selectable`], handing `f` each object with the node that holds it in the tree: its
|
||||
/// layer, sublayer, group or other container, or `None` for a top-level layer.
|
||||
fn walk_selectable_in(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
fn inside(n: &Node, parent: Option<&Node>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
if n.visible && !n.locked && f(n, parent) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
inside(c, f);
|
||||
inside(c, Some(n), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
|
||||
fn find(n: &Node, parent: Option<&Node>, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
if tops.contains(&n.id) {
|
||||
return inside(n, f);
|
||||
return inside(n, parent, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
find(c, tops, f);
|
||||
find(c, Some(n), tops, f);
|
||||
}
|
||||
}
|
||||
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
|
||||
for l in &d.layers {
|
||||
find(l, &tops, &mut f);
|
||||
find(l, None, &tops, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,7 +466,8 @@ fn reselect(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !st.selection.contains(*id)).collect();
|
||||
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !selected.contains(id)).collect();
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
ok()
|
||||
}
|
||||
@@ -491,11 +498,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = checked_ids_param(s, p, "ids", "select.add")?;
|
||||
s.select(|_, sel| {
|
||||
for i in ids {
|
||||
sel.add(i);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| sel.add_all(ids))?;
|
||||
selection_result(s)
|
||||
}
|
||||
|
||||
@@ -506,11 +509,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?;
|
||||
vec![checked_id(s, value, "select.toggle")?]
|
||||
};
|
||||
s.select(|_, sel| {
|
||||
for id in ids {
|
||||
sel.toggle(id);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| sel.toggle_all(ids))?;
|
||||
selection_result(s)
|
||||
}
|
||||
|
||||
@@ -1098,7 +1097,9 @@ fn select_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "give `fill`, `stroke` or both"));
|
||||
}
|
||||
let reads_as = |paint: Paint, hex: Option<&str>| hex.is_none_or(|h| paint.color().is_some_and(|c| c.to_hex() == h));
|
||||
select_where(s, C, p, |d, n| paint_reported(d, n) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref()))
|
||||
select_where(s, C, p, |_, n, parent| {
|
||||
paint_reported(n, parent) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// The longest note, in bytes, that Select by Note searches for.
|
||||
@@ -1219,11 +1220,11 @@ fn fold_case(c: char) -> impl Iterator<Item = char> {
|
||||
c.to_lowercase().map(|l| if l == 'ς' { 'σ' } else { l })
|
||||
}
|
||||
|
||||
/// Does `document.inspect` report a fill and stroke for `n`? A compound path's are its own, though
|
||||
/// it holds its members, and its members report none.
|
||||
fn paint_reported(d: &Document, n: &Node) -> bool {
|
||||
/// Does `document.inspect` report a fill and stroke for `n`, held by `parent`? A compound path's
|
||||
/// are its own, though it holds its members, and its members report none.
|
||||
fn paint_reported(n: &Node, parent: Option<&Node>) -> bool {
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
|
||||
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
compound(n) || (!n.is_container() && !parent.is_some_and(compound))
|
||||
}
|
||||
|
||||
/// The object Select > Same compares the others with, and whether isolation mode is inside a
|
||||
@@ -1260,30 +1261,30 @@ fn same_fill(s: &mut Session, cmd: &str, eq: impl Fn(&Node, &Node) -> bool) -> R
|
||||
fn same_in(s: &mut Session, cmd: &str, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (refn, members) = same_reference(st, cmd)?;
|
||||
let group = live_paint_group(&st.doc, refn.id);
|
||||
let group = live_paint_group(st.doc.parent_of(refn.id).and_then(|p| st.doc.node(p)));
|
||||
let refn = refn.clone();
|
||||
select_where(s, cmd, &json!({}), |d, n| {
|
||||
(!live_paint || live_paint_group(d, n.id) == group) && (if members { !n.is_container() } else { paint_reported(d, n) }) && eq(n, &refn)
|
||||
})
|
||||
select_where(s, cmd, &json!({}), |_, n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, &refn))
|
||||
}
|
||||
|
||||
/// The Live Paint group `id` is a face or edge of.
|
||||
fn live_paint_group(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
|
||||
/// Whether Select > Same compares `n`, held by `parent`, with its reference: with `live_paint`, only
|
||||
/// when `n` is a face or edge of the Live Paint group `group` (or of none, for `None`); in
|
||||
/// isolation mode inside a compound path (`members`), any object that is not a container;
|
||||
/// otherwise one that [`paint_reported`] accepts.
|
||||
fn same_candidate(n: &Node, parent: Option<&Node>, live_paint: bool, group: Option<NodeId>, members: bool) -> bool {
|
||||
(!live_paint || live_paint_group(parent) == group) && (if members { !n.is_container() } else { paint_reported(n, parent) })
|
||||
}
|
||||
|
||||
/// The Live Paint group an object held by `parent` is a face or edge of.
|
||||
fn live_paint_group(parent: Option<&Node>) -> Option<NodeId> {
|
||||
parent.filter(|p| is_live_paint(p)).map(|p| p.id)
|
||||
}
|
||||
|
||||
/// Select the objects [`walk_selectable`] visits that `f` accepts (not looking inside accepted
|
||||
/// ones); Select > Reselect repeats `cmd` with `p`.
|
||||
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node) -> bool) -> Result<Value> {
|
||||
/// ones); `f` is given each object with the node that holds it. Select > Reselect repeats `cmd`
|
||||
/// with `p`.
|
||||
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node, Option<&Node>) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut ids = vec![];
|
||||
walk_selectable(&st.doc, st.isolation, |n| {
|
||||
if f(&st.doc, n) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
let ids = matching(&st.doc, st.isolation, |n, parent| f(&st.doc, n, parent));
|
||||
let from = st.selection.objects.clone();
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
let st = s.doc_mut()?;
|
||||
@@ -1292,12 +1293,26 @@ pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Do
|
||||
Ok(json!({ "count": st.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// The objects [`walk_selectable`] visits that `f` accepts, in paint order, not looking inside
|
||||
/// accepted ones. `f` is given each object with the node that holds it.
|
||||
fn matching(d: &Document, iso: Option<NodeId>, f: impl Fn(&Node, Option<&Node>) -> bool) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
walk_selectable_in(d, iso, |n, parent| {
|
||||
if f(n, parent) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
ids
|
||||
}
|
||||
|
||||
fn same_graphic_style(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cmd = "select.same.graphicStyle";
|
||||
let st = s.doc()?;
|
||||
let (refn, _) = same_reference(st, cmd)?;
|
||||
let id = super::style::linked_style(&st.doc, refn).map(|g| g.id).ok_or_else(|| bad(cmd, "the selection has no graphic style"))?;
|
||||
select_where(s, cmd, &json!({}), |d, n| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
|
||||
select_where(s, cmd, &json!({}), |d, n, _| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
|
||||
}
|
||||
|
||||
/// An appearance attribute Select > Same > Appearance Attribute matches.
|
||||
@@ -1321,7 +1336,7 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Attribute::Item(ap.items.iter().rev().find(|i| i.is_fill()).cloned().ok_or_else(|| bad(cmd, "the object has no fill, stroke or effect"))?)
|
||||
}
|
||||
};
|
||||
select_where(s, cmd, p, |_, n| match &attr {
|
||||
select_where(s, cmd, p, |_, n, _| match &attr {
|
||||
Attribute::Item(it) => n.appearance.items.contains(it),
|
||||
Attribute::Effect(e) => n.appearance.effects.iter().any(|x| x.id == e.id && x.params == e.params),
|
||||
})
|
||||
@@ -1381,5 +1396,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod same_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Select > Same and Select by Color through [`walk_selectable_in`], which hands each object the
|
||||
//! node that holds it, against copies of the walk and the tests that looked each object's parent up
|
||||
//! by its id.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::{fill_of, is_live_paint, matching, same_candidate, same_paint, same_reference, selectable, stroke_of, walk_selectable_in};
|
||||
use crate::Session;
|
||||
|
||||
/// `walk_selectable` as it was before it handed each object its parent.
|
||||
fn walk_by_id(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if n.visible && !n.locked && f(n) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
inside(c, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if tops.contains(&n.id) {
|
||||
return inside(n, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
find(c, tops, f);
|
||||
}
|
||||
}
|
||||
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
|
||||
for l in &d.layers {
|
||||
find(l, &tops, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `paint_reported` as it was, looking up `n`'s parent by its id.
|
||||
fn paint_reported_by_id(d: &Document, n: &Node) -> bool {
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
|
||||
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
}
|
||||
|
||||
/// `live_paint_group` as it was, looking up the parent of `id`.
|
||||
fn live_paint_group_by_id(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
|
||||
}
|
||||
|
||||
/// The objects `select_where`'s loop took before the walk handed each object its parent.
|
||||
fn matching_by_id(d: &Document, iso: Option<NodeId>, f: impl Fn(&Document, &Node) -> bool) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
walk_by_id(d, iso, |n| {
|
||||
if f(d, n) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
ids
|
||||
}
|
||||
|
||||
/// The objects `same_in` took before the walk handed each object its parent.
|
||||
fn same_by_id(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
|
||||
let group = live_paint_group_by_id(d, refn.id);
|
||||
matching_by_id(d, iso, |d, n| {
|
||||
(!live_paint || live_paint_group_by_id(d, n.id) == group)
|
||||
&& (if members { !n.is_container() } else { paint_reported_by_id(d, n) })
|
||||
&& eq(n, refn)
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects `same_in` takes now.
|
||||
fn same_now(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
|
||||
let group = super::live_paint_group(d.parent_of(refn.id).and_then(|p| d.node(p)));
|
||||
matching(d, iso, |n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, refn))
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("`{cmd}` {p} failed: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
|
||||
}
|
||||
|
||||
fn sel(s: &mut Session, ids: &[NodeId]) {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
}
|
||||
|
||||
/// A 10 × 10 rectangle at (`x`, `y`) filled with `hex`.
|
||||
fn rect(s: &mut Session, x: f64, y: f64, hex: &str) -> NodeId {
|
||||
let r = id(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": 10.0, "height": 10.0})));
|
||||
run(s, "paint.setFill", json!({"ids": [r.0], "color": hex}));
|
||||
r
|
||||
}
|
||||
|
||||
/// A compound path of three rectangles at `y`, filled with `hex` → the compound path and its
|
||||
/// member paths.
|
||||
fn compound(s: &mut Session, y: f64, hex: &str) -> (NodeId, Vec<NodeId>) {
|
||||
let members: Vec<NodeId> = [0.0, 20.0, 40.0].map(|x| rect(s, 300.0 + x, y, hex)).into();
|
||||
sel(s, &members);
|
||||
let c = id(&run(s, "object.compoundPath.make", json!({})));
|
||||
run(s, "paint.setFill", json!({"ids": [c.0], "color": hex}));
|
||||
(c, members)
|
||||
}
|
||||
|
||||
/// A Live Paint group of two overlapping squares at `y`, its left face red, its middle face blue and
|
||||
/// its right face red → the group and its faces.
|
||||
fn live_paint(s: &mut Session, y: f64) -> (NodeId, Vec<NodeId>) {
|
||||
let a = id(&run(s, "shape.rectangle", json!({"x": 0.0, "y": y, "width": 100.0, "height": 100.0})));
|
||||
let b = id(&run(s, "shape.rectangle", json!({"x": 50.0, "y": y, "width": 100.0, "height": 100.0})));
|
||||
sel(s, &[a, b]);
|
||||
let g = id(&run(s, "livePaint.make", json!({})));
|
||||
let faces = [(25.0, "#ff0000"), (75.0, "#0000ff"), (125.0, "#ff0000")]
|
||||
.map(|(x, hex)| NodeId(run(s, "livePaint.fill", json!({"group": g.0, "point": [x, y + 50.0], "color": hex}))["face"].as_u64().unwrap()))
|
||||
.into();
|
||||
(g, faces)
|
||||
}
|
||||
|
||||
/// The objects of [`rich`] that tests pick from.
|
||||
struct Rich {
|
||||
plain: Vec<NodeId>,
|
||||
compound: NodeId,
|
||||
members: Vec<NodeId>,
|
||||
group: NodeId,
|
||||
live_paint: NodeId,
|
||||
faces: Vec<NodeId>,
|
||||
sublayer: NodeId,
|
||||
}
|
||||
|
||||
/// A document with red and blue rectangles, a compound path, a group with a hidden and a locked
|
||||
/// rectangle, a locked group, a Live Paint group, a sublayer holding a rectangle and a second
|
||||
/// compound path, and a hidden and a locked layer with a red rectangle each.
|
||||
fn rich() -> (Session, Rich) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut plain = vec![rect(&mut s, 0.0, 0.0, "#ff0000"), rect(&mut s, 20.0, 0.0, "#ff0000"), rect(&mut s, 40.0, 0.0, "#0000ff")];
|
||||
let (compound_id, members) = compound(&mut s, 0.0, "#ff0000");
|
||||
let [in_group, hidden, locked] = [0.0, 20.0, 40.0].map(|x| rect(&mut s, x, 200.0, "#ff0000"));
|
||||
let blue = rect(&mut s, 60.0, 200.0, "#0000ff");
|
||||
sel(&mut s, &[in_group, hidden, locked, blue]);
|
||||
let group = id(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "layer.setProps", json!({"id": hidden.0, "visible": false}));
|
||||
run(&mut s, "layer.setProps", json!({"id": locked.0, "locked": true}));
|
||||
let in_locked = rect(&mut s, 100.0, 200.0, "#ff0000");
|
||||
sel(&mut s, &[in_locked]);
|
||||
let locked_group = id(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "layer.setProps", json!({"id": locked_group.0, "locked": true}));
|
||||
let (live_paint_id, faces) = live_paint(&mut s, 300.0);
|
||||
plain.extend([in_group, blue]);
|
||||
let sublayer = id(&run(&mut s, "layer.newSublayer", json!({"parent": layer.0})));
|
||||
plain.push(rect(&mut s, 0.0, 500.0, "#ff0000"));
|
||||
compound(&mut s, 500.0, "#0000ff");
|
||||
for prop in ["visible", "locked"] {
|
||||
let l = id(&run(&mut s, "layer.new", json!({"top": true})));
|
||||
rect(&mut s, 200.0, 500.0, "#ff0000");
|
||||
run(&mut s, "layer.setProps", json!({"id": l.0, prop: prop == "locked"}));
|
||||
}
|
||||
let rich = Rich { plain, compound: compound_id, members, group, live_paint: live_paint_id, faces, sublayer };
|
||||
(s, rich)
|
||||
}
|
||||
|
||||
/// The isolation scopes to try: none, the group, the compound path, and the Live Paint group.
|
||||
fn scopes(r: &Rich) -> [Option<NodeId>; 4] {
|
||||
[None, Some(r.group), Some(r.compound), Some(r.live_paint)]
|
||||
}
|
||||
|
||||
/// Isolate `iso`, leaving isolation mode first.
|
||||
fn isolate(s: &mut Session, iso: Option<NodeId>) {
|
||||
if s.doc().unwrap().isolation.is_some() {
|
||||
run(s, "object.exitIsolation", json!({}));
|
||||
}
|
||||
if let Some(i) = iso {
|
||||
run(s, "object.isolate", json!({"id": i.0}));
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// The walk visits the objects it visited before, in the same order and with the same objects left
|
||||
/// out, and hands each the node that `Document::parent_of` names for it.
|
||||
#[test]
|
||||
fn the_walk_hands_each_object_the_node_that_holds_it() {
|
||||
let (mut s, r) = rich();
|
||||
// Look inside everything, and inside every other object only.
|
||||
let deeper: [fn(&Node) -> bool; 2] = [|_| true, |n| n.id.0 % 2 == 0];
|
||||
for iso in scopes(&r) {
|
||||
isolate(&mut s, iso);
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
for f in deeper {
|
||||
let mut before = vec![];
|
||||
walk_by_id(d, st.isolation, |n| {
|
||||
before.push((n.id, d.parent_of(n.id)));
|
||||
f(n)
|
||||
});
|
||||
let mut now = vec![];
|
||||
walk_selectable_in(d, st.isolation, |n, parent| {
|
||||
now.push((n.id, parent.map(|p| p.id)));
|
||||
f(n)
|
||||
});
|
||||
assert!(!now.is_empty(), "isolating {iso:?}");
|
||||
assert_eq!(now, before, "isolating {iso:?}");
|
||||
}
|
||||
}
|
||||
// Every face, member path and the sublayer's art were visited somewhere above.
|
||||
let st = s.doc().unwrap();
|
||||
assert!(r.faces.iter().chain(&r.members).all(|f| st.doc.node(*f).is_some()));
|
||||
assert!(st.doc.node(r.sublayer).is_some_and(|n| n.is_layer()));
|
||||
}
|
||||
|
||||
/// Select > Same and Select by Color select the objects they selected before, in the same order,
|
||||
/// with the same reply and the same Select > Reselect state, from every kind of reference object
|
||||
/// and in every isolation scope.
|
||||
#[test]
|
||||
fn select_same_takes_the_objects_it_took_when_it_looked_up_parents() {
|
||||
type Eq = fn(&Node, &Node) -> bool;
|
||||
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
|
||||
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
|
||||
let commands: [(&str, bool, Eq); 6] = [
|
||||
("select.same.fillColor", true, fill),
|
||||
("select.same.fillAndStroke", true, |a, b| {
|
||||
same_paint(&fill_of(a), &fill_of(b), false) && same_paint(&stroke_of(a).0, &stroke_of(b).0, false)
|
||||
}),
|
||||
("select.same.strokeColor", false, stroke),
|
||||
("select.same.opacity", false, |a, b| (a.opacity - b.opacity).abs() < 1e-6),
|
||||
("select.same.blendingMode", false, |a, b| a.blend == b.blend),
|
||||
("select.same.shapeType", false, |a, b| a.kind_label() == b.kind_label()),
|
||||
];
|
||||
let (mut s, r) = rich();
|
||||
assert!(!s.prefs.select_same_tint_percent);
|
||||
let froms: Vec<NodeId> = r.plain.iter().chain(&r.members).chain(&r.faces).copied().chain([r.compound]).collect();
|
||||
let mut checked = 0;
|
||||
for iso in scopes(&r) {
|
||||
isolate(&mut s, iso);
|
||||
for from in &froms {
|
||||
for (cmd, live_paint, eq) in commands {
|
||||
// An object outside the isolated one may not be selectable; the selection then
|
||||
// stays, and both sides compare with what it holds.
|
||||
let _ = s.execute("select.set", &json!({"ids": [from.0]}));
|
||||
let st = s.doc().unwrap();
|
||||
let Ok((refn, members)) = same_reference(st, cmd) else {
|
||||
assert!(s.execute(cmd, &json!({})).is_err(), "{cmd} from {from:?} isolating {iso:?}");
|
||||
continue;
|
||||
};
|
||||
let refn = refn.clone();
|
||||
let expected = same_by_id(&st.doc, st.isolation, &refn, members, live_paint, eq);
|
||||
assert_eq!(same_now(&st.doc, st.isolation, &refn, members, live_paint, eq), expected, "{cmd} from {from:?} isolating {iso:?}");
|
||||
let before = st.selection.objects.clone();
|
||||
let reply = run(&mut s, cmd, json!({}));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, expected, "{cmd} from {from:?} isolating {iso:?}");
|
||||
assert_eq!(reply, json!({"count": expected.len()}));
|
||||
assert_eq!(st.last_selection_cmd, Some((cmd.to_string(), json!({}), before)));
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
for hex in ["#ff0000", "#0000ff"] {
|
||||
let st = s.doc().unwrap();
|
||||
let reads_as = |n: &Node| fill_of(n).color().is_some_and(|c| c.to_hex() == hex);
|
||||
let expected = matching_by_id(&st.doc, st.isolation, |d, n| paint_reported_by_id(d, n) && reads_as(n));
|
||||
let p = json!({"fill": hex});
|
||||
let reply = run(&mut s, "select.color", p.clone());
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, expected, "select.color {hex} isolating {iso:?}");
|
||||
assert_eq!(reply, json!({"count": expected.len()}));
|
||||
assert_eq!(st.last_selection_cmd.as_ref().map(|(c, p, _)| (c.as_str(), p)), Some(("select.color", &p)));
|
||||
}
|
||||
}
|
||||
// Most of the references can be selected in some scope.
|
||||
assert!(checked > froms.len() * commands.len(), "{checked} checks");
|
||||
}
|
||||
|
||||
/// In a damaged document that holds an id twice, the parent that decides whether an object is a
|
||||
/// member of a compound path or a face of a Live Paint group is the one that holds the object the
|
||||
/// walk is at, not the one that holds the id's first place in the tree.
|
||||
#[test]
|
||||
fn select_same_reads_the_parent_of_the_object_it_is_at() {
|
||||
for in_live_paint in [false, true] {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let (_, inner) = if in_live_paint { live_paint(&mut s, 300.0) } else { compound(&mut s, 0.0, "#0000ff") };
|
||||
let from = rect(&mut s, 0.0, 0.0, "#ff0000");
|
||||
// A red rectangle above the others that has the id of a face or member path.
|
||||
let mut copy = s.doc().unwrap().doc.node(from).unwrap().clone();
|
||||
copy.id = inner[0];
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, copy).unwrap();
|
||||
let mut commands = vec![("select.same.fillColor", json!({})), ("select.same.fillAndStroke", json!({}))];
|
||||
// Select by Color takes the red faces of a Live Paint group too, so it is tried on the
|
||||
// compound path only.
|
||||
if !in_live_paint {
|
||||
commands.push(("select.color", json!({"fill": "#ff0000"})));
|
||||
}
|
||||
for (cmd, p) in commands {
|
||||
sel(&mut s, &[from]);
|
||||
let reply = run(&mut s, cmd, p);
|
||||
assert_eq!(reply["count"], 2, "{cmd}, Live Paint: {in_live_paint}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of `n` objects on one layer: red and blue rectangles, one in 25 a compound path of
|
||||
/// three, and two Live Paint groups that hold one in 25 each as faces → the session, with the first
|
||||
/// rectangle selected.
|
||||
fn big(n: usize) -> Session {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let (c, _) = compound(&mut s, 0.0, "#ff0000");
|
||||
let (g, _) = live_paint(&mut s, 300.0);
|
||||
let [red, blue] = ["#ff0000", "#0000ff"].map(|hex| rect(&mut s, 0.0, 0.0, hex));
|
||||
let mut d = Document::clone(&s.doc().unwrap().doc);
|
||||
let layer = d.layers[0].id;
|
||||
let template = |id: NodeId| d.node(id).unwrap().clone();
|
||||
let (c, g, red, blue) = (template(c), template(g), template(red), template(blue));
|
||||
fn renumber(n: &Node, d: &mut Document) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = d.alloc_id();
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
*c = Arc::new(renumber(c, d));
|
||||
}
|
||||
n
|
||||
}
|
||||
d.children_mut(Some(layer)).unwrap().clear();
|
||||
let faces: Vec<Arc<Node>> = g.children().into_iter().flatten().cloned().collect();
|
||||
for _ in 0..2 {
|
||||
let mut g = renumber(&g, &mut d);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
ch.clear();
|
||||
for i in 0..n / 25 {
|
||||
ch.push(Arc::new(renumber(&faces[i % faces.len()], &mut d)));
|
||||
}
|
||||
}
|
||||
d.insert(Some(layer), usize::MAX, g).unwrap();
|
||||
}
|
||||
for i in 0..n - 2 * (n / 25) {
|
||||
let node = match i % 25 {
|
||||
0 => renumber(&c, &mut d),
|
||||
k if k % 2 == 0 => renumber(&red, &mut d),
|
||||
_ => renumber(&blue, &mut d),
|
||||
};
|
||||
d.insert(Some(layer), usize::MAX, node).unwrap();
|
||||
}
|
||||
let first = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap().id;
|
||||
s.add_document(d, None);
|
||||
sel(&mut s, &[first]);
|
||||
s
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ms(d: Duration) -> f64 {
|
||||
d.as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Timings of Select > Same's search, by id lookups and with the walk's parents, on 5,000, 50,000
|
||||
/// and 200,000 objects, run in turn on the same document, 7 runs each. Ignored by default; it
|
||||
/// prints the median, fastest and slowest run and sets no bound on them:
|
||||
/// `cargo test --release -p vectorcraft-engine --lib select_same_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "a benchmark: run with --ignored --nocapture"]
|
||||
fn select_same_perf() {
|
||||
const RUNS: usize = 7;
|
||||
type Eq = fn(&Node, &Node) -> bool;
|
||||
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
|
||||
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
|
||||
eprintln!("select_same_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
eprintln!(
|
||||
"select_same_perf: {:>7} {:<12} {:>8} {:>26} {:>26}",
|
||||
"objects", "command", "selected", "by id ms (min-max)", "walk parents ms (min-max)"
|
||||
);
|
||||
for n in [5_000, 50_000, 200_000] {
|
||||
let s = big(n);
|
||||
let st = s.doc().unwrap();
|
||||
let (d, iso) = (&st.doc, st.isolation);
|
||||
let objects = {
|
||||
let mut k = 0;
|
||||
walk_selectable_in(d, iso, |_, _| {
|
||||
k += 1;
|
||||
true
|
||||
});
|
||||
k
|
||||
};
|
||||
for (cmd, live_paint, eq) in [("fillColor", true, fill), ("strokeColor", false, stroke)] {
|
||||
let (refn, members) = same_reference(st, cmd).unwrap();
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for run in 0..RUNS {
|
||||
// The two take turns going first.
|
||||
if run % 2 == 0 {
|
||||
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
|
||||
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
|
||||
} else {
|
||||
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
|
||||
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
|
||||
}
|
||||
assert_eq!(a, b, "{n} objects, {cmd}");
|
||||
}
|
||||
old.sort();
|
||||
new.sort();
|
||||
eprintln!(
|
||||
"select_same_perf: {objects:>7} {cmd:<12} {:>8} {:>10.3} ({:>6.3}-{:>7.3}) {:>10.3} ({:>6.3}-{:>7.3})",
|
||||
b.len(),
|
||||
ms(old[RUNS / 2]),
|
||||
ms(old[0]),
|
||||
ms(old[RUNS - 1]),
|
||||
ms(new[RUNS / 2]),
|
||||
ms(new[0]),
|
||||
ms(new[RUNS - 1]),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -549,6 +549,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) };
|
||||
arrows_and_profile(st);
|
||||
if let Some(b) = &brush {
|
||||
// The path's own brush settings (Options of Selected Object) go with the brush they set.
|
||||
if st.brush != *b {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
st.brush = b.clone();
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour | {swatch, tint?}] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused; `{swatch, tint}` is the paint paint.setFill gives, so a tint of a global or spot color becomes a tint swatch) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour | {swatch, tint?}] (added as new swatches; #rrggbbaa and #rgba are refused; `{swatch, tint}` below 100% of a global or spot color adds a tint swatch, \"Name 40%\", linked to it, and any other `{swatch}` its color), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
has_doc,
|
||||
swatch_new_group
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
has_doc,
|
||||
swatch_edit_group
|
||||
),
|
||||
@@ -146,9 +146,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stored = |c: Color| if mode.is_some() { c } else { super::paint::new_color(s, p, c) };
|
||||
let cs: Vec<Paint> = cs
|
||||
.iter()
|
||||
.map(|c| color_value(c).map(|c| Paint::solid(stored(c))))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| bad(C, "bad colour in `colors`"))?;
|
||||
.map(|c| match swatch_entry(s, c, C)? {
|
||||
Some(paint) => Ok(paint),
|
||||
None => color_value(c).map(|c| Paint::solid(stored(c))).ok_or_else(|| bad(C, "bad colour in `colors`")),
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if cs.is_empty() {
|
||||
return Err(bad(C, "`colors` is empty"));
|
||||
}
|
||||
@@ -216,6 +218,16 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": names[0], "names": names }))
|
||||
}
|
||||
|
||||
/// A `colors` entry of `swatch.new` or `swatch.newGroup` that names a color swatch,
|
||||
/// `{swatch, tint?}`: the paint `paint.setFill {swatch, tint}` applies (a tint of a global or spot
|
||||
/// color stays linked to it). `None` for an entry without `swatch`.
|
||||
fn swatch_entry(s: &Session, v: &Value, cmd: &str) -> Result<Option<Paint>> {
|
||||
let Some(name) = v.get("swatch") else { return Ok(None) };
|
||||
let name = name.as_str().ok_or_else(|| bad(cmd, format!("`swatch` in `colors` must be a swatch name, not {name}")))?;
|
||||
let tint = super::paint::tint_param(v, cmd)?;
|
||||
super::paint::swatch_solid(&s.doc()?.doc, name, tint).map(Some).map_err(|e| bad(cmd, e))
|
||||
}
|
||||
|
||||
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
|
||||
/// stores it.
|
||||
fn stored_paint(paint: Paint, p: &Value) -> Paint {
|
||||
@@ -475,10 +487,20 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut names = str_list(p, "swatches");
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
check_switches(p, &["fromArtwork", "toGlobal", "includeTints"], C)?;
|
||||
let colors: Vec<Color> = p
|
||||
// A `{swatch, tint}` entry below 100% becomes a tint swatch linked to its base; any other
|
||||
// entry becomes a process color swatch.
|
||||
let colors: Vec<Paint> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|v| match swatch_entry(s, v, C)? {
|
||||
Some(paint @ Paint::Solid { swatch: Some(_), tint, .. }) if tint < 1.0 => Ok(paint),
|
||||
Some(paint) => paint.color().map(Paint::solid).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
None => color_value(v).map(|c| Paint::solid(super::paint::new_color(s, p, c))).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let from_art = bool_or(p, "fromArtwork", false);
|
||||
@@ -486,15 +508,15 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tints = bool_or(p, "includeTints", false);
|
||||
let requested = name_param(p, "name");
|
||||
let (name, members, linked) = s.edit("New Color Group", |d, sel| {
|
||||
// New swatches: (colour, global).
|
||||
let mut new: Vec<(Color, bool)> = colors.iter().map(|c| (*c, false)).collect();
|
||||
// New swatches: (paint, global).
|
||||
let mut new: Vec<(Paint, bool)> = colors.iter().map(|c| (c.clone(), false)).collect();
|
||||
if from_art {
|
||||
if sel.objects.is_empty() {
|
||||
return Err(bad(C, "select artwork to make a group of its colours"));
|
||||
}
|
||||
let mut art = vec![];
|
||||
artwork_colors(d, &sel.objects, tints, &mut names, &mut art);
|
||||
new.extend(art.into_iter().map(|c| (c, to_global)));
|
||||
new.extend(art.into_iter().map(|c| (Paint::solid(c), to_global)));
|
||||
}
|
||||
let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group"));
|
||||
// Colour groups hold solid colours only.
|
||||
@@ -505,12 +527,13 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
group.swatches.iter().for_each(|sw| free.insert(&sw.name));
|
||||
for (c, global) in new {
|
||||
let nm = free.take(&color_name(c));
|
||||
if global {
|
||||
for (paint, global) in new {
|
||||
// A tint swatch is named "Name 40%", a colour after its values.
|
||||
let nm = free.take_new(&paint);
|
||||
if global && let Some(c) = paint.color() {
|
||||
links.push((c, nm.clone()));
|
||||
}
|
||||
group.swatches.push(Swatch { name: nm, paint: Paint::solid(c), global, spot: false });
|
||||
group.swatches.push(Swatch { name: nm, paint, global, spot: false });
|
||||
}
|
||||
let members: Vec<String> = group.swatches.iter().map(|w| w.name.clone()).collect();
|
||||
d.swatch_groups.push(group);
|
||||
@@ -1317,21 +1340,45 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
|
||||
fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.editGroup";
|
||||
let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?;
|
||||
let colors: Vec<Color> = p
|
||||
// A null removes the swatch at that place.
|
||||
let colors: Vec<Option<Color>> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| bad(C, "missing `colors`"))?
|
||||
.iter()
|
||||
.map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}"))))
|
||||
.map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) })
|
||||
.collect::<Result<_>>()?;
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
// A color its swatch already has keeps its model. The others take the document's.
|
||||
// A color its swatch already has keeps its model. The others take the document's. A color key
|
||||
// (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color
|
||||
// gives the swatch that color, unrounded.
|
||||
let old: Vec<Option<Color>> =
|
||||
s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default();
|
||||
let colors: Vec<Color> =
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let entries = p.get("colors").and_then(Value::as_array);
|
||||
let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse);
|
||||
let mut colors: Vec<Option<Color>> = colors
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
c.map(|c| match old.get(i).copied().flatten() {
|
||||
Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o,
|
||||
_ => super::paint::new_color(s, p, c),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// A null past the group's swatches removes nothing.
|
||||
while colors.len() > old.len() && colors.last() == Some(&None) {
|
||||
colors.pop();
|
||||
}
|
||||
let rename = str_param(p, "rename");
|
||||
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
|
||||
// The group's own colors, in order, under its own name change nothing: no undo step.
|
||||
if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group)
|
||||
&& rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group)
|
||||
&& old.len() == colors.len()
|
||||
&& old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c)
|
||||
{
|
||||
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
|
||||
}
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Swatches",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number → {library, added: [names in the document], existing: [names already there], applied?: name}",
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy to User Defined",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}",
|
||||
"{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}",
|
||||
has_user_folder,
|
||||
copy_to_user
|
||||
),
|
||||
@@ -109,6 +109,9 @@ pub struct Libraries<L = SwatchLibrary> {
|
||||
/// the file name instead. [`Libraries::rescan`] drops an entry whose file no longer holds those
|
||||
/// bytes, and keeps one whose file is missing so a file put back can be checked.
|
||||
saved_as: HashMap<String, SavedAs>,
|
||||
/// The documents loaded swatch libraries were read from, by library id, for those with pattern
|
||||
/// swatches: the patterns live there ([`Libraries::pattern_doc`]).
|
||||
pattern_docs: HashMap<String, Arc<vectorcraft_doc::Document>>,
|
||||
}
|
||||
|
||||
/// A User Defined file this session wrote: the library's name, and [`vectorcraft_doc::links::hash_bytes`]
|
||||
@@ -149,6 +152,38 @@ impl LibraryFile for SwatchLibrary {
|
||||
/// The extensions of library files [`palette_io::read_bytes`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"];
|
||||
|
||||
/// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the
|
||||
/// `.ai`, `.ait` and `.eps` (`.epsf`) documents whose swatches load as a library (`swatch.library.load`).
|
||||
pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "ait", "eps", "epsf"];
|
||||
|
||||
impl Libraries<SwatchLibrary> {
|
||||
/// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None`
|
||||
/// forgets the one kept for `id`.
|
||||
fn set_pattern_doc(&mut self, id: &str, doc: Option<Arc<vectorcraft_doc::Document>>) {
|
||||
match doc {
|
||||
Some(doc) => self.pattern_docs.insert(id.to_string(), doc),
|
||||
None => self.pattern_docs.remove(id),
|
||||
};
|
||||
}
|
||||
|
||||
/// The document holding the patterns of loaded library `id`'s pattern swatches.
|
||||
pub fn pattern_doc(&self, id: &str) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
self.pattern_docs.get(id).cloned()
|
||||
}
|
||||
|
||||
/// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own
|
||||
/// pattern swatches (a library panel draws them from it). Only the libraries that have pattern
|
||||
/// swatches are looked at, each by the address ranges of its swatch lists.
|
||||
pub fn pattern_source(&self, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
let Paint::Pattern { pattern, .. } = &w.paint else { return None };
|
||||
let at = std::ptr::from_ref(w);
|
||||
let holds = |v: &[Swatch]| v.as_ptr_range().contains(&at);
|
||||
let own = |lib: &SwatchLibrary| holds(&lib.swatches) || lib.groups.iter().any(|g| holds(&g.swatches));
|
||||
let (_, doc) = self.pattern_docs.iter().find(|(id, _)| self.extra.iter().any(|e| e.info.id == **id && own(&e.lib)))?;
|
||||
Some(doc.clone()).filter(|d| d.pattern(pattern).is_some())
|
||||
}
|
||||
}
|
||||
|
||||
/// A library file the save commands write ([`Libraries::write`]).
|
||||
pub(crate) enum FileData {
|
||||
/// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`.
|
||||
@@ -646,6 +681,12 @@ pub fn library_swatches(s: &Session, key: &str) -> Option<Vec<Swatch>> {
|
||||
Some(library(s, key)?.1.iter().filter(own).cloned().collect())
|
||||
}
|
||||
|
||||
/// The document holding the pattern of library swatch `w`: a built-in pattern library's or a loaded
|
||||
/// library's own pattern swatch (a library panel draws them from it).
|
||||
pub fn pattern_source(s: &Session, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
patternlib::swatch_source(w).or_else(|| s.swatch_libraries.pattern_source(w))
|
||||
}
|
||||
|
||||
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null).
|
||||
/// A `limitTo` that is not a string, such as `5`, names no library.
|
||||
pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Palette>> {
|
||||
@@ -694,13 +735,17 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The document's swatches `names` (swatches or colour groups; empty: all) as a library named
|
||||
/// `name`, without None and patterns.
|
||||
fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, cmd: &str) -> Result<SwatchLibrary> {
|
||||
/// `name`, without None, and without pattern swatches unless `patterns`.
|
||||
fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, patterns: bool, cmd: &str) -> Result<SwatchLibrary> {
|
||||
if let Some(n) = names.iter().find(|n| !d.swatch_name_taken(n)) {
|
||||
return Err(bad(cmd, format!("no swatch or colour group `{n}`")));
|
||||
}
|
||||
let want = |n: &str| names.is_empty() || names.iter().any(|x| x == n);
|
||||
let savable = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_));
|
||||
let savable = |w: &&Swatch| match w.paint {
|
||||
Paint::Solid { .. } | Paint::Gradient(_) => true,
|
||||
Paint::Pattern { .. } => patterns,
|
||||
_ => false,
|
||||
};
|
||||
let swatches = d.swatches.iter().filter(savable).filter(|w| want(&w.name)).cloned().collect();
|
||||
let groups = d
|
||||
.swatch_groups
|
||||
@@ -724,7 +769,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let names = names_param(p, C)?;
|
||||
let st = s.doc()?;
|
||||
let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = document_library(&st.doc, &names, name, C)?;
|
||||
let lib = document_library(&st.doc, &names, name, false, C)?;
|
||||
let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?;
|
||||
let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) };
|
||||
let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()});
|
||||
@@ -734,21 +779,44 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
// The document a library with pattern swatches was read from, which holds their patterns.
|
||||
let mut patterns = None;
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
|
||||
} else {
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
document_library(&loaded.doc, &[], stem(file).to_string(), C)
|
||||
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
|
||||
}
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
|
||||
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
|
||||
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
if defaults || lib.is_empty() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
}
|
||||
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
patterns = Some(Arc::new(loaded.doc));
|
||||
}
|
||||
Ok(lib)
|
||||
})?;
|
||||
if info.category == "loaded" {
|
||||
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
|
||||
}
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
|
||||
/// document's are.
|
||||
fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool {
|
||||
use vectorcraft_color::cms::Model;
|
||||
[Model::Rgb, Model::Cmyk].into_iter().any(|model| {
|
||||
let (swatches, groups) = default_swatches(model);
|
||||
d.swatches[..] == swatches[..] && d.swatch_groups[..] == groups[..]
|
||||
})
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "swatch.library.get")?;
|
||||
let ungrouped = lib.swatches.iter().map(|w| swatch_json(w, None));
|
||||
@@ -772,6 +840,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.copyToUser";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let (info, lib, copied) = match info.category {
|
||||
"loaded" if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) => {
|
||||
return Err(bad(C, format!("`{}` has pattern swatches, which a .vcswatches file can't hold", info.name)));
|
||||
}
|
||||
"loaded" => {
|
||||
let native = |lib: &SwatchLibrary| palette_io::write(lib, PaletteFormat::Native).map_err(|e| bad(C, e));
|
||||
s.swatch_libraries.copy_to_user(&info.id, PaletteFormat::Native.id(), native, C)?
|
||||
@@ -811,6 +882,22 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The swatch of `d` that library pattern swatch `w` stands for once its pattern is `target` in `d`:
|
||||
/// one that paints `target` placed as `w` places its pattern, named as `w` or a numbered copy of
|
||||
/// that name ("Tiles 2"); for a swatch named after its pattern, under any name.
|
||||
fn library_pattern_swatch(d: &vectorcraft_doc::Document, w: &Swatch, target: &str) -> Option<String> {
|
||||
let Paint::Pattern { pattern, xf } = &w.paint else { return None };
|
||||
let paint = Paint::Pattern { pattern: target.to_string(), xf: *xf };
|
||||
let named = |n: &str| {
|
||||
w.name == *pattern
|
||||
|| n == w.name
|
||||
|| n.strip_prefix(w.name.as_str())
|
||||
.and_then(|r| r.strip_prefix(' '))
|
||||
.is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
d.swatches_iter().find(|x| x.paint == paint && named(&x.name)).map(|x| x.name.clone())
|
||||
}
|
||||
|
||||
/// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch).
|
||||
fn taken_names(d: &vectorcraft_doc::Document) -> HashSet<String> {
|
||||
let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name));
|
||||
@@ -840,8 +927,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let focus = switch_or(p, "focus", true, C)?;
|
||||
let picked = picked(&lib, &names_param(p, C)?, C)?;
|
||||
// Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the
|
||||
// same pattern) are reused, not added again.
|
||||
let patterns = patternlib::library_doc(&info.id);
|
||||
// same pattern) are reused, not added again. The patterns are in a built-in pattern library's
|
||||
// document, or in the document a loaded library was read from.
|
||||
let patterns = patternlib::library_doc(&info.id).or_else(|| s.swatch_libraries.pattern_doc(&info.id));
|
||||
let d = &s.doc()?.doc;
|
||||
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
|
||||
// up once so that a large palette takes linear time.
|
||||
@@ -851,7 +939,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let there = |w: &Swatch| match (&w.paint, &patterns) {
|
||||
(Paint::Pattern { pattern, .. }, Some(src)) => {
|
||||
patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target))
|
||||
patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
|
||||
}
|
||||
_ => match by_name.get(w.name.as_str()) {
|
||||
Some(x) => x.paint == w.paint,
|
||||
@@ -873,32 +961,64 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let added: Vec<(String, String)> = if fresh.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
let (added, reused) = s.edit("Add to Swatches", |d, _| {
|
||||
let mut out = vec![];
|
||||
// Library pattern swatches that stand for a swatch added earlier in this call.
|
||||
let mut reused = vec![];
|
||||
// Each library group goes into one document group: the group of that name the document
|
||||
// already had, or one made here.
|
||||
let before = d.swatch_groups.len();
|
||||
let mut placed: Vec<(&str, usize)> = vec![];
|
||||
let mut taken = taken_names(d);
|
||||
// The swatches the patterns imported in this call brought with their art: (library
|
||||
// name, document name).
|
||||
let mut brought: Vec<(String, String)> = vec![];
|
||||
for (group, w) in fresh {
|
||||
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
// The pattern comes with its swatch; a pattern the document has without one
|
||||
// gets one.
|
||||
let target = patternlib::import(d, src, pattern)?;
|
||||
let name = match patternlib::pattern_swatch(d, &target) {
|
||||
Some(name) => name,
|
||||
None => {
|
||||
let name = d.free_swatch_name(&target);
|
||||
d.swatches.push(Swatch { name: name.clone(), paint: pattern_paint(&target), global: false, spot: false });
|
||||
name
|
||||
}
|
||||
};
|
||||
out.push((w.name.clone(), name));
|
||||
// gets one. The swatch a pattern that comes in brings is named after the pattern:
|
||||
// it takes the library swatch's name and color group instead.
|
||||
let had = taken_names(d);
|
||||
let (target, colors) = patternlib::import(d, src, pattern)?;
|
||||
brought.extend(colors);
|
||||
if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) {
|
||||
reused.push((w.name.clone(), name));
|
||||
taken = taken_names(d);
|
||||
continue;
|
||||
}
|
||||
let made = patternlib::pattern_swatch(d, &target).filter(|n| !had.contains(n));
|
||||
if let Some(made) = &made {
|
||||
d.swatches.retain(|x| x.name != *made);
|
||||
}
|
||||
taken = taken_names(d);
|
||||
continue;
|
||||
}
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
let sw = Swatch { name: name.clone(), ..(*w).clone() };
|
||||
let name = match made {
|
||||
Some(made) if w.name == *pattern => made,
|
||||
None if w.name == *pattern => d.free_swatch_name(&target),
|
||||
_ => free_in(&mut taken, &w.name),
|
||||
};
|
||||
taken.insert(name.clone());
|
||||
// The library swatch's placement of its pattern is kept.
|
||||
let paint = match &w.paint {
|
||||
Paint::Pattern { xf, .. } => Paint::Pattern { pattern: target, xf: *xf },
|
||||
_ => pattern_paint(&target),
|
||||
};
|
||||
(name.clone(), Swatch { name, paint, global: false, spot: false })
|
||||
} else {
|
||||
// A color a pattern added earlier in this call brought with its art is that
|
||||
// swatch: it moves to the library swatch's place.
|
||||
let at = brought.iter().position(|(from, _)| *from == w.name);
|
||||
let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| {
|
||||
let i = d.swatches.iter().position(|x| x.name == n)?;
|
||||
Some(d.swatches.remove(i))
|
||||
});
|
||||
match moved {
|
||||
Some(sw) => (sw.name.clone(), sw),
|
||||
None => {
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
(name.clone(), Swatch { name, ..(*w).clone() })
|
||||
}
|
||||
}
|
||||
};
|
||||
match group {
|
||||
Some(g) => {
|
||||
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
|
||||
@@ -919,8 +1039,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
out.push((w.name.clone(), name));
|
||||
}
|
||||
Ok(out)
|
||||
})?
|
||||
Ok((out, reused))
|
||||
})?;
|
||||
existing.extend(reused);
|
||||
added
|
||||
};
|
||||
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
|
||||
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
|
||||
|
||||
@@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> {
|
||||
Ok((a.min(b), a.max(b)))
|
||||
}
|
||||
|
||||
fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.editRange";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let t = text_ref(s, id)?;
|
||||
@@ -1883,13 +1883,14 @@ enum Step {
|
||||
BaselineShift,
|
||||
}
|
||||
|
||||
/// The Type tool's selected text while it edits (its typing session ends first: one undo step).
|
||||
/// The Type tool's selected text while it edits (its typing session ends first: one undo step,
|
||||
/// with typing that Real-time Drawing off left unapplied applied first).
|
||||
pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, usize)>> {
|
||||
let o = s.tool_options();
|
||||
let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
|
||||
if super::edit::typing_in_progress(s) {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let at = |k: &str| byte_param(&o, k).unwrap_or(0);
|
||||
Ok(Some((id, at("start"), at("end"))))
|
||||
|
||||
@@ -488,8 +488,14 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind, verb: &str) -> Result<Opt
|
||||
};
|
||||
char_attrs(&style)
|
||||
}
|
||||
// The paragraph at `start`.
|
||||
Kind::Para => para_attrs(t.para_at(t.paragraphs_in(at, at).start)),
|
||||
// The paragraph at `start`, without the number its list gives that paragraph alone.
|
||||
Kind::Para => {
|
||||
let mut para = t.para_at(t.paragraphs_in(at, at).start).clone();
|
||||
if let Some(l) = para.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
para_attrs(¶)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -639,6 +645,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
Kind::Para => {
|
||||
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
// A list's number belongs to one paragraph, not to a style.
|
||||
if st.list.is_some_and(|l| l.start.is_some()) {
|
||||
let k = "list.start";
|
||||
return Err(bad(&c, format!("unknown attribute `{k}`")));
|
||||
}
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
sort_tabs(&mut st, m, kept);
|
||||
para_attrs(&st)
|
||||
|
||||
@@ -736,6 +736,189 @@ fn numbered_lists_are_set_per_paragraph_saved_and_styled() {
|
||||
assert_eq!((list(&s, 0), list(&s, 1), list(&s, 2)), (None, None, None));
|
||||
}
|
||||
|
||||
/// `text.setFormat {startNumber}` gives the first numbered paragraph it touches a number, and the
|
||||
/// paragraphs after it count on from it; `restartNumbering` true gives it 1 and false takes the
|
||||
/// numbers away. Each change is one undo step, a call that changes nothing records none, and a
|
||||
/// bad value or both keys change nothing. The file keeps the number, Return and paragraph styles
|
||||
/// do not take it, a bulleted paragraph keeps none, and Convert to Text writes the numbers shown.
|
||||
#[test]
|
||||
fn a_numbered_paragraph_starts_at_a_given_number_or_restarts() {
|
||||
use vectorcraft_doc::text::{Bullet, ParaList};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "text": "Intro\nOne\nTwo\nThree\nFour", "area": {"width": 300, "height": 200}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let starts = |s: &Session| text(s).paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>();
|
||||
let numbers = |s: &Session| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let undo = |s: &Session| s.active().unwrap().history.undo.len();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
// A call over all the text gives the number to the first paragraph the same call numbers.
|
||||
s.execute("text.setFormat", &json!({"start": 6, "end": 24, "number": "arabic", "startNumber": 5})).unwrap();
|
||||
assert_eq!(starts(&s), [None, Some(5), None, None, None]);
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."]);
|
||||
// On "Three": `restartNumbering` gives it 1, and "Four" counts on from it.
|
||||
let steps = undo(&s);
|
||||
s.execute("text.setFormat", &json!({"start": 14, "end": 14, "restartNumbering": true})).unwrap();
|
||||
assert_eq!((numbers(&s), undo(&s)), (vec!["5.".to_string(), "6.".into(), "1.".into(), "2.".into()], steps + 1));
|
||||
// The same number again, or a call on a paragraph in no list, changes nothing.
|
||||
s.execute("text.setFormat", &json!({"start": 14, "end": 14, "startNumber": 1.0})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 3})).unwrap();
|
||||
assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1));
|
||||
// Bad values and both keys at once are errors and change nothing.
|
||||
for bad in [
|
||||
json!({"startNumber": 0}),
|
||||
json!({"startNumber": -2}),
|
||||
json!({"startNumber": 2.5}),
|
||||
json!({"startNumber": 1_000_000_000}),
|
||||
json!({"startNumber": "5"}),
|
||||
json!({"restartNumbering": "yes"}),
|
||||
json!({"startNumber": 3, "restartNumbering": true}),
|
||||
] {
|
||||
assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."], "one Undo takes the restart back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// The file keeps the numbers.
|
||||
assert_eq!(serde_json::to_value(text(&s).para_at(1)).unwrap()["list"], json!({"bullet": "dot", "number": "arabic", "start": 5}));
|
||||
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert_eq!(back.paragraph_styles(), text(&s).paragraph_styles());
|
||||
// Return at the end of "One" makes an item that counts on, without a number of its own.
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 9, "end": 9, "insert": "\nOne and a half"})).unwrap();
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "1.", "2."]);
|
||||
assert_eq!(starts(&s), [None, Some(5), None, None, Some(1), None]);
|
||||
// A paragraph style made from the paragraph does not keep its number, and a style's list
|
||||
// with a number is an error.
|
||||
s.execute("paraStyle.new", &json!({"name": "Item", "id": id, "start": 6, "end": 6})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Item", "id": id})).unwrap();
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
assert_eq!(numbers(&s), ["1.", "2.", "3.", "4.", "5.", "6."]);
|
||||
let given = json!({"name": "Given", "attrs": {"list": {"number": "arabic", "start": 4}}});
|
||||
assert!(s.execute("paraStyle.new", &given).is_err());
|
||||
// `restartNumbering` false takes every number the call touches away; a paragraph made bulleted
|
||||
// keeps none.
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 6, "end": 6, "startNumber": 3})).unwrap();
|
||||
assert_eq!(starts(&s)[..2], [Some(7), Some(3)]);
|
||||
s.execute("text.setFormat", &json!({"restartNumbering": false})).unwrap();
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "bullet": "dot"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(0).list, Some(ParaList::bulleted(Bullet::Dot)));
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "upperRoman"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(0).list.and_then(|l| l.start), None, "numbered again, it counts on");
|
||||
// Convert to Text writes the numbers the paragraphs showed.
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "arabic", "startNumber": 10})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 30, "end": 30, "restartNumbering": true})).unwrap();
|
||||
let shown = numbers(&s);
|
||||
assert_eq!(shown, ["10.", "11.", "12.", "13.", "1.", "2."]);
|
||||
s.execute("text.convertListToText", &json!({})).unwrap();
|
||||
let written: Vec<String> = text(&s).plain_text().split('\n').map(|p| p.split('\t').next().unwrap_or("").to_string()).collect();
|
||||
assert_eq!(written, shown);
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
assert!(text(&s).paragraph_styles().iter().all(|p| p.list.is_none()));
|
||||
}
|
||||
|
||||
/// In threaded type, a paragraph given a number in the first frame carries its count on through
|
||||
/// the later frames, and a paragraph given 1 in a later frame starts the count again there.
|
||||
#[test]
|
||||
fn a_given_number_carries_through_threaded_frames() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let story = (1..=10).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
let first = numbers(&s, a).len();
|
||||
assert!((2..10).contains(&first), "both frames hold items: {first}");
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 20})).unwrap();
|
||||
let want: Vec<String> = (20..30).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
// The first paragraph of the second frame given 1: the second frame counts from 1.
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "start": 0, "end": 0, "restartNumbering": true})).unwrap();
|
||||
let want: Vec<String> = (20..20 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
// Editing the first frame's number moves every later number on with it.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 2})).unwrap();
|
||||
let want: Vec<String> = (2..2 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
}
|
||||
|
||||
/// A number given in a threaded frame whose first paragraph continues from the frame before goes
|
||||
/// to the next numbered paragraph that begins in that frame, not to the item the earlier frame shows,
|
||||
/// and `restartNumbering` false there leaves that item's number alone.
|
||||
#[test]
|
||||
fn a_given_number_skips_the_paragraph_continued_from_the_frame_before() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let text = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let long = (1..=40).map(|i| format!("word{i}")).collect::<Vec<_>>().join(" ");
|
||||
let story = format!("One\n{long}\nThree");
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 250})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
assert!(text(&s, b).first_para_continues, "the second frame starts inside the long paragraph");
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["3.".to_string()]));
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "startNumber": 5})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["5.".to_string()]));
|
||||
// The long item, numbered in the first frame, keeps its number when the second frame's are taken away.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 4, "end": 4, "startNumber": 8})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["5.".to_string()]));
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "restartNumbering": false})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["9.".to_string()]));
|
||||
}
|
||||
|
||||
/// `startNumber` over several type objects goes to the first numbered paragraph with text among
|
||||
/// all of them, past an empty numbered object listed first; with no text anywhere it goes to the
|
||||
/// first numbered paragraph.
|
||||
#[test]
|
||||
fn a_given_number_goes_to_the_first_numbered_text_across_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let make =
|
||||
|s: &mut Session, y: u32, text: &str| s.execute("text.create", &json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap();
|
||||
let empty = make(&mut s, 10, "");
|
||||
let full = make(&mut s, 60, "One\nTwo");
|
||||
let start = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.para_at(0).list.and_then(|l| l.start),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
s.execute("text.setFormat", &json!({"ids": [empty, full], "number": "arabic"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [empty, full], "startNumber": 4})).unwrap();
|
||||
assert_eq!((start(&s, empty), start(&s, full)), (None, Some(4)));
|
||||
let other = make(&mut s, 120, "");
|
||||
s.execute("text.setFormat", &json!({"ids": [other, empty], "number": "arabic"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [other, empty], "startNumber": 6})).unwrap();
|
||||
assert_eq!((start(&s, other), start(&s, empty)), (Some(6), None));
|
||||
}
|
||||
|
||||
/// Bullets and Numbering… › Alignment: `text.setFormat {listAlign}` sets where the marker
|
||||
/// stands in the list paragraphs it touches, in one undo step, and refuses unknown values;
|
||||
/// a paragraph in no list gets no list from it. A list keeps its alignment when it changes
|
||||
|
||||
@@ -10,8 +10,8 @@ use super::object::choice;
|
||||
use super::threads::ThreadIndex;
|
||||
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
|
||||
switch_or, targets, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids,
|
||||
number_or, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Insert Character",
|
||||
["Type"],
|
||||
None,
|
||||
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects",
|
||||
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph",
|
||||
has_selection,
|
||||
insert_char
|
||||
),
|
||||
@@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plain = t.plain_text();
|
||||
let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8);
|
||||
// Soft wraps → explicit breaks (replace the space before the wrap when there is one).
|
||||
let mut breaks: Vec<usize> =
|
||||
lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect();
|
||||
// A line after a paragraph return or a forced line break (U+2028) already starts there.
|
||||
let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}']));
|
||||
let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect();
|
||||
breaks.sort_unstable();
|
||||
breaks.dedup();
|
||||
for b in breaks.into_iter().rev() {
|
||||
@@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> {
|
||||
"thirdSpace" => "\u{2004}",
|
||||
"quarterSpace" => "\u{2005}",
|
||||
"tab" => "\t",
|
||||
// Our text model breaks lines at paragraph returns only.
|
||||
"forcedLineBreak" | "paragraphReturn" => "\n",
|
||||
// A line break inside the paragraph, as Shift+Enter types it.
|
||||
"forcedLineBreak" => "\u{2028}",
|
||||
"paragraphReturn" => "\n",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(),
|
||||
(None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")),
|
||||
};
|
||||
if named_ids(p)?.is_none()
|
||||
&& let Some(r) = insert_at_type_caret(s, &text)?
|
||||
{
|
||||
return Ok(r);
|
||||
}
|
||||
let ids = texts(s, p, C)?;
|
||||
// When `text` is empty and every object ends with a run of text, the document and its undo
|
||||
// history stay as they are.
|
||||
@@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at
|
||||
/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited.
|
||||
fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> {
|
||||
let tool = s.tool_options();
|
||||
let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) };
|
||||
let len = vectorcraft_text::edit::runs_len(&t.runs);
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
let (a, b) = (x.min(y), x.max(y));
|
||||
// After Select All in threaded text the whole story is selected: the other frames' text goes
|
||||
// in the same edit, as when typing replaces it.
|
||||
let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect();
|
||||
let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) {
|
||||
let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty()));
|
||||
story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
if text.is_empty() && a == b && clear.is_empty() {
|
||||
return Ok(Some(ids_json(&[id])));
|
||||
}
|
||||
// A typing session ends first: the insertion is a step of its own.
|
||||
if tool.get("typing").and_then(Value::as_bool) == Some(true) {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
}
|
||||
// The frame's place in the story once the edit has cleared the frames in `clear`.
|
||||
let start: usize =
|
||||
super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum();
|
||||
let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?;
|
||||
let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize);
|
||||
// Threaded text re-flows in the edit: the caret goes to the frame its place moved to.
|
||||
super::panelcmds::select_story_range(s, id, start + caret, start + caret)?;
|
||||
Ok(Some(ids_json(&[id])))
|
||||
}
|
||||
|
||||
// ---------- Find and Replace ----------
|
||||
|
||||
fn is_word(c: char) -> bool {
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! variable name per column, which export writes with `#` before a visibility variable and `@`
|
||||
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
|
||||
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! visibility, `@` for image, `%` for graph, whose cells name graph data files, no prefix for
|
||||
//! text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
|
||||
//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension.
|
||||
@@ -1070,7 +1071,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
"{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. The files are read at import. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused (an `@Name` column's relative paths are kept as they are and taken from the document's folder when a data set is selected). A path on another computer, or on a network share other than the one `base` or the CSV is on, a device and a URL other than a `file:` URL without a host are refused, as image variables' paths are, before anything is read. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
json, read_file_head, str_param, variables_unlocked, write_file,
|
||||
};
|
||||
use crate::cmd::place::text::windows_1252;
|
||||
use crate::cmd::{MAX_GRAPH_DATA_FILE, text_param};
|
||||
|
||||
/// Cap on a graph variable's CSV (MCP and files are untrusted).
|
||||
pub(super) const MAX_GRAPH_CSV: usize = 256 * 1024;
|
||||
@@ -268,10 +269,11 @@ fn export_header(v: &Variable) -> String {
|
||||
|
||||
/// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`]
|
||||
/// writes, in a document without the variables: the first list names the variables whose header
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values
|
||||
/// aren't true or false, a header that names a variable an earlier column named), and the second
|
||||
/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`,
|
||||
/// and a graph variable, which no header cell defines).
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header over values, which it reads as
|
||||
/// paths of graph data files, a `#` header whose values aren't true or false, a header that names
|
||||
/// a variable an earlier column named), and the second the variables it reads as another variable
|
||||
/// (a variable whose name starts with `#`, `@` or `%` and isn't of that prefix's kind, and a graph
|
||||
/// variable, which the export writes without `%`).
|
||||
fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
const C: &str = "dataset.import";
|
||||
let none = BTreeMap::new();
|
||||
@@ -287,9 +289,11 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
refused.push(v.name.as_str());
|
||||
continue;
|
||||
};
|
||||
// A `%` header's cells are paths of graph data files, which the values the export writes aren't.
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| {
|
||||
let cell = value_to_cell(val);
|
||||
cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok()
|
||||
if files { cell.trim().is_empty() } else { cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() }
|
||||
});
|
||||
if !cells_read {
|
||||
refused.push(v.name.as_str());
|
||||
@@ -340,7 +344,9 @@ fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> {
|
||||
/// that earlier columns define) names that variable. Otherwise `#` before the name makes it a
|
||||
/// visibility variable, `@` makes it an image variable, and a cell without a prefix names a text
|
||||
/// variable. A prefixed name that is already a variable must be one of the prefix's kind; a new
|
||||
/// name is added to `defined`. A `%` cell that names no variable (graph data files) is refused.
|
||||
/// name is added to `defined`. `%` before a name makes it a graph variable whose column holds the
|
||||
/// paths of graph data files ([`graph_file_value`]); [`dataset_import`] tells such a column apart
|
||||
/// by a returned name that is not the cell.
|
||||
fn header_variable(
|
||||
cell: &str,
|
||||
column: usize,
|
||||
@@ -356,8 +362,8 @@ fn header_variable(
|
||||
(rest.trim(), VariableKind::Visibility)
|
||||
} else if let Some(rest) = cell.strip_prefix('@') {
|
||||
(rest.trim(), VariableKind::Image)
|
||||
} else if cell.starts_with('%') {
|
||||
return Err(bad(cmd, format!("column {column}: `{cell}` is a `%` column of graph data files, which are not read")));
|
||||
} else if let Some(rest) = cell.strip_prefix('%') {
|
||||
(rest.trim(), VariableKind::Graph)
|
||||
} else {
|
||||
(cell, VariableKind::Text)
|
||||
};
|
||||
@@ -375,13 +381,94 @@ fn header_variable(
|
||||
}
|
||||
}
|
||||
|
||||
/// The most bytes the `%` columns of one import read from graph data files and keep as graph
|
||||
/// values, counted together: each file's bytes once (it is read once, however many cells name it),
|
||||
/// and the graph value of every cell, which each data set holds a copy of.
|
||||
const MAX_GRAPH_FILES_TOTAL: usize = 256 * 1_048_576;
|
||||
|
||||
/// The graph data files the `%` columns of one import have read, by path, and the bytes counted
|
||||
/// against [`MAX_GRAPH_FILES_TOTAL`] so far.
|
||||
#[derive(Default)]
|
||||
struct GraphFiles {
|
||||
read: BTreeMap<String, String>,
|
||||
total: usize,
|
||||
}
|
||||
|
||||
/// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the
|
||||
/// graph variable `var`: the graph data file at `path` (taken from the folder `base` when
|
||||
/// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]),
|
||||
/// or no value for an empty cell. The path is followed as an image variable's path is
|
||||
/// ([`crate::cmd::fileio::document_path`]): only files on this computer, or on the network share
|
||||
/// `base` is on, are read. A relative path without `base`, a path on another computer or share, a
|
||||
/// device or a URL, a file that can't be read or is larger than 1 MB, a file that gives a graph
|
||||
/// value longer than [`MAX_GRAPH_CSV`] bytes and more than [`MAX_GRAPH_FILES_TOTAL`] bytes in all
|
||||
/// are refused, with the line and the column.
|
||||
fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result<Option<DataValue>> {
|
||||
const C: &str = "dataset.import";
|
||||
let path = path.trim();
|
||||
if path.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// Without `base`, a path that stays relative once a `file:` URL is read is refused here, so the
|
||||
// error says what to give.
|
||||
if base.is_none() && craft_docpath::resolve(path, None).is_ok_and(|p| !p.is_absolute()) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path"),
|
||||
));
|
||||
}
|
||||
// `document_path` takes a relative path from the folder of a document; any file name in `base`
|
||||
// stands for the CSV there.
|
||||
let document = base.map(|base| std::path::Path::new(base).join("data sets.csv").to_string_lossy().into_owned());
|
||||
let full = crate::cmd::fileio::document_path(path, document.as_deref())
|
||||
.map_err(|r| bad(C, format!("line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r}")))?;
|
||||
let csv = match files.read.get(&full) {
|
||||
Some(csv) => csv.clone(),
|
||||
None => {
|
||||
// One byte past the limit is enough to refuse the file.
|
||||
let bytes = read_file_head(&full, MAX_GRAPH_DATA_FILE + 1)
|
||||
.map_err(|e| bad(C, format!("line {line}, column {column}: the graph data file for `{var}` can't be read: {e}")))?;
|
||||
if bytes.len() > MAX_GRAPH_DATA_FILE {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes"),
|
||||
));
|
||||
}
|
||||
let csv = crate::cmd::graph::graph_csv_from_file(&bytes)?;
|
||||
if csv.len() > MAX_GRAPH_CSV {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes"
|
||||
),
|
||||
));
|
||||
}
|
||||
files.total += bytes.len();
|
||||
files.read.insert(full, csv.clone());
|
||||
csv
|
||||
}
|
||||
};
|
||||
files.total += csv.len();
|
||||
if files.total > MAX_GRAPH_FILES_TOTAL {
|
||||
return Err(bad(C, format!("line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all")));
|
||||
}
|
||||
Ok(Some(DataValue::Graph(csv)))
|
||||
}
|
||||
|
||||
/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it,
|
||||
/// and the variables the document doesn't define yet are defined, unbound. Two headers that name
|
||||
/// one variable are refused. The rows replace every dataset of the document and are named "Data
|
||||
/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// one variable are refused. The cells of a `%` column are paths of graph data files
|
||||
/// ([`graph_file_value`]); a relative one is taken from the folder `base` gives, else from the
|
||||
/// folder of the file `path` names. The rows replace every dataset of the document and are named
|
||||
/// "Data Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// stay. One undo step, and none when the variables and datasets stay as they were.
|
||||
pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.import";
|
||||
let base = match text_param(p, "base", C)? {
|
||||
Some("") => return Err(bad(C, "`base` is empty")),
|
||||
Some(base) => Some(absolute_path(base)),
|
||||
None => str_param(p, "path").and_then(|path| std::path::Path::new(&absolute_path(path)).parent().map(|d| d.to_string_lossy().into_owned())),
|
||||
};
|
||||
let (bytes, given_as_text) = datasets_csv_bytes(p, C)?;
|
||||
// `data` and `csv` are already text, NUL characters included (`dataset.export` writes them).
|
||||
let text = if given_as_text { String::from_utf8(bytes).map_err(|_| bad(C, "CSV is not UTF-8"))? } else { datasets_csv_text(&bytes, C)? };
|
||||
@@ -390,7 +477,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV is empty"));
|
||||
};
|
||||
let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
|
||||
let mut columns: Vec<(usize, String, VariableKind)> = Vec::new();
|
||||
// Each column: its index, its variable and kind, and whether its cells are graph data files.
|
||||
let mut columns: Vec<(usize, String, VariableKind, bool)> = Vec::new();
|
||||
let mut defined: Vec<Variable> = Vec::new();
|
||||
for (i, h) in header.iter().enumerate() {
|
||||
let cell = h.trim();
|
||||
@@ -398,11 +486,12 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("empty header in column {}", i + 1)));
|
||||
}
|
||||
let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?;
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) {
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, ..)| *n == name) {
|
||||
let (first, column) = (first + 1, i + 1);
|
||||
return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`")));
|
||||
}
|
||||
columns.push((i, name, kind));
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
columns.push((i, name, kind, files));
|
||||
}
|
||||
// Lock Variables refuses New Variable, so the import is refused when a header would define one.
|
||||
if !defined.is_empty() {
|
||||
@@ -412,13 +501,19 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV has a header but no data rows"));
|
||||
}
|
||||
let mut parsed: Vec<DataSet> = Vec::new();
|
||||
let mut files = GraphFiles::default();
|
||||
for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() {
|
||||
let name = format!("Data Set {}", n + 1);
|
||||
let mut values = BTreeMap::new();
|
||||
for &(col, ref var, kind) in &columns {
|
||||
for &(col, ref var, kind, from_files) in &columns {
|
||||
let cell = row.get(col).map(String::as_str).unwrap_or("");
|
||||
let was_quoted = quoted.get(col).copied().unwrap_or(false);
|
||||
if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? {
|
||||
let value = if from_files {
|
||||
graph_file_value(&mut files, cell, base.as_deref(), var, (line, col + 1))?
|
||||
} else {
|
||||
cell_to_value(kind, cell, was_quoted, var, line, C)?
|
||||
};
|
||||
if let Some(v) = value {
|
||||
values.insert(var.clone(), v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,7 +619,21 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap
|
||||
}
|
||||
}
|
||||
doc.variables = vars.into();
|
||||
left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label())))
|
||||
left_out_warning(other.iter().map(|v| left_out_kind(v.kind, v.trait_name.as_deref())))
|
||||
}
|
||||
|
||||
/// How the warning about variables that aren't text names the kind of one: Visibility, Linked File
|
||||
/// or Graph Data for a `trait` VectorCraft reads, Unknown for a variable without a `trait`, and any
|
||||
/// other `trait` as the file writes it, in backticks, each backtick in it doubled, so that a `trait`
|
||||
/// such as `Unknown` or `a (1), b` reads as one kind the file names.
|
||||
fn left_out_kind(kind: VariableKind, trait_name: Option<&str>) -> String {
|
||||
match (kind, trait_name) {
|
||||
(VariableKind::Visibility, _) => "Visibility".into(),
|
||||
(VariableKind::Image, _) => "Linked File".into(),
|
||||
(VariableKind::Graph, _) => "Graph Data".into(),
|
||||
(_, None) => "Unknown".into(),
|
||||
(_, Some(t)) => format!("`{}`", t.replace('`', "``")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load Variable Library: replace the document's variables and data sets with a variable library's
|
||||
@@ -668,10 +682,11 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names}))
|
||||
}
|
||||
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each: every
|
||||
/// kind once, in the order it first comes, with how many variables have it. `None` without any.
|
||||
fn left_out_warning<'a>(kinds: impl Iterator<Item = &'a str>) -> Option<String> {
|
||||
let mut counted: Vec<(&str, usize)> = Vec::new();
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each
|
||||
/// ([`left_out_kind`]): every kind once, in the order it first comes, with how many variables have
|
||||
/// it. `None` without any.
|
||||
fn left_out_warning(kinds: impl Iterator<Item = String>) -> Option<String> {
|
||||
let mut counted: Vec<(String, usize)> = Vec::new();
|
||||
for t in kinds {
|
||||
match counted.iter_mut().find(|(k, _)| *k == t) {
|
||||
Some((_, n)) => *n += 1,
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! Magic Wand panel's (session state, kept across tool switches); the tool runs
|
||||
//! `select.magicWand` on click.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -188,13 +190,14 @@ impl WandSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paintable leaves (paths, compounds, text, images) that are visible and editable.
|
||||
/// Paintable leaves (paths, compounds, text, images) that are visible and editable, in the order
|
||||
/// of the document walk.
|
||||
fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut compounds: Vec<NodeId> = vec![];
|
||||
let mut compounds: HashSet<NodeId> = HashSet::new();
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
compounds.push(n.id);
|
||||
compounds.insert(n.id);
|
||||
out.push(n.id);
|
||||
} else if !n.is_container() && !n.is_ruler_guide() {
|
||||
out.push(n.id);
|
||||
@@ -210,6 +213,18 @@ fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Shift-click: the selected objects in their order, then each hit that isn't selected yet.
|
||||
fn added(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let seen: HashSet<NodeId> = selected.iter().copied().collect();
|
||||
selected.iter().copied().chain(hits.into_iter().filter(|h| !seen.contains(h))).collect()
|
||||
}
|
||||
|
||||
/// Alt-click: the selected objects that aren't hits, in their order.
|
||||
fn subtracted(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let hits: HashSet<NodeId> = hits.into_iter().collect();
|
||||
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
|
||||
}
|
||||
|
||||
fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?;
|
||||
let st = s.doc()?;
|
||||
@@ -224,8 +239,8 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.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(),
|
||||
"subtract" => st.selection.objects.iter().copied().filter(|i| !hits.contains(i)).collect(),
|
||||
"add" => added(&st.selection.objects, hits),
|
||||
"subtract" => subtracted(&st.selection.objects, hits),
|
||||
"set" => hits,
|
||||
other => return Err(bad("select.magicWand", format!("unknown mode `{other}` (set, add, subtract)"))),
|
||||
};
|
||||
@@ -423,6 +438,252 @@ mod tests {
|
||||
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
|
||||
}
|
||||
|
||||
/// [`paintable`] with the compound paths kept in a list and searched for each object's parent.
|
||||
fn paintable_by_search(doc: &Document) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut compounds: Vec<NodeId> = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
compounds.push(n.id);
|
||||
out.push(n.id);
|
||||
} else if !n.is_container() && !n.is_ruler_guide() {
|
||||
out.push(n.id);
|
||||
}
|
||||
});
|
||||
let editable = doc.editable();
|
||||
out.retain(|id| {
|
||||
!doc.parent_of(*id).is_some_and(|p| compounds.contains(&p))
|
||||
&& editable(*id)
|
||||
&& doc.is_visible(*id)
|
||||
&& doc.node(*id).is_some_and(|n| n.visible)
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`added`] with the selection searched for each hit.
|
||||
fn added_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
|
||||
selected.iter().copied().chain(hits.iter().copied().filter(|h| !selected.contains(h))).collect()
|
||||
}
|
||||
|
||||
/// [`subtracted`] with the hits searched for each selected object.
|
||||
fn subtracted_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
|
||||
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
|
||||
}
|
||||
|
||||
/// A red fill for an even `k` and a blue one for an odd `k`, with a 1 pt black stroke.
|
||||
fn bench_paint(k: usize) -> vectorcraft_doc::Appearance {
|
||||
use vectorcraft_color::Color;
|
||||
let fill = if k.is_multiple_of(2) { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) };
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(fill), Paint::solid(Color::BLACK), 1.0)
|
||||
}
|
||||
|
||||
/// Path `k`: a 10 × 10 rectangle painted as [`bench_paint`]. Every 97th path is locked and
|
||||
/// every 89th hidden.
|
||||
fn bench_path(d: &mut Document, k: usize) -> Node {
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0);
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)), bench_paint(k));
|
||||
n.locked = k % 97 == 5;
|
||||
n.visible = k % 89 != 7;
|
||||
n
|
||||
}
|
||||
|
||||
/// A session whose document holds `blocks` × 200 paths on one layer. Each block has a group of
|
||||
/// 10 paths, 25 compound paths of 2 paths each and 140 loose paths, with the group and the
|
||||
/// compound paths among the loose paths. The compound paths alternate red and blue fills, and
|
||||
/// a few are locked or hidden.
|
||||
fn wand_session(blocks: usize) -> Session {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_geom::FillRule;
|
||||
let mut d = Document::new(4000.0, 4000.0);
|
||||
let mut k = 0;
|
||||
let mut next = |d: &mut Document| {
|
||||
k += 1;
|
||||
bench_path(d, k - 1)
|
||||
};
|
||||
let mut art = vec![];
|
||||
for slot in 0..blocks * 166 {
|
||||
let node = match slot % 166 {
|
||||
0 => {
|
||||
let members = (0..10).map(|_| Arc::new(next(&mut d))).collect();
|
||||
Node::group(d.alloc_id(), members)
|
||||
}
|
||||
c @ 1..=25 => {
|
||||
let members = (0..2).map(|_| Arc::new(next(&mut d))).collect();
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
n.appearance = bench_paint(c).into();
|
||||
n.locked = slot % 1001 == 3;
|
||||
n.visible = slot % 1003 != 5;
|
||||
n
|
||||
}
|
||||
_ => next(&mut d),
|
||||
};
|
||||
art.push(Arc::new(node));
|
||||
}
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
*ch = art;
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
s
|
||||
}
|
||||
|
||||
/// The objects the wand picks when `reference` is clicked, found as before membership sets.
|
||||
fn hits_by_search(s: &Session, reference: NodeId) -> Vec<NodeId> {
|
||||
let st = s.doc().unwrap();
|
||||
let r = st.doc.node(reference).unwrap();
|
||||
let w = s.menu.wand.clone();
|
||||
paintable_by_search(&st.doc).into_iter().filter(|i| w.matches(r, st.doc.node(*i).unwrap(), st.doc.color_mode)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membership_sets_give_the_same_objects_in_the_same_order_as_searches() {
|
||||
// 20,000 paths: 5,000 in 2,500 compound paths and 1,000 in 100 groups.
|
||||
let mut s = wand_session(100);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let all = paintable(doc);
|
||||
assert!(all == paintable_by_search(doc), "paintable objects differ");
|
||||
// Compound paths stay pickable unless locked or hidden, and their members never are.
|
||||
let pickable: HashSet<NodeId> = all.iter().copied().collect();
|
||||
let (mut compounds, mut skipped) = (0, 0);
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
compounds += 1;
|
||||
skipped += usize::from(n.locked || !n.visible);
|
||||
assert_eq!(pickable.contains(&n.id), n.visible && !n.locked, "compound path {}", n.id.0);
|
||||
assert!(children.iter().all(|m| !pickable.contains(&m.id)), "a member of compound path {} is pickable", n.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(compounds, 2_500);
|
||||
assert!(skipped > 0 && skipped < 100, "{skipped} locked or hidden compound paths");
|
||||
let reference = all[0];
|
||||
let hits = hits_by_search(&s, reference);
|
||||
assert!(hits.len() > 5_000 && hits.len() < all.len() / 2 + 1_000, "{} hits", hits.len());
|
||||
// A selection in another order than the document's: every third object from the end, both
|
||||
// hits and objects that aren't hits.
|
||||
let selected: Vec<NodeId> = all.iter().rev().step_by(3).copied().collect();
|
||||
assert!(selected.iter().any(|i| hits.contains(i)) && selected.iter().any(|i| !hits.contains(i)));
|
||||
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits), "Shift-click differs");
|
||||
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits), "Alt-click differs");
|
||||
// And through the command, in each mode.
|
||||
let ids: Vec<u64> = selected.iter().map(|i| i.0).collect();
|
||||
for (mode, want) in [("set", hits.clone()), ("add", added_by_search(&selected, &hits)), ("subtract", subtracted_by_search(&selected, &hits))]
|
||||
{
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
assert!(s.doc().unwrap().selection.objects == selected, "select.set kept the order");
|
||||
let r = s.execute("select.magicWand", &json!({"id": reference.0, "mode": mode})).unwrap();
|
||||
assert_eq!(r["count"], json!(want.len()), "{mode}");
|
||||
assert!(s.doc().unwrap().selection.objects == want, "{mode} selects other objects or another order");
|
||||
}
|
||||
}
|
||||
|
||||
/// Time the Magic Wand's paintable walk, Shift-click and Alt-click lists and a whole Shift-click
|
||||
/// on documents of 2,000, 20,000 and 50,000 paths, with membership sets and with the searches
|
||||
/// they replace, alternating 7 runs of each and giving the medians in ms. On Linux the times are
|
||||
/// the thread's CPU time.
|
||||
/// Run with `cargo test --release -p vectorcraft-engine --lib magic_wand_membership_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn magic_wand_membership_timing() {
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
/// The time of one call of `f`, averaged over `reps` calls.
|
||||
fn time(reps: u32, f: &mut dyn FnMut()) -> f64 {
|
||||
let start = (cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..reps {
|
||||
f();
|
||||
}
|
||||
let ms = match (start.0, cpu_ns()) {
|
||||
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
|
||||
_ => start.1.elapsed().as_secs_f64() * 1000.0,
|
||||
};
|
||||
ms / f64::from(reps)
|
||||
}
|
||||
fn median(v: &mut [f64]) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
/// Alternate `old` and `new` 7 times each and print their medians and every run. Each run
|
||||
/// takes the mean of enough calls for about 100 ms.
|
||||
fn compare(paths: usize, what: &str, old: &mut dyn FnMut(), new: &mut dyn FnMut()) {
|
||||
let reps = (100.0 / time(1, old).max(0.1)).clamp(1.0, 200.0) as u32;
|
||||
let (mut o, mut n) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
o.push(time(reps, old));
|
||||
n.push(time(reps, new));
|
||||
}
|
||||
let runs = format!("calls per run {reps}: {o:.3?} / {n:.3?}");
|
||||
println!("| {paths} | {what} | {:.3} | {:.3} | {runs}", median(&mut o), median(&mut n));
|
||||
}
|
||||
println!("clock: {}", if cpu_ns().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
println!("| paths | step | searches (ms) | sets (ms) | runs");
|
||||
for blocks in [10, 100, 250] {
|
||||
let mut s = wand_session(blocks);
|
||||
let paths = blocks * 200;
|
||||
let st = s.doc().unwrap();
|
||||
let all = paintable(&st.doc);
|
||||
assert!(all == paintable_by_search(&st.doc));
|
||||
let reference = all[0];
|
||||
let hits = hits_by_search(&s, reference);
|
||||
let selected: Vec<NodeId> = all.iter().rev().step_by(2).copied().collect();
|
||||
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits));
|
||||
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits));
|
||||
let doc = &st.doc;
|
||||
compare(
|
||||
paths,
|
||||
"paintable",
|
||||
&mut || {
|
||||
std::hint::black_box(paintable_by_search(doc));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(paintable(doc));
|
||||
},
|
||||
);
|
||||
compare(
|
||||
paths,
|
||||
"Shift-click list",
|
||||
&mut || {
|
||||
std::hint::black_box(added_by_search(&selected, &hits));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(added(&selected, hits.clone()));
|
||||
},
|
||||
);
|
||||
compare(
|
||||
paths,
|
||||
"Alt-click list",
|
||||
&mut || {
|
||||
std::hint::black_box(subtracted_by_search(&selected, &hits));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(subtracted(&selected, hits.clone()));
|
||||
},
|
||||
);
|
||||
// A whole Shift-click after the selection is set: [`magic_wand`], and its steps with
|
||||
// the searches.
|
||||
let ids = json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<u64>>() });
|
||||
let click = json!({"id": reference.0, "mode": "add"});
|
||||
let s = std::cell::RefCell::new(&mut s);
|
||||
compare(
|
||||
paths,
|
||||
"select.set, then Shift-click",
|
||||
&mut || {
|
||||
let s = &mut **s.borrow_mut();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
let before = s.doc().unwrap().selection.objects.clone();
|
||||
let picked = added_by_search(&before, &hits_by_search(s, reference));
|
||||
s.select(|_, sel| sel.set(picked)).unwrap();
|
||||
},
|
||||
&mut || {
|
||||
let s = &mut **s.borrow_mut();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
magic_wand(s, &click).unwrap();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -45,6 +45,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.optimizeToFileSize",
|
||||
"Optimize to File Size",
|
||||
[],
|
||||
None,
|
||||
"{desiredK: the desired file size in K (1024 bytes; above 0, at most 1048576), startWith?: current (default: the format given, its JPEG quality or GIF/PNG-8 colors lowered; GIF then takes lossy 100)|auto (GIF for art with transparency or at most 256 colors (blended over the matte without transparency), else JPEG; the other one when the first can't reach the size and the art is opaque), use?: allSlices (default: the image, or the image slices' files together)|eachSlice (every image slice's file)|currentSlice (the `slice` given, else the selected image slice, else the first), slice?: n (1-based, from slice.list), preset?, …the settings of document.exportForWeb} the settings whose files fit in the size, searched by encoding at most 32 trial settings (each one encodes every image it measures); slices share one setting, which every scope changes → {targetBytes, achieved (false: no setting tried fits, and settings are the smallest one found), bytes (as use measures them), format, settings, trials, images, warnings}; writes nothing and changes no remembered setting",
|
||||
has_doc,
|
||||
optimize_to_file_size
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.settings",
|
||||
"Save for Web Settings",
|
||||
@@ -1054,6 +1063,297 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Optimize to File Size ----------
|
||||
|
||||
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
|
||||
/// it measures once.
|
||||
pub const OPTIMIZE_TRIALS: usize = 32;
|
||||
/// The largest desired file size, in K (1 GiB).
|
||||
pub const MAX_DESIRED_K: f64 = 1_048_576.0;
|
||||
|
||||
/// Where Optimize to File Size starts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StartWith {
|
||||
/// The current format, with its JPEG quality or palette colors lowered.
|
||||
Current,
|
||||
/// GIF or JPEG, by the image's content.
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// The pixels `px` (`[x0, y0, x1, y1]`) of `r` as an image: borrowed when `px` is the whole render,
|
||||
/// else a copy.
|
||||
fn file_pixels(r: &WebRender, px: [u32; 4]) -> std::borrow::Cow<'_, [u8]> {
|
||||
if px == [0, 0, r.width, r.height] { std::borrow::Cow::Borrowed(r.rgba.as_slice()) } else { std::borrow::Cow::Owned(crop(r, px)) }
|
||||
}
|
||||
|
||||
/// The settings Optimize to File Size found.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SizeFit {
|
||||
pub settings: WebSettings,
|
||||
/// The size the settings give the measured images.
|
||||
pub bytes: usize,
|
||||
/// Whether `bytes` is within the target.
|
||||
pub achieved: bool,
|
||||
/// The trial settings encoded.
|
||||
pub trials: usize,
|
||||
}
|
||||
|
||||
/// The files a search measures and the trials it has left.
|
||||
struct Trials<'a> {
|
||||
doc: &'a Document,
|
||||
r: &'a WebRender,
|
||||
/// The pixels (`[x0, y0, x1, y1]`) of each file in `r`.
|
||||
files: &'a [[u32; 4]],
|
||||
/// Measure the largest file (else the files together).
|
||||
each: bool,
|
||||
left: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Trials<'_> {
|
||||
/// The size `s` gives the files, encoded one at a time; `None` when no trial is left.
|
||||
fn size(&mut self, s: &WebSettings) -> std::result::Result<Option<usize>, String> {
|
||||
if self.left == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
self.left -= 1;
|
||||
self.used += 1;
|
||||
let mut out = 0usize;
|
||||
for &px in self.files {
|
||||
let n = optimize(self.doc, &file_pixels(self.r, px), px[2] - px[0], px[3] - px[1], s)?.bytes.len();
|
||||
out = if self.each { out.max(n) } else { out.saturating_add(n) };
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// `(settings, bytes)` of a trial.
|
||||
pub type Trial = (WebSettings, usize);
|
||||
|
||||
/// Keep `(s, n)` in `smallest` when it is the smallest trial so far.
|
||||
fn keep_smallest(smallest: &mut Option<Trial>, s: WebSettings, n: usize) {
|
||||
if smallest.as_ref().is_none_or(|(_, b)| n < *b) {
|
||||
*smallest = Some((s, n));
|
||||
}
|
||||
}
|
||||
|
||||
/// The values [`highest_within`] measures spread over its range before it narrows a step.
|
||||
pub const OPTIMIZE_SAMPLES: u16 = 6;
|
||||
|
||||
/// Measures the size a setting gives; `None` when no trial is left.
|
||||
pub type MeasureSize<'a> = dyn FnMut(&WebSettings) -> std::result::Result<Option<usize>, String> + 'a;
|
||||
|
||||
/// The highest value in `lo..hi` that `set` gives `start` whose size is within `target`, when the
|
||||
/// value `hi` is over it. A lower value can give a larger file, so the search measures up to
|
||||
/// [`OPTIMIZE_SAMPLES`] values spread over the range, from `hi - 1` down, stops at the first that
|
||||
/// fits, and halves the step between it and the measured value above it, keeping the highest value
|
||||
/// measured within `target`. `None` when no value measured fits or no trial is left; the trials over
|
||||
/// the target go to `smallest`.
|
||||
pub fn highest_within(
|
||||
size: &mut MeasureSize,
|
||||
start: &WebSettings,
|
||||
(lo, hi): (u16, u16),
|
||||
set: fn(&mut WebSettings, u16),
|
||||
target: usize,
|
||||
smallest: &mut Option<Trial>,
|
||||
) -> std::result::Result<Option<Trial>, String> {
|
||||
let with = |v: u16| {
|
||||
let mut s = start.clone();
|
||||
set(&mut s, v);
|
||||
s
|
||||
};
|
||||
if lo >= hi {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = u32::from(hi - lo);
|
||||
let samples = u32::from(OPTIMIZE_SAMPLES).min(span);
|
||||
let (mut above, mut found) = (hi, None);
|
||||
for i in (0..samples).rev() {
|
||||
let step = if samples == 1 { 0 } else { (span - 1) * i / (samples - 1) };
|
||||
let v = lo.saturating_add(u16::try_from(step).unwrap_or(0));
|
||||
let s = with(v);
|
||||
let Some(n) = size(&s)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
found = Some((v, (s, n)));
|
||||
break;
|
||||
}
|
||||
keep_smallest(smallest, s, n);
|
||||
above = v;
|
||||
}
|
||||
let Some((mut lo, mut best)) = found else { return Ok(None) };
|
||||
let mut hi = above;
|
||||
while hi - lo > 1 {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let s = with(mid);
|
||||
let Some(n) = size(&s)? else { break };
|
||||
if n <= target {
|
||||
lo = mid;
|
||||
best = (s, n);
|
||||
} else {
|
||||
keep_smallest(smallest, s, n);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
Ok(Some(best))
|
||||
}
|
||||
|
||||
/// Sets the JPEG quality, for [`highest_within`].
|
||||
pub fn set_quality(s: &mut WebSettings, v: u16) {
|
||||
s.quality = u8::try_from(v).unwrap_or(100);
|
||||
}
|
||||
|
||||
/// Sets the palette colors, for [`highest_within`].
|
||||
pub fn set_colors(s: &mut WebSettings, v: u16) {
|
||||
s.colors = v;
|
||||
}
|
||||
|
||||
/// The best settings of `start`'s format within `target`: `start` when it fits, else the highest
|
||||
/// JPEG quality or the most palette colors [`highest_within`] finds that fit, and for GIF, when none
|
||||
/// is found, lossy 100 with the most colors that fit. When nothing tried fits, the smallest trial, not achieved.
|
||||
/// `None` when no trial is left.
|
||||
fn search_format(t: &mut Trials, start: &WebSettings, target: usize) -> std::result::Result<Option<SizeFit>, String> {
|
||||
let fit = |(settings, bytes): Trial, achieved: bool| SizeFit { settings, bytes, achieved, trials: 0 };
|
||||
let Some(n) = t.size(start)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
return Ok(Some(fit((start.clone(), n), true)));
|
||||
}
|
||||
let mut smallest = Some((start.clone(), n));
|
||||
let found = match start.format {
|
||||
WebFormat::Jpg => highest_within(&mut |s: &WebSettings| t.size(s), start, (1, u16::from(start.quality)), set_quality, target, &mut smallest)?,
|
||||
WebFormat::Gif | WebFormat::Png8 => {
|
||||
match highest_within(&mut |s: &WebSettings| t.size(s), start, (2, start.colors), set_colors, target, &mut smallest)? {
|
||||
None if start.format == WebFormat::Gif && start.lossy < 100 => {
|
||||
let lossy = WebSettings { lossy: 100, ..start.clone() };
|
||||
match t.size(&lossy)? {
|
||||
Some(n) if n <= target => Some((lossy, n)),
|
||||
Some(n) => {
|
||||
keep_smallest(&mut smallest, lossy.clone(), n);
|
||||
highest_within(&mut |s: &WebSettings| t.size(s), &lossy, (2, lossy.colors), set_colors, target, &mut smallest)?
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
}
|
||||
WebFormat::Png24 => None,
|
||||
};
|
||||
Ok(match (found, smallest) {
|
||||
(Some(f), _) => Some(fit(f, true)),
|
||||
(None, Some(s)) => Some(fit(s, false)),
|
||||
(None, None) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The format Auto Select GIF/JPEG starts with, and whether the files (`[x0, y0, x1, y1]` of `r`)
|
||||
/// are opaque: GIF for files with transparent pixels (when `transparency` keeps them) or at most
|
||||
/// 256 colors, else JPEG. The colors counted are the ones the files are written with: without
|
||||
/// `transparency`, the pixels blended over `matte`.
|
||||
fn auto_format(r: &WebRender, files: &[[u32; 4]], transparency: bool, matte: [u8; 3]) -> (WebFormat, bool) {
|
||||
let stride = r.width as usize * 4;
|
||||
let row =
|
||||
move |y: u32, x0: u32, x1: u32| r.rgba.get(y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4).unwrap_or_default();
|
||||
let pixels = || files.iter().flat_map(move |&[x0, y0, x1, y1]| (y0..y1).flat_map(move |y| row(y, x0, x1).as_chunks::<4>().0.iter()));
|
||||
let opaque = !transparency || pixels().all(|p| p[3] == 255);
|
||||
if !opaque {
|
||||
return (WebFormat::Gif, false);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
// An opaque pixel blends to itself.
|
||||
let few = pixels().all(|p| {
|
||||
seen.insert(flatten(p, matte).next().unwrap_or_default());
|
||||
seen.len() <= 256
|
||||
});
|
||||
(if few { WebFormat::Gif } else { WebFormat::Jpg }, true)
|
||||
}
|
||||
|
||||
/// Optimize to File Size: the settings, from `s`, whose files (the pixels `[x0, y0, x1, y1]` of
|
||||
/// `r`) fit in `target` bytes, measured together, or with `each` the largest one. At most
|
||||
/// [`OPTIMIZE_TRIALS`] trial settings are encoded, and a trial encodes the files one at a time.
|
||||
pub fn optimize_to_size(
|
||||
doc: &Document,
|
||||
r: &WebRender,
|
||||
files: &[[u32; 4]],
|
||||
s: &WebSettings,
|
||||
start: StartWith,
|
||||
each: bool,
|
||||
target: usize,
|
||||
) -> std::result::Result<SizeFit, String> {
|
||||
let mut t = Trials { doc, r, files, each, left: OPTIMIZE_TRIALS, used: 0 };
|
||||
let with = |format: WebFormat| WebSettings { format, ..s.clone() };
|
||||
let found = match start {
|
||||
_ if files.is_empty() => None,
|
||||
StartWith::Current => search_format(&mut t, s, target)?,
|
||||
StartWith::Auto => {
|
||||
let (first, opaque) = auto_format(r, files, s.transparency, s.matte_rgb()?.unwrap_or([255; 3]));
|
||||
let other = if first == WebFormat::Gif { WebFormat::Jpg } else { WebFormat::Gif };
|
||||
match search_format(&mut t, &with(first), target)? {
|
||||
Some(a) if !a.achieved && opaque => match search_format(&mut t, &with(other), target)? {
|
||||
Some(b) if b.achieved || b.bytes < a.bytes => Some(b),
|
||||
_ => Some(a),
|
||||
},
|
||||
a => a,
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut best = found.ok_or("Optimize to File Size: there is no image to measure")?;
|
||||
best.trials = t.used;
|
||||
Ok(best)
|
||||
}
|
||||
|
||||
fn optimize_to_file_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const O: &str = "webExport.optimizeToFileSize";
|
||||
let k = p
|
||||
.get("desiredK")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|k| k.is_finite() && *k > 0.0 && *k <= MAX_DESIRED_K)
|
||||
.ok_or_else(|| bad(O, "give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576"))?;
|
||||
let target = ((k * 1024.0).floor() as usize).max(1);
|
||||
let start = match p.get("startWith").map(Value::as_str) {
|
||||
None | Some(Some("current")) => StartWith::Current,
|
||||
Some(Some("auto")) => StartWith::Auto,
|
||||
Some(_) => return Err(bad(O, "`startWith` is `current` or `auto`")),
|
||||
};
|
||||
let scope = match p.get("use").map(Value::as_str) {
|
||||
None if p.get("slice").is_some() => "currentSlice",
|
||||
None => "allSlices",
|
||||
Some(Some(u @ ("allSlices" | "eachSlice" | "currentSlice"))) => u,
|
||||
Some(_) => return Err(bad(O, "`use` is `allSlices`, `eachSlice` or `currentSlice`")),
|
||||
};
|
||||
let slice = match p.get("slice").map(|v| v.as_u64().filter(|n| *n >= 1 && scope == "currentSlice")) {
|
||||
None => None,
|
||||
Some(Some(n)) => Some(n),
|
||||
Some(None) => return Err(bad(O, "`slice` is a slice number from `slice.list`, with `use: currentSlice`")),
|
||||
};
|
||||
let settings = s.web_settings(p).map_err(|e| bad(O, e))?;
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let r = render(doc, &settings).map_err(|e| bad(O, e))?;
|
||||
let warnings = undecoded(failed);
|
||||
let areas = doc.slice_layout();
|
||||
let selected = super::slices::selected_slices(doc, &st.selection);
|
||||
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(O, e))?;
|
||||
let image_cells: Vec<&Cell> =
|
||||
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).collect();
|
||||
let picked: Vec<&Cell> = match (scope, slice) {
|
||||
("currentSlice", Some(n)) => {
|
||||
let c = image_cells.iter().find(|c| c.area.number as u64 == n);
|
||||
vec![*c.ok_or_else(|| bad(O, format!("no slice {n} in the image (see slice.list)")))?]
|
||||
}
|
||||
("currentSlice", None) => {
|
||||
image_cells.iter().find(|c| c.area.id.is_some_and(|id| selected.contains(&id))).or(image_cells.first()).copied().into_iter().collect()
|
||||
}
|
||||
_ => image_cells,
|
||||
};
|
||||
let files: Vec<[u32; 4]> = if cells.is_empty() { vec![[0, 0, r.width, r.height]] } else { picked.iter().map(|c| c.px).collect() };
|
||||
let fit = optimize_to_size(doc, &r, &files, &settings, start, scope == "eachSlice", target).map_err(|e| bad(O, e))?;
|
||||
Ok(json!({
|
||||
"targetBytes": target, "achieved": fit.achieved, "bytes": fit.bytes, "format": fit.settings.format.id(),
|
||||
"settings": fit.settings.to_json(), "trials": fit.trials, "images": files.len(), "warnings": warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const S: &str = "webExport.settings";
|
||||
let base = if bool_or(p, "reset", false) { WebSettings::default() } else { s.last_web_settings() };
|
||||
|
||||
@@ -214,6 +214,10 @@ pub struct Prefs {
|
||||
/// runs on: a Wayland compositor may not show frames from another GPU (#502). Single-GPU
|
||||
/// machines are unaffected.
|
||||
pub gpu_preference: String,
|
||||
/// The desktop app's window presents without vsync, with frames capped at 240 a second (#6013).
|
||||
/// Read at startup (it takes effect after a restart); `--present-mode` and
|
||||
/// `VECTORCRAFT_PRESENT_MODE` take precedence over it.
|
||||
pub low_latency_drawing: bool,
|
||||
pub history_states: u32,
|
||||
pub real_time_drawing: bool,
|
||||
/// Rasterizer worker threads; -1 = automatic.
|
||||
@@ -503,6 +507,7 @@ impl Default for Prefs {
|
||||
gpu_performance: true,
|
||||
animated_zoom: true,
|
||||
gpu_preference: s("automatic"),
|
||||
low_latency_drawing: false,
|
||||
history_states: 500,
|
||||
real_time_drawing: true,
|
||||
render_threads: -1,
|
||||
|
||||
@@ -255,6 +255,21 @@ impl Session {
|
||||
(r, settled)
|
||||
}
|
||||
|
||||
/// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings
|
||||
/// of the preview that keeping typing in progress applied, for its status bar.
|
||||
pub fn begin_interaction_warned(&mut self, label: &str) -> Result<Vec<String>> {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.begin_interaction(label));
|
||||
r.map(|()| settled)
|
||||
}
|
||||
|
||||
/// Keep typing in progress as one undo step, applying the preview Real-time Drawing off left
|
||||
/// unapplied, and end the Type tool's typing session → the applied preview's warnings. Nothing
|
||||
/// changes when no typing is in progress.
|
||||
pub fn keep_typing(&mut self) -> Result<Vec<String>> {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| if cmd::typing_in_progress(s) { cmd::settle_interaction(s) } else { Ok(()) });
|
||||
r.map(|()| settled)
|
||||
}
|
||||
|
||||
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -24,6 +24,7 @@ mod build;
|
||||
mod cancel;
|
||||
mod caret_kerning;
|
||||
mod charstroke;
|
||||
mod circle_through;
|
||||
pub(super) mod clip;
|
||||
mod clipboard;
|
||||
mod clipflavours;
|
||||
@@ -2808,6 +2809,26 @@ fn an_isolated_compound_paths_member_moves_alone() {
|
||||
assert_eq!((x0(&s, outer), x0(&s, hole)), (5.0, 55.0), "the compound path selected: the whole ring");
|
||||
}
|
||||
|
||||
/// Rotate Bounding Box and Reset Bounding Box take the same objects as the transforms: a path of
|
||||
/// a compound path selected alone turns or squares its own box, and the compound path selected
|
||||
/// turns its box and its paths'.
|
||||
#[test]
|
||||
fn rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path() {
|
||||
let angle = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().bbox_angle;
|
||||
let mut s = session();
|
||||
let (c, outer, hole) = isolated_ring(&mut s);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [hole.0]})).unwrap();
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap();
|
||||
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (0.0, 0.0, 30.0), "only the hole's box turned");
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap();
|
||||
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 40.0), "the compound path and its paths");
|
||||
s.execute("select.set", &json!({"ids": [hole.0]})).unwrap();
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
|
||||
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 0.0), "Reset squared only the hole's box");
|
||||
}
|
||||
|
||||
/// The X, Y, W and H of the Properties and Transform panels run `object.setBounds`, which takes the
|
||||
/// same objects as the other transforms: a path of a compound path selected alone sets its own
|
||||
/// box and leaves the ring around it (#4046). The hole is off-centre, and a plain rectangle
|
||||
@@ -3312,6 +3333,26 @@ fn flare_ring_seed_moves_only_the_rings() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() {
|
||||
let mut s = session();
|
||||
let mut positions = Vec::new();
|
||||
for seed in [0, 1, 2, 5, 11, (1u64 << 53) - 1] {
|
||||
let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
let ring = children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap();
|
||||
let center = ring.geometric_bounds().unwrap().center();
|
||||
assert!((20.0..=1020.0).contains(¢er.x), "seed {seed}: {center:?}");
|
||||
assert!((center.y - 30.0).abs() < 1e-9);
|
||||
positions.push(center.x);
|
||||
}
|
||||
assert!((positions[0] - positions[1]).abs() > 1.0, "neighboring small seeds visibly move the first ring: {positions:?}");
|
||||
let lo = positions[..5].iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let hi = positions[..5].iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}");
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
|
||||
@@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its
|
||||
/// front at its center and onto its back 30 pt to the right (as the back is seen from behind),
|
||||
/// collected as a 3D asset in `format`.
|
||||
fn mapped(format: &str) -> (Session, u64) {
|
||||
let mut s = session();
|
||||
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
|
||||
let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}}));
|
||||
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]}));
|
||||
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]}));
|
||||
run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"}));
|
||||
let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap();
|
||||
(s, asset)
|
||||
}
|
||||
|
||||
/// The color of pixel `(x, y)` of PNG `png`.
|
||||
fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] {
|
||||
image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0
|
||||
}
|
||||
|
||||
fn is_red(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255
|
||||
}
|
||||
|
||||
fn is_blue(p: [u8; 4]) -> bool {
|
||||
p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
|
||||
for (format, names) in [
|
||||
("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]),
|
||||
("usdz", vec!["Box.usdz"]),
|
||||
("gltf", vec!["Box.gltf"]),
|
||||
("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]),
|
||||
] {
|
||||
let (mut s, _) = mapped(format);
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}");
|
||||
}
|
||||
// The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the
|
||||
// middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left
|
||||
// in the art's plane.
|
||||
let (mut s, _) = mapped("usda");
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (front, back) = (&out[1].1, &out[2].1);
|
||||
assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128));
|
||||
assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10)));
|
||||
let at = |pt: f64| (pt * 1.28) as u32;
|
||||
assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64));
|
||||
// The USDA's front cap shows the front picture through st, up from the picture's bottom.
|
||||
let usda = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert_eq!(usda.matches("primvars:st").count(), 2);
|
||||
assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap");
|
||||
// glTF holds both pictures, and a cap's coordinates stay inside its picture.
|
||||
let (mut s, _) = mapped("gltf");
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({})));
|
||||
let g: Value = serde_json::from_slice(&out[0].1).unwrap();
|
||||
assert_eq!(g["images"].as_array().map(Vec::len), Some(2));
|
||||
let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
|
||||
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() {
|
||||
let half = |a: u8| (120..=135).contains(&a);
|
||||
// A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the
|
||||
// graphic covers three quarters.
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let id = doc.asset(asset).unwrap().nodes[0];
|
||||
let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
|
||||
assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}");
|
||||
assert!(around[2] > 200 && half(around[3]), "{around:?}");
|
||||
let usda = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity");
|
||||
// An OBJ's opacity map has the alpha as gray levels.
|
||||
run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out[3].0, "Box-texture-1-opacity.png");
|
||||
let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8();
|
||||
let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]);
|
||||
assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}");
|
||||
// A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at
|
||||
// half opacity.
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
|
||||
run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
|
||||
assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}");
|
||||
assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}");
|
||||
// A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity.
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]});
|
||||
run(&mut s, "paint.setFill", json!({"gradient": clear}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
|
||||
assert!(is_red(on), "{on:?}");
|
||||
assert_eq!(around[3], 0, "{around:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() {
|
||||
let (mut s, asset) = mapped("obj");
|
||||
for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] {
|
||||
assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}");
|
||||
}
|
||||
// Without its graphics the box is one plain mesh, as before.
|
||||
let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0;
|
||||
run(&mut s, "select.set", json!({"ids": [id]}));
|
||||
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
let obj = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_pixels_are_counted_across_one_export() {
|
||||
let (s, asset) = mapped("gltf");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
|
||||
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap();
|
||||
let mut pixels = 0;
|
||||
let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap();
|
||||
assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128));
|
||||
let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128;
|
||||
let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err();
|
||||
assert!(e.contains("textureSize"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_graphics_that_draw_count_as_textures() {
|
||||
let parts_of = |s: &Session, asset: u64| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
|
||||
vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap()
|
||||
};
|
||||
let (mut s, asset) = mapped("obj");
|
||||
assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
|
||||
// With its symbol gone the graphic draws nothing, so the export writes no texture.
|
||||
run(&mut s, "symbol.delete", json!({"name": "Mark"}));
|
||||
assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_assets_round_trip_through_the_native_format() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -428,6 +428,75 @@ fn transform_panel_sizes_follow_the_turned_box() {
|
||||
assert!(near(angle(&s, a), 45.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_whole_number_references_match_integer_references() {
|
||||
for direct in [false, true] {
|
||||
for index in 0..=9 {
|
||||
let run = |reference: Value| {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
if direct {
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
|
||||
}
|
||||
let before = anchors(&s, a);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let n = undo_len(&s);
|
||||
s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
if !direct {
|
||||
let b = selection_box(&s);
|
||||
assert!(b.reference_point(index.min(8)).distance(Point::new(200.0, 300.0)) < 1e-6, "{b:?}");
|
||||
}
|
||||
let after = anchors(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(anchors(&s, a), before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(anchors(&s, a), after);
|
||||
after
|
||||
};
|
||||
assert_eq!(run(json!(index as f64)), run(json!(index)), "reference {index}, direct {direct}");
|
||||
if index == 8 {
|
||||
assert_eq!(run(json!(u64::MAX)), run(json!(8)), "large reference, direct {direct}");
|
||||
assert_eq!(run(json!(1e100)), run(json!(8)), "large float reference, direct {direct}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for reference in [None, Some(Value::Null)] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let mut p = json!({"x": 200, "y": 300});
|
||||
if let Some(reference) = reference {
|
||||
p["reference"] = reference;
|
||||
}
|
||||
s.execute("object.setBounds", &p).unwrap();
|
||||
assert!(selection_box(&s).center().distance(Point::new(200.0, 300.0)) < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_rejects_invalid_references_without_changes() {
|
||||
for direct in [false, true] {
|
||||
for reference in [json!(-1), json!(-1.0), json!(0.5), json!(8.5), json!("0"), json!(true), json!([]), json!({})] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
if direct {
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
|
||||
}
|
||||
let before = anchors(&s, a);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let n = undo_len(&s);
|
||||
assert!(s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).is_err(), "{reference}, direct {direct}");
|
||||
assert_eq!(anchors(&s, a), before);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
assert_eq!(undo_len(&s), n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_bounding_box_squares_the_box_in_one_step() {
|
||||
let mut s = session();
|
||||
@@ -510,6 +579,157 @@ fn reset_bounding_box_squares_the_turned_members_of_a_square_group() {
|
||||
assert_eq!(selection_box(&s).angle, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_turns_the_box_and_leaves_the_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let art = anchors(&s, a);
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 90})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["angle"].as_f64()), (Some(1), Some(90.0)));
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(anchors(&s, a), art, "the art stays where it is");
|
||||
// The box is at 90°, so its width runs along the rectangle's 50 pt side.
|
||||
let b = selection_box(&s);
|
||||
assert!(near(b.angle, 90.0));
|
||||
assert!(near(b.rect.width(), 50.0) && near(b.rect.height(), 100.0), "{b:?}");
|
||||
// By an angle from the box's angle; absolute sets it; the result wraps to (-180, 180].
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": 20})).unwrap();
|
||||
assert!(near(angle(&s, a), 110.0));
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 200, "absolute": true})).unwrap();
|
||||
assert!(near(r["angle"].as_f64().unwrap(), -160.0) && near(angle(&s, a), -160.0));
|
||||
// A box already at the angle changes nothing and adds no step.
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -160, "absolute": true})).unwrap();
|
||||
assert_eq!(r["changed"], 0);
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 360})).unwrap();
|
||||
assert_eq!(r["changed"], 0);
|
||||
assert_eq!(undo_len(&s), n);
|
||||
// Undo turns the box back; Reset Bounding Box squares it.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, a), 110.0));
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
|
||||
assert_eq!(anchors(&s, a), art);
|
||||
}
|
||||
|
||||
/// Turns that add up to 0 within the tolerance leave the box at exactly 0, so the box measures
|
||||
/// square to the page and Reset Bounding Box has nothing to square.
|
||||
#[test]
|
||||
fn rotate_bounding_box_back_to_zero_stores_zero() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
for by in [0.3, -0.1] {
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": by})).unwrap();
|
||||
}
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.2})).unwrap();
|
||||
assert_eq!((r["angle"].as_f64(), angle(&s, a)), (Some(0.0), 0.0), "{r}");
|
||||
assert_eq!(selection_box(&s).angle, 0.0);
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0);
|
||||
assert_eq!(undo_len(&s), n);
|
||||
// A negative zero is reported and stored as 0.
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.0, "absolute": true})).unwrap();
|
||||
let got = r["angle"].as_f64().unwrap();
|
||||
assert!(got == 0.0 && got.is_sign_positive(), "{r}");
|
||||
assert_eq!(r["changed"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_gives_a_mixed_selection_one_angle() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = turned_rect(&mut s);
|
||||
sel(&mut s, &[a, b]);
|
||||
// The objects share no angle, so the box is square to the page and turns from 0.
|
||||
assert_eq!(selection_box(&s).angle, 0.0);
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 2);
|
||||
assert_eq!(undo_len(&s), n + 1, "one step for both");
|
||||
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
|
||||
assert!(near(selection_box(&s).angle, 10.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, a), 0.0) && near(angle(&s, b), 45.0));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_turns_the_objects_inside_a_group_with_it() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let art = (anchors(&s, a), anchors(&s, b));
|
||||
// The group and both members, as Reset Bounding Box counts them.
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 3);
|
||||
// The members keep their 20° relative to the group's box.
|
||||
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
|
||||
assert_eq!((anchors(&s, a), anchors(&s, b)), art);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, g), 0.0) && near(angle(&s, a), 20.0) && near(angle(&s, b), 20.0));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
|
||||
// After Ungroup the members still share a turned box.
|
||||
s.execute("object.ungroup", &json!({})).unwrap();
|
||||
assert!(near(selection_box(&s).angle, 50.0));
|
||||
}
|
||||
|
||||
/// The art of a linked opacity mask turns with its object; an unlinked mask's art keeps its angle.
|
||||
#[test]
|
||||
fn rotate_bounding_box_turns_a_linked_masks_art_only() {
|
||||
let mask_angle = |s: &Session, a: NodeId| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.bbox_angle;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 2);
|
||||
assert!(near(angle(&s, a), 30.0) && near(mask_angle(&s, a), 30.0));
|
||||
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 1);
|
||||
assert!(near(angle(&s, a), 40.0) && near(mask_angle(&s, a), 30.0));
|
||||
}
|
||||
|
||||
/// Rotate Bounding Box and Reset Bounding Box act on the same boxes: after a turn of a group that
|
||||
/// holds an object with a linked opacity mask, Reset squares every box it turned.
|
||||
#[test]
|
||||
fn reset_bounding_box_squares_every_box_rotate_bounding_box_turned() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, c]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let art = (anchors(&s, a), anchors(&s, c));
|
||||
// The group, the masked object, its mask's art and the other rectangle.
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 25})).unwrap()["changed"], 4);
|
||||
assert!(object_angles(&s).iter().all(|x| near(*x, 25.0)), "{:?}", object_angles(&s));
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 4);
|
||||
assert!(object_angles(&s).iter().all(|x| *x == 0.0), "{:?}", object_angles(&s));
|
||||
assert_eq!((anchors(&s, a), anchors(&s, c)), art);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let n = undo_len(&s);
|
||||
for p in [json!({}), json!({"angle": null}), json!({"angle": "30"}), json!({"angle": 30, "absolute": "yes"})] {
|
||||
assert!(s.execute("object.rotateBoundingBox", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!((angle(&s, a), undo_len(&s)), (0.0, n));
|
||||
// Nothing selected: the command is not enabled.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).is_err());
|
||||
}
|
||||
|
||||
/// Two rectangles turned 20°, put in a container by `make`, turned 10° with it and reset, then
|
||||
/// released by `release`: nothing stands at an angle before or after the release.
|
||||
fn reset_then_release(make: &str, release: &str) -> Session {
|
||||
|
||||
@@ -120,8 +120,9 @@ fn a_blend_and_an_object_make_one_blend_with_more_keys() {
|
||||
}
|
||||
|
||||
/// Choosing the Blend tool again (its button, W, `tool.select`) finishes the blend: the first
|
||||
/// pick and the chain are dropped, and the document and the selection stay. Choosing another
|
||||
/// tool again keeps its work: the Pen's open path stays open.
|
||||
/// pick and the chain are dropped, and the document and the selection stay. The Pen chosen again
|
||||
/// ends the path it is drawing, as Escape does: the path stays open and the next click starts a
|
||||
/// new one.
|
||||
#[test]
|
||||
fn choosing_the_blend_tool_again_finishes_the_blend() {
|
||||
let mut s = session();
|
||||
@@ -148,7 +149,7 @@ fn choosing_the_blend_tool_again_finishes_the_blend() {
|
||||
click(&mut s, 20.0, 20.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
|
||||
assert_eq!(spec(&s, g).0, vec![b, c], "a was not added");
|
||||
// The Pen chosen again goes on drawing its open path.
|
||||
// The Pen chosen again ends its open path; the next click starts a new one.
|
||||
s.select_tool("pen", v).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let pen = |s: &mut Session, x: f64, y: f64| {
|
||||
@@ -156,16 +157,27 @@ fn choosing_the_blend_tool_again_finishes_the_blend() {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap();
|
||||
}
|
||||
};
|
||||
let anchors = |s: &Session, id| match node(s, id).kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
// With no path being drawn, choosing the Pen again changes nothing.
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().selection.objects.len()), (depth, 0));
|
||||
pen(&mut s, 100.0, 300.0);
|
||||
pen(&mut s, 200.0, 300.0);
|
||||
let p = s.doc().unwrap().selection.objects[0];
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
assert_eq!(s.tool_id(), "pen", "the Pen stays chosen");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "ending the path adds no undo step");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![p], "the path stays selected");
|
||||
pen(&mut s, 300.0, 300.0);
|
||||
let anchors = match node(&s, p).kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths[0].anchors.len(),
|
||||
_ => 0,
|
||||
};
|
||||
assert_eq!(anchors, 3, "the Pen keeps drawing the same path");
|
||||
assert_eq!(anchors(&s, p), vec![(2, false)], "the path stays open with its two anchors");
|
||||
let q = s.doc().unwrap().selection.objects[0];
|
||||
assert_ne!(q, p, "the click starts a new path");
|
||||
assert_eq!(anchors(&s, q), vec![(1, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -772,3 +784,142 @@ fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
|
||||
assert!(!v.no_spine, "{odd}");
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Two blends with different options, both selected: the first (Steps 3, along the path, Ease
|
||||
/// Out at 20%, Shift 10%) and the second (Distance 12 pt, along the page, Ease In Out at 60%,
|
||||
/// Shift -40%).
|
||||
fn two_different_blends(s: &mut Session) -> (NodeId, NodeId) {
|
||||
let b1 = make(s, 0.0, json!({"spacing": "steps", "orientation": "path"}));
|
||||
let b2 = make(s, 100.0, json!({"spacing": "distance", "value": 12, "orientation": "path"}));
|
||||
s.execute("object.blend.setEasing", &json!({"id": b1.0, "easingType": "easeOut", "ramp": 20, "colorShift": 10})).unwrap();
|
||||
s.execute("object.blend.setEasing", &json!({"id": b2.0, "easingType": "easeInOut", "ramp": 60, "colorShift": -40})).unwrap();
|
||||
sel(s, &[b2]);
|
||||
s.execute("object.blend.options", &json!({"orientation": "page"})).unwrap();
|
||||
sel(s, &[b1, b2]);
|
||||
(b1, b2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_on_several_blends_set_only_the_values_given() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let (before1, before2) = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
assert_ne!(before1.spacing, before2.spacing);
|
||||
// Each value given goes to every selected blend; each keeps its own for the others.
|
||||
for (p, apply) in [
|
||||
(json!({"colorShift": 30}), (|sp: &mut BlendSpec| sp.color_shift = 30.0) as fn(&mut BlendSpec)),
|
||||
(json!({"ramp": 45}), |sp| sp.ease.ramp = 0.45),
|
||||
(json!({"easingType": "easeOutIn"}), |sp| sp.ease.kind = vectorcraft_doc::BlendEaseType::OutIn),
|
||||
(json!({"orientation": "path"}), |sp| sp.orientation = BlendOrientation::AlignToPath),
|
||||
(json!({"spacing": "steps", "value": 7}), |sp| sp.spacing = BlendSpacing::Steps(7)),
|
||||
] {
|
||||
let (mut want1, mut want2) = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
apply(&mut want1);
|
||||
apply(&mut want2);
|
||||
s.execute("object.blend.options", &p).unwrap();
|
||||
assert_eq!((spec(&s, b1).1, spec(&s, b2).1), (want1, want2), "{p}");
|
||||
}
|
||||
// A spacing mode without a count keeps the count of a blend already in that mode; a blend in
|
||||
// another mode takes the mode's starting count.
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "distance", "value": 12})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(5)));
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "steps", "value": 12})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(12)));
|
||||
// The whole edit of both blends is one undo step.
|
||||
let depth = undo_len(&s);
|
||||
s.execute("object.blend.options", &json!({"colorShift": -5, "ramp": 5})).unwrap();
|
||||
assert_eq!(undo_len(&s), depth + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.color_shift, spec(&s, b2).1.color_shift), (30.0, 30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_with_an_id_edit_that_blend_alone() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let before2 = spec(&s, b2).1;
|
||||
let mut want1 = spec(&s, b1).1;
|
||||
s.execute("object.blend.options", &json!({"id": b1.0, "spacing": "distance", "value": 15, "ramp": 50, "colorShift": -20})).unwrap();
|
||||
want1.spacing = BlendSpacing::Distance(15.0);
|
||||
want1.ease.ramp = 0.5;
|
||||
want1.color_shift = -20.0;
|
||||
assert_eq!(spec(&s, b1).1, want1, "only the values given change");
|
||||
assert_eq!(spec(&s, b2).1, before2, "a selected blend that is not `id` stays as it was");
|
||||
// `id` works with nothing selected, and does not set the options new blends start with.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "orientation": "path"})).unwrap();
|
||||
assert_eq!(spec(&s, b2).1.orientation, BlendOrientation::AlignToPath);
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
|
||||
// A hidden or locked blend and an object that is not a blend are errors that change nothing.
|
||||
for (visible, locked) in [(false, false), (true, true)] {
|
||||
s.edit("state", |d, _| {
|
||||
let n = d.node_mut(b1).unwrap();
|
||||
(n.visible, n.locked) = (visible, locked);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (before, depth) = (spec(&s, b1).1, undo_len(&s));
|
||||
let error = s.execute("object.blend.options", &json!({"id": b1.0, "colorShift": 25})).unwrap_err().to_string();
|
||||
assert!(error.contains("the object is hidden or locked"), "{error}");
|
||||
assert_eq!((spec(&s, b1).1, undo_len(&s)), (before, depth));
|
||||
}
|
||||
let other = rect(&mut s, 300.0, 0.0, 10.0);
|
||||
for id in [json!(other.0), json!(999_999)] {
|
||||
let error = s.execute("object.blend.options", &json!({"id": id, "colorShift": 25})).unwrap_err().to_string();
|
||||
assert!(error.contains("not a blend"), "{error}");
|
||||
}
|
||||
// The blend's own spine decides whether easing is allowed, whatever is selected.
|
||||
s.execute("object.blend.createSpine", &json!({"mode": "never"})).unwrap();
|
||||
let bare = make(&mut s, 300.0, json!({}));
|
||||
sel(&mut s, &[b2]);
|
||||
let error = s.execute("object.blend.options", &json!({"id": bare.0, "ramp": 30})).unwrap_err().to_string();
|
||||
assert!(error.contains("the blend has no spine"), "{error}");
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "ramp": 30})).unwrap();
|
||||
assert_eq!(spec(&s, b2).1.ease.ramp, 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_that_change_nothing_or_are_refused_record_no_undo_step() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let before = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
let depth = undo_len(&s);
|
||||
// Values the blends already have, and no values at all.
|
||||
for p in [json!({}), json!({"smooth": false}), json!({"orientation": "page", "id": b2.0}), json!({"colorShift": 10, "id": b1.0})] {
|
||||
s.execute("object.blend.options", &p).unwrap();
|
||||
assert_eq!(undo_len(&s), depth, "{p}");
|
||||
}
|
||||
// An invalid value anywhere stops the whole call before anything changes.
|
||||
for p in [
|
||||
json!({"colorShift": 50, "ramp": 101}),
|
||||
json!({"colorShift": 50, "ramp": -1}),
|
||||
json!({"colorShift": 50, "ramp": "half"}),
|
||||
json!({"ramp": 50, "colorShift": -101}),
|
||||
json!({"ramp": 50, "easingType": "linear"}),
|
||||
json!({"ramp": 50, "spacing": "steps", "value": 0}),
|
||||
json!({"ramp": 50, "spacing": "distance", "value": -3}),
|
||||
json!({"ramp": 50, "id": "b1"}),
|
||||
json!({"ramp": 50, "orientation": "sideways"}),
|
||||
json!({"ramp": 50, "orientation": 1}),
|
||||
json!({"ramp": 50, "value": 3}),
|
||||
json!({"ramp": 50, "spacing": 123}),
|
||||
] {
|
||||
assert!(s.execute("object.blend.options", &p).is_err(), "{p}");
|
||||
assert_eq!((spec(&s, b1).1, spec(&s, b2).1, undo_len(&s)), (before.0.clone(), before.1.clone(), depth), "{p}");
|
||||
}
|
||||
// Make and the options new blends start with refuse an unknown orientation too.
|
||||
let error = s.execute("object.blend.make", &json!({"orientation": "sideways"})).unwrap_err().to_string();
|
||||
assert!(error.contains("orientation must be page or path"), "{error}");
|
||||
assert_eq!(undo_len(&s), depth);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
assert!(s.execute("object.blend.options", &json!({"orientation": "sideways"})).is_err());
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
|
||||
}
|
||||
@@ -81,6 +81,224 @@ fn apply_and_remove_brush_with_undo() {
|
||||
assert!(s.execute("brush.apply", &json!({"name": "Nope"})).is_err());
|
||||
}
|
||||
|
||||
/// The own brush settings of the first stroke of `id`.
|
||||
fn own_options(s: &Session, id: NodeId) -> Value {
|
||||
Value::Object(node(s, id).appearance.stroke().map(|st| st.brush_options.clone()).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The height of the brush art of `id`, drawn along a level line.
|
||||
fn art_height(s: &Session, id: NodeId) -> f64 {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
vectorcraft_brush::pieces_bounds(&vectorcraft_brush::node_pieces(d, &node(s, id)).unwrap()).unwrap().height()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_change_one_path_and_leave_the_brush() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
let width = s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"].clone();
|
||||
select(&mut s, &[a]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("brush.objectOptions", &json!({"params": {"width": 50, "flip_along": false}})).unwrap();
|
||||
assert_eq!(r["changed"], json!([a.0]));
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}), "flip_along equals the brush's own value and is dropped");
|
||||
assert_eq!(own_options(&s, b), json!({}));
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"], width, "the brush keeps its width");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!((art_height(&s, a) * 2.0 - art_height(&s, b)).abs() < 1e-6, "{} vs {}", art_height(&s, a), art_height(&s, b));
|
||||
// The same settings again, and a call without params, change nothing and add no undo step.
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap()["changed"], json!([]));
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"width": 50.0}));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
// An edit of the brush reaches the settings the path does not set.
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 200, "flip_across": true}})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
// The settings are saved in the native file.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let st = back.node(a).and_then(|n| n.appearance.stroke().cloned()).unwrap();
|
||||
assert_eq!(Value::Object(st.brush_options), json!({"width": 50.0}));
|
||||
// Undo puts the path back on the brush's settings.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
// Reset clears them, and so do applying a brush and removing it.
|
||||
s.execute("brush.objectOptions", &json!({"reset": true})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("brush.remove", &json!({})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
// Stroke Options' brush change clears them as well, and keeping the same brush keeps them.
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("stroke.setAdvanced", &json!({"brush": "Arrow"})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"overlap": true}));
|
||||
s.execute("stroke.setAdvanced", &json!({"brush": null})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
// Asking for the settings changes nothing, even when the brush has come to equal them.
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "params": {"overlap": true}})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"overlap": true}));
|
||||
assert_eq!(own_options(&s, a), json!({"overlap": true}));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_null_items_keep_each_paths_own() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Confetti", "ids": [a.0, b.0]})).unwrap();
|
||||
let brush_size = s.execute("brush.get", &json!({"name": "Confetti"})).unwrap()["size"].clone();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"size": [50, 80]}})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"size": [60, 120]}})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
// Only the smallest size changes: each path keeps its own largest size.
|
||||
let r = s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"size": [40, null]}})).unwrap();
|
||||
assert_eq!(r["changed"], json!([a.0, b.0]));
|
||||
assert_eq!(own_options(&s, a)["size"], json!([40.0, 80.0]));
|
||||
assert_eq!(own_options(&s, b)["size"], json!([40.0, 120.0]));
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for both paths");
|
||||
// A path without its own value keeps the brush's item.
|
||||
let c = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Confetti", "ids": [c.0]})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [c.0], "params": {"size": [null, 150]}})).unwrap();
|
||||
assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}");
|
||||
}
|
||||
|
||||
/// The size mode the first stroke of `id`, painted with Confetti, draws with.
|
||||
fn confetti_size_mode(s: &Session, id: NodeId) -> vectorcraft_brush::Variation {
|
||||
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let b = lib.iter().find(|b| b.name == "Confetti").unwrap();
|
||||
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
|
||||
vectorcraft_brush::BrushKind::Scatter(sc) => sc.modes()[0],
|
||||
k => panic!("not a scatter brush: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keep_the_modes_each_path_draws_with() {
|
||||
use vectorcraft_brush::Variation;
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("brush.apply", &json!({"name": "Confetti"})).unwrap();
|
||||
// Confetti's sizes vary at random from 60% to 140%; the second path's follow the pressure.
|
||||
select(&mut s, &[b]);
|
||||
s.execute("brush.objectOptions", &json!({"params": {"modes": ["pressure", null, null, null]}})).unwrap();
|
||||
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure));
|
||||
// One size with no mode keeps each path's mode.
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("brush.objectOptions", &json!({"params": {"size": [80, 80]}})).unwrap();
|
||||
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure));
|
||||
assert_eq!(own_options(&s, a)["size"], json!([80.0, 80.0]));
|
||||
// A mode the params give is set on each path.
|
||||
s.execute("brush.objectOptions", &json!({"params": {"size": [70, 90], "modes": ["fixed", null, null, null]}})).unwrap();
|
||||
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Fixed, Variation::Fixed));
|
||||
}
|
||||
|
||||
/// The widths (%) the first stroke of `id`, painted with Arrow, draws with at the lightest and the
|
||||
/// heaviest pressure.
|
||||
fn arrow_width_range(s: &Session, id: NodeId) -> (f64, f64) {
|
||||
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let b = lib.iter().find(|b| b.name == "Arrow").unwrap();
|
||||
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
|
||||
vectorcraft_brush::BrushKind::Art(a) => a.width_range(),
|
||||
k => panic!("not an art brush: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_changes() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0]})).unwrap();
|
||||
// Both widths follow the pressure; the first path's largest width is its width, the second
|
||||
// path's is its own.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100, "width_mode": "pressure"}})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 100, "width_mode": "pressure", "width_max": 150}})).unwrap();
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((100.0, 100.0), (100.0, 150.0)));
|
||||
// The width the path has already changes nothing.
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100}})).unwrap()["changed"], json!([]));
|
||||
assert_eq!(own_options(&s, a), json!({"width_mode": "pressure"}));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// A new smallest width leaves each path's largest width as it was.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 50}})).unwrap();
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((50.0, 100.0), (50.0, 150.0)));
|
||||
// A largest width the params give is set on each path.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 40, "width_max": 120}})).unwrap();
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 50}})).unwrap();
|
||||
let extend = |s: &mut Session, brush: &str, points: Value| {
|
||||
s.execute("brush.freehand", &json!({"points": points, "style": "brush", "brush": brush, "extend": {"id": a.0}})).unwrap();
|
||||
};
|
||||
// Continuing the path with its own brush keeps the settings.
|
||||
extend(&mut s, "Arrow", json!([[0, 0], [40, 30], [80, 10]]));
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
// Another brush, with a stroke or with only the brush changing, clears them.
|
||||
extend(&mut s, "Diamonds", json!([[0, 0]]));
|
||||
assert_eq!(brush_of(&s, a).as_deref(), Some("Diamonds"));
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keys_convert_with_the_document() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
|
||||
let key = json!({"model": "rgb", "r": 0.2, "g": 0.6, "b": 0.3});
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"colorization": {"method": "hueShift", "key": key}}})).unwrap();
|
||||
assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("rgb"));
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("cmyk"), "{}", own_options(&s, a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_refuse_what_they_cannot_set() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let c = line(&mut s);
|
||||
let plain = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "3 pt. Round", "ids": [c.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let err = |s: &mut Session, p: Value| s.execute("brush.objectOptions", &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [plain.0], "params": {"width": 50}})).contains("brush"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, c.0], "params": {"width": 50}})).contains("different types"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0], "params": {"angle": 10}})).contains("angle"));
|
||||
assert!(!err(&mut s, json!({"ids": [a.0], "params": {"width": "wide"}})).is_empty());
|
||||
assert!(!err(&mut s, json!({"ids": [a.0], "params": [1]})).is_empty());
|
||||
assert!(err(&mut s, json!({"ids": [a.0], "params": {"width": 50}, "reset": true})).contains("reset"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0], "reset": "yes"})).contains("reset"));
|
||||
s.execute("brush.apply", &json!({"name": "Bristle Round", "ids": [c.0]})).unwrap();
|
||||
let steps_bristle = undo_steps(&s);
|
||||
assert!(err(&mut s, json!({"ids": [c.0], "params": {"size": 2}})).contains("bristle"));
|
||||
assert_eq!(undo_steps(&s), steps_bristle);
|
||||
assert_eq!(steps + 1, steps_bristle, "only the bristle brush's apply added a step");
|
||||
// Values outside their ranges are clamped, as brush.options clamps them.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 1e308}})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 1000.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_adds_a_stroke_when_missing_and_reaches_into_groups() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() {
|
||||
assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group)));
|
||||
}
|
||||
|
||||
/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults.
|
||||
fn line_across(s: &mut Session, y: f64) -> NodeId {
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its
|
||||
/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not
|
||||
/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the
|
||||
/// drawn paths in the group and Redo makes again.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_drawn_paths_on_exit() {
|
||||
use vectorcraft_tools::builder::{face_at, faces, sources};
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
// Two lines from left of the group that end in its right face, so they cut only the other two.
|
||||
let line = |s: &mut Session, y: f64| {
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
};
|
||||
let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0));
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.isolation, None);
|
||||
assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step");
|
||||
assert_eq!(d.selection.objects, vec![g]);
|
||||
let n = node(&s, g);
|
||||
let src = sources(&n).unwrap();
|
||||
assert_eq!(src.children().unwrap().len(), 4);
|
||||
for id in [a, b] {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources");
|
||||
}
|
||||
assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three");
|
||||
assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill");
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
for y in [15.0, 85.0] {
|
||||
assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 3);
|
||||
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2);
|
||||
for id in [a, b] {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn");
|
||||
}
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 7);
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and
|
||||
/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are,
|
||||
/// while a group of paths drawn beside them joins it.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_only_paths_it_takes() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step");
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let hidden = line_across(&mut s, 50.0);
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(hidden).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing");
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 9, "the group of paths joined");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id));
|
||||
for id in [text, hidden] {
|
||||
assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group");
|
||||
assert!(d.node(id).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when
|
||||
/// isolation mode ends, as a locked path drawn there does.
|
||||
#[test]
|
||||
fn live_paint_isolation_leaves_a_group_holding_a_locked_path() {
|
||||
use vectorcraft_tools::builder::faces;
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
}
|
||||
|
||||
/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's
|
||||
/// faces and edges again, including type in a Live Paint group merged into another, and Release
|
||||
/// puts it beside the released paths.
|
||||
#[test]
|
||||
fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type");
|
||||
let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0);
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type");
|
||||
let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
|
||||
let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": h.0})).unwrap();
|
||||
let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths");
|
||||
s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for id in [text, text2] {
|
||||
assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken
|
||||
/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of
|
||||
/// paths named "Face" joins the group when isolation mode ends.
|
||||
#[test]
|
||||
fn live_paint_isolation_keeps_art_named_like_its_parts() {
|
||||
use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 9, "the group named Face joined");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
|
||||
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources");
|
||||
}
|
||||
|
||||
/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources
|
||||
/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges
|
||||
/// Live Paint made, and Expand keeps the type.
|
||||
#[test]
|
||||
fn live_paint_does_not_count_art_named_like_its_parts() {
|
||||
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len();
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let mut texts = vec![];
|
||||
for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() {
|
||||
let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap();
|
||||
let t = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap();
|
||||
texts.push(t);
|
||||
}
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made");
|
||||
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
|
||||
assert_eq!(info["faces"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(info["edges"].as_array().unwrap().len(), edges);
|
||||
let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64)));
|
||||
s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for t in texts {
|
||||
assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group
|
||||
/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and
|
||||
/// joins the group with the tile saved.
|
||||
#[test]
|
||||
fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() {
|
||||
use vectorcraft_tools::builder::{is_live_paint, sources};
|
||||
let mut s = session();
|
||||
two(&mut s);
|
||||
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap();
|
||||
assert!(s.interaction_unapplied());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.doc.pattern_edit.is_none());
|
||||
let art = &st.doc.pattern("P").unwrap().art;
|
||||
let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group");
|
||||
assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources");
|
||||
}
|
||||
|
||||
/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does,
|
||||
/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let a = line_across(&mut s, 50.0);
|
||||
s.execute("object.isolate", &json!({"id": a.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group");
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(layer));
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 6);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id));
|
||||
}
|
||||
|
||||
/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live
|
||||
/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
for to_layer in [false, true] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": paths.0})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group");
|
||||
if to_layer {
|
||||
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
|
||||
} else {
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
}
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
|
||||
/// graphic style link, and return it as it then is.
|
||||
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
|
||||
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Whether the geometric bounds of `id` are `want` to within 10⁻⁹ pt.
|
||||
fn bounds_are(s: &Session, id: NodeId, want: vectorcraft_geom::Rect) -> bool {
|
||||
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
|
||||
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// The largest distance of `points` from the path of `id`.
|
||||
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
|
||||
let n = node(s, id);
|
||||
let path = n.path_data().unwrap();
|
||||
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// (0, 0), (80, 0) and (0, 60) lie on the circle centered at (40, 30) with radius 50 (their
|
||||
/// right angle stands on the diameter). The circle is a live ellipse with the current paint, is
|
||||
/// selected, passes through the points to within the four-curve circle's error (about 0.03% of the
|
||||
/// radius), and one undo removes it.
|
||||
#[test]
|
||||
fn the_circle_through_three_given_points_is_exact_and_one_undo_step() {
|
||||
let mut s = session();
|
||||
let reference = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap());
|
||||
let undo = undo_len(&s);
|
||||
let points = [Point::new(0.0, 0.0), Point::new(80.0, 0.0), Point::new(0.0, 60.0)];
|
||||
let out = s.execute(C, &json!({"points": [[0, 0], [80, 0], [0, 60]]})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
let id = id_of(&out);
|
||||
let n = node(&s, id);
|
||||
match &n.kind {
|
||||
NodeKind::Path { live: Some(live), .. } => match live.as_ref() {
|
||||
LiveShape::Ellipse { w, h, pie, .. } => assert_eq!((*w, *h, *pie), (100.0, 100.0, (0.0, 360.0))),
|
||||
other => panic!("not a live ellipse: {other:?}"),
|
||||
},
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(-10.0, -20.0, 90.0, 80.0)));
|
||||
assert!(farthest_from_path(&s, id, &points) < 50.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
|
||||
assert_eq!(n.appearance, node(&s, reference).appearance, "the current paint, as the Ellipse tool draws");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
}
|
||||
|
||||
/// Two points that are the same, or three on one line, are refused with a message; nothing is
|
||||
/// drawn and no undo step is recorded. Points nearly on one line still give their circle.
|
||||
#[test]
|
||||
fn coincident_or_collinear_points_are_refused() {
|
||||
let mut s = session();
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
for points in [json!([[10, 10], [10, 10], [50, 80]]), json!([[0, 0], [50, 50], [100, 100]]), json!([[5, 5], [5, 5], [5, 5]])] {
|
||||
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
|
||||
assert!(e.contains("no circle passes through these points"), "{points}: {e}");
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "{points}");
|
||||
}
|
||||
// 0.01 pt off a chord 200 pt long: the sagitta formula r = (h² + (L/2)²) / 2h.
|
||||
let out = s.execute(C, &json!({"points": [[100, 200], [300, 200], [200, 199.99]]})).unwrap();
|
||||
let want = (0.01f64 * 0.01 + 100.0 * 100.0) / 0.02;
|
||||
let (cx, cy, r) = (out["cx"].as_f64().unwrap(), out["cy"].as_f64().unwrap(), out["radius"].as_f64().unwrap());
|
||||
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
|
||||
}
|
||||
|
||||
/// Points that are not three pairs of finite numbers are an error, not a fallback.
|
||||
#[test]
|
||||
fn malformed_points_are_refused() {
|
||||
let mut s = session();
|
||||
let undo = undo_len(&s);
|
||||
for points in [
|
||||
json!([[0, 0], [10, 0]]),
|
||||
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
|
||||
json!([[0, 0], [10, 0], [0]]),
|
||||
json!([[0, 0], [10, 0], ["0", 10]]),
|
||||
json!("0,0 10,0 0,10"),
|
||||
json!([[0, 0], [10, 0], [0, 10, 3]]),
|
||||
] {
|
||||
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
|
||||
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// With `points` left out, the three anchor points selected with Direct Selection give the
|
||||
/// circle, from one path or several; any other number of them is an error.
|
||||
#[test]
|
||||
fn three_direct_selected_anchor_points_give_the_circle() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<Value> = [(0, 0), (80, 0), (0, 60), (50, 120)].iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
let path = id_of(&s.execute("path.create", &json!({ "anchors": anchors })).unwrap());
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
// Anchors of two paths.
|
||||
let other = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 60}, {"x": 0, "y": 200}]})).unwrap());
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
|
||||
let out = s.execute(C, &json!({"points": null})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
|
||||
// Two or four anchors, or a path of four anchors selected whole.
|
||||
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
let e = s.execute(C, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
// A path of three anchors selected whole counts all three, as the other anchor commands count
|
||||
// them; with an object that is not a path also selected, there is no circle.
|
||||
let triangle = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [triangle.0]})).unwrap();
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let text = id_of(&s.execute("text.create", &json!({"x": 300, "y": 300, "text": "A"})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [triangle.0, text.0]})).unwrap();
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
let undo = undo_len(&s);
|
||||
// Two selected segments hold three ends, which are not selected anchor points.
|
||||
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
|
||||
let e = s.execute(C, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// With Align New Objects to Pixel Grid on, the circle is still drawn through the points: it is
|
||||
/// not pixel-aligned, so the grid does not move it.
|
||||
#[test]
|
||||
fn the_circle_is_not_moved_onto_the_pixel_grid() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
let id = id_of(&s.execute(C, &json!({ "points": pairs })).unwrap());
|
||||
assert!(farthest_from_path(&s, id, &points) < 51.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
|
||||
assert!(!node(&s, id).extras().pixel_aligned);
|
||||
}
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one
|
||||
/// undo step; Escape drops the points placed so far.
|
||||
#[test]
|
||||
fn three_shift_clicks_with_the_ellipse_tool_draw_the_circle_through_them() {
|
||||
let mut s = session();
|
||||
s.select_tool("ellipse", view()).unwrap();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
click(&mut s, shift, 100.0, 100.0);
|
||||
click(&mut s, shift, 180.0, 100.0);
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two points draw nothing yet");
|
||||
click(&mut s, shift, 100.0, 160.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(90.0, 80.0, 190.0, 180.0)));
|
||||
// Escape after two points: the next three clicks start afresh.
|
||||
click(&mut s, shift, 0.0, 0.0);
|
||||
click(&mut s, shift, 10.0, 300.0);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
click(&mut s, shift, 200.0, 200.0);
|
||||
click(&mut s, shift, 280.0, 200.0);
|
||||
let undo = undo_len(&s);
|
||||
click(&mut s, shift, 200.0, 260.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(190.0, 180.0, 290.0, 280.0)));
|
||||
}
|
||||
Loaded 100 of 536 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user