Pathfinder: each Pathfinder effect keeps its own Pathfinder Options

The live Pathfinder effects now carry precision, removeRedundantPoints
and removeUnpainted as their own params. Applying one fills any missing
value from the Pathfinder Options in force, and the effect evaluates
with its own values instead of fixed defaults. Opening one from the
Appearance panel or editing it shows a Pathfinder Options form with its
values. An edit is one undo step, an edit that changes nothing records
none, and a precision outside 0.001 to 10 pt or a non-boolean flag is
refused. Effects saved without these params draw as before.
This commit is contained in:
dotCooCoo committed 2026-11-14 22:09:42 -08:00
1 parent 0c1ac3bdc5
commit 41aa34692b
14 files changed
+467 -32

No files matched your search

+4 -8
View File
@@ -826,15 +826,11 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
}
for (id, label, _) in PATHFINDER_EFFECTS {
if id == "pathfinder.softMix" {
v.push(g(
id,
label,
PATHFINDER,
"{mixingRate?: 1..100 % (50)} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)",
json!({"mixingRate": 50.0}),
));
v.push(g(id, label, PATHFINDER, crate::group::SOFT_MIX_PARAMS_DOC, json!({"mixingRate": 50.0})));
} else {
v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({})));
// No dialog defaults, so the Effect menu applies it directly; effect.apply fills its
// Pathfinder Options in.
v.push(g(id, label, PATHFINDER, crate::group::PATHFINDER_PARAMS_DOC, json!({})));
}
}
v.extend(crate::addons::color::catalog());
+93 -8
View File
@@ -51,6 +51,80 @@ fn op_of(id: &str) -> Option<PathfinderOp> {
PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2)
}
/// Does effect `id` keep Pathfinder Options of its own ([`PathfinderEffectOptions`]): one of
/// [`PATHFINDER_EFFECTS`] (Trap has options of its own)?
pub fn takes_pathfinder_options(id: &str) -> bool {
op_of(id).is_some()
}
/// The parameters holding a Pathfinder effect's Pathfinder Options.
pub const PATHFINDER_OPTION_KEYS: [&str; 3] = ["precision", "removeRedundantPoints", "removeUnpainted"];
/// The range of a Pathfinder effect's `precision` (pt), the Pathfinder panel's range.
pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive<f64> = 0.001..=10.0;
/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`.
macro_rules! options_doc {
() => {
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, the other operations ignore it)"
};
}
/// The documentation of [`PATHFINDER_OPTION_KEYS`], shared by the Pathfinder effects' parameters.
pub const PATHFINDER_OPTIONS_DOC: &str = options_doc!();
/// The parameters of a Pathfinder effect other than Soft Mix.
pub const PATHFINDER_PARAMS_DOC: &str = concat!("{", options_doc!(), "} (groups and layers: live Pathfinder over the members)");
/// The parameters of Effect › Pathfinder › Soft Mix.
pub const SOFT_MIX_PARAMS_DOC: &str = concat!(
"{mixingRate?: 1..100 % (50), ",
options_doc!(),
"} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)"
);
/// The Pathfinder Options a Pathfinder effect evaluates with, read from its parameters. An effect
/// without them (saved before effects kept their own) evaluates as it did then: the default
/// precision, with no points or pieces removed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PathfinderEffectOptions {
/// Refit tolerance of the results, in points ([`PATHFINDER_EFFECT_PRECISION`]).
pub precision: f64,
/// Drop anchors that don't change a result's shape.
pub remove_redundant_points: bool,
/// Divide and Outline leave out the pieces of members with no visible fill.
pub remove_unpainted: bool,
}
impl Default for PathfinderEffectOptions {
fn default() -> Self {
PathfinderEffectOptions { precision: po::DEFAULT_PRECISION, remove_redundant_points: false, remove_unpainted: false }
}
}
impl PathfinderEffectOptions {
/// The options in `p`: a missing or non-numeric value takes its default and a precision out of
/// range its nearest bound, so a live effect always evaluates.
pub fn from_params(p: &Value) -> Self {
let d = PathfinderEffectOptions::default();
let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end());
PathfinderEffectOptions {
precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi),
remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points),
remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted),
}
}
/// These options as the parameters [`PATHFINDER_OPTION_KEYS`] name.
pub fn to_params(self) -> Value {
serde_json::json!({
"precision": self.precision,
"removeRedundantPoints": self.remove_redundant_points,
"removeUnpainted": self.remove_unpainted,
})
}
}
/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape?
pub fn has_pathfinder(n: &Node) -> bool {
n.is_compound_shape()
@@ -512,6 +586,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
continue;
}
let Some(op) = op_of(&e.id) else { continue };
let options = PathfinderEffectOptions::from_params(&e.params);
let shape_mode =
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
let nodes = SymbolNodes::default();
@@ -535,7 +610,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
let key = sources.len() as u64;
if let Some(top) = lv.pop() {
shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, key));
shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key));
sources.push(top);
}
} else {
@@ -551,24 +626,29 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
if shapes.is_empty() {
return Some(vec![]);
}
// Remove Redundant Points: each result loses the anchors that don't change its shape.
let tidy = |path: PathData| if options.remove_redundant_points { po::remove_redundant_points(&path, options.precision) } else { path };
stack = if op == PathfinderOp::SoftMix {
let rate = mixing_rate(&e.params);
po::regions(&shapes)
po::regions_with(&shapes, options.precision)
.into_iter()
.filter(|r| !r.path.is_empty())
.map(|r| Arc::new(soft_mix_face(r.path, &r.sources, rate, &shapes, &sources)))
.map(|r| Arc::new(soft_mix_face(tidy(r.path), &r.sources, rate, &shapes, &sources)))
.collect()
} else if op == PathfinderOp::HardMix {
po::regions(&shapes)
po::regions_with(&shapes, options.precision)
.into_iter()
.filter(|r| !r.path.is_empty())
.map(|r| Arc::new(hard_mix_face(r.path, &r.sources, &shapes, &sources)))
.map(|r| Arc::new(hard_mix_face(tidy(r.path), &r.sources, &shapes, &sources)))
.collect()
} else {
po::pathfinder(op, &shapes)
// Divide and Outline Will Remove Unpainted Artwork: the pieces of members with no
// visible fill go.
let unpainted = options.remove_unpainted && matches!(op, PathfinderOp::Divide | PathfinderOp::Outline);
po::pathfinder_with(op, &shapes, options.precision)
.into_iter()
.filter(|r| !r.path.is_empty())
.map(|r| Arc::new(styled(&sources[r.key as usize], r.path, op == PathfinderOp::Outline)))
.filter(|r| !r.path.is_empty() && !(unpainted && !has_visible_fill(&sources[r.key as usize])))
.map(|r| Arc::new(styled(&sources[r.key as usize], tidy(r.path), op == PathfinderOp::Outline)))
.collect()
};
}
@@ -647,6 +727,11 @@ pub fn paints(item: &AppearanceItem) -> bool {
}
}
/// Has `n` a visible fill that paints, as the Pathfinder panel's Remove Unpainted Artwork counts it?
fn has_visible_fill(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()))
}
/// Do the own fills or strokes of `n`, a group or layer, paint anything?
pub(crate) fn has_own_paint(n: &Node) -> bool {
is_container(n) && n.appearance.items.iter().any(paints)
+3 -2
View File
@@ -74,8 +74,9 @@ pub use bake::{
};
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
OutlineHook, PATHFINDER_EFFECT_PRECISION, PATHFINDER_EFFECTS, PATHFINDER_OPTION_KEYS, PATHFINDER_OPTIONS_DOC, PathfinderEffectOptions,
compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves,
member_shapes, paints, pathfinder_children, shape_art, takes_pathfinder_options,
};
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
+46
View File
@@ -467,10 +467,29 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
super::params::check_effect_color(C, id, &params)?;
super::params::check_effect_channel(C, id, &params)?;
super::params::check_effect_center(C, id, &params)?;
super::params::check_effect_pathfinder(C, id, &params)?;
// Crop Marks take their style from the preferences when applied.
if id == effects::CROP_MARKS && params.get("style").is_none() {
params["style"] = json!(s.crop_mark_style().id());
}
// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those `params`
// give aside. They join the journal entry, so replaying it gives the same effect.
if effects::takes_pathfinder_options(id) {
let current = super::pathops::current_pf_options(s);
let options = effects::PathfinderEffectOptions {
precision: current.precision,
remove_redundant_points: current.remove_redundant_points,
remove_unpainted: current.remove_unpainted,
};
if let Value::Object(filled) = options.to_params() {
for (key, v) in filled {
if params.get(&key).is_none() {
params[key.as_str()] = v;
}
}
}
s.note_journal("params", params.clone());
}
if texture_load_effect(id) {
load_texture(&mut params, C)?;
}
@@ -791,6 +810,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
super::params::check_effect_color(C, effect, &params)?;
super::params::check_effect_channel(C, effect, &params)?;
super::params::check_effect_center(C, effect, &params)?;
super::params::check_effect_pathfinder(C, effect, &params)?;
}
if edited.iter().any(|e| texture_load_effect(e)) {
load_texture(&mut params, C)?;
@@ -810,6 +830,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "ids": [] }));
}
}
// Pathfinder effects given the values they already evaluate with, and nothing else to change,
// are no edit and record no undo step.
if kind.is_none() && warp_id.is_none() && visible.is_none() {
let d = &s.doc()?.doc;
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, &params)) {
return Ok(json!({ "ids": [] }));
}
}
// An SVG filter is named by its id: another filter renames the effect.
if edited.iter().any(|e| e == effects::SVG_FILTER)
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
@@ -878,6 +907,23 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&ids) }))
}
/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
/// defaults is unchanged) and every other value given equal to the one it has?
fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
if !effects::takes_pathfinder_options(&e.id) {
return false;
}
let Some(given) = params.as_object().filter(|m| !m.is_empty()) else { return true };
let current = effects::merged_params(&e.id, &e.params);
let mut after = current.clone();
if let Value::Object(m) = &mut after {
m.extend(given.clone());
}
let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
others_same && effects::PathfinderEffectOptions::from_params(&current) == effects::PathfinderEffectOptions::from_params(&after)
}
// ---------- Load Texture ----------
/// Effect › Distort › Glass.
+30 -4
View File
@@ -383,7 +383,30 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
}
check_effect_color(id, effect, params)?;
check_effect_channel(id, effect, params)?;
check_effect_center(id, effect, params)
check_effect_center(id, effect, params)?;
check_effect_pathfinder(id, effect, params)
}
/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given
/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and
/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves
/// before they edit, as they run [`check_effect_color`].
pub(crate) fn check_effect_pathfinder(id: &str, effect: &str, params: &Value) -> Result<()> {
use vectorcraft_render::effects;
if !effects::takes_pathfinder_options(effect) {
return Ok(());
}
if let Some(v) = params.get("precision")
&& !v.as_f64().is_some_and(|p| effects::PATHFINDER_EFFECT_PRECISION.contains(&p))
{
return Err(bad(id, "precision must be from 0.001 to 10 pt"));
}
for key in ["removeRedundantPoints", "removeUnpainted"] {
if params.get(key).is_some_and(|v| !v.is_boolean()) {
return Err(bad(id, format!("`{key}` must be true or false")));
}
}
Ok(())
}
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
@@ -424,9 +447,10 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels
/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop
/// Marks have checks of their own; they aren't listed.
/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and
/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough
/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of
/// Crop Marks have checks of their own; they aren't listed.
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
use vectorcraft_render::effects;
let number = || Some(Value::from(0.0));
@@ -435,6 +459,8 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
"variation" if effect == "stylize.scribble" => number(),
"width" if effect == "path.outlineStroke" => number(),
"linear" if effect == "blur.gaussian" => Some(Value::Bool(false)),
"precision" if effects::takes_pathfinder_options(effect) => number(),
"removeRedundantPoints" | "removeUnpainted" if effects::takes_pathfinder_options(effect) => Some(Value::Bool(false)),
_ => None,
}
}
+10 -3
View File
@@ -566,14 +566,21 @@ fn pf_label(op: PathfinderOp) -> &'static str {
}
}
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
/// The Pathfinder Options in the preferences, as the panel's operations and a new Pathfinder effect
/// take them.
pub(crate) fn current_pf_options(s: &Session) -> PathfinderOptions {
let mut stored = s.prefs.pathfinder;
if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) {
// A preferences file edited by hand: the default, rather than refitting everything away.
stored.precision = po::DEFAULT_PRECISION;
}
stored
}
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
let stored = current_pf_options(s);
let keys = ["precision", "removeRedundantPoints", "removeUnpainted"];
let given: serde_json::Map<String, Value> =
p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
+137
View File
@@ -1720,6 +1720,143 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() {
assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err());
}
/// The leaf objects of `n`, in paint order.
fn leaves_of(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::Node>) {
match n.children() {
Some(children) => children.iter().for_each(|c| leaves_of(c, out)),
None => out.push(n.clone()),
}
}
/// Apply the live Pathfinder effect `effect` with `params` to the selection, then expand its
/// appearance: the objects it draws.
fn live_pieces(s: &mut Session, effect: &str, params: Value) -> Vec<vectorcraft_doc::Node> {
let g = ids(&s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap())[0];
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
let mut out = vec![];
leaves_of(&node(s, g), &mut out);
out
}
/// The parameters of the first effect of the selected object.
fn first_effect_params(s: &Session) -> Value {
let st = s.doc().unwrap();
st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[0].params.clone()
}
/// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those its params
/// give aside, and its journal entry carries them.
#[test]
fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("object.pathfinder.options", &json!({"precision": 1, "removeRedundantPoints": true, "removeUnpainted": true})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap();
let all = json!({"precision": 1.0, "removeRedundantPoints": true, "removeUnpainted": true});
assert_eq!(first_effect_params(&s), all);
assert_eq!(s.journal.last().unwrap().1["params"], all, "the journal entry gives the options it used");
s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"precision": 0.5}})).unwrap();
let st = s.doc().unwrap();
let mix = &st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[1].params;
assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true}));
}
/// A live Pathfinder effect evaluates with its own options as the panel's operations do with
/// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled
/// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing.
#[test]
fn a_pathfinder_effect_evaluates_with_its_own_options() {
for (precision, faces) in [(0.01, 3), (1.0, 2)] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(live_pieces(&mut s, "pathfinder.divide", json!({"precision": precision})).len(), faces, "precision {precision}");
}
for on in [false, true] {
let mut s = session();
filled_and_unfilled(&mut s);
let divided = live_pieces(&mut s, "pathfinder.divide", json!({"removeUnpainted": on}));
let unfilled = divided.iter().filter(|n| n.appearance.fill_paint().is_none()).count();
assert_eq!((unfilled, divided.len() - unfilled), (if on { 0 } else { 2 }, 1), "removeUnpainted {on}");
}
for on in [false, true] {
let mut s = session();
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let united = live_pieces(&mut s, "pathfinder.add", json!({"removeRedundantPoints": on}));
let count = united[0].path_data().unwrap().anchor_count();
assert!(if on { count == 4 } else { count > 4 }, "removeRedundantPoints {on}: {count} anchors");
}
}
/// An effect saved before Pathfinder effects kept their own options draws as one given their
/// defaults, so older documents look as they did.
#[test]
fn a_pathfinder_effect_saved_without_options_draws_as_before() {
let draw = |params: Value| {
let mut s = session();
filled_and_unfilled(&mut s);
let g = ids(&s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap())[0];
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = params;
Ok(())
})
.unwrap();
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
serde_json::to_value(node(&s, g)).unwrap()
};
assert_eq!(draw(json!({})), draw(json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false})));
}
/// `effect.setParams` edits a Pathfinder effect's options as one undo step, records none for the
/// values it already evaluates with, and refuses values out of range or of the wrong type.
#[test]
fn pathfinder_effect_options_edit_as_one_step_and_refuse_bad_values() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
let before = steps(&s);
let same = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 0.01, "removeUnpainted": false}})).unwrap();
assert_eq!((same, steps(&s)), (json!({"ids": []}), before), "the values it has: no step");
// An effect saved without options evaluates with the defaults: given them, it is unchanged.
let g = s.doc().unwrap().selection.objects[0];
s.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = json!({});
Ok(())
})
.unwrap();
let before = steps(&s);
let defaults = json!({"index": 0, "params": {"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}});
assert_eq!(s.execute("effect.setParams", &defaults).unwrap(), json!({"ids": []}));
assert_eq!(steps(&s), before);
s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 2, "removeRedundantPoints": true}})).unwrap();
assert_eq!(steps(&s), before + 1, "one step");
assert_eq!(first_effect_params(&s), json!({"precision": 2, "removeRedundantPoints": true}));
let kept = doc(&s);
for bad in [
json!({"precision": 0}),
json!({"precision": 11}),
json!({"precision": "1 pt"}),
json!({"precision": null}),
json!({"removeRedundantPoints": "yes"}),
json!({"removeUnpainted": 1}),
] {
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": bad})).is_err(), "setParams {bad}");
assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.trim", "params": bad})).is_err(), "apply {bad}");
assert_eq!(doc(&s), kept, "{bad} changes nothing");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first_effect_params(&s), json!({}), "undo restores the options");
}
/// A single group containing multiple overlapping paths is accepted by Crop.
#[test]
fn crop_operates_on_a_single_selected_group_of_paths() {
+3 -1
View File
@@ -28,7 +28,9 @@ pub use edit::{
};
pub use fit::{fit_cubics, fit_cubics_through};
pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path};
pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within};
pub use pathfinder::{
FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within,
};
pub use planar::{
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point,
live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
+1 -1
View File
@@ -557,7 +557,7 @@ pub fn regions(shapes: &[Shape]) -> Vec<Region> {
}
/// [`regions`] refit to `precision`.
pub(crate) fn regions_with(shapes: &[Shape], precision: f64) -> Vec<Region> {
pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec<Region> {
arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default()
}
+113 -1
View File
@@ -18,7 +18,16 @@ use crate::theme::Tokens;
use crate::{VectorcraftApp, widgets};
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |d| if super::warp_effect::is_warp(&d.str("__effect")) { tl!("Warp Options").to_string() } else { heading_label(d) },
heading: |d| {
let id = d.str("__effect");
if super::warp_effect::is_warp(&id) {
tl!("Warp Options").to_string()
} else if has_only_pathfinder_options(&id) {
tl!("Pathfinder Options").to_string()
} else {
heading_label(d)
}
},
body,
confirm,
preview: true,
@@ -125,6 +134,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
fields.insert("__editTarget".into(), edit_target);
fields.insert("__index".into(), json!(k));
fields.extend(params_of(e));
fill_pathfinder_options(app, id, &mut fields, false);
}
None => {
if let Some(k) = applied.iter().rposition(|e| e.id == id) {
@@ -135,6 +145,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
return Ok(json!({ "pending": EXISTS }));
}
fields.extend(info.defaults.as_object().cloned().unwrap_or_default());
fill_pathfinder_options(app, id, &mut fields, true);
if super::warp_effect::is_warp(id) {
super::warp_effect::merge_remembered(&mut fields, app.last_warp.as_ref());
}
@@ -155,6 +166,50 @@ fn target_effects(app: &VectorcraftApp, p: &Value) -> (Value, Vec<vectorcraft_do
app.session.appearance_effect_target(&params).map(|(target, effects)| (target, effects.to_vec())).unwrap_or_else(|| (json!({}), vec![]))
}
/// Is `id` a Pathfinder effect whose only options are its Pathfinder Options (every one but Soft
/// Mix, which also has a Mixing Rate)?
fn has_only_pathfinder_options(id: &str) -> bool {
vectorcraft_effects::takes_pathfinder_options(id)
&& vectorcraft_effects::default_params(id).is_some_and(|d| d.as_object().is_none_or(Map::is_empty))
}
/// A Pathfinder effect's Pathfinder Options in `fields`, where they are missing: for a new effect
/// (`fresh`) the Pathfinder panel's current options, as `effect.apply` takes them; for an applied
/// one saved without them, the values it evaluates with.
fn fill_pathfinder_options(app: &VectorcraftApp, id: &str, fields: &mut Map<String, Value>, fresh: bool) {
if !vectorcraft_effects::takes_pathfinder_options(id) {
return;
}
let options = if fresh {
let mut current = app.session.prefs.pathfinder;
if !vectorcraft_effects::PATHFINDER_EFFECT_PRECISION.contains(&current.precision) {
current.precision = vectorcraft_engine::PathfinderOptions::default().precision;
}
json!(current)
} else {
vectorcraft_effects::PathfinderEffectOptions::default().to_params()
};
for (key, v) in options.as_object().into_iter().flatten() {
fields.entry(key.clone()).or_insert_with(|| v.clone());
}
}
/// A Pathfinder effect's fields: Soft Mix's Mixing Rate as the other effects show their
/// parameters, then the Pathfinder Options. Returns whether the values changed.
fn pathfinder_fields(ui: &mut egui::Ui, d: &mut Dialog, id: &str, unit: vectorcraft_doc::Unit) -> bool {
let before = d.fields.clone();
if !has_only_pathfinder_options(id) {
let options: Vec<(String, Value)> =
vectorcraft_effects::PATHFINDER_OPTION_KEYS.iter().filter_map(|k| d.fields.remove(*k).map(|v| (k.to_string(), v))).collect();
let doc = vectorcraft_effects::effect_info(id).map(|e| e.params).unwrap_or_default();
form::param_fields(ui, d, &|_| false, &|k| choices(id, k), &|k| doc_rank(doc, k), unit);
d.fields.extend(options);
ui.add_space(6.0);
}
super::pathfinder_options::fields(ui, d);
before != d.fields
}
/// An applied effect's values over its defaults.
fn params_of(e: &vectorcraft_doc::Effect) -> Map<String, Value> {
match vectorcraft_effects::merged_params(&e.id, &e.params) {
@@ -174,6 +229,7 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String>
let id = d.str("__effect");
let defaults = vectorcraft_effects::default_params(&id);
fields.extend(defaults.and_then(|v| v.as_object().cloned()).unwrap_or_default());
fill_pathfinder_options(app, &id, &mut fields, true);
if super::warp_effect::is_warp(id.as_str()) {
super::warp_effect::merge_remembered(&mut fields, app.last_warp.as_ref());
}
@@ -183,6 +239,7 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String>
let applied = app.session.appearance_effect_target(&edit_target).map(|(_, effects)| effects.to_vec()).unwrap_or_default();
let params = applied.get(k).map(params_of).unwrap_or_default();
fields.extend(params);
fill_pathfinder_options(app, &d.str("__effect"), &mut fields, false);
fields.insert("__item".into(), target);
}
fields.insert("preview".into(), json!(true));
@@ -237,6 +294,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
super::raster_effects::effect_fields(app, ui, d);
values_changed(d)
}
None if vectorcraft_effects::takes_pathfinder_options(&id) => pathfinder_fields(ui, d, &id, app.session.general_unit()),
None => {
let doc = vectorcraft_effects::effect_info(&id).map(|e| e.params).unwrap_or_default();
let unit = app.session.general_unit();
@@ -1502,4 +1560,58 @@ mod tests {
"OK applies it"
);
}
/// An applied Pathfinder effect opens Pathfinder Options with its own values (the defaults for
/// one saved without them); OK keeps a change as one undo step, and OK with nothing changed
/// records none. Soft Mix's dialog has Mixing Rate too, and a new one takes the panel's options.
#[test]
fn a_pathfinder_effect_opens_pathfinder_options_with_its_own_values() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
app.run("effect.apply", json!({"effect": "pathfinder.add", "params": {"precision": 0.5}})).unwrap();
let g = app.session.doc().unwrap().selection.objects[0];
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
let paint = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()));
app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap();
let text = paint(&mut app);
for s in ["Pathfinder Options", "Precision:", "Remove Redundant Points", "Divide and Outline Will Remove Unpainted Artwork"] {
assert!(text.lines().any(|l| l == s), "{s} in {text}");
}
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["precision"], json!(0.5));
let before = steps(&app);
super::super::confirm(&mut app).unwrap();
assert_eq!(steps(&app), before, "OK with nothing changed records no step");
app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap();
paint(&mut app);
app.ui.dialog.as_mut().unwrap().fields.insert("removeRedundantPoints".into(), json!(true));
paint(&mut app);
super::super::confirm(&mut app).unwrap();
assert_eq!(steps(&app), before + 1, "one step");
let params = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(g).unwrap().appearance.effects[0].params.clone();
assert_eq!(params(&app)["removeRedundantPoints"], json!(true));
// Saved without options, it opens with the values it evaluates with.
app.session
.edit("t", |d, _| {
d.node_mut(g).unwrap().appearance.effects[0].params = json!({});
Ok(())
})
.unwrap();
app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap();
let fields = &app.ui.dialog.as_ref().unwrap().fields;
assert_eq!(
(&fields["precision"], &fields["removeRedundantPoints"], &fields["removeUnpainted"]),
(&json!(0.01), &json!(false), &json!(false))
);
app.ui.dialog = None;
let _ = app.session.cancel_interaction();
// A new Soft Mix takes the panel's options and shows Mixing Rate beside them.
app.run("object.pathfinder.options", json!({"removeUnpainted": true})).unwrap();
app.run("effect.dialog", json!({"effect": "pathfinder.softMix"})).unwrap();
let text = paint(&mut app);
assert!(text.contains("Mixing Rate") && text.lines().any(|l| l == "Remove Redundant Points"), "{text}");
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["removeUnpainted"], json!(true));
}
}
@@ -29,6 +29,14 @@ fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) {
}
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
fields(ui, d);
false
}
/// Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, editing
/// `precision`, `removeRedundantPoints` and `removeUnpainted` in `d` (this dialog's, and a
/// Pathfinder effect's in the effect dialog).
pub(super) fn fields(ui: &mut egui::Ui, d: &mut Dialog) {
let range = vectorcraft_engine::cmd::PATHFINDER_PRECISION_RANGE;
grid(ui, |ui| {
label(ui, tl!("Precision:"));
@@ -41,7 +49,6 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.add_space(8.0);
check(ui, d, "removeRedundantPoints", tl!("Remove Redundant Points"));
check(ui, d, "removeUnpainted", tl!("Divide and Outline Will Remove Unpainted Artwork"));
false
}
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
+3 -2
View File
@@ -1200,9 +1200,10 @@ fn effect_row(app: &mut VectorcraftApp, ui: &mut Ui, item: Option<usize>, k: usi
(row_rect, resp)
}
/// Does the effect have a dialog (any parameters)?
/// Does the effect have a dialog (any parameters, or a Pathfinder effect's Pathfinder Options)?
fn has_options(id: &str) -> bool {
vectorcraft_effects::default_params(id).is_some_and(|d| d.as_object().is_some_and(|o| !o.is_empty()))
vectorcraft_effects::takes_pathfinder_options(id)
|| vectorcraft_effects::default_params(id).is_some_and(|d| d.as_object().is_some_and(|o| !o.is_empty()))
}
/// Inline editor for an applied effect's parameters, labeled as the effect dialogs' generic fields
+1 -1
View File
@@ -24,7 +24,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md](
| Crop Marks | Crop Marks | 1/1 | — |
| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints below the one before, the fills above covering the strokes of the copies below, instead of one path of every copy (#5920), and a group's copies each hold all its members except guides, the original group on top (#6316); a clipping group, a group with a fill or stroke of its own, a group whose type is kept as type, and a group with a member that carries a geometry, Pathfinder or 3D effect copy each member in its place |
| Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) |
| Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own |
| Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own; each of the other Pathfinder effects keeps its own Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, taken from Pathfinder Options when applied and edited in Pathfinder Options opened from its Appearance panel row ([Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html)) |
| Rasterize | Rasterize… (as a live effect) | 1/1 | — |
| Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets |
| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `<filter>` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning |
+15
View File
@@ -4887,6 +4887,21 @@ whatever the options are then.
{"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}}
```
Each Effect › Pathfinder effect (`pathfinder.add` … `pathfinder.softMix`, not Trap) keeps Pathfinder Options of its own
in its params: `precision` (a number, 0.001–10 pt), `removeRedundantPoints` and `removeUnpainted` (true or false), which
mean what they mean for the panel's operations; the other operations ignore `removeUnpainted`. `effect.apply` fills
the ones `params` leave out from the current Pathfinder Options, and the values join its journal entry. An effect saved
without them evaluates with precision 0.01 and both switches off, as before effects kept them. `effect.setParams
{index, params: {precision?, removeRedundantPoints?, removeUnpainted?}}` edits them as one undo step; values the
effect already evaluates with record no undo step and return `{ids: []}`. A precision out of range, or a switch that
isn't true or false, is refused with an error and nothing changes. In the app, a Pathfinder effect's name or a
double-click on its row in the Appearance panel opens Pathfinder Options for it (Soft Mix's dialog also has Mixing
Rate).
```json
{"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"params":{"precision":1,"removeRedundantPoints":true}}}}
```
Compound shapes (the Pathfinder panel menu, and Alt-clicking a Shape Mode button): `object.compoundShape.make
{mode?, ids?}` makes the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends,
envelopes) the members of one live compound shape, each in shape mode `mode` (`"add"`, the default, `"subtract"`,