diff --git a/Cargo.lock b/Cargo.lock index e8aa942dfa..7f31d49e51 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1047,7 +1047,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0" +source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116" dependencies = [ "chrono", "dunce", diff --git a/Cargo.toml b/Cargo.toml index 28cd269e91..4b14fbb371 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,8 +19,8 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } -# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] } +# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/contributors/people.toml b/contributors/people.toml index 4883c236ad..80ba8da523 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -180,3 +180,6 @@ sync_github_name = true [people.ashokram-si] real_name = "Ashok Ram" + +[people.dylanmtaylor] +sync_github_name = true diff --git a/crates/effects/src/addons.rs b/crates/effects/src/addons.rs new file mode 100644 index 0000000000..39e5bab973 --- /dev/null +++ b/crates/effects/src/addons.rs @@ -0,0 +1,6 @@ +//! Effects of VectorCraft's built-in add-ons, one module per add-on. +//! +//! - [`color`]: Color Effects' live Exposure, Desaturate and Invert Colors, colour adjustments +//! evaluated with the others ([`crate::adjust`]). + +pub mod color; diff --git a/crates/effects/src/addons/color.rs b/crates/effects/src/addons/color.rs new file mode 100644 index 0000000000..2d5ebea919 --- /dev/null +++ b/crates/effects/src/addons/color.rs @@ -0,0 +1,132 @@ +//! Color Effects (a built-in add-on): live Exposure, Desaturate and Invert Colors, in Effect › Color +//! Effects. They are colour adjustments ([`crate::is_adjustment`]): they recolour what an object +//! paints as the others do, in stack order with them. + +use serde_json::{Value, json}; + +use crate::catalog::{EffectInfo, Lengths}; +use crate::util::num; + +/// Exposure: brighten or darken in stops of light, with an offset and a gamma. +pub const EXPOSURE: &str = "addon.color.exposure"; +/// Desaturate: every colour to the grey of its lightness. +pub const DESATURATE: &str = "addon.color.desaturate"; +/// Invert Colors: every colour to its RGB inverse. +pub const INVERT: &str = "addon.color.invert"; + +/// The add-on's effects, in menu order. +pub const EFFECTS: [&str; 3] = [DESATURATE, EXPOSURE, INVERT]; + +/// Is `id` one of the add-on's effects? +pub fn is_color_effect(id: &str) -> bool { + EFFECTS.contains(&id) +} + +/// The add-on's catalogue entries. +pub(crate) fn catalog() -> Vec { + const MENU: &[&str] = &["Effect", "Color Effects"]; + let e = |id, label, params, defaults| EffectInfo { id, label, menu: MENU, params, defaults, raster: false, lengths: Lengths::default() }; + vec![ + e(DESATURATE, "Desaturate", "{} turns every colour the object paints to the grey of its lightness (each colour keeps its model)", json!({})), + e( + EXPOSURE, + "Exposure…", + "{exposure: stops -20..20 (0; mostly the highlights: each stop doubles or halves the light), offset: -0.5..0.5 (0; lifts or sinks the shadows and midtones), gamma: 0.1..10 (1; above 1 lightens the midtones)} recolours as Brightness/Contrast does, in linear light", + json!({"exposure": 0.0, "offset": 0.0, "gamma": 1.0}), + ), + e(INVERT, "Invert Colors", "{} turns every colour the object paints to its RGB inverse (each colour keeps its model)", json!({})), + ] +} + +/// One of the add-on's adjustments, its parameters normalised. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Adjust { + /// Linear light times `gain`, plus `offset`, to the power 1 / `gamma`. + Exposure { + gain: f32, + offset: f32, + gamma: f32, + }, + Desaturate, + Invert, +} + +impl Adjust { + pub(crate) fn parse(id: &str, p: &Value) -> Option { + Some(match id { + EXPOSURE => Adjust::Exposure { + gain: 2f64.powf(num(p, "exposure", 0.0).clamp(-20.0, 20.0)) as f32, + offset: num(p, "offset", 0.0).clamp(-0.5, 0.5) as f32, + gamma: num(p, "gamma", 1.0).clamp(0.1, 10.0) as f32, + }, + DESATURATE => Adjust::Desaturate, + INVERT => Adjust::Invert, + _ => return None, + }) + } + + pub(crate) fn apply(&self, rgb: [f32; 3]) -> [f32; 3] { + match self { + Adjust::Exposure { gain, offset, gamma } => rgb.map(|v| to_srgb((to_linear(v) * gain + offset).max(0.0).powf(1.0 / gamma))), + Adjust::Desaturate => { + let [r, g, b] = rgb; + [(r.max(g).max(b) + r.min(g).min(b)) / 2.0; 3] + } + Adjust::Invert => rgb.map(|v| 1.0 - v), + } + } +} + +fn to_linear(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +fn to_srgb(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::color_map; + use vectorcraft_doc::Effect; + + fn map(id: &str, params: Value) -> crate::ColorMap { + color_map(&[Effect { id: id.into(), params, visible: true }]).unwrap() + } + + fn close(a: [f32; 3], b: [f32; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) + } + + #[test] + fn the_effects_are_colour_adjustments_in_their_own_menu() { + for id in EFFECTS { + assert!(crate::is_adjustment(id), "{id}"); + assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]); + } + } + + #[test] + fn exposure_works_in_stops_of_linear_light() { + let grey = [0.5; 3]; + assert!(close(map(EXPOSURE, json!({})).apply_rgb(grey), grey), "neutral by default"); + // One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686. + assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3])); + assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3])); + assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows"); + assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6); + assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped"); + } + + #[test] + fn desaturate_and_invert() { + assert!(close(map(DESATURATE, json!({})).apply_rgb([1.0, 0.0, 0.0]), [0.5; 3])); + assert!(close(map(DESATURATE, json!({})).apply_rgb([1.0, 1.0, 0.0]), [0.5; 3]), "lightness is kept, not luminance"); + assert!(close(map(INVERT, json!({})).apply_rgb([1.0, 0.25, 0.0]), [0.0, 0.75, 1.0])); + let both = map(INVERT, json!({})).then(&map(INVERT, json!({}))); + assert!(close(both.apply_rgb([0.2, 0.4, 0.6]), [0.2, 0.4, 0.6])); + } +} diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index faa7a5a7c5..7350958cc3 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -27,7 +27,7 @@ pub const ADJUSTMENTS: [&str; 6] = /// Is `id` a colour adjustment effect? pub fn is_adjustment(id: &str) -> bool { - ADJUSTMENTS.contains(&id) + ADJUSTMENTS.contains(&id) || crate::addons::color::is_color_effect(id) } fn visible_adjustment(e: &Effect) -> bool { @@ -88,6 +88,8 @@ enum Adjust { ShiftToColor { target: [f32; 3], amount: f32, preserve: bool }, /// Warm/cool and magenta/green shifts, -1..1. TemperatureTint { temperature: f32, tint: f32 }, + /// One of the Color Effects add-on's. + Addon(crate::addons::color::Adjust), } /// The colour adjustments of an effect list, composed in order. @@ -175,7 +177,7 @@ impl Adjust { preserve: flag(p, "preserveLightness", true), }, "adjust.temperatureTint" => Adjust::TemperatureTint { temperature: amount(p, "temperature"), tint: amount(p, "tint") }, - _ => return None, + _ => Adjust::Addon(crate::addons::color::Adjust::parse(id, p)?), }) } @@ -225,6 +227,7 @@ impl Adjust { let (t, m) = (temperature * 0.3, tint * 0.3); [r * (1.0 + t), g * (1.0 - m), b * (1.0 - t)] } + Adjust::Addon(a) => a.apply([r, g, b]), } } } diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index d10d931d65..32e611c62a 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -791,6 +791,7 @@ pub fn effect_catalog() -> Vec { v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({}))); } } + v.extend(crate::addons::color::catalog()); v.push(g(TRAP, "Trap…", PATHFINDER, trap::EFFECT_PARAMS_DOC, trap::effect_defaults())); v.push(g( CROP_MARKS, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index a732e2dfff..b15a642c3d 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -34,6 +34,7 @@ //! anchored at the object's centre. #![forbid(unsafe_code)] +pub mod addons; mod adjust; mod bake; mod clip; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 061d293b9f..decb8a668d 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow Illustrator's menu structure. +mod addons; pub(crate) mod appearance; mod assets; mod attributes; @@ -322,6 +323,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(perspgrid::specs()); v.extend(shortcutset::specs()); v.extend(importmatches::specs()); + v.extend(addons::specs()); v }) } diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs new file mode 100644 index 0000000000..8741abdfd8 --- /dev/null +++ b/crates/engine/src/cmd/addons.rs @@ -0,0 +1,16 @@ +//! VectorCraft's built-in add-ons: extra tools beyond the standard menus, each a module of its own +//! with commands under `addon..*` (see `docs/mcp.md`). + +mod cleanup; +mod color; +mod pathtools; + +use super::CommandSpec; + +/// The commands of every built-in add-on. +pub fn specs() -> Vec { + let mut v = cleanup::specs(); + v.extend(color::specs()); + v.extend(pathtools::specs()); + v +} diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs new file mode 100644 index 0000000000..0b29b07e26 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -0,0 +1,362 @@ +//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the +//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path +//! Pieces. Its panel and its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's. + +mod checks; +#[cfg(test)] +mod tests; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, SubPath}; +use vectorcraft_pathops::addons as po; + +use self::checks::{Kind, MAX_OBJECTS, Outcome, Scope, set_path}; +use super::super::edit::selected_roots; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// Simplify Anchors' tolerance by default, and the drift (pt) each step of it allows. +const TOLERANCE: f64 = 20.0; +pub(super) const PT_PER_TOLERANCE: f64 = 0.02; +/// Rejoin Path Pieces' gap by default, and the widest (pt). +const GAP: f64 = 0.1; +const MAX_GAP: f64 = 6.0; +/// Most anchors Simplify Anchors takes at once. +const MAX_ANCHORS: usize = 2_000_000; +/// Most rounds of fixes `addon.cleanup.fix` runs. +const FIX_ROUNDS: usize = 3; +/// Most ids a finding lists (its count counts them all). +const MAX_LISTED: usize = 1000; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.cleanup.simplify", + "Simplify Anchors (Keep Shape)…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay → {ids, before, after} anchor counts", + has_selection, + simplify + ), + cmd!( + query "addon.cleanup.check", + "Health Check", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), kinds?: [kind…] (default: all: emptyText, strayPoints (paths of one anchor), unpainted, zeroOpacity, duplicateObjects (a path stacked on an identical one), offArtboard, duplicateAnchors (neighbours within 0.01 pt), tinyHandles (under 0.01 pt), collinearAnchors (corners on a straight run, turning less than sine 0.005), nearPoints (anchors within 0.01 pt of other paths' anchors), nearlyClosed (ends within 0.01 pt), filledOpenPaths (filled, unstroked open paths), needlessClipGroups (an unpainted clip that clips nothing, hides everything, or is a rectangle round all its art), needlessCompounds (one path or none), needlessGroups (one member or none, nothing of their own), emptyArtboards (the document only))} find issues without changing anything; locked and hidden objects are left out → {scope, total, findings: [{kind, label, count, ids (the objects, at most 1000), artboards (indexes)}]} for the kinds found", + has_doc, + check + ), + cmd!( + query "addon.cleanup.show", + "Show Issue", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{kind: kind (see addon.cleanup.check), scope?: \"selection\"|\"document\"} select the objects with that issue → {kind, count, ids, artboards}", + has_doc, + show + ), + cmd!( + "addon.cleanup.fix", + "Fix All Issues", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}", + has_doc, + fix + ), + cmd!( + "addon.cleanup.deepUngroup", + "Deep Ungroup…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in → {ids (the objects left, selected), ungrouped (groups)}", + has_selection, + deep_ungroup + ), + cmd!( + "addon.cleanup.rejoin", + "Rejoin Path Pieces…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}", + has_selection, + rejoin + ), + ] +} + +/// The paths (not guides) under `roots`, compound path members included. +fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { + let mut out = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { guide: false, .. }) { + out.push(c.id); + } + }); + } + out +} + +fn simplify(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.simplify"; + let tolerance = number_or(p, "tolerance", TOLERANCE, C)?; + if !(1.0..=100.0).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 1 to 100")); + } + let protect = switch_or(p, "protectCorners", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); + let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum(); + if before > MAX_ANCHORS { + return Err(EngineError::Other("Simplify Anchors: the paths have too many anchors to simplify at once".into())); + } + let changed: Vec<(NodeId, PathData)> = paths + .iter() + .filter_map(|(id, path)| { + let np = po::simplify_keep_shape(path, tolerance * PT_PER_TOLERANCE, protect); + (np != **path).then_some((*id, np)) + }) + .collect(); + let removed: usize = changed.iter().filter_map(|(id, np)| Some(d.node(*id)?.path_data()?.anchor_count().saturating_sub(np.anchor_count()))).sum(); + let after = before.saturating_sub(removed); + // When no anchor can go, the document and its undo history stay as they are. + if !changed.is_empty() { + s.edit("Simplify Anchors (Keep Shape)", |d, sel| { + for (id, np) in changed { + // The anchors left are new ones: the path is selected whole. + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "before": before, "after": after })) +} + +/// The scope a check, show or fix request names (by default the selection, or the document while +/// nothing is selected) and its name. +fn scope_of(s: &Session, p: &Value, cmd: &str) -> Result<(Scope, &'static str)> { + let roots = selected_roots(s)?; + match text_param(p, "scope", cmd)? { + Some("document") => Ok((Scope::Document, "document")), + None if roots.is_empty() => Ok((Scope::Document, "document")), + Some("selection") if roots.is_empty() => Err(bad(cmd, "nothing selected")), + Some("selection") | None => Ok((Scope::Objects(roots), "selection")), + Some(other) => Err(bad(cmd, format!("`scope` must be \"selection\" or \"document\", not {other:?}"))), + } +} + +/// The kinds a request names (all by default), in the order Fix runs them. +fn kinds_of(p: &Value, cmd: &str) -> Result> { + let given: Vec = match p.get("kinds") { + None | Some(Value::Null) => return Ok(Kind::ALL.to_vec()), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().and_then(Kind::parse).ok_or_else(|| bad(cmd, format!("unknown issue kind {v}")))).collect::>()? + } + Some(_) => return Err(bad(cmd, "`kinds` must be a list of issue kinds")), + }; + Ok(Kind::ALL.into_iter().filter(|k| given.contains(k)).collect()) +} + +/// Kind `kind`'s fix run on a copy of the active document: what Fix would change. +fn dry_run(s: &Session, kind: Kind, scope: &Scope) -> Result { + let st = s.doc()?; + let (mut d, mut sel, mut scope) = ((*st.doc).clone(), st.selection.clone(), scope.clone()); + kind.fix(&mut d, &mut sel, &mut scope) +} + +fn finding(kind: Kind, o: &Outcome) -> Value { + let ids: Vec = o.ids.iter().take(MAX_LISTED).map(|i| i.0).collect(); + json!({ "kind": kind.id(), "label": kind.label(), "count": o.count, "ids": ids, "artboards": o.artboards }) +} + +fn check(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.check"; + let (scope, name) = scope_of(s, p, C)?; + let mut findings = vec![]; + let mut total = 0; + for kind in kinds_of(p, C)? { + let o = dry_run(s, kind, &scope)?; + if o.count > 0 { + total += o.count; + findings.push(finding(kind, &o)); + } + } + Ok(json!({ "scope": name, "total": total, "findings": findings })) +} + +fn show(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.show"; + let id = text_param(p, "kind", C)?.ok_or_else(|| bad(C, "missing `kind`"))?; + let kind = Kind::parse(id).ok_or_else(|| bad(C, format!("unknown issue kind {id:?}")))?; + let (scope, _) = scope_of(s, p, C)?; + let o = dry_run(s, kind, &scope)?; + if o.count == 0 { + return Err(EngineError::Other("None of these issues are left: check again".into())); + } + // Artboards are no objects to select: the selection stays as it is for them. + let ids = o.ids.clone(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids))?; + } + Ok(finding(kind, &o)) +} + +fn fix(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.fix"; + let (mut scope, name) = scope_of(s, p, C)?; + let kinds = kinds_of(p, C)?; + // Fixed on a copy, kind after kind (what one leaves, the next cleans up), then kept as one step. + let st = s.doc()?; + let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone()); + let mut fixed = Map::new(); + let mut total = 0; + // A fix can leave issues for a kind that ran before it (groups unwrapped side by side may hold + // duplicates): the kinds run again, a few rounds at most, until a round finds nothing. + for _ in 0..FIX_ROUNDS { + let before = total; + for &kind in &kinds { + let o = kind.fix(&mut d, &mut sel, &mut scope)?; + if o.count > 0 { + total += o.count; + let n = fixed.get(kind.id()).and_then(Value::as_u64).unwrap_or(0); + fixed.insert(kind.id().into(), json!(n + o.count as u64)); + } + } + if total == before { + break; + } + } + // With nothing to fix, the document and its undo history stay as they are. + if total > 0 { + sel.prune(&d); + s.edit("Fix Issues", |doc, selection| { + *doc = d; + *selection = sel; + Ok(()) + })?; + } + Ok(json!({ "scope": name, "total": total, "fixed": fixed })) +} + +/// Is `n` a group Deep Ungroup takes apart (a clipping group only with `clips`)? +fn ungroupable(n: &Node, clips: bool) -> bool { + matches!(n.kind, NodeKind::Group { clip, .. } if clips || !clip) +} + +/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts +/// the groups. Members take on the opacity of the groups they were in, and a clipping path +/// becomes a plain path. +fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { + if !ungroupable(&n, clips) { + out.push(n); + return; + } + let NodeKind::Group { children, clip } = &n.kind else { return }; + *count += 1; + for (k, c) in children.iter().enumerate() { + let mut c = (**c).clone(); + if *clip + && k == 0 + && let NodeKind::Path { clipping, .. } = &mut c.kind + { + *clipping = false; + } + c.opacity *= n.opacity; + flatten(c, clips, out, count); + } +} + +fn deep_ungroup(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.deepUngroup"; + let clips = switch_or(p, "includeClipGroups", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let (mut items, mut selected, mut count) = (vec![], vec![], 0); + for id in &roots { + match d.node(*id).filter(|n| ungroupable(n, clips)) { + Some(n) => { + let mut out = vec![]; + flatten(n.clone(), clips, &mut out, &mut count); + selected.extend(out.iter().map(|n| n.id)); + items.push((*id, out)); + } + None => selected.push(*id), + } + } + // With no group to take apart, the document and its undo history stay as they are. + if !items.is_empty() { + let ids = selected.clone(); + s.edit("Deep Ungroup", |d, sel| { + d.insert_beside(items, true)?; + sel.set(ids); + Ok(()) + })?; + } + Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::>(), "ungrouped": count })) +} + +/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order +/// (compound path members, clipping paths and guides stay out). +fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> { + fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) { + match &n.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } => { + if let [sp] = path.subpaths.as_slice() + && !sp.closed + { + out.push((n.id, sp.clone())); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)), + _ => {} + } + } + let mut out = vec![]; + roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); + let editable = d.editable(); + out.retain(|(id, _)| editable(*id)); + out +} + +fn rejoin(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.rejoin"; + let gap = number_or(p, "gap", GAP, C)?; + if !(0.0..=MAX_GAP).contains(&gap) { + return Err(bad(C, "`gap` must be from 0 to 6 pt")); + } + let roots = checked_ids_or_selection(s, p, C)?; + let found = pieces(&s.doc()?.doc, &roots); + if found.len() > MAX_OBJECTS { + return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into())); + } + let subpaths: Vec = found.iter().map(|(_, sp)| sp.clone()).collect(); + // Each chain becomes its topmost piece (the last in paint order); the others go. + let (mut kept, mut gone) = (vec![], vec![]); + for j in po::rejoin(&subpaths, gap) { + let ids: Vec = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect(); + let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue }; + gone.extend(ids.into_iter().filter(|id| *id != top)); + kept.push((top, j.path)); + } + if !kept.is_empty() { + let ids: Vec = kept.iter().map(|k| k.0).collect(); + s.edit("Rejoin Path Pieces", |d, sel| { + for (id, sp) in &kept { + set_path(d, *id, PathData::single(sp.clone())); + } + d.remove_many(&gone)?; + sel.set(ids); + Ok(()) + })?; + } + let ids: Vec = kept.iter().map(|k| k.0.0).collect(); + Ok(json!({ "ids": ids, "joined": kept.len(), "removed": gone.len() })) +} diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs new file mode 100644 index 0000000000..46c81293dd --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -0,0 +1,454 @@ +//! Document Health Check: the kinds of issue Artwork Cleanup looks for, and how each is fixed. A +//! check runs a kind's fix on a copy of the document, so what a check finds is what Fix changes. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_color::BlendMode; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{Appearance, Document, Knockout, Node, NodeExtras, NodeId, NodeKind, Selection, SymbolBoxes}; +use vectorcraft_geom::{PathData, Point, Rect}; +use vectorcraft_pathops::addons as po; + +use super::super::super::edit::outermost; +use super::super::super::layer::empty_artboards; +use crate::Result; + +/// Sine of the turn below which an anchor on a straight run is collinear. +const COLLINEAR: f64 = 0.005; +/// Distance (pt) within which anchors coincide, handles are tiny and path ends meet. +const NEAR: f64 = 0.01; +/// Most objects a check looks at; the rest of a larger document is left as it is. +pub(super) const MAX_OBJECTS: usize = 250_000; +/// Most anchors Near Anchors compares. +const MAX_ANCHORS: usize = 1_000_000; +/// Most rounds of unwrapping nested groups. +const MAX_PASSES: usize = 64; + +/// One kind of issue. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Kind { + EmptyText, + StrayPoints, + Unpainted, + ZeroOpacity, + DuplicateObjects, + OffArtboard, + DuplicateAnchors, + TinyHandles, + CollinearAnchors, + NearPoints, + NearlyClosed, + FilledOpenPaths, + NeedlessClipGroups, + NeedlessCompounds, + NeedlessGroups, + EmptyArtboards, +} + +impl Kind { + /// Every kind, in the order Fix runs them (removing art first can leave groups to unwrap). + pub(super) const ALL: [Kind; 16] = [ + Kind::EmptyText, + Kind::StrayPoints, + Kind::Unpainted, + Kind::ZeroOpacity, + Kind::DuplicateObjects, + Kind::OffArtboard, + Kind::DuplicateAnchors, + Kind::TinyHandles, + Kind::CollinearAnchors, + Kind::NearPoints, + Kind::NearlyClosed, + Kind::FilledOpenPaths, + Kind::NeedlessClipGroups, + Kind::NeedlessCompounds, + Kind::NeedlessGroups, + Kind::EmptyArtboards, + ]; + + /// (id, label) of the kind. + fn names(self) -> (&'static str, &'static str) { + match self { + Kind::EmptyText => ("emptyText", "Empty Text"), + Kind::StrayPoints => ("strayPoints", "Stray Points"), + Kind::Unpainted => ("unpainted", "Unpainted Objects"), + Kind::ZeroOpacity => ("zeroOpacity", "Zero-Opacity Objects"), + Kind::DuplicateObjects => ("duplicateObjects", "Duplicate Objects"), + Kind::OffArtboard => ("offArtboard", "Off-Artboard Art"), + Kind::DuplicateAnchors => ("duplicateAnchors", "Duplicate Anchors"), + Kind::TinyHandles => ("tinyHandles", "Tiny Handles"), + Kind::CollinearAnchors => ("collinearAnchors", "Collinear Anchors"), + Kind::NearPoints => ("nearPoints", "Nearly Coincident Anchors"), + Kind::NearlyClosed => ("nearlyClosed", "Nearly Closed Paths"), + Kind::FilledOpenPaths => ("filledOpenPaths", "Filled Open Paths"), + Kind::NeedlessClipGroups => ("needlessClipGroups", "Needless Clipping Groups"), + Kind::NeedlessCompounds => ("needlessCompounds", "Needless Compound Paths"), + Kind::NeedlessGroups => ("needlessGroups", "Needless Groups"), + Kind::EmptyArtboards => ("emptyArtboards", "Empty Artboards"), + } + } + + pub(super) fn id(self) -> &'static str { + self.names().0 + } + + pub(super) fn label(self) -> &'static str { + self.names().1 + } + + pub(super) fn parse(id: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.id() == id) + } + + /// Fix this kind of issue in `scope` of `d` → what changed. + pub(super) fn fix(self, d: &mut Document, sel: &mut Selection, scope: &mut Scope) -> Result { + match self { + Kind::DuplicateAnchors => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::merge_duplicate_anchors(sp, NEAR)).sum()), + Kind::TinyHandles => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::retract_tiny_handles(sp, NEAR)).sum()), + Kind::CollinearAnchors => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::remove_collinear_anchors(sp, COLLINEAR)).sum()), + Kind::NearlyClosed => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| usize::from(po::close_nearly_closed(sp, NEAR))).sum()), + Kind::FilledOpenPaths => reshape(d, scope, close_filled), + Kind::NearPoints => near_points(d, scope), + Kind::EmptyArtboards => artboards(d, sel, scope), + _ => restructure(d, scope, self), + } + } + + /// What replaces object `n` (at `place`) when it is this kind of issue: nothing to remove it, + /// its members to unwrap it. `None` when it isn't one. + fn replacement(self, cx: &Context, n: &Node, place: Place) -> Option> { + let removable = !place.clips && !is_guide_or_clip(n); + let gone = |is: bool| is.then(Vec::new); + match self { + Kind::EmptyText => gone(matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), + Kind::StrayPoints => gone(removable && matches!(&n.kind, NodeKind::Path { path, .. } if path.anchor_count() <= 1)), + Kind::Unpainted => gone(removable && !place.in_compound && is_shape(n) && !is_painted(&n.appearance)), + Kind::ZeroOpacity => gone(removable && !place.in_compound && n.opacity <= 0.0), + Kind::DuplicateObjects => gone(removable && duplicates_the_one_below(cx.d, n)), + Kind::OffArtboard => gone(place.top && !is_guide_or_clip(n) && off_artboards(cx, n)), + Kind::NeedlessGroups => needless_group(n), + Kind::NeedlessCompounds => needless_compound(n), + Kind::NeedlessClipGroups => needless_clip_group(cx, n), + _ => None, + } + } +} + +/// What a fix changed (or a check found): how many issues, the objects they are on and the +/// artboards (by index) they are. +#[derive(Clone, Debug, Default)] +pub(super) struct Outcome { + pub count: usize, + pub ids: Vec, + pub artboards: Vec, +} + +/// What a check looks at: the whole document, or the objects given and what is inside them. +#[derive(Clone, Debug)] +pub(super) enum Scope { + Document, + Objects(Vec), +} + +/// Where an object sits. +#[derive(Clone, Copy, Default)] +struct Place { + /// A member of a compound path. + in_compound: bool, + /// The clipping path of its group or layer. + clips: bool, + /// A top-level object of the scope (on a layer, or given). + top: bool, +} + +/// The document a pass looks at, with its symbols measured once. +struct Context<'a> { + d: &'a Document, + symbols: SymbolBoxes<'a>, +} + +/// The visible, unlocked objects in `scope` with where they sit, in paint order: groups, layers, +/// clip groups and compound paths are looked into; live and generated art (blends, envelopes, +/// graphs, symbols…) is taken as it is. +fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> { + let mut out = vec![]; + let top = Place { top: true, ..Place::default() }; + match scope { + Scope::Document => d.layers.iter().for_each(|l| visit(l, top, &mut out)), + Scope::Objects(ids) => ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, top, &mut out)), + } + let editable = d.editable(); + out.retain(|(n, _)| editable(n.id)); + out +} + +fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) { + if !n.visible || n.locked || out.len() >= MAX_OBJECTS { + return; + } + let inner = |clip: bool, i: usize, top: bool| Place { clips: clip && i == 0, top, in_compound: false }; + match &n.kind { + // A layer's objects are top-level ones. + NodeKind::Layer { children, clip, .. } => children.iter().enumerate().for_each(|(i, c)| visit(c, inner(*clip, i, true), out)), + NodeKind::Group { children, clip } if !is_generated(n) => { + out.push((n, place)); + children.iter().enumerate().for_each(|(i, c)| visit(c, inner(*clip, i, false), out)); + } + NodeKind::Compound { children, .. } => { + out.push((n, place)); + children.iter().for_each(|c| visit(c, Place { in_compound: true, ..Place::default() }, out)); + } + _ => out.push((n, place)), + } +} + +/// A group that stands for live or generated art: its members aren't loose art to clean. +fn is_generated(n: &Node) -> bool { + let e = n.extras(); + e.graph.is_some() || e.shaper.is_some() || e.dimension.is_some() || e.objects_on_path.is_some() || e.live_paint_gaps.is_some() || e.compound_shape +} + +fn is_guide_or_clip(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. }) +} + +fn is_shape(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) +} + +fn is_painted(a: &Appearance) -> bool { + a.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0, + }) +} + +/// A container with nothing of its own to show: full opacity, normal blending, no fill, stroke, +/// effect, mask, knockout or anything else attached. +fn is_plain(n: &Node) -> bool { + n.opacity >= 1.0 + && n.blend == BlendMode::Normal + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && !n.isolate + && n.knockout == Knockout::Neutral + && *n.extras() == NodeExtras::default() +} + +/// Is `n` a plain path (full opacity, normal blending) identical to the object just below it? +fn duplicates_the_one_below(d: &Document, n: &Node) -> bool { + if !matches!(n.kind, NodeKind::Path { .. }) || n.opacity < 1.0 || n.blend != BlendMode::Normal { + return false; + } + let below = d.position(n.id).and_then(|(parent, i, _)| d.children(parent)?.get(i.checked_sub(1)?).cloned()); + below.is_some_and(|b| { + b.visible && b.kind == n.kind && b.appearance == n.appearance && b.opacity == n.opacity && b.blend == n.blend && b.extras() == n.extras() + }) +} + +fn inside(a: Rect, b: Rect) -> bool { + a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1 +} + +fn meets(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Does `n` lie wholly off every artboard (a document without artboards has none off them)? +fn off_artboards(cx: &Context, n: &Node) -> bool { + let Some(b) = n.visual_bounds_with(&cx.symbols) else { return false }; + // As Delete Empty Artboards measures: a millionth of a point covers rounding at the edges. + !cx.d.artboards.is_empty() && !cx.d.artboards.iter().any(|a| meets(a.rect.inflate(1e-6, 1e-6), b)) +} + +/// A plain group of one member or none: its member, or nothing. +fn needless_group(n: &Node) -> Option> { + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + (children.len() <= 1 && is_plain(n)).then(|| children.iter().map(|c| (**c).clone()).collect()) +} + +/// A compound path of one path or none: that path, painted as the compound was, or nothing. +fn needless_compound(n: &Node) -> Option> { + let NodeKind::Compound { children, rule } = &n.kind else { return None }; + let mut path = match children.as_slice() { + [] => return Some(vec![]), + [one] => (**one).clone(), + _ => return None, + }; + let NodeKind::Path { rule: r, .. } = &mut path.kind else { return None }; + *r = *rule; + path.appearance = n.appearance.clone(); + path.opacity = n.opacity; + path.blend = n.blend; + path.extras = n.extras.clone(); + Some(vec![path]) +} + +/// A plain clip group whose unpainted clipping path changes nothing: it clips nothing or lies wholly +/// away from its art (nothing shows: nothing is left), or it is a rectangle around all its art (its +/// art is left). +fn needless_clip_group(cx: &Context, n: &Node) -> Option> { + let NodeKind::Group { children, clip: true } = &n.kind else { return None }; + if !is_plain(n) { + return None; + } + let Some((clip, art)) = children.split_first() else { return Some(vec![]) }; + let paint = clip.clip_paint(); + if paint.fill.is_some() || paint.stroke.is_some() { + return None; + } + let clip_box = clip.geometric_bounds()?; + let art_box = art.iter().filter_map(|a| a.visual_bounds_with(&cx.symbols)).reduce(|a, b| a.union(b)); + match art_box { + None => Some(vec![]), + Some(b) if !meets(clip_box, b) => Some(vec![]), + Some(b) if is_rectangle(clip) && inside(b, clip_box.inflate(1e-6, 1e-6)) => Some(art.iter().map(|a| (**a).clone()).collect()), + _ => None, + } +} + +/// Is `n` a path drawing a square-to-the-page rectangle: four corners on its bounds, no curves? +fn is_rectangle(n: &Node) -> bool { + let NodeKind::Path { path, .. } = &n.kind else { return false }; + let (Some(b), [sp]) = (path.bounds(), path.subpaths.as_slice()) else { return false }; + let corner = |p: Point| ((p.x - b.x0).abs() < 1e-6 || (p.x - b.x1).abs() < 1e-6) && ((p.y - b.y0).abs() < 1e-6 || (p.y - b.y1).abs() < 1e-6); + sp.closed && sp.anchors.len() == 4 && sp.anchors.iter().all(|a| !a.has_in() && !a.has_out() && corner(a.p)) +} + +/// Replace the objects with this kind of issue (the outermost ones each round, until none is +/// left) by what [`Kind::replacement`] gives. +fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result { + let mut out = Outcome::default(); + for _ in 0..MAX_PASSES { + let found: Vec<(NodeId, Vec)> = { + let d: &Document = d; + let cx = Context { d, symbols: d.symbol_boxes() }; + let all: Vec<(NodeId, Vec)> = + objects(d, scope).into_iter().filter_map(|(n, pl)| Some((n.id, kind.replacement(&cx, n, pl)?))).collect(); + let keep: HashSet = outermost(d, all.iter().map(|(id, _)| *id).collect()).into_iter().collect(); + all.into_iter().filter(|(id, _)| keep.contains(id)).collect() + }; + if found.is_empty() { + break; + } + if let Scope::Objects(roots) = scope { + for (id, nodes) in &found { + if let Some(at) = roots.iter().position(|r| r == id) { + roots.splice(at..=at, nodes.iter().map(|n| n.id)); + } + } + } + out.ids.extend(found.iter().map(|(id, _)| *id)); + d.insert_beside(found, true)?; + } + out.count = out.ids.len(); + Ok(out) +} + +/// Run `f` on a copy of each path in scope (not guides), and keep the copies it changed: `f` +/// returns how many issues it fixed. +fn reshape(d: &mut Document, scope: &Scope, f: impl Fn(&Node, &mut PathData) -> usize) -> Result { + let changed: Vec<(NodeId, PathData, usize)> = objects(d, scope) + .into_iter() + .filter_map(|(n, _)| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return None }; + let mut p = path.clone(); + let k = f(n, &mut p); + (k > 0).then_some((n.id, p, k)) + }) + .collect(); + let mut out = Outcome::default(); + for (id, p, k) in changed { + set_path(d, id, p); + out.count += k; + out.ids.push(id); + } + Ok(out) +} + +/// Give path `id` the geometry `p` (it stops being a live shape). +pub(super) fn set_path(d: &mut Document, id: NodeId, p: PathData) { + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = p; + *live = None; + } +} + +/// Filled Open Paths: close the open subpaths of a path with a fill and no stroke. +fn close_filled(n: &Node, p: &mut PathData) -> usize { + let items = &n.appearance.items; + let filled = items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none())); + let stroked = items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0)); + if !filled || stroked { + return 0; + } + let mut count = 0; + for sp in p.subpaths.iter_mut().filter(|sp| !sp.closed && sp.anchors.len() >= 2) { + sp.closed = true; + count += 1; + } + count +} + +/// Nearly Coincident Anchors: anchors of the paths in scope within [`NEAR`] of one another (but +/// not neighbours on one path, which Duplicate Anchors merges) move onto the first of them. +fn near_points(d: &mut Document, scope: &Scope) -> Result { + // Each anchor: (path, subpath, anchor, its subpath's length and closedness). + let mut refs: Vec<(NodeId, usize, usize, usize, bool)> = vec![]; + let mut points: Vec = vec![]; + for (n, _) in objects(d, scope) { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { continue }; + for (si, sp) in path.subpaths.iter().enumerate() { + for (ai, a) in sp.anchors.iter().enumerate().take(MAX_ANCHORS.saturating_sub(points.len())) { + refs.push((n.id, si, ai, sp.anchors.len(), sp.closed)); + points.push(a.p); + } + } + } + let neighbours = |i: usize, j: usize| { + let (Some(a), Some(b)) = (refs.get(i), refs.get(j)) else { return false }; + let gap = a.2.abs_diff(b.2); + a.0 == b.0 && a.1 == b.1 && (gap == 1 || (a.4 && gap + 1 == a.3)) + }; + let mut moves: HashMap> = HashMap::new(); + let mut count = 0; + for group in po::near_point_groups(&points, NEAR, neighbours) { + let Some(&to) = group.first().and_then(|&i| points.get(i)) else { continue }; + for &i in &group { + if let (Some(&(id, si, ai, ..)), Some(&p)) = (refs.get(i), points.get(i)) + && p != to + { + moves.entry(id).or_default().push((si, ai, to)); + count += 1; + } + } + } + let mut ids: Vec = moves.keys().copied().collect(); + ids.sort_unstable(); + for id in &ids { + let Some(mut p) = d.node(*id).and_then(Node::path_data).cloned() else { continue }; + for &(si, ai, to) in moves.get(id).into_iter().flatten() { + if let Some(a) = p.anchor_mut(si, ai) { + a.translate(to - a.p); + } + } + set_path(d, *id, p); + } + Ok(Outcome { count, ids, artboards: vec![] }) +} + +/// Empty Artboards: the artboards with no art on them (as Delete Empty Artboards finds them), +/// deleted with their guides. Only a check of the whole document looks at artboards. +fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result { + let Scope::Document = scope else { return Ok(Outcome::default()) }; + let empty = empty_artboards(d); + // The last first, so the others keep their places. + for &i in empty.iter().rev() { + if i < d.artboards.len() { + let id = d.artboards.remove(i).id; + d.retire_artboard_id(id); + d.retain_guides(sel, |_, g| g.artboard != Some(id)); + } + } + Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty }) +} diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs new file mode 100644 index 0000000000..3351dd7550 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -0,0 +1,336 @@ +//! Artwork Cleanup's commands: Simplify Anchors (Keep Shape), the health check's kinds found and +//! fixed one by one, Fix as one undo step, scopes, Show, Deep Ungroup and Rejoin Path Pieces. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_geom::{FillRule, Rect}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +/// A path through `pts` (anchors as `{x, y, out?}` objects). +fn path(s: &mut Session, anchors: Value, closed: bool) -> NodeId { + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId { + path(s, pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(), false) +} + +fn node(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).cloned() +} + +fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) { + s.edit("t", |d, _| { + f(d.node_mut(id).unwrap()); + Ok(()) + }) + .unwrap(); +} + +/// Put `id` inside a new container that `kind` makes of its members. +fn wrap(s: &mut Session, id: NodeId, kind: fn(Vec>) -> NodeKind) -> NodeId { + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(&[id], |c| Node::new(w, kind(c)))?) + }) + .unwrap() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn anchors(s: &Session, id: NodeId) -> usize { + node(s, id).unwrap().path_data().unwrap().anchor_count() +} + +/// How many issues of `kind` a check of `scope` finds. +fn found(s: &mut Session, kind: &str, scope: &str) -> usize { + let r = s.execute("addon.cleanup.check", &json!({"kinds": [kind], "scope": scope})).unwrap(); + r["findings"].as_array().unwrap().iter().find(|f| f["kind"] == kind).map_or(0, |f| f["count"].as_u64().unwrap() as usize) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn simplify_keeps_the_shape_with_fewer_anchors_in_one_step() { + let mut s = session(); + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(anchors(&s, e), 16); + let bounds = node(&s, e).unwrap().geometric_bounds().unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(16), Some(anchors(&s, e) as u64))); + assert!(anchors(&s, e) <= 8, "{r}"); + let now = node(&s, e).unwrap().geometric_bounds().unwrap(); + for (a, b) in [(bounds.x0, now.x0), (bounds.y0, now.y0), (bounds.x1, now.x1), (bounds.y1, now.y1)] { + assert!((a - b).abs() < 0.4, "{bounds:?} → {now:?}"); + } + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, e), 16); + // A rectangle's corners stay; the anchors on its sides go. + let r = rect(&mut s, 200.0, 50.0, 100.0, 60.0); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(anchors(&s, r), 8); + s.execute("addon.cleanup.simplify", &json!({"protectCorners": true})).unwrap(); + assert_eq!(anchors(&s, r), 4); + // Nothing left to remove: no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + for bad in [json!({"tolerance": 0}), json!({"tolerance": 101}), json!({"tolerance": "20"}), json!({"protectCorners": 1})] { + assert!(s.execute("addon.cleanup.simplify", &bad).is_err(), "{bad}"); + } +} + +/// Each kind: what makes the issue in a fresh document (beside a clean rectangle). +fn make_issue(s: &mut Session, kind: &str) { + match kind { + "emptyText" => { + s.execute("text.create", &json!({"x": 20, "y": 20, "text": " "})).unwrap(); + } + "strayPoints" => { + path(s, json!([{"x": 30, "y": 30}]), false); + } + "unpainted" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + change(s, id, |n| n.appearance = Appearance::default().into()); + } + "zeroOpacity" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + change(s, id, |n| n.opacity = 0.0); + } + "duplicateObjects" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + s.edit("t", |d, _| { + let mut copy = d.node(id).unwrap().clone(); + copy.id = d.alloc_id(); + let (parent, i, _) = d.position(id).unwrap(); + Ok(d.insert(parent, i + 1, copy)?) + }) + .unwrap(); + } + "offArtboard" => { + rect(s, -500.0, -500.0, 30.0, 30.0); + } + "duplicateAnchors" => { + line(s, &[(10.0, 150.0), (50.0, 150.0), (50.005, 150.0), (50.0, 190.0)]); + } + "tinyHandles" => { + path(s, json!([{"x": 10, "y": 150, "out": [10.004, 150]}, {"x": 60, "y": 190}]), false); + } + "collinearAnchors" => { + line(s, &[(10.0, 150.0), (30.0, 150.0), (50.0, 150.0), (50.0, 190.0)]); + } + "nearPoints" => { + line(s, &[(10.0, 150.0), (50.0, 150.0)]); + line(s, &[(50.005, 150.0), (90.0, 190.0)]); + } + "nearlyClosed" => { + line(s, &[(10.0, 150.0), (50.0, 150.0), (50.0, 190.0), (10.005, 150.0)]); + } + "filledOpenPaths" => { + let id = line(s, &[(10.0, 150.0), (50.0, 150.0), (50.0, 190.0)]); + change(s, id, |n| n.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0).into()); + } + "needlessClipGroups" => { + let inner = rect(s, 30.0, 160.0, 20.0, 20.0); + let clip = rect(s, 20.0, 150.0, 50.0, 50.0); + select(s, &[inner, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + } + "needlessCompounds" => { + // A compound path holds the paint of its paths. + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + let look = node(s, id).unwrap().appearance; + let compound = wrap(s, id, |children| NodeKind::Compound { children, rule: FillRule::NonZero }); + change(s, compound, |n| n.appearance = look); + } + "needlessGroups" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + wrap(s, id, |children| NodeKind::Group { children, clip: false }); + } + "emptyArtboards" => { + s.edit("t", |d, _| { + let mut a = d.artboards[0].clone(); + a.id = d.next_artboard_id(); + a.rect = Rect::new(1000.0, 1000.0, 1100.0, 1100.0); + d.artboards.push(a); + Ok(()) + }) + .unwrap(); + } + _ => panic!("no setup for {kind}"), + } +} + +const KINDS: [&str; 16] = [ + "emptyText", + "strayPoints", + "unpainted", + "zeroOpacity", + "duplicateObjects", + "offArtboard", + "duplicateAnchors", + "tinyHandles", + "collinearAnchors", + "nearPoints", + "nearlyClosed", + "filledOpenPaths", + "needlessClipGroups", + "needlessCompounds", + "needlessGroups", + "emptyArtboards", +]; + +#[test] +fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() { + let mut clean = session(); + let r = rect(&mut clean, 200.0, 20.0, 80.0, 60.0); + let before = node(&clean, r).unwrap(); + assert_eq!(clean.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0, "clean art has no issues"); + assert_eq!(clean.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + assert_eq!(node(&clean, r).unwrap(), before); + for kind in KINDS { + let mut s = session(); + let r = rect(&mut s, 200.0, 20.0, 80.0, 60.0); + make_issue(&mut s, kind); + select(&mut s, &[]); + assert!(found(&mut s, kind, "document") > 0, "{kind} not found"); + let fixed = s.execute("addon.cleanup.fix", &json!({"kinds": [kind], "scope": "document"})).unwrap(); + assert!(fixed["fixed"][kind].as_u64().unwrap() > 0, "{kind}: {fixed}"); + assert_eq!(found(&mut s, kind, "document"), 0, "{kind} still found after Fix"); + assert_eq!(s.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0, "{kind} left other issues"); + assert_eq!(node(&s, r).unwrap(), before, "{kind} changed the clean rectangle"); + } +} + +#[test] +fn fix_all_is_one_undo_step() { + let mut s = session(); + for kind in KINDS { + make_issue(&mut s, kind); + } + select(&mut s, &[]); + let total = s.execute("addon.cleanup.check", &json!({})).unwrap()["total"].as_u64().unwrap(); + assert!(total >= 16, "{total}"); + let (steps, doc) = (undo_steps(&s), s.doc().unwrap().doc.clone()); + let r = s.execute("addon.cleanup.fix", &json!({})).unwrap(); + assert_eq!(r["scope"], "document"); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, doc.layers); + assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len()); +} + +#[test] +fn the_scope_is_the_selection_or_the_document() { + let mut s = session(); + let a = path(&mut s, json!([{"x": 30, "y": 30}]), false); + let b = path(&mut s, json!([{"x": 60, "y": 30}]), false); + select(&mut s, &[a]); + let r = s.execute("addon.cleanup.check", &json!({"kinds": ["strayPoints"]})).unwrap(); + assert_eq!((r["scope"].as_str(), r["total"].as_u64()), (Some("selection"), Some(1))); + assert_eq!(found(&mut s, "strayPoints", "document"), 2); + s.execute("addon.cleanup.fix", &json!({"kinds": ["strayPoints"]})).unwrap(); + assert!(node(&s, a).is_none() && node(&s, b).is_some(), "only the selection is fixed"); + // Nothing selected: the document. + let r = s.execute("addon.cleanup.check", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["total"].as_u64()), (Some("document"), Some(1))); + assert!(s.execute("addon.cleanup.check", &json!({"scope": "selection"})).is_err(), "nothing selected"); + for bad in [json!({"scope": "page"}), json!({"kinds": ["nope"]}), json!({"kinds": "strayPoints"}), json!({"kinds": [1]})] { + assert!(s.execute("addon.cleanup.check", &bad).is_err(), "{bad}"); + assert!(s.execute("addon.cleanup.fix", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn show_selects_the_objects_with_the_issue() { + let mut s = session(); + rect(&mut s, 200.0, 20.0, 80.0, 60.0); + let stray = path(&mut s, json!([{"x": 30, "y": 30}]), false); + select(&mut s, &[]); + let r = s.execute("addon.cleanup.show", &json!({"kind": "strayPoints"})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [stray]); + assert!(s.execute("addon.cleanup.show", &json!({"kind": "emptyText", "scope": "document"})).is_err(), "no such issue"); + assert!(s.execute("addon.cleanup.show", &json!({})).is_err() && s.execute("addon.cleanup.show", &json!({"kind": "x"})).is_err()); +} + +#[test] +fn deep_ungroup_takes_apart_every_level_but_clipping_groups() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + select(&mut s, &[b, c]); + let inner = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, inner, |n| n.opacity = 0.5); + let clipped = rect(&mut s, 100.0, 10.0, 10.0, 10.0); + let clip = rect(&mut s, 95.0, 5.0, 30.0, 30.0); + select(&mut s, &[clipped, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[a, inner, clip_group]); + let outer = id_of(&s.execute("object.group", &json!({})).unwrap()); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!(r["ungrouped"], 2); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.doc().unwrap().doc; + let layer: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [a, b, c, clip_group]); + assert!(d.node(outer).is_none() && d.node(inner).is_none()); + assert_eq!(d.node(b).unwrap().opacity, 0.5, "members keep their groups' opacity"); + assert_eq!(s.doc().unwrap().selection.objects.len(), 4); + // Asked to, clipping groups come apart too, their clipping paths kept as plain paths. + select(&mut s, &[clip_group]); + s.execute("addon.cleanup.deepUngroup", &json!({"includeClipGroups": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(clip_group).is_none()); + assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Path { clipping: false, .. })); +} + +#[test] +fn rejoin_joins_pieces_within_the_gap_only() { + let mut s = session(); + let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]); + let b = line(&mut s, &[(50.05, 10.0), (90.0, 50.0)]); + let far = line(&mut s, &[(92.0, 50.0), (120.0, 50.0)]); + select(&mut s, &[a, b, far]); + let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap(); + assert_eq!((r["joined"].as_u64(), r["removed"].as_u64()), (Some(1), Some(1))); + // The topmost piece takes the joined path. + assert!(node(&s, a).is_none()); + assert_eq!(anchors(&s, b), 3); + assert_eq!(anchors(&s, far), 2, "beyond the gap"); + select(&mut s, &[b, far]); + let r = s.execute("addon.cleanup.rejoin", &json!({"gap": 3})).unwrap(); + assert_eq!(r["joined"], 1); + assert_eq!(anchors(&s, far), 4); + for bad in [json!({"gap": -1}), json!({"gap": 7}), json!({"gap": "1"})] { + assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}"); + } +} diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs new file mode 100644 index 0000000000..633760f6e5 --- /dev/null +++ b/crates/engine/src/cmd/addons/color.rs @@ -0,0 +1,49 @@ +//! Color Effects (`addon.color.*`), a built-in add-on: its live effects (Exposure, Desaturate and +//! Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as Filter writes +//! any colour adjustment into the colours themselves. Its panel and its submenu, Object › Plug-ins › +//! Color Effects, are the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_render::effects; + +use super::super::colorcmds::recolor; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, text_param}; +use crate::{Result, Session}; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.color.filter", + "Apply as Filter", + ["Object", "Plug-ins", "Color Effects"], + None, + "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay → {changed}", + has_selection, + filter + )] +} + +fn filter(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.color.filter"; + let id = text_param(p, "effect", C)?.ok_or_else(|| bad(C, "missing `effect`"))?; + if !effects::is_adjustment(id) { + return Err(bad(C, format!("`{id}` is not a colour adjustment"))); + } + let params = match p.get("params") { + None | Some(Value::Null) => json!({}), + Some(v @ Value::Object(_)) => v.clone(), + Some(_) => return Err(bad(C, "`params` must be an object")), + }; + let fx = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?; + let ids = checked_ids_or_selection(s, p, C)?; + // Settings that change nothing still make the pass, which then leaves every colour as it was. + let Some(map) = effects::color_map(&[fx]) else { return Ok(json!({ "changed": 0 })) }; + let mut given = p.clone(); + if let Some(o) = given.as_object_mut() { + o.insert("ids".into(), json!(ids.iter().map(|i| i.0).collect::>())); + } + let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); + recolor(s, &given, label, &|c| map.apply(c)) +} diff --git a/crates/engine/src/cmd/addons/color/tests.rs b/crates/engine/src/cmd/addons/color/tests.rs new file mode 100644 index 0000000000..c458fb51bd --- /dev/null +++ b/crates/engine/src/cmd/addons/color/tests.rs @@ -0,0 +1,89 @@ +//! Color Effects: its live effects through effect.apply, and Apply as Filter. + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A document with a selected red rectangle, unstroked. +fn red_rect() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + (s, id) +} + +fn fill_hex(s: &Session, id: NodeId) -> String { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color().unwrap().to_hex() +} + +fn pixel(s: &Session) -> [u8; 4] { + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true).pixel(50, 50) +} + +#[test] +fn the_live_effects_draw_without_changing_the_colours() { + for (effect, params, drawn) in [ + ("addon.color.invert", json!({}), [0, 255, 255, 255]), + ("addon.color.desaturate", json!({}), [128, 128, 128, 255]), + ("addon.color.exposure", json!({"exposure": -20}), [0, 0, 0, 255]), + ] { + let (mut s, id) = red_rect(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + assert_eq!(fill_hex(&s, id), "#ff0000", "{effect}"); + assert_eq!(pixel(&s), drawn, "{effect}"); + } +} + +#[test] +fn a_filter_recolours_the_object_as_one_undo_step() { + let (mut s, id) = red_rect(); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute("addon.color.filter", &json!({"effect": "addon.color.invert"})).unwrap(); + assert_eq!(v["changed"], 1); + assert_eq!(fill_hex(&s, id), "#00ffff"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.appearance.effects.is_empty(), "no effect is added"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_hex(&s, id), "#ff0000"); +} + +#[test] +fn a_filter_takes_any_colour_adjustment_with_its_params() { + let (mut s, id) = red_rect(); + s.execute("addon.color.filter", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + assert_eq!(fill_hex(&s, id), "#00ff00"); + // Live effects already on the object stay live, on top of the new colours. + s.execute("effect.apply", &json!({"effect": "addon.color.invert"})).unwrap(); + s.execute("addon.color.filter", &json!({"effect": "addon.color.desaturate", "ids": [id.0]})).unwrap(); + assert_eq!(fill_hex(&s, id), "#808080"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.effects.len(), 1); + // The stroke only: the fill stays. + s.execute("addon.color.filter", &json!({"effect": "addon.color.invert", "fill": false})).unwrap(); + assert_eq!(fill_hex(&s, id), "#808080"); +} + +#[test] +fn bad_requests_are_refused() { + let (mut s, id) = red_rect(); + let undo = s.doc().unwrap().history.undo.len(); + for p in [ + json!({}), + json!({"effect": 3}), + json!({"effect": "distort.roughen"}), + json!({"effect": "adjust.nothing"}), + json!({"effect": "addon.color.invert", "params": [1]}), + json!({"effect": "addon.color.invert", "ids": [999_999]}), + json!({"effect": "addon.color.invert", "ids": ["x"]}), + ] { + assert!(s.execute("addon.color.filter", &p).is_err(), "{p}"); + } + assert_eq!(fill_hex(&s, id), "#ff0000"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("addon.color.filter", &json!({"effect": "addon.color.invert"})).is_err(), "nothing selected"); +} diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs new file mode 100644 index 0000000000..1020c46a74 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -0,0 +1,676 @@ +//! Path Precision Tools (`addon.pathtools.*`), a built-in add-on: the Anchor Eraser Brush's stroke, +//! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's +//! anchor edits and Split / Add Points at Crossings. Its tools, panel and submenu (Object › +//! Plug-ins › Path Precision Tools) are the tools crate's and the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, SubPath}; +use vectorcraft_pathops::addons::{self as po, pathtools as pt}; + +use super::super::draw2::{replace_with_pieces, usize_opt}; +use super::super::pathops::Beside; +use super::super::{ + CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, finite_numbers, has_doc, has_selection, number_or, switch_or, text_param, +}; +use super::cleanup::PT_PER_TOLERANCE; +use crate::{EngineError, Result, Session}; + +/// The Anchor Eraser Brush's tolerance by default (the scale Simplify Anchors (Keep Shape) uses). +const ERASE_TOLERANCE: f64 = 10.0; +/// Most points one brush stroke carries. +const MAX_STROKE_POINTS: usize = 100_000; +/// Most anchors one command edits at once. +const MAX_ANCHORS: usize = 2_000_000; +/// The narrowest a brush gets at the lightest pen pressure (pt). +const MIN_RADIUS: f64 = 0.05; +/// The widest brush (pt). +const MAX_DIAMETER: f64 = 2500.0; +/// The farthest an end is extended at once (pt). +const MAX_EXTEND: f64 = 1e6; +/// Most anchors Add Points puts on each segment. +const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.erase", + "Anchor Eraser Brush", + [], + None, + "{points: [[x, y] | [x, y, pressure 0..1]…] (the brush's path, at most 100000 points), diameter?: pt 0.1..2500 (20; a point's pressure scales it), tolerance?: 1..100 (10; the outline may move up to tolerance × 0.02 pt), ignoreTolerance?: bool (false: every anchor under the brush that can go goes, its neighbours refitted), plain?: bool (false: true deletes them without refitting the handles beside them), ids?: [id…] (default: the selection)} remove the anchors of the paths under the objects that the brush passes over and that can go while the outline stays within the tolerance, as one undo step; open ends stay → {ids, removed}", + has_selection, + erase + ), + cmd!( + "addon.pathtools.extend", + "Extend Path", + [], + None, + "{id, subpath?: index (0), end: \"start\"|\"end\", length?: pt (negative shortens; never all of it), to?: [x, y] (instead of length: the length that brings the end nearest this point), mode?: \"straight\"|\"bezier\" (stretch the last segment's curve, no anchor added)|\"arc\" (along the circle the end curves on, at most half way round) (\"straight\")} lengthen an open path at an end the way it runs there, or shorten it back along itself, as one undo step → {id, length (pt)}", + has_doc, + extend + ), + cmd!( + query "addon.pathtools.inspect", + "Measure & Inspect", + [], + None, + "{id, x, y, tolerance?: pt (3; how near an anchor counts as over it)} what the path reads at the point nearest (x, y): {subpath, closed, anchors, length, area (pt², an open subpath closed by a straight line), segment, t, point: [x, y], segmentLength, tangent (degrees counter-clockwise), radius (of curvature, null where straight), anchor?: {index, x, y, smooth, angle (at the anchor, null at an open end), in?: {length, angle}, out?: {length, angle}}}", + has_doc, + inspect + ), + cmd!( + "addon.pathtools.setAnchor", + "Set Anchor", + [], + None, + "{x?, y?: pt (on the page), inLength?, outLength?: pt (0 retracts), inAngle?, outAngle?: degrees counter-clockwise} move the selected anchors (with their handles) and set their handles, as one undo step: direct-selected anchors, or every anchor of a path selected whole; a smooth anchor's other handle turns with the one set → {anchors}", + has_selection, + set_anchor + ), + cmd!( + "addon.pathtools.smooth", + "Make Smooth", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ratio?: 0.1..0.5 (0.3905: a square's corners make a circle)} make the selected anchors smooth: a lone handle is mirrored; without handles, both stand at right angles to the bisector of the angle at the anchor, ratio × the nearer neighbour's distance long; two handles are put in line; an open end without handles aims at its neighbour's handle. One undo step → {anchors (changed)}", + has_selection, + smooth + ), + cmd!( + "addon.pathtools.corner", + "Make Corner", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{retract?: bool (true: the handles go; false: they stay where they are and move apart)} make the selected anchors corners, as one undo step → {anchors (changed)}", + has_selection, + corner + ), + cmd!( + "addon.pathtools.equalize", + "Equalize Handles", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} give each selected anchor's two handles their average length (a missing one is made opposite the other), as one undo step → {anchors (changed)}", + has_selection, + equalize + ), + cmd!( + "addon.pathtools.removeKeepShape", + "Remove Points, Keep Shape", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} remove the direct-selected anchors, refitting the handles beside each so the outline keeps its shape as best it can, as one undo step; open ends stay → {removed}", + has_selection, + remove_keep_shape + ), + cmd!( + "addon.pathtools.addPoints", + "Add Points to Segments…", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{count?: 1..100 (1)} add count anchors to each selected segment (a segment between two selected anchors, or every segment of a path selected whole), splitting it into pieces of equal length; the shape doesn't change. One undo step → {added}", + has_selection, + add_points + ), + cmd!( + "addon.pathtools.close", + "Close Path", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{mode?: \"handles\" (keep the ends' handles)|\"straight\" (a straight closing segment)|\"smooth\" (the ends made smooth), ratio?: 0.1..0.5 (0.3905, for smooth)} close the open subpaths of the selected paths, as one undo step → {closed}", + has_selection, + close + ), + cmd!( + "addon.pathtools.crossings", + "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), 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)}", + has_selection, + crossings + ), + ] +} + +/// The editable paths (not guides) under `roots`, compound path members included. +fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { + let editable = d.editable(); + let mut out = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { guide: false, .. }) && editable(c.id) { + out.push(c.id); + } + }); + } + out +} + +/// Put `np` in path `id`'s place; its live shape goes (its anchors are edited). +fn set_path(d: &mut Document, id: NodeId, np: PathData) { + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = np; + *live = None; + } +} + +/// Error unless the paths together have at most [`MAX_ANCHORS`] anchors. +fn check_size<'a>(paths: impl IntoIterator, cmd: &str) -> Result<()> { + if paths.into_iter().map(PathData::anchor_count).sum::() > MAX_ANCHORS { + return Err(bad(cmd, "the paths have too many anchors to edit at once")); + } + Ok(()) +} + +// ---------- Anchor Eraser Brush ---------- + +/// The brush's points (with the radius each has), from `points`. +fn stroke(p: &Value, radius: f64, cmd: &str) -> Result> { + let list = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must be a list of [x, y] points"))?; + if list.len() > MAX_STROKE_POINTS { + return Err(bad(cmd, "too many `points` (at most 100000)")); + } + list.iter() + .map(|v| { + let point = |[x, y]: [f64; 2], pressure: f64| (Point::new(x, y), (radius * pressure.clamp(0.0, 1.0)).max(MIN_RADIUS)); + finite_numbers::<2>(v) + .map(|xy| point(xy, 1.0)) + .or_else(|| finite_numbers::<3>(v).map(|[x, y, f]| point([x, y], f))) + .ok_or_else(|| bad(cmd, format!("bad point {v}: expected [x, y] or [x, y, pressure]"))) + }) + .collect() +} + +/// Does the brush, sweeping through `pts`, cover `q`? +fn under_brush(pts: &[(Point, f64)], q: Point) -> bool { + let hit = |(a, ra): (Point, f64), (b, rb): (Point, f64)| { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((q - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + q.distance(a + ab * t) <= ra + (rb - ra) * t + }; + match pts { + [only] => hit(*only, *only), + _ => pts.windows(2).any(|w| matches!(w, [a, b] if hit(*a, *b))), + } +} + +/// The anchors of `sp` that go when the brush passes over those marked, removed without refitting +/// the handles beside them: open ends stay, and the subpath keeps two anchors (three closed). +fn delete_marked(sp: &SubPath, marked: &[bool]) -> SubPath { + let n = sp.anchors.len(); + let min = if sp.closed { 3 } else { 2 }; + let mut left = n.saturating_sub(min); + let mut out = sp.clone(); + let keep: Vec = (0..n) + .map(|i| { + let end = !sp.closed && (i == 0 || i + 1 == n); + let go = !end && left > 0 && marked.get(i).copied().unwrap_or(false); + left -= usize::from(go); + !go + }) + .collect(); + let mut it = keep.iter(); + out.anchors.retain(|_| it.next().copied().unwrap_or(true)); + out +} + +fn erase(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.erase"; + let diameter = number_or(p, "diameter", 20.0, C)?; + if !(0.1..=MAX_DIAMETER).contains(&diameter) { + return Err(bad(C, "`diameter` must be from 0.1 to 2500 pt")); + } + let tolerance = number_or(p, "tolerance", ERASE_TOLERANCE, C)?; + if !(1.0..=100.0).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 1 to 100")); + } + let (ignore, plain) = (switch_or(p, "ignoreTolerance", false, C)?, switch_or(p, "plain", false, C)?); + let pts = stroke(p, diameter / 2.0, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); + check_size(paths.iter().map(|(_, p)| *p), C)?; + let tol = if ignore { f64::INFINITY } else { tolerance * PT_PER_TOLERANCE }; + let mut removed = 0; + let mut changed = vec![]; + for (id, path) in paths { + let subs: Vec = path + .subpaths + .iter() + .map(|sp| { + let marked: Vec = sp.anchors.iter().map(|a| !pts.is_empty() && under_brush(&pts, a.p)).collect(); + match marked.contains(&true) { + false => sp.clone(), + true if plain => delete_marked(sp, &marked), + true => po::simplify_anchors_keep_shape(sp, tol, &marked), + } + }) + .collect(); + let np = PathData::new(subs); + if np != *path { + removed += path.anchor_count().saturating_sub(np.anchor_count()); + changed.push((id, np)); + } + } + edit_whole(s, "Anchor Eraser Brush", changed)?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "removed": removed })) +} + +/// Replace paths with the new data given, as one step (none when there is nothing to change); each +/// is selected whole, as its anchors' indexes changed. +fn edit_whole(s: &mut Session, label: &str, changed: Vec<(NodeId, PathData)>) -> Result<()> { + if changed.is_empty() { + return Ok(()); + } + s.edit(label, |d, sel| { + for (id, np) in changed { + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + } + Ok(()) + }) +} + +// ---------- Extend Path ---------- + +/// The open subpath an `extend` request names: (path id, subpath index, its data). +fn open_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, SubPath)> { + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), cmd)?; + let si = usize_opt(p, "subpath", cmd)?.unwrap_or(0); + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(cmd, "`id` is not a path"))?; + let sp = path.subpaths.get(si).ok_or_else(|| bad(cmd, "no such subpath"))?; + if sp.closed || sp.anchors.len() < 2 { + return Err(bad(cmd, "the subpath has no ends to extend (it is closed or a single point)")); + } + Ok((id, si, sp.clone())) +} + +fn extend(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.extend"; + let (id, si, sp) = open_subpath(s, p, C)?; + let at_start = match text_param(p, "end", C)? { + Some("start") => true, + Some("end") => false, + _ => return Err(bad(C, "`end` must be \"start\" or \"end\"")), + }; + let mode = match text_param(p, "mode", C)? { + None => pt::ExtendMode::Straight, + Some(m) => pt::ExtendMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"straight\", \"bezier\" or \"arc\""))?, + }; + let length = match (p.get("to").filter(|v| !v.is_null()), p.get("length").filter(|v| !v.is_null())) { + (Some(to), None) => { + let [x, y] = finite_numbers::<2>(to).ok_or_else(|| bad(C, "`to` must be [x, y]"))?; + pt::extend_length_to(&sp, at_start, Point::new(x, y), mode).ok_or_else(|| bad(C, "the path can't be extended"))? + } + (None, Some(_)) => number_or(p, "length", 0.0, C)?, + _ => return Err(bad(C, "give `length` or `to`")), + }; + if !length.is_finite() || length.abs() > MAX_EXTEND { + return Err(bad(C, "`length` must be a number of at most 1000000 pt either way")); + } + let new = pt::extend_open(&sp, at_start, length, mode).ok_or_else(|| bad(C, "the path is too short to shorten that much"))?; + if new != sp { + s.edit("Extend Path", |d, sel| { + let n = d.node(id).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(id))?; + let mut np = n; + if let Some(slot) = np.subpaths.get_mut(si) { + *slot = new; + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + Ok(()) + })?; + } + Ok(json!({ "id": id.0, "length": length })) +} + +// ---------- Measure & Inspect ---------- + +fn polar(h: Option<(f64, f64)>) -> Value { + h.map_or(Value::Null, |(length, angle)| json!({ "length": length, "angle": angle })) +} + +fn inspect(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.inspect"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let (x, y) = (number_or(p, "x", f64::NAN, C)?, number_or(p, "y", f64::NAN, C)?); + let tolerance = number_or(p, "tolerance", 3.0, C)?; + if !(x.is_finite() && y.is_finite()) || !(tolerance >= 0.0 && tolerance.is_finite()) { + return Err(bad(C, "give `x` and `y` (and a `tolerance` of 0 or more)")); + } + let path = s.doc()?.doc.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?; + let i = pt::inspect(path, Point::new(x, y), tolerance).ok_or_else(|| bad(C, "the path has no segments to measure"))?; + let anchor = i.anchor.map(|a| { + json!({ "index": a.index, "x": a.p.x, "y": a.p.y, "smooth": a.smooth, "angle": a.angle, "in": polar(a.handle_in), "out": polar(a.handle_out) }) + }); + Ok(json!({ + "subpath": i.subpath, "closed": i.closed, "anchors": i.anchors, "length": i.length, "area": i.area, + "segment": i.segment, "t": i.t, "point": [i.point.x, i.point.y], "segmentLength": i.segment_length, + "tangent": i.tangent, "radius": i.radius, "anchor": anchor, + })) +} + +// ---------- Anchor Inspector ---------- + +/// The anchors the Anchor Inspector acts on, per path: each path's direct-selected anchors, or +/// every anchor of a path selected whole (with `whole`), keyed by subpath. +type Picked = Vec<(NodeId, BTreeMap>)>; + +/// The selected anchors ([`Picked`]); `whole` counts the anchors of paths selected whole. +fn picked_anchors(s: &Session, whole: bool) -> Result { + let st = s.doc()?; + let (d, sel) = (&st.doc, &st.selection); + let roots = super::super::edit::selected_roots(s)?; + let mut out = vec![]; + for id in paths_under(d, &roots) { + let Some(path) = d.node(id).and_then(|n| n.path_data()) else { continue }; + let refs: Vec = match sel.anchors.get(&id).filter(|a| !a.is_empty()) { + Some(set) => set.iter().copied().collect(), + None if whole => path.anchors().map(|(si, ai, _)| (si, ai)).collect(), + None => continue, + }; + let mut by_sub: BTreeMap> = BTreeMap::new(); + for (si, ai) in refs.into_iter().filter(|(si, ai)| path.subpaths.get(*si).is_some_and(|sp| *ai < sp.anchors.len())) { + by_sub.entry(si).or_default().insert(ai); + } + if !by_sub.is_empty() { + out.push((id, by_sub)); + } + } + Ok(out) +} + +/// Edit each selected anchor ([`picked_anchors`]) in place with `f` (true when it changed one), as +/// one step labelled `label`; the selection stays. → how many anchors changed. +fn edit_anchors(s: &mut Session, label: &str, cmd: &str, f: impl Fn(&mut SubPath, usize) -> bool) -> Result { + let picked = picked_anchors(s, true)?; + if picked.is_empty() { + return Err(bad(cmd, "select paths or anchor points")); + } + let d = &s.doc()?.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), cmd)?; + let mut count = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(mut np) = d.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; + let before = count; + for (si, anchors) in by_sub { + let Some(sp) = np.subpaths.get_mut(*si) else { continue }; + count += anchors.iter().filter(|&&i| f(sp, i)).count(); + } + if count > before { + changed.push((*id, np)); + } + } + if !changed.is_empty() { + s.edit(label, |d, _| { + for (id, np) in changed { + set_path(d, id, np); + } + Ok(()) + })?; + } + Ok(count) +} + +/// A smoothing `ratio` param (default [`pt::SMOOTH_RATIO`]). +fn ratio(p: &Value, cmd: &str) -> Result { + let r = number_or(p, "ratio", pt::SMOOTH_RATIO, cmd)?; + let (lo, hi) = pt::SMOOTH_RATIO_RANGE; + if !(lo..=hi).contains(&r) { + return Err(bad(cmd, "`ratio` must be from 0.1 to 0.5")); + } + Ok(r) +} + +fn smooth(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.smooth"; + let r = ratio(p, C)?; + let n = edit_anchors(s, "Make Smooth", C, |sp, i| pt::auto_smooth(sp, i, r))?; + Ok(json!({ "anchors": n })) +} + +fn corner(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.corner"; + let retract = switch_or(p, "retract", true, C)?; + let n = edit_anchors(s, "Make Corner", C, |sp, i| pt::make_corner(sp, i, retract))?; + Ok(json!({ "anchors": n })) +} + +fn equalize(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.pathtools.equalize"; + let n = edit_anchors(s, "Equalize Handles", C, pt::equalize_handles)?; + Ok(json!({ "anchors": n })) +} + +/// A number param that is given, finite, and (with `range`) inside it. +fn given(p: &Value, key: &str, range: Option<(f64, f64)>, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + match range { + Some((lo, hi)) if !(lo..=hi).contains(&x) => Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))), + _ => Ok(Some(x)), + } + } + } +} + +fn set_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.setAnchor"; + const LIMIT: Option<(f64, f64)> = Some((-1e7, 1e7)); + let (x, y) = (given(p, "x", LIMIT, C)?, given(p, "y", LIMIT, C)?); + let lengths = [given(p, "inLength", Some((0.0, 1e7)), C)?, given(p, "outLength", Some((0.0, 1e7)), C)?]; + let angles = [given(p, "inAngle", LIMIT, C)?, given(p, "outAngle", LIMIT, C)?]; + if [x, y].iter().chain(&lengths).chain(&angles).all(Option::is_none) { + return Err(bad(C, "give x, y, or a handle's length or angle")); + } + let n = edit_anchors(s, "Set Anchor", C, |sp, i| { + let Some(a) = sp.anchors.get_mut(i) else { return false }; + let before = *a; + let to = Point::new(x.unwrap_or(a.p.x), y.unwrap_or(a.p.y)); + a.translate(to - a.p); + for (out, (len, ang)) in [false, true].into_iter().zip(lengths.into_iter().zip(angles)) { + if len.is_none() && ang.is_none() { + continue; + } + let h = if out { a.h_out } else { a.h_in }; + let (l0, a0) = pt::handle_polar(a.p, h).unwrap_or((0.0, if out { 0.0 } else { 180.0 })); + let (l, deg) = (len.unwrap_or(l0), ang.unwrap_or(a0)); + // A length alone keeps a smooth anchor's other handle where it is; an angle turns it too. + let other = if out { a.h_in } else { a.h_out }; + a.set_handle(out, pt::handle_at(a.p, l, deg), false); + if ang.is_none() { + if out { a.h_in = other } else { a.h_out = other } + } + } + *a != before + })?; + Ok(json!({ "anchors": n })) +} + +fn remove_keep_shape(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.pathtools.removeKeepShape"; + let picked = picked_anchors(s, false)?; + if picked.is_empty() { + return Err(bad(C, "direct-select the anchor points to remove")); + } + let d = &s.doc()?.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let mut removed = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(mut np) = d.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; + for (si, anchors) in by_sub { + let Some(sp) = np.subpaths.get_mut(*si) else { continue }; + // From the last back, so the indexes left stay right. + for &i in anchors.iter().rev() { + if let Some((out, _)) = po::remove_anchor_keep_shape(sp, i) { + *sp = out; + removed += 1; + } + } + } + if np != *d.node(*id).and_then(|n| n.path_data()).ok_or(EngineError::NoNode(*id))? { + changed.push((*id, np)); + } + } + edit_whole(s, "Remove Points, Keep Shape", changed)?; + Ok(json!({ "removed": removed })) +} + +fn add_points(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.addPoints"; + let count = number_or(p, "count", 1.0, C)?; + if !(1.0..=MAX_ADD as f64).contains(&count) || count.fract() != 0.0 { + return Err(bad(C, "`count` must be a whole number from 1 to 100")); + } + let picked = picked_anchors(s, true)?; + let st = s.doc()?; + let d = &st.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let mut added = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; + let picked_segments = st.selection.segments.get(id); + let mut np = path.clone(); + for (si, sp) in np.subpaths.iter_mut().enumerate() { + let Some(anchors) = by_sub.get(&si) else { continue }; + let n = sp.anchors.len(); + // Picked segments, else those between two selected anchors. + let segs: BTreeSet = match picked_segments { + Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(), + None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n.max(1)))).collect(), + }; + let (out, marks) = pt::add_points(sp, Some(&segs), count as usize); + added += marks.len(); + *sp = out; + } + if np != *path { + changed.push((*id, np)); + } + } + if added == 0 { + return Err(bad(C, "select segments, or paths, to add points to")); + } + edit_whole(s, "Add Points to Segments", changed)?; + Ok(json!({ "added": added })) +} + +fn close(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.close"; + let mode = match text_param(p, "mode", C)? { + None => pt::CloseMode::Handles, + Some(m) => pt::CloseMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"handles\", \"straight\" or \"smooth\""))?, + }; + let r = ratio(p, C)?; + let roots = super::super::edit::selected_roots(s)?; + let d = &s.doc()?.doc; + let mut closed = 0; + let mut changed = vec![]; + for id in paths_under(d, &roots) { + let Some(path) = d.node(id).and_then(|n| n.path_data()) else { continue }; + let mut np = path.clone(); + let n = np.subpaths.iter_mut().map(|sp| pt::close(sp, mode, r)).filter(|c| *c).count(); + if n > 0 { + closed += n; + changed.push((id, np)); + } + } + if changed.is_empty() { + return Err(bad(C, "select open paths to close")); + } + s.edit("Close Path", |d, _| { + for (id, np) in changed { + set_path(d, id, np); + } + Ok(()) + })?; + Ok(json!({ "closed": closed })) +} + +// ---------- Split / Add Points at Crossings ---------- + +fn crossings(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.crossings"; + let (cut, self_crossings) = (switch_or(p, "cut", false, C)?, switch_or(p, "selfCrossings", false, C)?); + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<&PathData> = ids.iter().filter_map(|id| d.node(*id)?.path_data()).collect(); + if paths.len() != ids.len() { + return Err(EngineError::Other("Add Points at Crossings: a path went missing".into())); + } + let places = pt::crossings(&paths, self_crossings) + .ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross (at most 10000 segments)"))?; + let mut count = 0; + // Each path that is crossed: its new subpaths, and the anchors at the crossings on each. + let mut changed: Vec<(NodeId, Vec, Vec>)> = vec![]; + for ((id, path), on) in ids.iter().zip(&paths).zip(places) { + if on.is_empty() { + continue; + } + let mut subs = vec![]; + let mut marks = vec![]; + for (si, sp) in path.subpaths.iter().enumerate() { + let here: Vec<(usize, f64)> = on.iter().filter(|(s, ..)| *s == si).map(|&(_, seg, t)| (seg, t)).collect(); + let (out, m) = pt::insert_at(sp, &here); + count += m.len(); + subs.push(out); + marks.push(m); + } + changed.push((*id, subs, marks)); + } + if changed.is_empty() { + return Ok(json!({ "ids": [], "crossings": 0 })); + } + let label = if cut { "Split at Crossings" } else { "Add Points at Crossings" }; + let out = s.edit(label, |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, ..)| *id).collect::>()); + for (id, subs, marks) in changed { + sel.anchors.remove(&id); + sel.segments.remove(&id); + if !cut { + set_path(d, id, PathData::new(subs)); + all.push(id); + continue; + } + let pieces: Vec = subs.iter().zip(&marks).flat_map(|(sp, m)| sp.cut_at(m)).collect(); + // A path of one subpath becomes a path per piece; a compound shape's pieces stay its subpaths. + if subs.len() == 1 { + let made = replace_with_pieces(d, &mut beside, id, pieces.into_iter().map(PathData::single).collect())?; + for n in &made { + if !sel.contains(*n) { + sel.add(*n); + } + } + all.extend(made); + } else { + set_path(d, id, PathData::new(pieces)); + all.push(id); + } + } + beside.finish(d)?; + Ok(all) + })?; + Ok(json!({ "ids": out.iter().map(|i| i.0).collect::>(), "crossings": count })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs new file mode 100644 index 0000000000..90822c7749 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -0,0 +1,275 @@ +//! Path Precision Tools' commands: each one undo step, bad params refused, and the tools' gestures +//! through the session. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{AnchorKind, PathData, Point}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()) +} + +/// A circle of 16 anchors about (100, 100), radius 50, selected. +fn circle(s: &mut Session) -> NodeId { + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + e +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +/// Direct-select anchors `anchors` (of subpath 0) of `id`. +fn select_anchors(s: &mut Session, id: NodeId, anchors: &[usize]) { + s.select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, anchors.iter().map(|a| (0, *a)).collect::>()); + }) + .unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +#[test] +fn the_brush_removes_anchors_under_it_keeping_the_shape() { + let mut s = session(); + let e = circle(&mut s); + assert_eq!(path(&s, e).anchor_count(), 16); + let bounds = path(&s, e).bounds().unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.erase", &json!({"points": [[150, 40], [150, 160]], "diameter": 60, "tolerance": 100})).unwrap(); + let left = path(&s, e).anchor_count(); + assert!(left < 16 && left > 8, "{left}"); + assert_eq!(r["removed"], json!(16 - left)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let b = path(&s, e).bounds().unwrap(); + assert!((b.x1 - bounds.x1).abs() < 2.5 && (b.y0 - bounds.y0).abs() < 0.01, "{b:?} vs {bounds:?}"); + // The anchors away from the brush stay: those on the left of the circle. + assert!(path(&s, e).anchors().filter(|(_, _, a)| a.p.x < 100.0).count() >= 7); + // A plain delete takes every anchor under it, whatever the shape. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.erase", &json!({"points": [[150, 40], [150, 160]], "diameter": 60, "plain": true})).unwrap(); + assert!(path(&s, e).anchors().all(|(_, _, a)| a.p.x < 121.0)); + // Nothing under the brush: no step. + let n = steps(&s); + s.execute("addon.pathtools.erase", &json!({"points": [[390, 290]], "diameter": 5})).unwrap(); + assert_eq!(steps(&s), n); + refuses( + &mut s, + "addon.pathtools.erase", + &[ + json!({}), + json!({"points": "x"}), + json!({"points": [[1, "y"]]}), + json!({"points": [[100, 100]], "diameter": 0}), + json!({"points": [[100, 100]], "diameter": 3000}), + json!({"points": [[100, 100]], "tolerance": 0}), + json!({"points": [[100, 100]], "plain": "yes"}), + ], + ); +} + +#[test] +fn the_brush_tool_is_one_undo_step_per_stroke() { + let mut s = session(); + let e = circle(&mut s); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("anchorEraserBrush", view).unwrap(); + assert_eq!(s.tool_id(), "anchorEraserBrush"); + s.set_tool_option("size", &json!(60)); + s.set_tool_option("tolerance", &json!(100)); + let n = steps(&s); + for (k, y) in + [(PointerKind::Down, 40.0), (PointerKind::Drag, 80.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 160.0), (PointerKind::Up, 160.0)] + { + s.pointer(&PointerEvent::new(k, 150.0, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1); + assert!(path(&s, e).anchor_count() < 16); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, e).anchor_count(), 16); +} + +#[test] +fn extend_lengthens_and_shortens_an_end() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 100.0), (100.0, 100.0)], false); + let n = steps(&s); + s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "end", "length": 50})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].anchors.last().unwrap().p, Point::new(150.0, 100.0)); + assert_eq!(steps(&s), n + 1); + s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "start", "to": [-30, 120], "mode": "bezier"})).unwrap(); + assert!((path(&s, l).subpaths[0].anchors[0].p.x + 30.0).abs() < 1e-6); + let r = s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "end", "length": -60})).unwrap(); + assert_eq!(r["length"], json!(-60.0)); + assert!((path(&s, l).length() - 120.0).abs() < 1e-3, "{}", path(&s, l).length()); + assert_eq!(steps(&s), n + 3); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + refuses( + &mut s, + "addon.pathtools.extend", + &[ + json!({"id": l.0, "end": "end"}), + json!({"id": l.0, "end": "middle", "length": 5}), + json!({"id": l.0, "end": "end", "length": 5, "to": [1, 1]}), + json!({"id": l.0, "end": "end", "length": 5, "mode": "spiral"}), + json!({"id": l.0, "end": "end", "length": -1000}), + json!({"id": l.0, "end": "end", "length": 1e9}), + json!({"id": l.0, "end": "end", "to": [1]}), + json!({"id": l.0, "subpath": 3, "end": "end", "length": 5}), + json!({"id": sq.0, "end": "end", "length": 5}), + json!({"id": 99999, "end": "end", "length": 5}), + ], + ); +} + +#[test] +fn inspect_reads_the_path_under_a_point() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap()); + let v = s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 99, "y": 1})).unwrap(); + assert_eq!((v["closed"].clone(), v["anchors"].clone()), (json!(true), json!(4))); + assert!((v["length"].as_f64().unwrap() - 300.0).abs() < 1e-6 && (v["area"].as_f64().unwrap() - 5000.0).abs() < 1e-6); + assert!((v["anchor"]["angle"].as_f64().unwrap() - 90.0).abs() < 1e-9); + assert!(v["radius"].is_null()); + assert!(s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 1})).is_err()); + assert!(s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 1, "y": 1, "tolerance": -1})).is_err()); +} + +#[test] +fn smooth_corner_and_equalize_edit_the_selected_anchors_in_one_step_each() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + select(&mut s, &[r]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.smooth", &json!({})).unwrap()["anchors"], json!(4)); + assert!(path(&s, r).anchors().all(|(_, _, a)| a.kind == AnchorKind::Smooth && (a.h_out - a.p).hypot() > 39.0)); + assert_eq!(steps(&s), n + 1); + // Only the direct-selected anchor. + select_anchors(&mut s, r, &[0]); + s.execute("addon.pathtools.corner", &json!({})).unwrap(); + let p = path(&s, r); + assert!(!p.subpaths[0].anchors[0].has_out() && p.subpaths[0].anchors[1].has_out()); + assert_eq!(steps(&s), n + 2); + // Equalise: one handle made to match the other. + select_anchors(&mut s, r, &[1]); + s.execute("addon.pathtools.setAnchor", &json!({"outLength": 10})).unwrap(); + let a = path(&s, r).subpaths[0].anchors[1]; + assert!(((a.h_out - a.p).hypot() - 10.0).abs() < 1e-9 && (a.h_in - a.p).hypot() > 39.0); + s.execute("addon.pathtools.equalize", &json!({})).unwrap(); + let a = path(&s, r).subpaths[0].anchors[1]; + assert!(((a.h_out - a.p).hypot() - (a.h_in - a.p).hypot()).abs() < 1e-9); + // A selection with nothing to change makes no step. + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.equalize", &json!({})).unwrap()["anchors"], json!(0)); + assert_eq!(steps(&s), n); + refuses(&mut s, "addon.pathtools.smooth", &[json!({"ratio": 0.9}), json!({"ratio": "x"})]); + refuses(&mut s, "addon.pathtools.corner", &[json!({"retract": 1})]); +} + +#[test] +fn set_anchor_moves_anchors_and_sets_handles() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (50.0, 0.0), (100.0, 0.0)], false); + select_anchors(&mut s, l, &[1]); + let n = steps(&s); + s.execute("addon.pathtools.setAnchor", &json!({"x": 60, "y": 20, "outLength": 30, "outAngle": 90})).unwrap(); + let a = path(&s, l).subpaths[0].anchors[1]; + assert_eq!(a.p, Point::new(60.0, 20.0)); + assert!(a.h_out.distance(Point::new(60.0, -10.0)) < 1e-9, "{a:?}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.setAnchor", &[json!({}), json!({"x": "1"}), json!({"inLength": -2}), json!({"y": f64::MAX})]); +} + +#[test] +fn remove_keep_shape_takes_the_direct_selected_anchors() { + let mut s = session(); + let e = circle(&mut s); + // Selected whole: nothing to say which anchors go. + refuses(&mut s, "addon.pathtools.removeKeepShape", &[json!({})]); + select_anchors(&mut s, e, &[1, 5]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.removeKeepShape", &json!({})).unwrap()["removed"], json!(2)); + assert_eq!(path(&s, e).anchor_count(), 14); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn add_points_splits_selected_segments_evenly() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.addPoints", &json!({"count": 3})).unwrap()["added"], json!(3)); + let xs: Vec = path(&s, l).anchors().map(|(_, _, a)| a.p.x).collect(); + assert!(xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0]).all(|(x, w)| (x - w).abs() < 1e-3), "{xs:?}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.addPoints", &[json!({"count": 0}), json!({"count": 101}), json!({"count": 1.5})]); + // An anchor alone selects no segment. + select_anchors(&mut s, l, &[1]); + refuses(&mut s, "addon.pathtools.addPoints", &[json!({})]); +} + +#[test] +fn close_joins_open_ends() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (50.0, 80.0)], false); + select(&mut s, &[l]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.close", &json!({"mode": "smooth"})).unwrap()["closed"], json!(1)); + assert!(path(&s, l).subpaths[0].closed); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.close", &[json!({}), json!({"mode": "round"})]); +} + +#[test] +fn crossings_add_anchors_or_cut_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(0.0, 0.0), (100.0, 100.0)], false); + let b = line(&mut s, &[(0.0, 100.0), (100.0, 0.0)], false); + select(&mut s, &[a, b]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.crossings", &json!({})).unwrap()["crossings"], json!(2)); + assert_eq!((path(&s, a).anchor_count(), path(&s, b).anchor_count()), (3, 3)); + assert!(path(&s, a).subpaths[0].anchors[1].p.distance(Point::new(50.0, 50.0)) < 1e-6); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.pathtools.crossings", &json!({"cut": true})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 4, "{r}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.crossings", &[json!({"cut": "yes"}), json!({"ids": [123456]})]); +} diff --git a/crates/pathops/src/addons.rs b/crates/pathops/src/addons.rs new file mode 100644 index 0000000000..b60e4a33ae --- /dev/null +++ b/crates/pathops/src/addons.rs @@ -0,0 +1,17 @@ +//! Geometry for VectorCraft's built-in add-ons, one module per add-on, with the kernels they share. +//! +//! - [`keep_shape`]: remove anchors while refitting their neighbours' handles, so the outline keeps +//! its shape within a tolerance (shared by every add-on that takes anchors away). +//! - [`cleanup`]: Artwork Cleanup's path repairs (collinear, duplicate and near anchors, tiny +//! handles, nearly closed paths) and Rejoin Path Pieces. +//! - [`pathtools`]: Path Precision Tools' anchor edits, path readouts, extending open paths and +//! finding where paths cross. + +pub mod cleanup; +pub mod keep_shape; +pub mod pathtools; + +pub use cleanup::{ + Rejoined, close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles, +}; +pub use keep_shape::{SHARP_CORNER_DEG, remove_anchor_keep_shape, simplify_anchors_keep_shape, simplify_keep_shape}; diff --git a/crates/pathops/src/addons/cleanup.rs b/crates/pathops/src/addons/cleanup.rs new file mode 100644 index 0000000000..edb3489007 --- /dev/null +++ b/crates/pathops/src/addons/cleanup.rs @@ -0,0 +1,323 @@ +//! Artwork Cleanup's path repairs, each on one subpath and returning how much it changed (so a +//! check is the repair run on a copy): collinear anchors, duplicate anchors, tiny handles and +//! nearly closed paths; [`near_point_groups`] finds anchors to snap together, and [`rejoin`] welds +//! open pieces whose ends meet back into paths. + +use std::collections::HashMap; + +use kurbo::{Point, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath}; + +use crate::fit::{end_tangent, start_tangent}; + +/// The fewest anchors a subpath keeps: two when open, three when closed. +fn min_anchors(sp: &SubPath) -> usize { + if sp.closed { 3 } else { 2 } +} + +/// `a`'s handle offset `h - a.p` moved onto `p`. +fn moved(p: Point, a_p: Point, h: Point) -> Point { + p + (h - a_p) +} + +/// Remove the corner anchors (no handles, straight segments both sides) where a straight run goes +/// on in the same direction: the sine of the angle it turns there is at most `tolerance`. Open ends +/// stay, and a subpath keeps two anchors (three when closed) → how many went. +pub fn remove_collinear_anchors(sp: &mut SubPath, tolerance: f64) -> usize { + let mut removed = 0; + let mut i = 0; + while i < sp.anchors.len() && sp.anchors.len() > min_anchors(sp) { + let n = sp.anchors.len(); + let inner = sp.closed || (i > 0 && i + 1 < n); + let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get((i + n - 1) % n), sp.anchors.get(i), sp.anchors.get((i + 1) % n)) else { break }; + let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in(); + let (a, b) = (cur.p - prev.p, next.p - cur.p); + let len = a.hypot() * b.hypot(); + if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance { + sp.anchors.remove(i); + removed += 1; + } else { + i += 1; + } + } + removed +} + +/// Merge each anchor lying within `distance` of the one before it (and a closed subpath's last +/// anchor within `distance` of its first) into that one, which keeps its in handle and takes the +/// merged anchor's out handle → how many went. +pub fn merge_duplicate_anchors(sp: &mut SubPath, distance: f64) -> usize { + let before = sp.anchors.len(); + let mut out: Vec = Vec::with_capacity(before); + for a in sp.anchors.drain(..) { + match out.last_mut() { + Some(l) if l.p.distance(a.p) <= distance => *l = Anchor::with_handles(l.p, l.h_in, moved(l.p, a.p, a.h_out)), + _ => out.push(a), + } + } + if sp.closed + && out.len() > 1 + && let (Some(first), Some(last)) = (out.first(), out.last()) + && first.p.distance(last.p) <= distance + && let Some(last) = out.pop() + && let Some(f) = out.first_mut() + { + *f = Anchor::with_handles(f.p, moved(f.p, last.p, last.h_in), f.h_out); + } + sp.anchors = out; + before - sp.anchors.len() +} + +/// Retract the handles shorter than `length` (but not already on their anchor); an anchor that +/// loses a handle becomes a corner → how many handles were retracted. +pub fn retract_tiny_handles(sp: &mut SubPath, length: f64) -> usize { + let mut count = 0; + for a in &mut sp.anchors { + for out in [false, true] { + let h = if out { &mut a.h_out } else { &mut a.h_in }; + let l = h.distance(a.p); + if l > EPS && l < length { + *h = a.p; + a.kind = AnchorKind::Corner; + count += 1; + } + } + } + count +} + +/// Close an open subpath of three or more anchors whose ends lie within `distance` of each other: +/// the last anchor merges into the first, which takes its in handle → whether it closed. +pub fn close_nearly_closed(sp: &mut SubPath, distance: f64) -> bool { + let ends_meet = sp.anchors.first().zip(sp.anchors.last()).is_some_and(|(f, l)| f.p.distance(l.p) <= distance); + if sp.closed || sp.anchors.len() < 3 || !ends_meet { + return false; + } + let Some(last) = sp.anchors.pop() else { return false }; + if let Some(first) = sp.anchors.first_mut() { + *first = Anchor::with_handles(first.p, moved(first.p, last.p, last.h_in), first.h_out); + } + sp.closed = true; + true +} + +/// Groups of `points` to snap together: points within `distance` of one another (and so on, one +/// to the next) that aren't all at the same place, skipping the pairs `linked` names (such as +/// neighbouring anchors of one path). Each group lists its points in order; snapping them all to +/// the first one makes them coincide. Non-finite points and a distance that isn't a positive number +/// find nothing. +pub fn near_point_groups(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec> { + if !(distance > 0.0 && distance.is_finite()) { + return vec![]; + } + let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) { + grid.entry(cell(*p)).or_default().push(i); + } + let mut parent: Vec = (0..points.len()).collect(); + fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i).filter(|&&p| p != i) { + let up = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = up; + } + i = p; + } + i + } + for (&(cx, cy), members) in &grid { + for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { + let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; + for &i in members { + for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) { + let (Some(a), Some(b)) = (points.get(i), points.get(j)) else { continue }; + let d = a.distance(*b); + if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) { + let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); + if let Some(slot) = parent.get_mut(ri.max(rj)) { + *slot = ri.min(rj); + } + } + } + } + } + } + // Only pairs that aren't at the same place were joined, so no group is all at one place. + let mut groups: HashMap> = HashMap::new(); + for i in 0..points.len() { + groups.entry(root(&mut parent, i)).or_default().push(i); + } + let mut out: Vec> = groups.into_values().filter(|g| g.len() > 1).collect(); + out.sort_unstable(); + out +} + +/// Open pieces welded into one path by [`rejoin`]: `members` index the pieces in the order they +/// run along `path`. +#[derive(Clone, Debug, PartialEq)] +pub struct Rejoined { + pub members: Vec, + pub path: SubPath, +} + +/// One end of a piece: (piece, true for its last anchor). +type End = (usize, bool); + +/// The direction pointing out of the piece at `end`. +fn outward(sp: &SubPath, last: bool) -> Option { + let n = sp.segment_count(); + Some(match last { + true => end_tangent(&sp.segment(n.checked_sub(1)?)), + false => -start_tangent(&sp.segment(0)), + }) +} + +/// Weld the open `pieces` whose ends lie within `gap` of each other back into paths: an end meets +/// at most one other, and where an end could meet several, it meets the one the path turns least +/// to go on into (then the nearest). A piece may run either way; a chain whose ends meet closes. +/// Each junction keeps the earlier piece's anchor and the later piece's out handle. Pieces that are +/// closed, have fewer than two anchors or a non-finite coordinate stay out. → the chains of two or +/// more pieces, and the single pieces that closed. +pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec { + if !(gap >= 0.0 && gap.is_finite()) { + return vec![]; + } + let usable = |sp: &&SubPath| { + !sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) + }; + // Each usable end: where it is and the way out of its piece there. + let ends: Vec<(End, Point, Vec2)> = pieces + .iter() + .enumerate() + .filter(|(_, sp)| usable(sp)) + .flat_map(|(i, sp)| [(i, sp, false), (i, sp, true)]) + .filter_map(|(i, sp, last)| { + let a = if last { sp.anchors.last() } else { sp.anchors.first() }?; + Some(((i, last), a.p, outward(sp, last)?)) + }) + .collect(); + let points: Vec = ends.iter().map(|e| e.1).collect(); + // Every pair of ends within the gap, by the turn across the junction. + let mut pairs: Vec<(f64, f64, End, End)> = vec![]; + for (a, b) in candidate_pairs(&points, gap.max(1e-9)) { + let (Some(&(ea, pa, oa)), Some(&(eb, pb, ob))) = (ends.get(a), ends.get(b)) else { continue }; + // A piece's own two ends meet only when closing it leaves a shape (three anchors). + if ea.0 == eb.0 && pieces.get(ea.0).is_none_or(|sp| sp.anchors.len() < 3) { + continue; + } + let d = pa.distance(pb); + if d <= gap { + pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb)); + } + } + pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1))); + let mut link: HashMap = HashMap::new(); + for (_, _, a, b) in pairs { + if !link.contains_key(&a) && !link.contains_key(&b) { + link.insert(a, b); + link.insert(b, a); + } + } + chains(pieces, &link) +} + +/// Pairs (a < b) of `points` that may lie within `gap`: those in neighbouring grid cells. +fn candidate_pairs(points: &[Point], gap: f64) -> Vec<(usize, usize)> { + let cell = |p: Point| ((p.x / gap).floor() as i64, (p.y / gap).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, p) in points.iter().enumerate() { + grid.entry(cell(*p)).or_default().push(i); + } + let mut out = vec![]; + for (i, p) in points.iter().enumerate() { + let (cx, cy) = cell(*p); + for dx in -1..=1 { + for dy in -1..=1 { + let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue }; + out.extend(others.iter().filter(|&&j| j > i).map(|&j| (i, j))); + } + } + } + out +} + +/// Walk the links between piece ends into chains. +fn chains(pieces: &[SubPath], link: &HashMap) -> Vec { + let mut seen = vec![false; pieces.len()]; + let mut out = vec![]; + for start in 0..pieces.len() { + if seen.get(start) != Some(&false) || !(link.contains_key(&(start, false)) || link.contains_key(&(start, true))) { + continue; + } + // A member is (piece, reversed): it comes in by end (piece, reversed) and leaves by + // (piece, !reversed). Back up to the chain's first piece, or round to `start` in a loop. + let mut first = (start, false); + let mut closed = false; + for _ in 0..pieces.len() { + let Some(&(p, at_last)) = link.get(&first) else { break }; + // The piece before leaves by its end `at_last`. + let prev = (p, !at_last); + if prev.0 == start { + closed = true; + break; + } + first = prev; + } + let members = walk(link, first, closed, &mut seen); + if let Some(path) = assemble(pieces, &members, closed) { + out.push(Rejoined { members: members.iter().map(|m| m.0).collect(), path }); + } + } + out +} + +/// The pieces of the chain that begins with `first` (piece, reversed), in order. +fn walk(link: &HashMap, first: (usize, bool), closed: bool, seen: &mut [bool]) -> Vec<(usize, bool)> { + let mut members = vec![]; + let mut cur = first; + loop { + match seen.get_mut(cur.0) { + Some(s) if !*s => *s = true, + _ => break, + } + members.push(cur); + // A piece run forwards leaves by its last anchor. + let Some(&(p, at_last)) = link.get(&(cur.0, !cur.1)) else { break }; + let next = (p, at_last); + if closed && next.0 == first.0 { + break; + } + cur = next; + } + members +} + +/// The anchors of `pieces` along the chain `members`, each piece's start merged into the end before it. +fn assemble(pieces: &[SubPath], members: &[(usize, bool)], closed: bool) -> Option { + if members.len() < 2 && !closed { + return None; + } + let mut anchors: Vec = vec![]; + for &(i, reversed) in members { + let mut sp = pieces.get(i)?.clone(); + if reversed { + sp.reverse(); + } + let mut rest = sp.anchors.into_iter(); + match (anchors.last_mut(), rest.next()) { + (Some(l), Some(f)) => *l = Anchor::with_handles(l.p, l.h_in, moved(l.p, f.p, f.h_out)), + (None, Some(f)) => anchors.push(f), + _ => {} + } + anchors.extend(rest); + } + let mut sp = SubPath::new(anchors, false); + if closed && !close_nearly_closed(&mut sp, f64::INFINITY) { + sp.closed = sp.anchors.len() >= 2; + } + Some(sp) +} + +#[cfg(test)] +mod tests; diff --git a/crates/pathops/src/addons/cleanup/tests.rs b/crates/pathops/src/addons/cleanup/tests.rs new file mode 100644 index 0000000000..3e1c58d42b --- /dev/null +++ b/crates/pathops/src/addons/cleanup/tests.rs @@ -0,0 +1,134 @@ +use kurbo::{Point, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, SubPath}; + +use super::{close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles}; + +fn line(pts: &[(f64, f64)], closed: bool) -> SubPath { + SubPath::polyline(&pts.iter().map(|&p| p.into()).collect::>(), closed) +} + +fn points(sp: &SubPath) -> Vec<(f64, f64)> { + sp.anchors.iter().map(|a| (a.p.x, a.p.y)).collect() +} + +#[test] +fn collinear_anchors_go_and_corners_stay() { + let mut sp = line(&[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 5.0)], true); + assert_eq!(remove_collinear_anchors(&mut sp, 0.005), 2); + assert_eq!(points(&sp), [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + assert_eq!(remove_collinear_anchors(&mut sp, 0.005), 0, "clean art is left alone"); + // A turn back on itself is not a straight run; an open end stays. + let mut back = line(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)], false); + assert_eq!(remove_collinear_anchors(&mut back, 0.005), 0); + // An anchor with a handle is not a corner on a straight run. + let mut curved = line(&[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)], false); + curved.anchors[1] = Anchor::smooth((5.0, 0.0).into(), (7.0, 0.0).into()); + assert_eq!(remove_collinear_anchors(&mut curved, 0.005), 0); + // A slight bend within the tolerance goes; a larger one stays. + let mut bend = line(&[(0.0, 0.0), (100.0, 0.1), (200.0, 0.0)], false); + assert_eq!(remove_collinear_anchors(&mut bend.clone(), 0.0001), 0); + assert_eq!(remove_collinear_anchors(&mut bend, 0.005), 1); +} + +#[test] +fn duplicate_anchors_merge_keeping_the_outer_handles() { + let mut sp = SubPath::new( + vec![ + Anchor::with_handles((0.0, 0.0).into(), (0.0, 0.0).into(), (0.0, 0.0).into()), + Anchor::with_handles((10.0, 0.0).into(), (8.0, 0.0).into(), (10.0, 0.0).into()), + Anchor::with_handles((10.005, 0.0).into(), (10.005, 0.0).into(), (10.005, 3.0).into()), + Anchor::corner((10.0, 10.0).into()), + ], + false, + ); + assert_eq!(merge_duplicate_anchors(&mut sp, 0.01), 1); + assert_eq!(sp.anchors.len(), 3); + let a = sp.anchors[1]; + assert_eq!((a.p, a.h_in), (Point::new(10.0, 0.0), Point::new(8.0, 0.0))); + assert!(a.h_out.distance(Point::new(10.0, 3.0)) < 1e-9, "{:?}", a.h_out); + assert_eq!(merge_duplicate_anchors(&mut sp, 0.01), 0); + // A closed path's last anchor on its first merges into it. + let mut ring = line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 0.0)], true); + assert_eq!(merge_duplicate_anchors(&mut ring, 0.01), 1); + assert_eq!(points(&ring), [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]); +} + +#[test] +fn tiny_handles_retract() { + let p = Point::new(5.0, 5.0); + let mut sp = SubPath::new(vec![Anchor { p, h_in: p - Vec2::new(0.004, 0.0), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Smooth }], false); + assert_eq!(retract_tiny_handles(&mut sp, 0.01), 1); + let a = sp.anchors[0]; + assert_eq!((a.h_in, a.kind), (p, AnchorKind::Corner)); + assert_eq!(a.h_out, p + Vec2::new(3.0, 0.0), "a long handle stays"); + assert_eq!(retract_tiny_handles(&mut sp, 0.01), 0); +} + +#[test] +fn nearly_closed_paths_close() { + let mut sp = line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.005, 0.0)], false); + assert!(close_nearly_closed(&mut sp, 0.01)); + assert!(sp.closed); + assert_eq!(points(&sp), [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]); + let mut apart = line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (1.0, 0.0)], false); + assert!(!close_nearly_closed(&mut apart, 0.01)); + assert!(!apart.closed); + let mut two = line(&[(0.0, 0.0), (0.0, 0.0)], false); + assert!(!close_nearly_closed(&mut two, 0.01), "two anchors make no shape"); +} + +#[test] +fn near_points_group_but_linked_and_equal_ones_do_not() { + let pts: Vec = [(0.0, 0.0), (0.005, 0.0), (5.0, 5.0), (5.0, 5.0), (9.0, 9.0), (9.004, 9.0), (f64::NAN, 0.0)].map(Into::into).to_vec(); + let groups = near_point_groups(&pts, 0.01, |a, b| (a, b) == (4, 5)); + assert_eq!(groups, [vec![0, 1]], "equal points and linked ones are not snapped"); + assert!(near_point_groups(&pts, 0.0, |_, _| false).is_empty()); + assert!(near_point_groups(&pts, f64::NAN, |_, _| false).is_empty()); + // Far coordinates don't overflow the grid. + let far: Vec = [(1e300, 1e300), (-1e300, 1e300)].map(Into::into).to_vec(); + assert!(near_point_groups(&far, 1e-300, |_, _| false).is_empty()); +} + +#[test] +fn rejoin_welds_pieces_within_the_gap() { + // Three pieces of one zig-zag, the middle one drawn backwards, plus one too far away. + let pieces = [ + line(&[(0.0, 0.0), (10.0, 0.0)], false), + line(&[(20.0, 10.0), (10.05, 0.0)], false), + line(&[(20.0, 10.0), (30.0, 10.0)], false), + line(&[(31.0, 10.0), (40.0, 10.0)], false), + ]; + let out = rejoin(&pieces, 0.1); + assert_eq!(out.len(), 1, "{out:?}"); + assert_eq!(out[0].members, [0, 1, 2]); + assert_eq!(points(&out[0].path), [(0.0, 0.0), (10.0, 0.0), (20.0, 10.0), (30.0, 10.0)]); + assert!(!out[0].path.closed); + // With a wider gap the last piece joins too. + assert_eq!(rejoin(&pieces, 1.0)[0].members, [0, 1, 2, 3]); + // Nothing within the gap: nothing joins. + assert!(rejoin(&pieces[2..], 0.5).is_empty()); +} + +#[test] +fn rejoin_takes_the_straightest_continuation_and_closes_loops() { + // Piece 0 ends at the origin; piece 1 goes straight on, piece 2 turns back. + let pieces = [line(&[(-10.0, 0.0), (0.0, 0.0)], false), line(&[(0.0, 0.0), (0.0, 10.0)], false), line(&[(0.0, 0.0), (10.0, 0.0)], false)]; + let out = rejoin(&pieces, 0.1); + assert_eq!(out.len(), 1); + assert_eq!(out[0].members, [0, 2]); + // Four sides of a square close into one path. + let sides = [ + line(&[(0.0, 0.0), (10.0, 0.0)], false), + line(&[(10.0, 0.0), (10.0, 10.0)], false), + line(&[(0.0, 10.0), (10.0, 10.0)], false), + line(&[(0.0, 10.0), (0.0, 0.0)], false), + ]; + let out = rejoin(&sides, 0.1); + assert_eq!(out.len(), 1); + assert!(out[0].path.closed); + assert_eq!(out[0].path.anchors.len(), 4); + // Closed, single-anchor and non-finite pieces stay out; bad gaps join nothing. + let odd = [line(&[(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], true), line(&[(1.0, 0.0)], false), line(&[(f64::NAN, 0.0), (0.0, 1.0)], false)]; + assert!(rejoin(&odd, 1.0).is_empty()); + assert!(rejoin(&sides, f64::NAN).is_empty() && rejoin(&sides, -1.0).is_empty()); +} diff --git a/crates/pathops/src/addons/keep_shape.rs b/crates/pathops/src/addons/keep_shape.rs new file mode 100644 index 0000000000..396795ebbd --- /dev/null +++ b/crates/pathops/src/addons/keep_shape.rs @@ -0,0 +1,317 @@ +//! Shape-keeping anchor removal: an anchor goes, and the handles of its two neighbours that face it +//! are refitted (their directions kept, their lengths fitted) so one segment follows the two that +//! met there. [`remove_anchor_keep_shape`] removes one anchor and says how far the outline moved; +//! [`simplify_keep_shape`] removes as many as it can while every new segment stays within a +//! tolerance of the original outline. + +use kurbo::{CubicBez, ParamCurve, ParamCurveNearest}; +use vectorcraft_geom::{Anchor, PathData, SubPath}; + +use crate::edit::remove_anchor; +use crate::fit::{end_tangent, start_tangent}; + +/// The turn (degrees) at an anchor above which `protect_corners` keeps it. +pub const SHARP_CORNER_DEG: f64 = 30.0; + +/// Points sampled along each curve to measure how far two outlines are apart. +const SAMPLES: usize = 8; + +/// Nearest-point accuracy (pt) of those measurements. +const ACCURACY: f64 = 1e-6; + +/// The segment that takes the place of the two meeting at `cur` once it is removed: from `prev` +/// to `next`, their facing handles refitted ([`remove_anchor`]). +fn merged(prev: &Anchor, cur: &Anchor, next: &Anchor) -> CubicBez { + let mut run = SubPath::new(vec![*prev, *cur, *next], false); + remove_anchor(&mut run, 1); + match run.anchors.as_slice() { + [a, b] => CubicBez::new(prev.p, a.h_out, b.h_in, next.p), + _ => CubicBez::new(prev.p, prev.h_out, next.h_in, next.p), + } +} + +/// How far `fitted` strays from the run of segments `original` it replaces, measured both ways +/// (pt): the farthest a sampled point of either lies from the other. +fn deviation(original: &[&CubicBez], fitted: &CubicBez) -> f64 { + let t = |k: usize| k as f64 / SAMPLES as f64; + let mut worst: f64 = 0.0; + for c in original { + for k in 0..=SAMPLES { + worst = worst.max(fitted.nearest(c.eval(t(k)), ACCURACY).distance_sq); + } + } + for k in 1..SAMPLES { + let p = fitted.eval(t(k)); + worst = worst.max(original.iter().map(|c| c.nearest(p, ACCURACY).distance_sq).fold(f64::INFINITY, f64::min)); + } + worst.sqrt() +} + +/// The fewest anchors a subpath keeps: two when open, three when closed. +fn min_anchors(sp: &SubPath) -> usize { + if sp.closed { 3 } else { 2 } +} + +/// Indices of anchor `i`'s neighbours in a subpath of `n` anchors (`None` for an open end). +fn neighbours(n: usize, closed: bool, i: usize) -> Option<(usize, usize)> { + match closed { + true => (n > 0).then(|| ((i + n - 1) % n, (i + 1) % n)), + false => (i > 0 && i + 1 < n).then(|| (i - 1, i + 1)), + } +} + +fn finite(sp: &SubPath) -> bool { + sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) +} + +/// Does the path turn by more than [`SHARP_CORNER_DEG`] at anchor `i` (an inner anchor)? +fn is_sharp(sp: &SubPath, i: usize) -> bool { + let Some((prev, _)) = neighbours(sp.anchors.len(), sp.closed, i) else { return false }; + let (into, out) = (end_tangent(&sp.segment(prev)), start_tangent(&sp.segment(i))); + into.dot(out).clamp(-1.0, 1.0).acos().to_degrees() > SHARP_CORNER_DEG +} + +/// Give anchors `prev` and `next` the facing handles of segment `c`. +fn apply(sp: &mut SubPath, prev: usize, next: usize, c: &CubicBez) { + if let Some(a) = sp.anchors.get_mut(prev) { + a.h_out = c.p1; + } + if let Some(a) = sp.anchors.get_mut(next) { + a.h_in = c.p2; + } +} + +/// Remove anchor `index` of `sp`, refitting the handles of its neighbours that face it so one +/// segment follows the two that met there → (the new subpath, how far its outline strays from the +/// old one, in points). `None` when the anchor can't go: out of range, an end of an open subpath, +/// a non-finite coordinate, or the subpath would keep fewer than two (open) or three (closed) +/// anchors. +pub fn remove_anchor_keep_shape(sp: &SubPath, index: usize) -> Option<(SubPath, f64)> { + let n = sp.anchors.len(); + if n <= min_anchors(sp) || index >= n || !finite(sp) { + return None; + } + let (prev, next) = neighbours(n, sp.closed, index)?; + let c = merged(sp.anchors.get(prev)?, sp.anchors.get(index)?, sp.anchors.get(next)?); + let error = deviation(&[&sp.segment(prev), &sp.segment(index)], &c); + let mut out = sp.clone(); + apply(&mut out, prev, next, &c); + out.anchors.remove(index); + Some((out, error)) +} + +/// Remove as many anchors of `path` as can go while its outline stays within `tolerance` points of +/// where it was, refitting the handles beside each ([`remove_anchor_keep_shape`]). Every new segment +/// is measured against the original outline it replaces, so removals don't add up past the +/// tolerance. With `protect_corners`, anchors where the path turns by more than +/// [`SHARP_CORNER_DEG`] stay. Open ends always stay. A subpath with a non-finite coordinate, and a +/// tolerance that isn't a positive number, are left as they are. +pub fn simplify_keep_shape(path: &PathData, tolerance: f64, protect_corners: bool) -> PathData { + if !(tolerance > 0.0 && tolerance.is_finite()) { + return path.clone(); + } + PathData::new(path.subpaths.iter().map(|sp| Reducer::new(sp, protect_corners).run(tolerance)).collect()) +} + +/// [`simplify_keep_shape`] on subpath `sp` where only the anchors `may_go` marks (one flag per +/// anchor, by index) may go: what the Anchor Eraser Brush passes over. Open ends always stay. An +/// infinite tolerance removes every marked anchor that can go. +pub fn simplify_anchors_keep_shape(sp: &SubPath, tolerance: f64, may_go: &[bool]) -> SubPath { + if tolerance.is_nan() || tolerance <= 0.0 { + return sp.clone(); + } + let mut r = Reducer::new(sp, false); + r.kept = (0..sp.anchors.len()).map(|i| !may_go.get(i).copied().unwrap_or(false)).collect(); + r.run(tolerance) +} + +/// One subpath being reduced: what is left of it, and where its anchors were in the original. +struct Reducer<'a> { + original: &'a SubPath, + segments: Vec, + /// Anchors of the original that stay whatever the tolerance (sharp corners). + kept: Vec, + cur: SubPath, + /// The original index of each anchor left. + origin: Vec, +} + +impl<'a> Reducer<'a> { + fn new(sp: &'a SubPath, protect_corners: bool) -> Self { + let n = sp.anchors.len(); + Reducer { + original: sp, + segments: (0..sp.segment_count()).map(|i| sp.segment(i)).collect(), + kept: (0..n).map(|i| protect_corners && is_sharp(sp, i)).collect(), + cur: sp.clone(), + origin: (0..n).collect(), + } + } + + /// Each pass removes the anchors whose removal strays least, no two side by side (so each + /// segment measured is the one that results), until none can go. + fn run(mut self, tolerance: f64) -> SubPath { + if self.cur.anchors.len() <= min_anchors(self.original) || !finite(self.original) { + return self.cur; + } + while self.pass(tolerance) {} + self.cur + } + + /// The original segments between original anchors `from` and `to`, round the end of a closed + /// path. + fn span(&self, from: usize, to: usize) -> Option> { + Some(match from < to { + true => self.segments.get(from..to)?.iter().collect(), + false => self.segments.get(from..)?.iter().chain(self.segments.get(..to)?).collect(), + }) + } + + /// Anchor `i` of what is left, if it may go: (how far its removal strays, the segment that + /// replaces its two). + fn candidate(&self, i: usize, tolerance: f64) -> Option<(f64, CubicBez)> { + if self.origin.get(i).and_then(|&o| self.kept.get(o)) != Some(&false) { + return None; + } + let (prev, next) = neighbours(self.cur.anchors.len(), self.cur.closed, i)?; + let a = &self.cur.anchors; + let c = merged(a.get(prev)?, a.get(i)?, a.get(next)?); + let e = deviation(&self.span(*self.origin.get(prev)?, *self.origin.get(next)?)?, &c); + (e <= tolerance).then_some((e, c)) + } + + /// One pass: whether any anchor went. + fn pass(&mut self, tolerance: f64) -> bool { + let m = self.cur.anchors.len(); + let min = min_anchors(self.original); + if m <= min { + return false; + } + let mut found: Vec<(f64, usize, CubicBez)> = (0..m).filter_map(|i| self.candidate(i, tolerance).map(|(e, c)| (e, i, c))).collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut gone = vec![false; m]; + let mut left = m - min; + for (_, i, c) in found { + let Some((prev, next)) = neighbours(m, self.cur.closed, i) else { continue }; + if left == 0 || gone.get(prev) != Some(&false) || gone.get(next) != Some(&false) { + continue; + } + apply(&mut self.cur, prev, next, &c); + if let Some(g) = gone.get_mut(i) { + *g = true; + } + left -= 1; + } + let mut keep = gone.iter().map(|g| !g); + self.cur.anchors.retain(|_| keep.next().unwrap_or(true)); + let mut keep = gone.iter().map(|g| !g); + self.origin.retain(|_| keep.next().unwrap_or(true)); + left < m - min + } +} + +#[cfg(test)] +mod tests { + use kurbo::{ParamCurveNearest, Point, Vec2}; + use vectorcraft_geom::{Anchor, PathData, SubPath}; + + use super::{remove_anchor_keep_shape, simplify_keep_shape}; + + /// A circle of radius `r` about the origin drawn with `n` smooth anchors. + fn circle(r: f64, n: usize) -> SubPath { + let step = std::f64::consts::TAU / n as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan() * r; + let anchors = (0..n) + .map(|i| { + let a = step * i as f64; + let p = Point::new(r * a.cos(), r * a.sin()); + Anchor::smooth(p, p + Vec2::new(-a.sin(), a.cos()) * k) + }) + .collect(); + SubPath::new(anchors, true) + } + + /// The farthest a point of `sp`'s outline lies from the circle of radius `r`. + fn off_circle(sp: &SubPath, r: f64) -> f64 { + (0..sp.segment_count()) + .flat_map(|i| (0..=20).map(move |k| (i, k as f64 / 20.0))) + .map(|(i, t)| (kurbo::ParamCurve::eval(&sp.segment(i), t).to_vec2().hypot() - r).abs()) + .fold(0.0, f64::max) + } + + #[test] + fn a_circle_keeps_its_shape_with_fewer_anchors() { + let sp = circle(50.0, 16); + let out = simplify_keep_shape(&PathData::single(sp), 0.2, false); + let s = &out.subpaths[0]; + assert!(s.anchors.len() <= 8 && s.anchors.len() >= 3, "{} anchors left", s.anchors.len()); + assert!(s.closed); + assert!(off_circle(s, 50.0) <= 0.2 + 1e-6, "strays {}", off_circle(s, 50.0)); + } + + #[test] + fn one_removal_reports_how_far_the_outline_moved() { + let sp = circle(50.0, 16); + let (out, err) = remove_anchor_keep_shape(&sp, 3).unwrap(); + assert_eq!(out.anchors.len(), 15); + assert!(err < 0.05, "{err}"); + assert!((off_circle(&out, 50.0) - err).abs() < 0.05); + // A corner of a square moves its outline a long way. + let sq = SubPath::polyline(&[(0.0, 0.0).into(), (10.0, 0.0).into(), (10.0, 10.0).into(), (0.0, 10.0).into()], true); + let (_, err) = remove_anchor_keep_shape(&sq, 1).unwrap(); + assert!((err - 50f64.sqrt()).abs() < 1e-3, "{err}"); + } + + #[test] + fn sharp_corners_stay_when_protected() { + // A 90° corner at (1, 0) that a 1 pt tolerance would otherwise take away. + let sp = SubPath::polyline(&[(0.0, 0.0).into(), (1.0, 0.0).into(), (1.0, 1.0).into()], false); + let path = PathData::single(sp); + assert_eq!(simplify_keep_shape(&path, 1.0, false).anchor_count(), 2); + assert_eq!(simplify_keep_shape(&path, 1.0, true).anchor_count(), 3); + // Collinear anchors on a straight edge go either way; the square's corners stay. + let sq = SubPath::polyline( + &[(0.0, 0.0).into(), (5.0, 0.0).into(), (10.0, 0.0).into(), (10.0, 10.0).into(), (0.0, 10.0).into(), (0.0, 5.0).into()], + true, + ); + let out = simplify_keep_shape(&PathData::single(sq), 0.01, true); + let pts: Vec = out.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [(0.0, 0.0).into(), (10.0, 0.0).into(), (10.0, 10.0).into(), (0.0, 10.0).into()] as [Point; 4]); + } + + #[test] + fn removals_do_not_add_up_past_the_tolerance() { + // A gentle arc of many anchors: each removal alone is small, together they would flatten it. + let pts: Vec = (0..=40).map(|i| Point::new(i as f64, (i as f64 / 40.0 * std::f64::consts::PI).sin() * 3.0)).collect(); + let sp = SubPath::polyline(&pts, false); + let out = simplify_keep_shape(&PathData::single(sp.clone()), 0.1, false); + let s = &out.subpaths[0]; + assert!(s.anchors.len() < 41); + for p in &pts { + let d = (0..s.segment_count()).map(|i| s.segment(i).nearest(*p, 1e-6).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + assert!(d <= 0.1 + 1e-6, "{p:?} is {d} away"); + } + } + + #[test] + fn degenerate_input_is_left_alone() { + let line = SubPath::polyline(&[(0.0, 0.0).into(), (1.0, 0.0).into()], false); + assert!(remove_anchor_keep_shape(&line, 0).is_none(), "two anchors stay"); + let three = SubPath::polyline(&[(0.0, 0.0).into(), (1.0, 0.0).into(), (2.0, 0.0).into()], false); + assert!(remove_anchor_keep_shape(&three, 0).is_none(), "an open end stays"); + assert!(remove_anchor_keep_shape(&three, 9).is_none(), "out of range"); + assert_eq!(remove_anchor_keep_shape(&three, 1).unwrap().0.anchors.len(), 2); + let tri = SubPath::polyline(&[(0.0, 0.0).into(), (1.0, 0.0).into(), (0.0, 1.0).into()], true); + assert!(remove_anchor_keep_shape(&tri, 1).is_none(), "a closed path keeps three"); + let nan = SubPath::polyline(&[(0.0, 0.0).into(), (f64::NAN, 0.0).into(), (2.0, 0.0).into()], false); + assert!(remove_anchor_keep_shape(&nan, 1).is_none()); + for path in [PathData::default(), PathData::single(SubPath::default()), PathData::single(nan.clone()), PathData::single(three.clone())] { + // Compared as text: NaN never equals itself. + for tol in [f64::NAN, -1.0, 0.0, f64::INFINITY] { + assert_eq!(format!("{:?}", simplify_keep_shape(&path, tol, false)), format!("{path:?}")); + } + let _ = simplify_keep_shape(&path, 1.0, true); + } + assert_eq!(format!("{:?}", simplify_keep_shape(&PathData::single(nan.clone()), 1.0, false)), format!("{:?}", PathData::single(nan))); + } +} diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs new file mode 100644 index 0000000000..c7444fab6b --- /dev/null +++ b/crates/pathops/src/addons/pathtools.rs @@ -0,0 +1,334 @@ +//! Path Precision Tools' geometry: anchor edits for the Anchor Inspector (smooth by the auto-smooth +//! rule, equalise handles, add evenly spaced anchors, close), the readouts the Measure & Inspect +//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]) and the places +//! where paths cross ([`crossings`]). + +mod crossings; +mod extend; +#[cfg(test)] +mod tests; + +use std::collections::BTreeSet; + +use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2}; +use vectorcraft_geom::{AnchorKind, PathData, SubPath}; + +pub use crossings::{MAX_CROSSING_SEGMENTS, crossings, insert_at}; +pub use extend::{ExtendMode, extend_length_to, extend_open}; + +use crate::fit::{end_tangent, start_tangent}; + +/// The auto-smooth rule's handle length as a share of the nearer neighbour's distance: the share +/// that makes a square's four corners a circle. +pub const SMOOTH_RATIO: f64 = 0.3905; +/// The smallest and largest smoothing ratio. +pub const SMOOTH_RATIO_RANGE: (f64, f64) = (0.1, 0.5); +/// Most anchors [`add_points`] puts on one segment. +pub const MAX_ADDED_PER_SEGMENT: usize = 100; + +/// Arc-length accuracy (pt) of the measurements here. +const ACCURACY: f64 = 1e-6; +/// Shorter than this (pt) is no handle and no distance. +const TINY: f64 = 1e-9; + +fn unit(v: Vec2) -> Option { + let l = v.hypot(); + (l > TINY && l.is_finite()).then(|| v / l) +} + +/// The indices of anchor `i`'s neighbours in `sp` (`None` past an open end). +fn neighbours(sp: &SubPath, i: usize) -> (Option, Option) { + let n = sp.anchors.len(); + let prev = if i > 0 { Some(i - 1) } else { (sp.closed && n > 1).then(|| n - 1) }; + let next = if i + 1 < n { Some(i + 1) } else { (sp.closed && n > 1).then_some(0) }; + (prev.filter(|&j| j != i), next.filter(|&j| j != i)) +} + +/// Make anchor `i` smooth by the auto-smooth rule: a lone handle is mirrored at its length; with +/// none, both handles stand at right angles to the bisector of the angle its neighbours make at +/// it, each `ratio` × the nearer neighbour's distance long; two handles are brought into line, +/// keeping their lengths. An open end without handles gets one aimed at its neighbour's facing +/// handle. False when nothing changes or there is no direction to take. +pub fn auto_smooth(sp: &mut SubPath, i: usize, ratio: f64) -> bool { + let (prev, next) = neighbours(sp, i); + let at = |j: Option| j.and_then(|j| sp.anchors.get(j)).copied(); + let (prev, next) = (at(prev), at(next)); + let Some(a) = sp.anchors.get_mut(i) else { return false }; + let before = *a; + let p = a.p; + match (a.has_in(), a.has_out()) { + (true, true) => { + let (Some(o), Some(n)) = (unit(a.h_out - p), unit(p - a.h_in)) else { return false }; + // Already in line: only the kind may change. + if o.cross(n).abs() <= 1e-12 && o.dot(n) > 0.0 { + a.kind = AnchorKind::Smooth; + return *a != before; + } + let Some(d) = unit(o + n) else { return false }; + a.h_out = p + d * (a.h_out - p).hypot(); + a.h_in = p - d * (a.h_in - p).hypot(); + } + (true, false) if next.is_some() => a.h_out = p - (a.h_in - p), + (false, true) if prev.is_some() => a.h_in = p - (a.h_out - p), + (false, false) => match (prev, next) { + (Some(pr), Some(nx)) => { + let (dp, dn) = (pr.p.distance(p), nx.p.distance(p)); + let (Some(up), Some(un)) = (unit(pr.p - p), unit(nx.p - p)) else { return false }; + let Some(dir) = unit(un - up) else { return false }; + let len = dp.min(dn) * ratio; + a.h_out = p + dir * len; + a.h_in = p - dir * len; + } + // An open end: aim at the neighbour's facing handle (or the neighbour itself). + (None, Some(nx)) => { + let Some(dir) = unit(nx.h_in - p) else { return false }; + a.h_out = p + dir * (nx.p.distance(p) * ratio); + } + (Some(pr), None) => { + let Some(dir) = unit(pr.h_out - p) else { return false }; + a.h_in = p + dir * (pr.p.distance(p) * ratio); + } + (None, None) => return false, + }, + _ => return false, + } + a.kind = if a.has_in() && a.has_out() { AnchorKind::Smooth } else { AnchorKind::Corner }; + *a != before +} + +/// Make anchor `i` a corner: its handles retracted with `retract`, else left where they are. +/// False when nothing changes. +pub fn make_corner(sp: &mut SubPath, i: usize, retract: bool) -> bool { + let Some(a) = sp.anchors.get_mut(i) else { return false }; + let before = *a; + if retract { + a.retract(); + } + a.kind = AnchorKind::Corner; + *a != before +} + +/// Give anchor `i`'s two handles the same length, their average, each keeping its direction; a +/// missing one (where there is a segment for it) is made opposite the other at its length. False +/// when there is nothing to equalise. +pub fn equalize_handles(sp: &mut SubPath, i: usize) -> bool { + let (prev, next) = neighbours(sp, i); + let Some(a) = sp.anchors.get_mut(i) else { return false }; + let before = *a; + let p = a.p; + match (a.has_in(), a.has_out()) { + (true, true) => { + let len = ((a.h_in - p).hypot() + (a.h_out - p).hypot()) / 2.0; + let (Some(di), Some(dout)) = (unit(a.h_in - p), unit(a.h_out - p)) else { return false }; + a.h_in = p + di * len; + a.h_out = p + dout * len; + } + (true, false) if next.is_some() => a.h_out = p - (a.h_in - p), + (false, true) if prev.is_some() => a.h_in = p - (a.h_out - p), + _ => return false, + } + *a != before +} + +/// `sp` with `count` anchors added on each of `segments` (all of them when `None`), splitting each +/// into `count + 1` pieces of equal length; the shape doesn't change. → (the subpath, the indexes of +/// the anchors added). +pub fn add_points(sp: &SubPath, segments: Option<&BTreeSet>, count: usize) -> (SubPath, BTreeSet) { + let count = count.min(MAX_ADDED_PER_SEGMENT); + let mut hits = vec![]; + for seg in (0..sp.segment_count()).filter(|s| segments.is_none_or(|set| set.contains(s))) { + let c = sp.segment(seg); + let len = c.arclen(ACCURACY); + if !(len > TINY && len.is_finite()) { + continue; + } + hits.extend((1..=count).map(|k| (seg, c.inv_arclen(len * k as f64 / (count + 1) as f64, ACCURACY)))); + } + insert_at(sp, &hits) +} + +/// How [`close`] joins an open subpath's ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CloseMode { + /// With the handles the ends already have. + Handles, + /// With a straight segment. + Straight, + /// With a segment that leaves both ends smoothly ([`auto_smooth`]). + Smooth, +} + +impl CloseMode { + pub const ALL: [Self; 3] = [Self::Handles, Self::Straight, Self::Smooth]; + + pub fn id(self) -> &'static str { + match self { + Self::Handles => "handles", + Self::Straight => "straight", + Self::Smooth => "smooth", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.id() == s) + } +} + +/// Close open subpath `sp` (of two anchors or more) the way `mode` says. False when it is closed +/// already or too short. +pub fn close(sp: &mut SubPath, mode: CloseMode, ratio: f64) -> bool { + if sp.closed || sp.anchors.len() < 2 { + return false; + } + if mode == CloseMode::Straight { + if let Some(a) = sp.anchors.first_mut() { + a.h_in = a.p; + } + if let Some(a) = sp.anchors.last_mut() { + a.h_out = a.p; + } + } + sp.closed = true; + if mode == CloseMode::Smooth { + let last = sp.anchors.len() - 1; + auto_smooth(sp, 0, ratio); + auto_smooth(sp, last, ratio); + } + true +} + +/// A handle's length (pt) and direction (degrees counter-clockwise on the page from the x axis); +/// `None` for no handle. +pub fn handle_polar(p: Point, h: Point) -> Option<(f64, f64)> { + let v = h - p; + let len = v.hypot(); + (len > TINY).then(|| (len, angle_of(v))) +} + +/// Direction of `v` in degrees counter-clockwise on the page (y points down), in (-180, 180]. +pub fn angle_of(v: Vec2) -> f64 { + (-v.y).atan2(v.x).to_degrees() + 0.0 +} + +/// Where a handle `len` long at `deg` degrees (counter-clockwise on the page) from `p` ends. +pub fn handle_at(p: Point, len: f64, deg: f64) -> Point { + let (s, c) = deg.to_radians().sin_cos(); + p + Vec2::new(c, -s) * len +} + +/// What the Measure & Inspect tool reads off a path at a point near it. +#[derive(Clone, Debug, PartialEq)] +pub struct Inspection { + pub subpath: usize, + pub closed: bool, + pub anchors: usize, + /// The subpath's length (pt). + pub length: f64, + /// The area the subpath encloses (pt², an open one closed by a straight line). + pub area: f64, + pub segment: usize, + pub t: f64, + /// The point on the path nearest the pointer. + pub point: Point, + pub segment_length: f64, + /// The direction the path runs there, in degrees counter-clockwise on the page. + pub tangent: f64, + /// The radius of curvature there (pt); `None` where the path runs straight. + pub radius: Option, + /// The anchor near the pointer, when one is. + pub anchor: Option, +} + +/// An anchor's readouts. +#[derive(Clone, Debug, PartialEq)] +pub struct AnchorInspection { + pub index: usize, + pub p: Point, + pub smooth: bool, + /// The angle the path makes at the anchor (degrees: 90 at a square's corner, 180 where it runs + /// straight on); `None` at an open end. + pub angle: Option, + /// Each handle's (length, direction): `None` for no handle. + pub handle_in: Option<(f64, f64)>, + pub handle_out: Option<(f64, f64)>, +} + +/// Radius of curvature of `c` at `t`: `None` where it runs straight or has no direction. +fn radius_at(c: &CubicBez, t: f64) -> Option { + use kurbo::ParamCurveDeriv; + let d1 = c.deriv(); + let d = d1.eval(t).to_vec2(); + let dd = d1.deriv().eval(t).to_vec2(); + let speed = d.hypot(); + let k = d.cross(dd) / (speed * speed * speed); + (speed > TINY && k.is_finite() && k.abs() > 1e-9).then(|| 1.0 / k.abs()) +} + +/// The direction `c` runs at `t` (unit), falling back to its chord's ends where the derivative +/// vanishes (a retracted handle). +fn tangent_at(c: &CubicBez, t: f64) -> Vec2 { + use kurbo::ParamCurveDeriv; + unit(c.deriv().eval(t).to_vec2()).unwrap_or_else(|| if t < 0.5 { start_tangent(c) } else { end_tangent(c) }) +} + +/// The readouts of anchor `i` of `sp`. +pub fn inspect_anchor(sp: &SubPath, i: usize) -> Option { + let a = sp.anchors.get(i)?; + let (prev, next) = neighbours(sp, i); + let angle = match (prev, next) { + (Some(pr), Some(_)) if sp.segment_count() > 0 => { + let (into, out) = (end_tangent(&sp.segment(pr)), start_tangent(&sp.segment(i))); + Some((-into).dot(out).clamp(-1.0, 1.0).acos().to_degrees()) + } + _ => None, + }; + Some(AnchorInspection { + index: i, + p: a.p, + smooth: a.kind == AnchorKind::Smooth, + angle, + handle_in: handle_polar(a.p, a.h_in), + handle_out: handle_polar(a.p, a.h_out), + }) +} + +/// What `path` reads at `p`: its point nearest `p` and the readouts there, and the anchor within +/// `tol` of `p` if one is. `None` for a path with no segments or one with a non-finite coordinate. +pub fn inspect(path: &PathData, p: Point, tol: f64) -> Option { + let finite = |q: Point| q.x.is_finite() && q.y.is_finite(); + if !finite(p) || !path.anchors().all(|(_, _, a)| finite(a.p) && finite(a.h_in) && finite(a.h_out)) { + return None; + } + let (si, seg, t, point, _) = path.nearest(p)?; + let sp = path.subpaths.get(si)?; + let c = sp.segment(seg); + let anchor = [(seg, c.p0), ((seg + 1) % sp.anchors.len(), c.p3)] + .into_iter() + .filter(|(_, q)| q.distance(p) <= tol) + .min_by(|a, b| a.1.distance(p).total_cmp(&b.1.distance(p))) + .and_then(|(i, _)| inspect_anchor(sp, i)); + Some(Inspection { + subpath: si, + closed: sp.closed, + anchors: sp.anchors.len(), + length: (0..sp.segment_count()).map(|s| sp.segment(s).arclen(ACCURACY)).sum(), + area: sp.signed_area().abs(), + segment: seg, + t, + point, + segment_length: c.arclen(ACCURACY), + tangent: angle_of(tangent_at(&c, t)), + radius: radius_at(&c, t), + anchor, + }) +} + +/// The point of `sp`'s segments nearest `p`: (segment, t, distance). +pub(crate) fn nearest_on(sp: &SubPath, p: Point) -> Option<(usize, f64, f64)> { + (0..sp.segment_count()) + .map(|s| { + let n = sp.segment(s).nearest(p, ACCURACY); + (s, n.t, n.distance_sq.sqrt()) + }) + .min_by(|a, b| a.2.total_cmp(&b.2)) +} diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs new file mode 100644 index 0000000000..8598e42081 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -0,0 +1,192 @@ +//! Where paths cross: [`crossings`] finds the places, [`insert_at`] puts anchors there (which +//! Split / Add Points at Crossings then keeps or cuts at). + +use std::collections::{BTreeMap, BTreeSet}; + +use kurbo::{CubicBez, ParamCurve, ParamCurveNearest, Point, Rect}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; + +/// Most segments [`crossings`] compares at once. +pub const MAX_CROSSING_SEGMENTS: usize = 10_000; +/// Most subdivision steps one [`crossings`] call takes. +const MAX_STEPS: usize = 4_000_000; +/// A piece of curve whose inner control points lie this close (pt) to its chord counts as straight. +const FLAT: f64 = 1e-4; +/// Deepest a curve is halved. +const MAX_DEPTH: u32 = 96; +/// Crossings closer than this (pt) are one. +const SAME: f64 = 1e-3; +/// A parameter this close to a segment's end is its anchor. +const END: f64 = 1e-6; + +/// A place on a path: (subpath, segment, t). +pub type Place = (usize, usize, f64); + +fn control_box(c: &CubicBez) -> Rect { + Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3) +} + +fn flat(c: &CubicBez) -> bool { + let chord = c.p3 - c.p0; + let len = chord.hypot(); + let off = |p: Point| if len > 1e-12 { chord.cross(p - c.p0).abs() / len } else { p.distance(c.p0) }; + off(c.p1) <= FLAT && off(c.p2) <= FLAT +} + +/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel +/// ones never do). +fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { + let (da, db) = (a.p3 - a.p0, b.p3 - b.p0); + let den = da.cross(db); + if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 { + return None; + } + let w = b.p0 - a.p0; + let (s, u) = (w.cross(db) / den, w.cross(da) / den); + let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); + (within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0))) +} + +/// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control +/// boxes meet until each piece is straight. `None` once `budget` steps are spent. +fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option> { + let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)]; + let mut found: Vec<(f64, f64)> = vec![]; + while let Some((a0, a1, b0, b1, depth)) = stack.pop() { + *budget = budget.checked_sub(1)?; + let (ca, cb) = (a.subsegment(a0..a1), b.subsegment(b0..b1)); + if !control_box(&ca).inflate(SAME, SAME).overlaps(control_box(&cb)) { + continue; + } + if (flat(&ca) && flat(&cb)) || depth >= MAX_DEPTH { + if let Some((s, u)) = chords_cross(&ca, &cb) { + // The pieces are straight but their parameters needn't run evenly along them. + let x = ca.p0.lerp(ca.p3, s); + let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t); + found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0))); + } + continue; + } + // Halve the larger of the pieces still curved: two curves lying along each other then + // split along their length, not into every pair of pieces. + let size = |c: &CubicBez| if flat(c) { -1.0 } else { control_box(c).size().to_vec2().hypot() }; + let d = depth + 1; + if size(&ca) >= size(&cb) { + let am = (a0 + a1) / 2.0; + stack.extend([(a0, am, b0, b1, d), (am, a1, b0, b1, d)]); + } else { + let bm = (b0 + b1) / 2.0; + stack.extend([(a0, a1, b0, bm, d), (a0, a1, bm, b1, d)]); + } + } + found.sort_by(|x, y| x.0.total_cmp(&y.0)); + // The same crossing found by neighbouring pieces counts once. + found.dedup_by(|x, y| a.eval(x.0).distance(a.eval(y.0)) < SAME && b.eval(x.1).distance(b.eval(y.1)) < SAME); + Some(found) +} + +/// Do segments `i` and `j` of `sp` meet at an anchor they share? +fn adjacent(sp: &SubPath, i: usize, j: usize) -> bool { + let n = sp.segment_count(); + i.abs_diff(j) == 1 || (sp.closed && n > 1 && i.abs_diff(j) == n - 1) +} + +/// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself): for +/// each path, the places on it, in order. Segments that meet at an anchor they share don't count as +/// crossing there. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled +/// to sort out, or when a coordinate isn't finite. +pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option>> { + let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![]; + for (k, path) in paths.iter().enumerate() { + for (si, sp) in path.subpaths.iter().enumerate() { + for s in 0..sp.segment_count() { + let c = sp.segment(s); + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { + return None; + } + segs.push((k, si, s, c, control_box(&c))); + if segs.len() > MAX_CROSSING_SEGMENTS { + return None; + } + } + } + } + let mut out: Vec> = vec![vec![]; paths.len()]; + let mut budget = MAX_STEPS; + for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() { + for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) { + if ka == kb + && (!self_crossings || (sa == sb && paths.get(*ka).and_then(|p| p.subpaths.get(*sa)).is_some_and(|sp| adjacent(sp, *ia, *ib)))) + { + continue; + } + if !ra.inflate(SAME, SAME).overlaps(*rb) { + continue; + } + for (ta, tb) in segment_crossings(ca, cb, &mut budget)? { + out.get_mut(*ka)?.push((*sa, *ia, ta)); + out.get_mut(*kb)?.push((*sb, *ib, tb)); + } + } + } + for places in &mut out { + places.sort_by(|x, y| (x.0, x.1).cmp(&(y.0, y.1)).then(x.2.total_cmp(&y.2))); + places.dedup_by(|x, y| (x.0, x.1) == (y.0, y.1) && (x.2 - y.2).abs() < END); + } + Some(out) +} + +/// `sp` with an anchor at each of `places` (segment, t), the shape unchanged → (the subpath, the +/// indexes of the anchors at those places: the new ones, and existing ones where a place falls on +/// an anchor). Places off the subpath are left out. +pub fn insert_at(sp: &SubPath, places: &[(usize, f64)]) -> (SubPath, BTreeSet) { + let (n, segs) = (sp.anchors.len(), sp.segment_count()); + let mut inner: BTreeMap> = BTreeMap::new(); + let mut at_anchor = vec![]; + for &(seg, t) in places.iter().filter(|(seg, t)| *seg < segs && t.is_finite()) { + match t { + _ if t <= END => at_anchor.push(seg), + _ if t >= 1.0 - END => at_anchor.push((seg + 1) % n), + _ => inner.entry(seg).or_default().push(t), + } + } + for ts in inner.values_mut() { + ts.sort_by(f64::total_cmp); + ts.dedup_by(|x, y| (*x - *y).abs() < END); + } + // Each split segment's pieces, cut from the original curve so their parameters stay true. + let mut anchors = sp.anchors.clone(); + let mut added: BTreeMap> = BTreeMap::new(); + for (&seg, ts) in &inner { + let c = sp.segment(seg); + let bounds: Vec = std::iter::once(0.0).chain(ts.iter().copied()).chain([1.0]).collect(); + let pieces: Vec = bounds.windows(2).filter_map(|w| Some(c.subsegment(*w.first()?..*w.get(1)?))).collect(); + if sp.segment_is_line(seg) { + added.insert(seg, pieces.iter().skip(1).map(|q| Anchor::corner(q.p0)).collect()); + continue; + } + let made = pieces.windows(2).filter_map(|w| match w { + [a, b] => Some(Anchor { p: b.p0, h_in: a.p2, h_out: b.p1, kind: AnchorKind::Smooth }), + _ => None, + }); + added.insert(seg, made.collect()); + if let (Some(first), Some(a)) = (pieces.first(), anchors.get_mut(seg)) { + a.h_out = first.p1; + } + if let (Some(last), Some(a)) = (pieces.last(), anchors.get_mut((seg + 1) % n)) { + a.h_in = last.p2; + } + } + let mut out = SubPath::new(Vec::with_capacity(n + places.len()), sp.closed); + for (i, a) in anchors.into_iter().enumerate() { + out.anchors.push(a); + out.anchors.extend(added.remove(&i).unwrap_or_default()); + } + let added_before = |j: usize| inner.range(..j).map(|(_, v)| v.len()).sum::(); + let mut marks: BTreeSet = at_anchor.into_iter().map(|j| j + added_before(j)).collect(); + for (&seg, ts) in &inner { + let base = seg + added_before(seg); + marks.extend((1..=ts.len()).map(|m| base + m)); + } + (out, marks) +} diff --git a/crates/pathops/src/addons/pathtools/extend.rs b/crates/pathops/src/addons/pathtools/extend.rs new file mode 100644 index 0000000000..d86e70366d --- /dev/null +++ b/crates/pathops/src/addons/pathtools/extend.rs @@ -0,0 +1,220 @@ +//! Lengthen an open path at one end, carrying on the way it runs there, or shorten it back along +//! itself: [`extend_open`], and [`extend_length_to`] for the length that brings the end nearest a +//! point (what a drag asks for). + +use std::f64::consts::{FRAC_PI_2, PI}; + +use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, Point, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, SubPath}; + +use super::{ACCURACY, TINY, nearest_on}; +use crate::fit::end_tangent; + +/// How an end carries on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExtendMode { + /// In a straight line along the end's direction. + Straight, + /// By stretching the last segment's curve on past its end (no anchor added). + Bezier, + /// Along the circle that matches the end's curvature, at most half way round. + Arc, +} + +impl ExtendMode { + pub const ALL: [Self; 3] = [Self::Straight, Self::Bezier, Self::Arc]; + + pub fn id(self) -> &'static str { + match self { + Self::Straight => "straight", + Self::Bezier => "bezier", + Self::Arc => "arc", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.id() == s) + } +} + +/// The least length (pt) shortening leaves of a path. +const MIN_LEFT: f64 = 1e-3; +/// An end straighter than this radius (pt) carries on in a straight line in [`ExtendMode::Arc`]. +const MAX_RADIUS: f64 = 1e6; +/// The farthest (in its parameter) [`ExtendMode::Bezier`] stretches a segment. +const MAX_STRETCH: f64 = 1024.0; + +fn finite(sp: &SubPath) -> bool { + let ok = |p: Point| p.x.is_finite() && p.y.is_finite(); + sp.anchors.iter().all(|a| ok(a.p) && ok(a.h_in) && ok(a.h_out)) +} + +fn length(sp: &SubPath) -> f64 { + (0..sp.segment_count()).map(|s| sp.segment(s).arclen(ACCURACY)).sum() +} + +/// The last segment of an open subpath of two anchors or more. +fn last_segment(sp: &SubPath) -> Option { + let n = sp.segment_count(); + (n > 0).then(|| sp.segment(n - 1)) +} + +/// Open subpath `sp` (two anchors or more) lengthened by `length` pt at its first (`at_start`) or +/// last anchor the way `mode` says, or shortened along itself by a negative `length`. `None` when it +/// is closed, too short, not finite, or shortening would leave nothing of it. +pub fn extend_open(sp: &SubPath, at_start: bool, length: f64, mode: ExtendMode) -> Option { + if sp.closed || sp.anchors.len() < 2 || !length.is_finite() || !finite(sp) { + return None; + } + let mut s = sp.clone(); + if at_start { + s.reverse(); + } + let mut out = match mode { + _ if length < 0.0 => trim_end(&s, -length)?, + _ if length == 0.0 => s, + ExtendMode::Straight => straight_end(s, length)?, + ExtendMode::Bezier => bezier_end(s, length)?, + ExtendMode::Arc => arc_end(s, length)?, + }; + if at_start { + out.reverse(); + } + Some(out) +} + +/// The length (pt) [`extend_open`] takes to bring the end of `sp` nearest `to`: positive along the +/// way `mode` carries the end on, negative back along the path (never all of it). `None` when there +/// is no such end. +pub fn extend_length_to(sp: &SubPath, at_start: bool, to: Point, mode: ExtendMode) -> Option { + if !(to.x.is_finite() && to.y.is_finite()) { + return None; + } + let mut s = sp.clone(); + if at_start { + s.reverse(); + } + let total = length(&s); + let end = s.anchors.last()?.p; + // Long enough to reach past the pointer; the original stays a prefix of the result. + let probe = (to.distance(end) * 2.0).max(1.0); + let ext = extend_open(&s, false, probe, mode)?; + let (seg, t, _) = nearest_on(&ext, to)?; + let before: f64 = (0..seg).map(|k| ext.segment(k).arclen(ACCURACY)).sum(); + let along = before + ext.segment(seg).subsegment(0.0..t).arclen(ACCURACY); + Some((along - total).max(MIN_LEFT - total)) +} + +/// `sp` with `cut` pt taken off its end. +fn trim_end(sp: &SubPath, cut: f64) -> Option { + if cut >= length(sp) - MIN_LEFT { + return None; + } + let mut s = sp.clone(); + let mut left = cut; + while left > 0.0 { + let c = last_segment(&s)?; + let len = c.arclen(ACCURACY); + let line = s.segment_is_line(s.segment_count() - 1); + if left >= len { + s.anchors.pop(); + left -= len; + if let Some(a) = s.anchors.last_mut() { + a.h_out = a.p; + a.kind = AnchorKind::Corner; + } + continue; + } + let part = c.subsegment(0.0..c.inv_arclen(len - left, ACCURACY)); + let k = s.anchors.len(); + if let Some(a) = s.anchors.get_mut(k - 2).filter(|_| !line) { + a.h_out = part.p1; + } + if let Some(a) = s.anchors.last_mut() { + *a = if line { Anchor::corner(part.p3) } else { Anchor { p: part.p3, h_in: part.p2, h_out: part.p3, kind: AnchorKind::Corner } }; + } + break; + } + (s.anchors.len() >= 2).then_some(s) +} + +/// `sp` with a straight segment `len` pt long added at its end, along its end's direction. +fn straight_end(mut s: SubPath, len: f64) -> Option { + let dir = end_tangent(&last_segment(&s)?); + let a = s.anchors.last_mut()?; + a.h_out = a.p; + let p = a.p + dir * len; + s.anchors.push(Anchor::corner(p)); + Some(s) +} + +/// `sp` with its last segment's curve stretched on by `len` pt (its end anchor moved, no anchor +/// added); a straight last segment just grows. +fn bezier_end(mut s: SubPath, len: f64) -> Option { + let c = last_segment(&s)?; + let k = s.anchors.len(); + if s.segment_is_line(k - 2) { + let p = c.p3 + end_tangent(&c) * len; + *s.anchors.last_mut()? = Anchor::corner(p); + return Some(s); + } + let target = c.arclen(ACCURACY) + len; + let reach = |t: f64| c.subsegment(0.0..t).arclen(ACCURACY); + let mut hi = 2.0; + while reach(hi) < target && hi < MAX_STRETCH { + hi *= 2.0; + } + let mut lo = 1.0; + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if reach(mid) < target { lo = mid } else { hi = mid } + } + let ext = c.subsegment(0.0..hi); + s.anchors.get_mut(k - 2)?.h_out = ext.p1; + *s.anchors.last_mut()? = Anchor { p: ext.p3, h_in: ext.p2, h_out: ext.p3, kind: AnchorKind::Corner }; + Some(s) +} + +/// The signed radius of the circle through three points (positive when the turn from `a` through +/// `b` to `c` is counter-clockwise in the x→y sense); `None` when they lie in a line. +fn signed_radius(a: Point, b: Point, c: Point) -> Option { + let cross = (b - a).cross(c - b); + let r = (b - a).hypot() * (c - b).hypot() * (c - a).hypot() / (2.0 * cross.abs()); + (cross.abs() > TINY && r.is_finite()).then(|| r.copysign(cross)) +} + +/// `v` turned by `a` radians (x toward y). +fn rot(v: Vec2, a: f64) -> Vec2 { + let (s, c) = a.sin_cos(); + Vec2::new(v.x * c - v.y * s, v.x * s + v.y * c) +} + +/// `sp` carried on by an arc `len` pt long (at most half a circle) of the circle that leaves its +/// end in its direction with the curvature it ends with; straight where it ends straight. +fn arc_end(mut s: SubPath, len: f64) -> Option { + let c = last_segment(&s)?; + let dir = end_tangent(&c); + let Some(r) = signed_radius(c.eval(0.96), c.eval(0.98), c.p3).filter(|r| r.abs() <= MAX_RADIUS) else { return straight_end(s, len) }; + let radius = r.abs(); + let turn = (len / radius).min(PI).copysign(r); + let normal: Vec2 = Vec2::new(-dir.y, dir.x) * r.signum(); + let p = c.p3; + let centre = p + normal * radius; + let pieces = (turn.abs() / FRAC_PI_2).ceil().max(1.0) as usize; + let step = turn / pieces as f64; + let h = 4.0 / 3.0 * (step.abs() / 4.0).tan() * radius; + let at = |phi: f64| (centre + rot(p - centre, phi), rot(dir, phi)); + let first = at(0.0); + let end = s.anchors.last_mut()?; + end.h_out = first.0 + first.1 * h; + if end.has_in() { + end.kind = AnchorKind::Smooth; + } + for j in 1..=pieces { + let (q, t) = at(step * j as f64); + let h_out = if j < pieces { q + t * h } else { q }; + let kind = if j < pieces { AnchorKind::Smooth } else { AnchorKind::Corner }; + s.anchors.push(Anchor { p: q, h_in: q - t * h, h_out, kind }); + } + Some(s) +} diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs new file mode 100644 index 0000000000..dc2203a0e0 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -0,0 +1,296 @@ +use std::collections::BTreeSet; + +use kurbo::{ParamCurve, ParamCurveArclen, Point, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; + +use super::*; +use crate::addons::simplify_anchors_keep_shape; + +fn pt(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn line(pts: &[(f64, f64)], closed: bool) -> SubPath { + SubPath::polyline(&pts.iter().map(|&(x, y)| pt(x, y)).collect::>(), closed) +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +fn length(sp: &SubPath) -> f64 { + (0..sp.segment_count()).map(|i| sp.segment(i).arclen(1e-6)).sum() +} + +/// The farthest any sampled point of `sp` lies off the circle about `c` of radius `r`. +fn off_circle(sp: &SubPath, c: Point, r: f64) -> f64 { + (0..sp.segment_count()) + .flat_map(|i| (0..=16).map(move |k| (i, k as f64 / 16.0))) + .map(|(i, t)| (sp.segment(i).eval(t).distance(c) - r).abs()) + .fold(0.0, f64::max) +} + +#[test] +fn auto_smooth_turns_a_square_into_a_circle() { + let mut sq = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true); + for i in 0..4 { + assert!(auto_smooth(&mut sq, i, SMOOTH_RATIO)); + } + let a = sq.anchors[1]; + assert_eq!(a.kind, AnchorKind::Smooth); + // Each handle is the ratio × the side long, at right angles to the corner's bisector. + assert!(near((a.h_out - a.p).hypot(), 39.05, 1e-9) && near((a.h_in - a.p).hypot(), 39.05, 1e-9)); + assert!(near((a.h_out - a.p).dot(Vec2::new(-1.0, 1.0)), 0.0, 1e-9)); + // The four corners make a circle through them, to within its cubic approximation. + assert!(off_circle(&sq, pt(50.0, 50.0), 50f64.hypot(50.0)) < 0.2, "{}", off_circle(&sq, pt(50.0, 50.0), 50f64.hypot(50.0))); + // A smooth anchor stays as it is. + assert!(!auto_smooth(&mut sq, 1, SMOOTH_RATIO)); +} + +#[test] +fn auto_smooth_mirrors_a_lone_handle_and_aims_open_ends() { + let mut sp = SubPath::new( + vec![Anchor::corner(pt(0.0, 0.0)), Anchor::with_handles(pt(50.0, 0.0), pt(40.0, -10.0), pt(50.0, 0.0)), Anchor::corner(pt(100.0, 0.0))], + false, + ); + assert!(auto_smooth(&mut sp, 1, SMOOTH_RATIO)); + assert_eq!(sp.anchors[1].h_out, pt(60.0, 10.0)); + // An open end with no handle aims at its neighbour's facing handle. + assert!(auto_smooth(&mut sp, 0, SMOOTH_RATIO)); + let h = sp.anchors[0].h_out; + assert!(near(h.distance(pt(0.0, 0.0)), 50.0 * SMOOTH_RATIO, 1e-9)); + assert!(near((h - pt(0.0, 0.0)).cross(pt(40.0, -10.0) - pt(0.0, 0.0)), 0.0, 1e-9), "{h:?}"); + // Two handles out of line are brought into line, keeping their lengths. + let mut bent = SubPath::new( + vec![Anchor::corner(pt(0.0, 0.0)), Anchor::with_handles(pt(50.0, 0.0), pt(40.0, 0.0), pt(50.0, 20.0)), Anchor::corner(pt(100.0, 0.0))], + false, + ); + assert!(auto_smooth(&mut bent, 1, SMOOTH_RATIO)); + let a = bent.anchors[1]; + assert!( + near((a.h_in - a.p).cross(a.h_out - a.p), 0.0, 1e-9) && near((a.h_out - a.p).hypot(), 20.0, 1e-9) && near((a.h_in - a.p).hypot(), 10.0, 1e-9) + ); +} + +#[test] +fn equalise_averages_lengths_and_makes_a_missing_handle() { + let mut sp = SubPath::new( + vec![Anchor::corner(pt(0.0, 0.0)), Anchor::with_handles(pt(50.0, 0.0), pt(40.0, 0.0), pt(80.0, 0.0)), Anchor::corner(pt(100.0, 0.0))], + false, + ); + assert!(equalize_handles(&mut sp, 1)); + assert_eq!((sp.anchors[1].h_in, sp.anchors[1].h_out), (pt(30.0, 0.0), pt(70.0, 0.0))); + assert!(!equalize_handles(&mut sp, 1), "already equal"); + let mut one = SubPath::new( + vec![Anchor::corner(pt(0.0, 0.0)), Anchor::with_handles(pt(50.0, 0.0), pt(50.0, 0.0), pt(50.0, 20.0)), Anchor::corner(pt(100.0, 0.0))], + false, + ); + assert!(equalize_handles(&mut one, 1)); + assert_eq!(one.anchors[1].h_in, pt(50.0, -20.0)); + assert!(!equalize_handles(&mut one, 0), "no handles to equalise"); +} + +#[test] +fn make_corner_retracts_or_keeps_handles() { + let a = Anchor::smooth(pt(50.0, 0.0), pt(60.0, 0.0)); + let mut sp = SubPath::new(vec![Anchor::corner(pt(0.0, 0.0)), a, Anchor::corner(pt(100.0, 0.0))], false); + assert!(make_corner(&mut sp, 1, false)); + assert_eq!((sp.anchors[1].kind, sp.anchors[1].h_out), (AnchorKind::Corner, pt(60.0, 0.0))); + assert!(make_corner(&mut sp, 1, true)); + assert!(!sp.anchors[1].has_in() && !sp.anchors[1].has_out()); +} + +#[test] +fn add_points_splits_segments_into_equal_lengths() { + let sp = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 40.0)], false); + let (out, added) = add_points(&sp, Some(&BTreeSet::from([0])), 3); + let xs: Vec = out.anchors.iter().map(|a| a.p.x).collect(); + for (x, want) in xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0, 100.0]) { + assert!(near(*x, want, 1e-4), "{xs:?}"); + } + assert_eq!((xs.len(), added), (6, BTreeSet::from([1, 2, 3]))); + // On a curve the pieces have the same length and the shape stays. + let mut sq = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true); + for i in 0..4 { + auto_smooth(&mut sq, i, SMOOTH_RATIO); + } + let (out, added) = add_points(&sq, None, 2); + assert_eq!((out.anchors.len(), added.len()), (12, 8)); + let lens: Vec = (0..3).map(|i| out.segment(i).arclen(1e-6)).collect(); + assert!(near(lens[0], lens[1], 1e-3) && near(lens[1], lens[2], 1e-3), "{lens:?}"); + assert!(near(length(&out), length(&sq), 1e-4)); +} + +#[test] +fn close_joins_ends_three_ways() { + let open = SubPath::new( + vec![Anchor::with_handles(pt(0.0, 0.0), pt(-10.0, 10.0), pt(10.0, -10.0)), Anchor::corner(pt(100.0, 0.0)), Anchor::corner(pt(50.0, 80.0))], + false, + ); + let mut kept = open.clone(); + assert!(close(&mut kept, CloseMode::Handles, SMOOTH_RATIO)); + assert!(kept.closed && kept.anchors[0].h_in == pt(-10.0, 10.0)); + let mut straight = open.clone(); + assert!(close(&mut straight, CloseMode::Straight, SMOOTH_RATIO)); + assert!(straight.closed && straight.segment_is_line(2)); + let mut smooth = open.clone(); + assert!(close(&mut smooth, CloseMode::Smooth, SMOOTH_RATIO)); + assert!(smooth.anchors[2].has_in() && smooth.anchors[2].has_out(), "the last anchor is made smooth"); + assert!(!close(&mut smooth, CloseMode::Smooth, SMOOTH_RATIO), "closed already"); + assert_eq!(CloseMode::parse("straight"), Some(CloseMode::Straight)); +} + +#[test] +fn extend_straight_lengthens_and_shortens_either_end() { + let sp = line(&[(0.0, 0.0), (100.0, 0.0)], false); + let end = extend_open(&sp, false, 50.0, ExtendMode::Straight).unwrap(); + assert_eq!(end.anchors.last().unwrap().p, pt(150.0, 0.0)); + let start = extend_open(&sp, true, 20.0, ExtendMode::Straight).unwrap(); + assert_eq!(start.anchors.first().unwrap().p, pt(-20.0, 0.0)); + let short = extend_open(&sp, false, -30.0, ExtendMode::Straight).unwrap(); + assert_eq!(short.anchors.len(), 2); + assert!(near(short.anchors[1].p.x, 70.0, 1e-6)); + // Shortening past an anchor drops it. + let bent = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 10.0)], false); + let cut = extend_open(&bent, false, -40.0, ExtendMode::Straight).unwrap(); + assert_eq!(cut.anchors.len(), 2); + assert!(near(cut.anchors[1].p.x, 70.0, 1e-6)); + // Nothing is left of a path shortened by its whole length; closed paths have no ends. + assert!(extend_open(&sp, false, -100.0, ExtendMode::Straight).is_none()); + assert!(extend_open(&line(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], true), false, 5.0, ExtendMode::Straight).is_none()); + assert!(extend_open(&sp, false, f64::NAN, ExtendMode::Arc).is_none()); +} + +/// A quarter of the circle of radius 100 about the origin, from (100, 0) to (0, 100). +fn quarter() -> SubPath { + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan() * 100.0; + SubPath::new( + vec![Anchor::with_handles(pt(100.0, 0.0), pt(100.0, 0.0), pt(100.0, k)), Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(0.0, 100.0))], + false, + ) +} + +#[test] +fn extend_arc_follows_the_circle_the_end_curves_along() { + let sp = quarter(); + let len = std::f64::consts::FRAC_PI_2 * 100.0; + let out = extend_open(&sp, false, len, ExtendMode::Arc).unwrap(); + // The circle matches the curvature the (cubic) quarter ends with, within a percent or so of + // the true circle's. + assert!(off_circle(&out, Point::ORIGIN, 100.0) < 3.0, "{}", off_circle(&out, Point::ORIGIN, 100.0)); + let end = out.anchors.last().unwrap().p; + assert!(end.distance(pt(-100.0, 0.0)) < 5.0, "{end:?}"); + assert!(near(length(&out), 2.0 * len, 0.2)); + // At most half way round. + let long = extend_open(&sp, false, 10.0 * len, ExtendMode::Arc).unwrap(); + assert!(near(length(&long) - len, std::f64::consts::PI * 100.0, 6.0), "{}", length(&long) - len); + // A straight end carries on straight. + let straight = extend_open(&line(&[(0.0, 0.0), (10.0, 0.0)], false), false, 5.0, ExtendMode::Arc).unwrap(); + assert_eq!(straight.anchors.last().unwrap().p, pt(15.0, 0.0)); +} + +#[test] +fn extend_bezier_stretches_the_last_curve_without_new_anchors() { + let sp = quarter(); + let before = length(&sp); + let out = extend_open(&sp, false, 30.0, ExtendMode::Bezier).unwrap(); + assert_eq!(out.anchors.len(), 2); + assert!(near(length(&out), before + 30.0, 1e-3), "{}", length(&out)); + let p = out.segment(0).eval(0.5); + assert!((p.to_vec2().hypot() - 100.0).abs() < 15.0); +} + +#[test] +fn the_length_a_drag_asks_for() { + let sp = line(&[(0.0, 0.0), (100.0, 0.0)], false); + assert!(near(extend_length_to(&sp, false, pt(130.0, 10.0), ExtendMode::Straight).unwrap(), 30.0, 1e-6)); + assert!(near(extend_length_to(&sp, false, pt(40.0, 5.0), ExtendMode::Straight).unwrap(), -60.0, 1e-6)); + assert!(near(extend_length_to(&sp, true, pt(-25.0, 3.0), ExtendMode::Straight).unwrap(), 25.0, 1e-6)); + // Never the whole path. + assert!(extend_length_to(&sp, false, pt(-50.0, 0.0), ExtendMode::Straight).unwrap() > -100.0); + let arc = extend_length_to(&quarter(), false, pt(-100.0, 0.0), ExtendMode::Arc).unwrap(); + assert!(near(arc, std::f64::consts::FRAC_PI_2 * 100.0, 3.0), "{arc}"); + assert!(extend_length_to(&sp, false, pt(f64::NAN, 0.0), ExtendMode::Straight).is_none()); +} + +#[test] +fn crossings_are_found_on_both_paths() { + let a = PathData::single(line(&[(0.0, 0.0), (100.0, 100.0)], false)); + let b = PathData::single(line(&[(0.0, 100.0), (100.0, 0.0)], false)); + let hits = crossings(&[&a, &b], false).unwrap(); + assert_eq!(hits.len(), 2); + assert_eq!(hits[0].len(), 1); + assert!(near(hits[0][0].2, 0.5, 1e-6) && near(hits[1][0].2, 0.5, 1e-6)); + // A circle crossed by a line: twice. + let mut circle = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true); + for i in 0..4 { + auto_smooth(&mut circle, i, SMOOTH_RATIO); + } + let across = PathData::single(line(&[(-40.0, 50.0), (140.0, 50.0)], false)); + let circle = PathData::single(circle); + let hits = crossings(&[&circle, &across], false).unwrap(); + assert_eq!((hits[0].len(), hits[1].len()), (2, 2), "{hits:?}"); + // A path doesn't cross itself where its segments meet, and only crosses itself when asked. + let bow = PathData::single(line(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)], false)); + assert!(crossings(&[&bow], false).unwrap()[0].is_empty()); + assert_eq!(crossings(&[&bow], true).unwrap()[0].len(), 2, "one crossing, on two of its segments"); + // Two identical paths lying on each other don't tangle the search. + let sq = PathData::single(circle.subpaths[0].clone()); + assert!(crossings(&[&sq, &circle], false).is_some()); + // A path ending on another meets it there: at its end anchor, and part way along the other. + let t = PathData::single(line(&[(50.0, 50.0), (50.0, 150.0)], false)); + let hits = crossings(&[&b, &t], false).unwrap(); + assert_eq!((hits[0].len(), hits[1].len()), (1, 1), "{hits:?}"); + assert!(near(hits[1][0].2, 0.0, 1e-6) && near(b.subpaths[0].segment(0).eval(hits[0][0].2).x, 50.0, 1e-6)); +} + +#[test] +fn insert_at_keeps_the_shape_and_names_the_new_anchors() { + let sp = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false); + let (out, marks) = insert_at(&sp, &[(1, 0.5), (0, 0.25), (0, 0.75), (1, 1.0), (7, 0.5)]); + let pts: Vec = out.anchors.iter().map(|a| a.p).collect(); + let c = sp.segment(0); + let want = [pt(0.0, 0.0), c.eval(0.25), c.eval(0.75), pt(100.0, 0.0), pt(100.0, 50.0), pt(100.0, 100.0)]; + assert_eq!(pts.len(), want.len()); + assert!(pts.iter().zip(want).all(|(p, w)| p.distance(w) < 1e-9), "{pts:?}"); + assert_eq!(marks, BTreeSet::from([1, 2, 4, 5])); + // The closing segment of a closed path. + let tri = line(&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)], true); + let (out, marks) = insert_at(&tri, &[(2, 0.5)]); + assert_eq!((out.anchors.len(), out.anchors[3].p, marks), (4, pt(0.0, 50.0), BTreeSet::from([3]))); +} + +#[test] +fn inspect_reads_lengths_area_angles_and_curvature() { + let rect = PathData::single(line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], true)); + let i = inspect(&rect, pt(50.0, 1.0), 3.0).unwrap(); + assert_eq!((i.closed, i.anchors, i.segment), (true, 4, 0)); + assert!(near(i.length, 300.0, 1e-6) && near(i.area, 5000.0, 1e-6) && near(i.segment_length, 100.0, 1e-6)); + assert_eq!((i.radius, i.anchor.is_none()), (None, true)); + let corner = inspect(&rect, pt(99.0, 1.0), 3.0).unwrap().anchor.unwrap(); + assert_eq!(corner.index, 1); + assert!(near(corner.angle.unwrap(), 90.0, 1e-9)); + let r = inspect(&PathData::single(quarter()), pt(71.0, 71.0), 1.0).unwrap(); + assert!(near(r.radius.unwrap(), 100.0, 1.0), "{:?}", r.radius); + assert!(near(r.tangent, -135.0, 1.0), "{}", r.tangent); + let open = inspect(&PathData::single(quarter()), pt(100.0, 0.0), 1.0).unwrap().anchor.unwrap(); + assert_eq!(open.angle, None, "an open end has no angle"); + assert!(inspect(&PathData::default(), pt(0.0, 0.0), 1.0).is_none()); + // Handle readouts: length and direction counter-clockwise on the page. + assert_eq!(handle_polar(pt(0.0, 0.0), pt(0.0, -10.0)), Some((10.0, 90.0))); + assert!(handle_at(pt(0.0, 0.0), 10.0, 90.0).distance(pt(0.0, -10.0)) < 1e-9); +} + +#[test] +fn the_brush_kernel_removes_only_marked_anchors() { + let pts: Vec<(f64, f64)> = (0..=10).map(|i| (i as f64 * 10.0, 0.0)).collect(); + let sp = line(&pts, false); + let marked: Vec = (0..=10).map(|i| (3..=5).contains(&i)).collect(); + let out = simplify_anchors_keep_shape(&sp, 0.1, &marked); + let xs: Vec = out.anchors.iter().map(|a| a.p.x).collect(); + assert_eq!(xs, [0.0, 10.0, 20.0, 60.0, 70.0, 80.0, 90.0, 100.0]); + // Off the line, a removal within tolerance only. + let bump = line(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (30.0, 5.0), (40.0, 0.0)], false); + assert_eq!(simplify_anchors_keep_shape(&bump, 0.1, &[true; 5]).anchors.len(), 4, "only the anchor on the straight run goes"); + assert_eq!(simplify_anchors_keep_shape(&bump, f64::INFINITY, &[true; 5]).anchors.len(), 2, "unless tolerance is ignored"); +} diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 4a656f98fd..d73d25fd00 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -6,6 +6,7 @@ //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +pub mod addons; mod boolean; mod budget; mod edit; diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs new file mode 100644 index 0000000000..b34cfb1f57 --- /dev/null +++ b/crates/tools/src/addons.rs @@ -0,0 +1,53 @@ +//! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All +//! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's +//! submenu selects them. Like every tool they only emit commands (`addon..*`). + +pub mod anchor_eraser; +pub mod extend_path; +pub mod measure_inspect; + +use crate::{Tool, ToolInfo}; + +/// Path Precision Tools' tools, one flyout group. +pub const PATH_TOOLS: &[ToolInfo] = &[ + ToolInfo { id: anchor_eraser::ID, label: "Anchor Eraser Brush", shortcut: None, icon: "dc-remove-brush" }, + ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" }, + ToolInfo { id: measure_inspect::ID, label: "Measure & Inspect Tool", shortcut: None, icon: "ruler" }, +]; + +/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS]; + +/// The heading the All Tools drawer lists tool `id` under: its add-on's name. +pub fn heading(id: &str) -> Option<&'static str> { + PATH_TOOLS.iter().any(|t| t.id == id).then_some("Path Precision Tools") +} + +/// Create an add-on tool by id (None = not one of them). +pub fn create(id: &str) -> Option> { + Some(match id { + anchor_eraser::ID => Box::new(anchor_eraser::AnchorEraserTool::default()), + extend_path::ID => Box::new(extend_path::ExtendPathTool::default()), + measure_inspect::ID => Box::new(measure_inspect::MeasureInspectTool::default()), + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_addon_tool_is_made_and_catalogued_but_not_in_the_toolbar() { + for t in GROUPS.iter().flat_map(|g| g.iter()) { + assert_eq!(create(t.id).map(|tool| tool.id()), Some(t.id)); + assert_eq!(crate::tool_info(t.id).map(|i| i.label), Some(t.label)); + assert!(crate::create(t.id).id() == t.id); + assert!(t.shortcut.is_none(), "no default shortcut"); + assert!(!crate::TOOL_GROUPS.iter().any(|g| g.iter().any(|x| x.id == t.id)), "{} is not in the toolbar's groups", t.id); + assert_eq!(heading(t.id), Some("Path Precision Tools")); + } + assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID)); + assert!(create("pen").is_none() && heading("pen").is_none()); + } +} diff --git a/crates/tools/src/addons/anchor_eraser.rs b/crates/tools/src/addons/anchor_eraser.rs new file mode 100644 index 0000000000..1eae255bc2 --- /dev/null +++ b/crates/tools/src/addons/anchor_eraser.rs @@ -0,0 +1,231 @@ +//! Anchor Eraser Brush (Path Precision Tools): paint over selected paths and the anchors the round +//! brush passes over go, their neighbours' handles refitted, wherever the outline can do without +//! them within the tolerance (`addon.pathtools.erase`, previewed while painting, one undo step per +//! stroke). Alt removes every anchor under the brush that can go whatever the tolerance; Cmd/Ctrl +//! deletes them without refitting. `[` and `]` make the brush smaller and larger. With Pressure on, +//! a pen's pressure scales the brush. + +use serde_json::{Value, json}; +use vectorcraft_geom::Point; + +use crate::{Action, Cursor, MAX_STROKE_SAMPLES, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, previews_at}; + +/// The tool's id. +pub const ID: &str = "anchorEraserBrush"; +/// The brush's diameter on screen (px) by default, and its range. +pub const SIZE: f64 = 20.0; +pub const SIZE_RANGE: (f64, f64) = (1.0, 2500.0); +/// The tolerance by default and its range. +pub const TOLERANCE: f64 = 10.0; +pub const TOLERANCE_RANGE: (f64, f64) = (1.0, 100.0); +/// The undo step's name. +const LABEL: &str = "Anchor Eraser Brush"; +/// The brush's outline colour. +const RED: [u8; 3] = [0xe0, 0x30, 0x30]; + +pub struct AnchorEraserTool { + /// Diameter on screen (px). + size: f64, + tolerance: f64, + pressure: bool, + /// The stroke under way: its points and their pen pressure. + points: Vec<(Point, f32)>, + /// The modifiers the stroke started with: Alt ignores the tolerance, Cmd/Ctrl skips refitting. + mods: Mods, + painting: bool, + /// Where the brush is. + at: Option, +} + +impl Default for AnchorEraserTool { + fn default() -> Self { + Self { size: SIZE, tolerance: TOLERANCE, pressure: false, points: vec![], mods: Mods::default(), painting: false, at: None } + } +} + +impl AnchorEraserTool { + /// `addon.pathtools.erase`'s params for the stroke so far. + fn params(&self, cx: &ToolContext) -> Value { + let points: Vec = self + .points + .iter() + .map(|(p, f)| if self.pressure && *f < 1.0 { json!([p.x, p.y, (f64::from(*f) * 1000.0).round() / 1000.0]) } else { json!([p.x, p.y]) }) + .collect(); + json!({ + "points": points, + "diameter": cx.tol(self.size).clamp(0.1, SIZE_RANGE.1), + "tolerance": self.tolerance, + "ignoreTolerance": self.mods.alt, + "plain": self.mods.cmd, + }) + } +} + +impl Tool for AnchorEraserTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.painting + } + + fn wants_samples(&self) -> bool { + true + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.at = Some(ev.pos); + match ev.kind { + // Nothing selected: nothing to erase from. + PointerKind::Down if !cx.selection.objects.is_empty() => { + self.points = vec![(ev.pos, ev.pressure)]; + self.mods = ev.mods; + self.painting = true; + vec![Action::Begin(LABEL.into()), Action::Preview("addon.pathtools.erase".into(), self.params(cx))] + } + PointerKind::Drag if self.painting => { + if self.points.len() >= MAX_STROKE_SAMPLES { + return vec![]; + } + self.points.push((ev.pos, ev.pressure)); + if previews_at(self.points.len()) { vec![Action::Preview("addon.pathtools.erase".into(), self.params(cx))] } else { vec![] } + } + PointerKind::Up if self.painting => { + if self.points.len() < MAX_STROKE_SAMPLES && self.points.last().is_none_or(|(p, _)| *p != ev.pos) { + self.points.push((ev.pos, ev.pressure)); + } + self.painting = false; + let out = vec![Action::Preview("addon.pathtools.erase".into(), self.params(cx)), Action::Commit]; + self.points.clear(); + out + } + _ => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape if self.painting => { + self.painting = false; + self.points.clear(); + vec![Action::Cancel] + } + ToolKey::BracketLeft | ToolKey::BracketRight => { + let step = if key == ToolKey::BracketLeft { 1.0 / 1.25 } else { 1.25 }; + self.size = (self.size * step).round().clamp(SIZE_RANGE.0, SIZE_RANGE.1); + vec![] + } + _ => vec![], + } + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + matches!(key, ToolKey::BracketLeft | ToolKey::BracketRight) || (self.painting && key == ToolKey::Escape) + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.at = None; + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let Some(at) = self.at else { return vec![] }; + let r = cx.tol(self.size / 2.0); + let circle = kurbo::Shape::to_path(&kurbo::Circle::new(at, r), 0.1 * r.max(1e-6)); + vec![Overlay::Path { path: circle, color: RED, width: 1.0, dashed: false }] + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::AnchorEraser + } + + fn options(&self) -> Value { + json!({ "size": self.size, "tolerance": self.tolerance, "pressure": self.pressure }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + let num = |v: &Value, (lo, hi): (f64, f64)| v.as_f64().filter(|x| x.is_finite()).map(|x| x.clamp(lo, hi)); + match key { + "size" => self.size = num(v, SIZE_RANGE).unwrap_or(self.size), + "tolerance" => self.tolerance = num(v, TOLERANCE_RANGE).unwrap_or(self.tolerance), + "pressure" => self.pressure = v.as_bool().unwrap_or(self.pressure), + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use vectorcraft_doc::Selection; + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + #[test] + fn a_stroke_previews_the_erase_and_commits_once() { + let (d, id) = doc_with_rect(); + let mut sel = Selection::default(); + sel.set([id]); + let p = paint(); + let cx = cx(&d, &sel, &p); + let mut t = AnchorEraserTool::default(); + let down = t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)); + assert_eq!(down.first(), Some(&Action::Begin(LABEL.into()))); + assert!(t.busy()); + let drag = t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 100.0)); + let Some(Action::Preview(cmd, params)) = drag.first() else { panic!("{drag:?}") }; + assert_eq!(cmd, "addon.pathtools.erase"); + assert_eq!(params["points"], json!([[100.0, 100.0], [150.0, 100.0]])); + assert_eq!((params["diameter"].clone(), params["tolerance"].clone()), (json!(20.0), json!(10.0))); + let up = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 100.0)); + assert!(matches!(up.as_slice(), [Action::Preview(..), Action::Commit]), "{up:?}"); + assert!(!t.busy()); + // Alt ignores the tolerance; Cmd deletes without refitting; Escape cancels. + let alt = Mods { alt: true, cmd: true, ..Mods::default() }; + let down = t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0).with_mods(alt)); + let Some(Action::Preview(_, params)) = down.get(1) else { panic!("{down:?}") }; + assert_eq!((params["ignoreTolerance"].clone(), params["plain"].clone()), (json!(true), json!(true))); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 100.0, 100.0)).is_empty()); + } + + #[test] + fn nothing_selected_paints_nothing() { + let (d, _) = doc_with_rect(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = AnchorEraserTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 120.0, 100.0)).is_empty()); + assert!(!t.busy()); + } + + #[test] + fn options_size_the_brush_and_pressure_scales_it() { + let (d, id) = doc_with_rect(); + let mut sel = Selection::default(); + sel.set([id]); + let p = paint(); + let mut cx = cx(&d, &sel, &p); + cx.zoom = 2.0; + let mut t = AnchorEraserTool::default(); + t.set_option("size", &json!(40)); + t.set_option("tolerance", &json!(500)); + t.set_option("pressure", &json!(true)); + assert_eq!(t.options(), json!({"size": 40.0, "tolerance": 100.0, "pressure": true})); + let mut down = ev(PointerKind::Down, 10.0, 10.0); + down.pressure = 0.5; + let a = t.pointer(&cx, &down); + let Some(Action::Preview(_, params)) = a.get(1) else { panic!("{a:?}") }; + assert_eq!(params["diameter"], json!(20.0), "40 px at 200%"); + assert_eq!(params["points"], json!([[10.0, 10.0, 0.5]])); + // The brush shows round the pointer, and `]` makes it larger. + assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Path { .. }])); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options()["size"], json!(50.0)); + assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::AnchorEraser); + } +} diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs new file mode 100644 index 0000000000..d1f54861ca --- /dev/null +++ b/crates/tools/src/addons/extend_path.rs @@ -0,0 +1,282 @@ +//! Extend Path tool (Path Precision Tools): drag an end of an open path (selected or not) to carry +//! the path on the way it runs there, or back along itself to shorten it +//! (`addon.pathtools.extend`, previewed while dragging, one undo step). Over an end, a dashed line +//! shows how it would go on. E cycles the mode (straight, the last curve stretched, an arc of the +//! circle the end curves along); Shift steps the length by the keyboard increment; back over the +//! end, the length snaps to none. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{Point, SubPath}; +use vectorcraft_pathops::addons::pathtools::{ExtendMode, extend_length_to, extend_open}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "extendPath"; +/// The undo step's name. +const LABEL: &str = "Extend Path"; +/// How far ahead (px) the hover preview shows an end going on. +const PREVIEW_PX: f64 = 60.0; +const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; + +/// An end of an open subpath. +#[derive(Clone, Debug, PartialEq)] +struct End { + id: NodeId, + subpath: usize, + start: bool, + p: Point, + /// The subpath as it was. + sp: SubPath, +} + +#[derive(Default)] +pub struct ExtendPathTool { + mode: Mode, + hover: Option, + /// The end being dragged and the length the drag asks for. + drag: Option<(End, f64)>, +} + +/// [`ExtendMode`], with the default the tool starts with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Mode(ExtendMode); + +impl Default for Mode { + fn default() -> Self { + Mode(ExtendMode::Straight) + } +} + +/// The end of an editable open path nearest `p` within the point tolerance. +fn end_at(cx: &ToolContext, p: Point) -> Option { + let tol = cx.point_tol(); + let mut best: Option<(f64, NodeId, usize, bool, Point)> = None; + cx.doc.walk(|n| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return }; + for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed && sp.anchors.len() >= 2) { + for (start, a) in [(true, sp.anchors.first()), (false, sp.anchors.last())] { + let Some(a) = a else { continue }; + let d = a.p.distance(p); + if d <= tol && best.is_none_or(|b| d < b.0) { + best = Some((d, n.id, si, start, a.p)); + } + } + } + }); + let (_, id, subpath, start, at) = best.filter(|b| cx.doc.is_editable(b.1))?; + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?.clone(); + Some(End { id, subpath, start, p: at, sp }) +} + +impl ExtendPathTool { + /// The length a drag to `p` asks for: back over the end none, with Shift in steps of the + /// keyboard increment. + fn length_at(&self, cx: &ToolContext, end: &End, p: Point, mods: Mods) -> f64 { + if p.distance(end.p) <= cx.point_tol() { + return 0.0; + } + let len = extend_length_to(&end.sp, end.start, p, self.mode.0).unwrap_or(0.0); + let step = cx.keyboard_increment; + if mods.shift && step > 0.0 && step.is_finite() { (len / step).round() * step } else { len } + } + + fn params(&self, end: &End, length: f64) -> Value { + json!({ + "id": end.id.0, + "subpath": end.subpath, + "end": if end.start { "start" } else { "end" }, + "length": length, + "mode": self.mode.0.id(), + }) + } +} + +/// The length of `sp` (pt). +fn length_of(sp: &SubPath) -> f64 { + (0..sp.segment_count()).map(|i| kurbo::ParamCurveArclen::arclen(&sp.segment(i), 1e-6)).sum() +} + +impl Tool for ExtendPathTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.drag.is_some() + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Move => { + self.hover = end_at(cx, ev.pos); + vec![] + } + PointerKind::Down => { + let Some(end) = end_at(cx, ev.pos) else { return vec![] }; + self.hover = None; + self.drag = Some((end, 0.0)); + vec![Action::Begin(LABEL.into())] + } + PointerKind::Drag | PointerKind::Up => { + let Some((end, _)) = self.drag.take() else { return vec![] }; + let length = self.length_at(cx, &end, ev.pos, ev.mods); + let preview = Action::Preview("addon.pathtools.extend".into(), self.params(&end, length)); + if ev.kind == PointerKind::Drag { + self.drag = Some((end, length)); + return vec![preview]; + } + // Back where it started: nothing to keep. + if length == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] } + } + PointerKind::DoubleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape if self.drag.is_some() => { + self.drag = None; + vec![Action::Cancel] + } + ToolKey::Letter('e') => { + let all = ExtendMode::ALL; + let i = all.iter().position(|m| *m == self.mode.0).unwrap_or(0); + self.mode = Mode(all.get((i + 1) % all.len()).copied().unwrap_or(ExtendMode::Straight)); + vec![] + } + _ => vec![], + } + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Letter('e') || (self.drag.is_some() && key == ToolKey::Escape) + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let size = 7.0; + if let Some((end, length)) = &self.drag { + let total = length_of(&end.sp) + length; + return vec![ + Overlay::Anchor { p: end.p, color: BLUE, filled: false, size }, + Overlay::Measure { + p: end.p + kurbo::Vec2::new(cx.tol(12.0), cx.tol(12.0)), + text: format!("Length: {}\nΔ: {}", cx.len(total), cx.len(*length)), + }, + ]; + } + let Some(end) = &self.hover else { return vec![] }; + let mut out = vec![Overlay::Anchor { p: end.p, color: BLUE, filled: true, size }]; + // How the end would go on. + if let Some(ext) = extend_open(&end.sp, end.start, cx.tol(PREVIEW_PX), self.mode.0) { + let (k, n) = (end.sp.anchors.len(), ext.anchors.len()); + // From the old end on; a stretched last curve (no anchor added) shows whole. + let from = if n > k { k - 1 } else { n.saturating_sub(2) }; + let tail = if end.start { ext.anchors.get(..n - from) } else { ext.anchors.get(from..) }; + if let Some(tail) = tail { + let mut bp = vectorcraft_geom::BezPath::new(); + SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp); + out.push(Overlay::Path { path: bp, color: GREY, width: 1.0, dashed: true }); + } + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::ExtendPath + } + + fn options(&self) -> Value { + json!({ "mode": self.mode.0.id() }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + if key == "mode" + && let Some(m) = v.as_str().and_then(ExtendMode::parse) + { + self.mode = Mode(m); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use vectorcraft_doc::{Appearance, Document, Node, Selection}; + use vectorcraft_geom::PathData; + + /// A document with an open line from (100, 100) to (200, 100). + fn doc_with_line() -> (Document, NodeId) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let sp = SubPath::polyline(&[Point::new(100.0, 100.0), Point::new(200.0, 100.0)], false); + d.insert(Some(l), 0, Node::path(id, PathData::single(sp), Appearance::default_art())).unwrap(); + (d, id) + } + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + #[test] + fn dragging_an_end_previews_the_extension_and_commits() { + let (d, id) = doc_with_line(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = ExtendPathTool::default(); + // Hovering the end shows it and how it would go on. + assert!(t.pointer(&cx, &ev(PointerKind::Move, 201.0, 101.0)).is_empty()); + let ov = t.overlays(&cx); + assert!(matches!(ov.as_slice(), [Overlay::Anchor { filled: true, .. }, Overlay::Path { dashed: true, .. }]), "{ov:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 201.0, 101.0)), vec![Action::Begin(LABEL.into())]); + let drag = t.pointer(&cx, &ev(PointerKind::Drag, 240.0, 105.0)); + let Some(Action::Preview(cmd, params)) = drag.first() else { panic!("{drag:?}") }; + assert_eq!(cmd, "addon.pathtools.extend"); + assert_eq!((params["id"].clone(), params["end"].clone(), params["mode"].clone()), (json!(id.0), json!("end"), json!("straight"))); + assert!((params["length"].as_f64().unwrap() - 40.0).abs() < 1e-6); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.contains("Length: 140")))); + let up = t.pointer(&cx, &ev(PointerKind::Up, 160.0, 100.0)); + assert!(matches!(up.as_slice(), [Action::Preview(_, p), Action::Commit] if (p["length"].as_f64().unwrap() + 40.0).abs() < 1e-6), "{up:?}"); + // The start end too, and Shift steps the length. + t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)); + let mut shifted = ev(PointerKind::Drag, 87.4, 100.0); + shifted.mods.shift = true; + let drag = t.pointer(&cx, &shifted); + let Some(Action::Preview(_, params)) = drag.first() else { panic!("{drag:?}") }; + assert_eq!((params["end"].clone(), params["length"].clone()), (json!("start"), json!(13.0))); + // Back on the end: nothing to keep. + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 100.0, 100.0)), vec![Action::Cancel]); + } + + #[test] + fn away_from_ends_nothing_happens_and_e_cycles_the_mode() { + let (d, _) = doc_with_line(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = ExtendPathTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)).is_empty(), "the middle of the path"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 150.0, 100.0)).is_empty()); + assert!(t.overlays(&cx).is_empty()); + assert!(t.claims_key(&cx, ToolKey::Letter('e'))); + for want in ["bezier", "arc", "straight"] { + t.key(&cx, ToolKey::Letter('e'), Mods::default()); + assert_eq!(t.options()["mode"], json!(want)); + } + t.set_option("mode", &json!("arc")); + t.set_option("mode", &json!("spiral")); + assert_eq!(t.options()["mode"], json!("arc")); + assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::ExtendPath); + // A closed path has no ends. + let (d, _) = doc_with_rect(); + let cx = crate::testutil::cx(&d, &sel, &p); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)).is_empty()); + } +} diff --git a/crates/tools/src/addons/measure_inspect.rs b/crates/tools/src/addons/measure_inspect.rs new file mode 100644 index 0000000000..d46edb6c64 --- /dev/null +++ b/crates/tools/src/addons/measure_inspect.rs @@ -0,0 +1,216 @@ +//! Measure & Inspect tool (Path Precision Tools): drag between two points to read their distance, +//! angle and offsets (Shift: 45° steps), which stay shown until the next drag; hover a path to +//! read it there: open or closed and its anchor count, the segment's and the path's length, the +//! area it encloses, the radius of curvature and the direction it runs at the pointer, and over an +//! anchor its angle and handles. Readouts are in the document's units; nothing is drawn into the +//! document (`addon.pathtools.inspect` gives agents the same readouts). + +use serde_json::{Value, json}; +use vectorcraft_doc::hit::{HitOptions, hit_test}; +use vectorcraft_doc::{NodeId, Unit}; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_pathops::addons::pathtools::{Inspection, inspect}; + +use crate::xform::measure; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "measureInspect"; +const CYAN: [u8; 3] = [0x00, 0xa8, 0xff]; +const ORANGE: [u8; 3] = [0xff, 0x8a, 0x00]; + +#[derive(Default)] +pub struct MeasureInspectTool { + line: Option<(Point, Point)>, + dragging: bool, + /// The line measured before the drag under way, which Escape puts back. + before: Option<(Point, Point)>, + /// The path under the pointer and what it reads there. + hover: Option<(NodeId, Inspection)>, +} + +/// An area of `pt2` square points in `unit` (`12.5 mm²`). +fn area_label(unit: Unit, pt2: f64) -> String { + let side = unit.from_pt(1.0); + format!("{:.2} {}²", pt2 * side * side, unit.suffix()) +} + +/// The readouts of `i`, a line each. +fn readout(cx: &ToolContext, i: &Inspection) -> String { + let mut lines = vec![ + format!("{} · {} anchors", if i.closed { "Closed path" } else { "Open path" }, i.anchors), + format!("Segment: {}", cx.len(i.segment_length)), + format!("Path: {}", cx.len(i.length)), + format!("Area: {}", area_label(cx.unit, i.area)), + format!("Tangent: {:.1}°", i.tangent), + match i.radius { + Some(r) => format!("Radius: {}", cx.len(r)), + None => "Radius: straight".into(), + }, + ]; + if let Some(a) = &i.anchor { + let kind = if a.smooth { "smooth" } else { "corner" }; + lines.push(match a.angle { + Some(deg) => format!("Anchor {} ({kind}) · Angle: {deg:.1}°", a.index + 1), + None => format!("Anchor {} ({kind}) · open end", a.index + 1), + }); + for (name, h) in [("In", a.handle_in), ("Out", a.handle_out)] { + if let Some((len, deg)) = h { + lines.push(format!("{name}: {} at {deg:.1}°", cx.len(len))); + } + } + } + lines.join("\n") +} + +impl MeasureInspectTool { + /// The path whose outline is under `p`, and its readouts there. + fn inspect_at(cx: &ToolContext, p: Point) -> Option<(NodeId, Inspection)> { + // Outlines only: a fill under the pointer is not a path to read. + let hit = hit_test(cx.doc, p, HitOptions { outline: true, ..cx.hit_options() })?; + let path = cx.doc.node(hit.leaf)?.path_data()?; + let i = inspect(path, p, cx.point_tol())?; + (i.point.distance(p) <= cx.pick_tol() * 2.0).then_some((hit.leaf, i)) + } +} + +impl Tool for MeasureInspectTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.dragging + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Move => self.hover = Self::inspect_at(cx, ev.pos), + PointerKind::Down => { + let (p, _) = crate::guides::snap_draw(cx, ev.pos, &[]); + self.before = self.line; + self.line = Some((p, p)); + self.dragging = true; + self.hover = None; + } + PointerKind::Drag | PointerKind::Up if self.dragging => { + if let Some((a, _)) = self.line { + let b = if ev.mods.shift { + a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle) + } else { + crate::guides::snap_draw(cx, ev.pos, &[]).0 + }; + self.line = Some((a, b)); + } + self.dragging = ev.kind == PointerKind::Drag; + } + _ => {} + } + vec![] + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.dragging { + self.dragging = false; + self.line = self.before; + } + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + let off = Vec2::new(cx.tol(14.0), cx.tol(14.0)); + if let Some((a, b)) = self.line.filter(|(a, b)| a != b) { + let (dist, ang, dx, dy) = measure(a, b); + out.push(Overlay::Line { a, b, color: CYAN, dashed: false }); + out.push(Overlay::Measure { p: b + off, text: format!("D: {}\nAngle: {ang:.1}°\n{}", cx.len(dist), cx.offset_label(dx, dy)) }); + } + if let Some((id, i)) = self.hover.as_ref().filter(|_| !self.dragging) { + if let Some(sp) = + cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(i.subpath)).filter(|sp| i.segment < sp.segment_count()) + { + let c = sp.segment(i.segment); + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to(c.p0); + bp.curve_to(c.p1, c.p2, c.p3); + out.push(Overlay::Path { path: bp, color: ORANGE, width: 2.0, dashed: false }); + } + let at = i.anchor.as_ref().map_or(i.point, |a| a.p); + out.push(Overlay::Anchor { p: at, color: ORANGE, filled: i.anchor.is_some(), size: 6.0 }); + out.push(Overlay::Measure { p: at + off, text: readout(cx, i) }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { + Cursor::MeasureInspect + } + + /// The last measurement, as the Measure tool reports it. + fn options(&self) -> Value { + match self.line { + Some((a, b)) => { + let (d, ang, dx, dy) = measure(a, b); + json!({ "x": a.x, "y": a.y, "distance": d, "angle": ang, "dx": dx, "dy": dy }) + } + None => Value::Null, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use vectorcraft_doc::Selection; + + #[test] + fn a_drag_measures_and_hovering_a_path_reads_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let mut t = MeasureInspectTool::default(); + for (k, x, y) in [(PointerKind::Down, 10.0, 10.0), (PointerKind::Drag, 40.0, -30.0), (PointerKind::Up, 40.0, -30.0)] { + assert!(t.pointer(&cx, &PointerEvent::new(k, x, y)).is_empty(), "nothing goes into the document"); + } + assert!((t.options()["distance"].as_f64().unwrap() - 50.0).abs() < 1e-9); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 50")))); + // Hover the rectangle's top edge (100, 100)–(200, 100), then its corner. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 150.0, 101.0)); + let text = t + .overlays(&cx) + .into_iter() + .filter_map(|o| if let Overlay::Measure { text, .. } = o { Some(text) } else { None }) + .find(|t| t.contains("Segment")) + .expect("the readout"); + assert!(text.contains("Closed path · 4 anchors") && text.contains("Segment: 100") && text.contains("Path: 400"), "{text}"); + assert!(text.contains("Area: 10000.00 pt²") && text.contains("Radius: straight"), "{text}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 199.0, 101.0)); + let ov = t.overlays(&cx); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.contains("Angle: 90.0°"))), "{ov:?}"); + // Away from every outline (inside the fill) there is nothing to read. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 150.0, 150.0)); + assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.contains("Segment")))); + assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::MeasureInspect); + } + + #[test] + fn escape_puts_back_the_measurement_before() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let mut t = MeasureInspectTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 30.0, 0.0)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.busy()); + assert_eq!(t.options(), Value::Null); + assert_eq!(area_label(Unit::Points, 2.0), "2.00 pt²"); + } +} diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 955325a0f6..4ec7c0753f 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -137,8 +137,9 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[t("zoom", "Zoom Tool", Some("Z"), "tool-zoom")], ]; +/// Every tool: the toolbar's, then the add-ons' ([`crate::addons::GROUPS`]). pub fn all_tools() -> impl Iterator { - TOOL_GROUPS.iter().flat_map(|g| g.iter()) + TOOL_GROUPS.iter().chain(crate::addons::GROUPS).flat_map(|g| g.iter()) } pub fn tool_info(id: &str) -> Option<&'static ToolInfo> { diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index 513f8ceb19..1b5097e0be 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -171,6 +171,12 @@ pub enum Cursor { MeshAdd, /// Puppet Warp over the selection's mesh where a pin can go: a click adds one. PuppetPin, + /// The Anchor Eraser Brush (Path Precision Tools add-on); the brush's circle is drawn round it. + AnchorEraser, + /// The Extend Path tool (Path Precision Tools add-on). + ExtendPath, + /// The Measure & Inspect tool (Path Precision Tools add-on). + MeasureInspect, } impl Cursor { @@ -261,7 +267,10 @@ impl Cursor { | Cursor::SymbolStyler | Cursor::Scissors | Cursor::MeshAdd - | Cursor::PuppetPin => Cursor::Crosshair, + | Cursor::PuppetPin + | Cursor::AnchorEraser + | Cursor::ExtendPath + | Cursor::MeasureInspect => Cursor::Crosshair, c => c, } } @@ -295,7 +304,10 @@ impl Cursor { | Cursor::SymbolStainer | Cursor::SymbolScreener | Cursor::SymbolStyler - | Cursor::Scissors => Some(Cursor::Crosshair), + | Cursor::Scissors + | Cursor::AnchorEraser + | Cursor::ExtendPath + | Cursor::MeasureInspect => Some(Cursor::Crosshair), Cursor::TypeVertical => Some(Cursor::Text), Cursor::MeshAdd | Cursor::PuppetPin => Some(Cursor::PenAdd), Cursor::ScissorsNotAllowed => Some(Cursor::NotAllowed), diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index dd3feae0bb..30fd82c750 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -672,6 +672,24 @@ group = "Drawing and editing tools" shown_when = ["The Print Tiling tool: a drag moves the printable page area over the artboard (it snaps to the artboard's edges)."] hotspot = "The page corner being placed." +[[cursor]] +id = "AnchorEraser" +group = "Drawing and editing tools" +shown_when = ["The Anchor Eraser Brush (Path Precision Tools add-on): a drag over selected paths removes the anchors under the brush that the outline can do without. The app draws the brush's size as a circle around the cursor."] +hotspot = "The brush centre." + +[[cursor]] +id = "ExtendPath" +group = "Drawing and editing tools" +shown_when = ["The Extend Path tool (Path Precision Tools add-on): a drag from an end of an open path lengthens or shortens the path there."] +hotspot = "Exact: the end being dragged follows it." + +[[cursor]] +id = "MeasureInspect" +group = "Drawing and editing tools" +shown_when = ["The Measure & Inspect tool (Path Precision Tools add-on): drag to measure distance and angle; hover a path to read its lengths, area, curvature and angles."] +hotspot = "Exact, because precision matters here (an open centre suits it)." + # ── Symbolism tools ─────────────────────────────────────────────────────────────────────────────── # The brush size is drawn by the app as a circle around the cursor. diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index dc2b7696b0..29bac11734 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -7,6 +7,7 @@ //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +pub mod addons; pub mod bbox; pub mod builder; pub mod catalog; @@ -291,6 +292,7 @@ pub fn create(id: &str) -> Box { .or_else(|| intertwine::create(other)) .or_else(|| objects_on_path::create(other)) .or_else(|| touchtype::create(other)) + .or_else(|| addons::create(other)) .unwrap_or_else(|| Box::new(NoopTool(tool_info(other).map(|t| t.id).unwrap_or("selection")))), } } diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 9e2cb90a9e..f27f56330d 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -66,6 +66,9 @@ const ROWS: &[Row] = &[ ], ), (&["artboard"], None, &["moveArt", "scaleArt"]), + // The add-ons' tools (`crate::addons`). + (&[crate::addons::anchor_eraser::ID], None, &["size", "tolerance", "pressure"]), + (&[crate::addons::extend_path::ID], None, &["mode"]), // Flare Tool Options (`extra::FLARE_OPTIONS` and the Rays and Rings checkboxes). ( &["flare"], diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs new file mode 100644 index 0000000000..850ab59762 --- /dev/null +++ b/crates/ui-egui/src/addons.rs @@ -0,0 +1,18 @@ +//! VectorCraft's built-in add-ons in the interface: each has a panel and a submenu at the top of +//! Object › Plug-ins, and acts through its engine commands (`addon..*`). + +pub mod cleanup; +pub mod color; +pub mod pathtools; + +use crate::menus::Item; + +/// The add-ons' submenus, then a separator: the head of Object › Plug-ins. +pub fn plugin_menu() -> Vec { + vec![ + Item::Sub("Artwork Cleanup", cleanup::menu()), + Item::Sub("Color Effects", color::menu()), + Item::Sub("Path Precision Tools", pathtools::menu()), + Item::Sep, + ] +} diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs new file mode 100644 index 0000000000..66c7f537df --- /dev/null +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -0,0 +1,191 @@ +//! Artwork Cleanup's panel and submenu (Object › Plug-ins › Artwork Cleanup). The panel runs the +//! Document Health Check on the selection, or the document while nothing is selected, lists what it +//! found, and shows or fixes the issues picked in the list (Fix All: every issue listed), each fix +//! one undo step. Below, the add-on's one-click tools open their options as their menu items do. + +use egui::{Align, Layout, Ui}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::{empty_state, pstate, set_pstate}; +use crate::widgets::{self, dim_label}; + +/// The panel's id (`window.panel {panel: "artworkCleanup"}`). +pub const ID: &str = "artworkCleanup"; + +/// Where the panel keeps its last check (panel state). +const STATE: &str = "artwork-cleanup"; + +/// The one-click tools: (menu label, command, the options their dialog opens with). +fn tools() -> [(&'static str, &'static str, Value); 3] { + [ + ("Simplify Anchors (Keep Shape)…", "addon.cleanup.simplify", json!({"tolerance": 20, "protectCorners": false})), + ("Rejoin Path Pieces…", "addon.cleanup.rejoin", json!({"gap": 0.1})), + ("Deep Ungroup…", "addon.cleanup.deepUngroup", json!({"includeClipGroups": false})), + ] +} + +/// Object › Plug-ins › Artwork Cleanup. +pub fn menu() -> Vec { + let mut items = vec![Item::Cmd("Document Health Check", "window.panel", json!({ "panel": ID })), Item::Sep]; + items.extend(tools().into_iter().map(|(label, id, p)| Item::Cmd(label, id, p))); + items.extend([Item::Sep, Item::Cmd("Fix All Issues", "addon.cleanup.fix", Value::Null)]); + items +} + +/// The panel's last check. +#[derive(Clone, Default)] +struct Results { + /// Whether a check has run (for this panel). + checked: bool, + /// The scope it looked at (`selection` or `document`). + scope: String, + /// The document and its revision it looked at. + doc: usize, + revision: u64, + /// What it found: (kind, label, count). + rows: Vec<(String, String, u64)>, + /// The kinds picked in the list. + picked: Vec, + /// What the last fix did. + status: String, +} + +/// Run the check (in `scope`, or the default one) → its results. +fn check(app: &mut VectorcraftApp, scope: Option<&str>) -> Results { + let p = scope.map_or_else(|| json!({}), |s| json!({ "scope": s })); + let mut r = Results { checked: true, doc: app.session.active_index().unwrap_or(0), ..Results::default() }; + r.revision = app.session.active().map_or(0, |d| d.revision); + match app.session.execute("addon.cleanup.check", &p) { + Ok(v) => { + r.scope = v["scope"].as_str().unwrap_or("document").to_string(); + let row = |f: &Value| Some((f["kind"].as_str()?.to_string(), f["label"].as_str()?.to_string(), f["count"].as_u64()?)); + r.rows = v["findings"].as_array().into_iter().flatten().filter_map(row).collect(); + } + Err(e) => app.status(e.to_string()), + } + r +} + +/// Fix the issues of `kinds` in the last check's scope, then check that scope again. +fn fix(app: &mut VectorcraftApp, r: &Results, kinds: Vec) -> Results { + match app.run("addon.cleanup.fix", json!({ "scope": r.scope, "kinds": kinds })) { + Ok(v) => { + let fixed = v["total"].as_u64().unwrap_or(0).to_string(); + // A selection fixed away leaves nothing to check again: nothing is left. + let mut again = if app.session.active().is_some_and(|d| d.selection.is_empty()) && r.scope == "selection" { + Results { checked: true, scope: r.scope.clone(), ..Results::default() } + } else { + check(app, Some(&r.scope)) + }; + again.status = crate::i18n::fmt(tl!("Issues fixed: {count}"), &[("count", &fixed)]); + again + } + Err(e) => { + app.status(e); + r.clone() + } + } +} + +/// What the panel's buttons asked for this frame. +enum Action { + Check, + Show(String), + Fix(Vec), + Tool(usize), +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + empty_state(ui, "sparkles", tl!("No document"), tl!("Open a document to check it for issues.")); + return; + }; + let (selected, revision, doc) = (!st.selection.is_empty(), st.revision, app.session.active_index().unwrap_or(0)); + let mut r: Results = pstate(ui.ctx(), STATE); + if r.doc != doc { + r = Results::default(); + } + let mut action = None; + let width = ui.available_width(); + if widgets::flat_button(ui, if selected { tl!("Check Selection") } else { tl!("Check Document") }, width).clicked() { + action = Some(Action::Check); + } + if r.checked { + ui.add_space(4.0); + results(ui, &mut r, &mut action); + if r.revision != revision { + dim_label(ui, tl!("Changed since the last check.")); + } + } + widgets::divider(ui); + ui.add_enabled_ui(selected, |ui| { + for (i, (label, ..)) in tools().iter().enumerate() { + if widgets::flat_button(ui, tl!(label), width).clicked() { + action = Some(Action::Tool(i)); + } + } + }); + match action { + Some(Action::Check) => r = check(app, None), + Some(Action::Show(kind)) => { + if let Err(e) = app.run("addon.cleanup.show", json!({ "kind": kind, "scope": r.scope })) { + app.status(e); + } + } + Some(Action::Fix(kinds)) => r = fix(app, &r, kinds), + Some(Action::Tool(i)) => { + if let Some((label, id, p)) = tools().into_iter().nth(i) { + let (id, p) = crate::menus::click_target(label, id, &p); + crate::menus::invoke(app, &id, p); + } + } + None => {} + } + set_pstate(ui.ctx(), STATE, r); +} + +/// The list of what the check found (click picks a row, Ctrl/Cmd- or Shift-click adds one), and +/// Show, Fix Selected and Fix All. +fn results(ui: &mut Ui, r: &mut Results, action: &mut Option) { + if r.rows.is_empty() { + dim_label(ui, tl!("No issues found.")); + } + for (kind, label, count) in &r.rows { + let on = r.picked.contains(kind); + let clicked = ui + .horizontal(|ui| { + let resp = ui.selectable_label(on, tl!(label)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| dim_label(ui, &count.to_string())); + resp.clicked() + }) + .inner; + if clicked { + match ui.input(|i| i.modifiers.command || i.modifiers.shift) { + true if on => r.picked.retain(|k| k != kind), + true => r.picked.push(kind.clone()), + false => r.picked = vec![kind.clone()], + } + } + } + if !r.status.is_empty() { + dim_label(ui, &r.status); + } + ui.horizontal(|ui| { + if ui.add_enabled_ui(r.picked.len() == 1, |ui| widgets::flat_button(ui, tl!("Show"), 56.0)).inner.clicked() + && let Some(kind) = r.picked.first() + { + *action = Some(Action::Show(kind.clone())); + } + if ui.add_enabled_ui(!r.picked.is_empty(), |ui| widgets::flat_button(ui, tl!("Fix Selected"), 88.0)).inner.clicked() { + *action = Some(Action::Fix(r.picked.clone())); + } + if ui.add_enabled_ui(!r.rows.is_empty(), |ui| widgets::flat_button(ui, tl!("Fix All"), 64.0)).inner.clicked() { + *action = Some(Action::Fix(r.rows.iter().map(|row| row.0.clone()).collect())); + } + }); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/cleanup/tests.rs b/crates/ui-egui/src/addons/cleanup/tests.rs new file mode 100644 index 0000000000..041a3410b3 --- /dev/null +++ b/crates/ui-egui/src/addons/cleanup/tests.rs @@ -0,0 +1,67 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{ID, STATE, check, fix, show}; +use crate::panels::set_pstate; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with a rectangle and a stray point (a path of one anchor), nothing selected. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("path.create", json!({"anchors": [{"x": 80, "y": 80}]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app +} + +#[test] +fn the_plugins_submenu_opens_the_panel_and_lists_the_tools() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let under = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Artwork Cleanup"] && e.label == label); + let item = under("Document Health Check").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("window.panel"), &json!({ "panel": ID }))); + for (label, id) in [ + ("Simplify Anchors (Keep Shape)…", "addon.cleanup.simplify"), + ("Rejoin Path Pieces…", "addon.cleanup.rejoin"), + ("Deep Ungroup…", "addon.cleanup.deepUngroup"), + ("Fix All Issues", "addon.cleanup.fix"), + ] { + assert_eq!(under(label).and_then(|e| e.command.as_deref()), Some(id), "{label}"); + } + // Install Plug-in… still follows. + assert!(entries.iter().any(|e| e.path == ["Object", "Plug-ins"] && e.label == "Install Plug-in…")); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); + // The tools open their options first, as dialogs. + let (target, p) = menus::click_target("Deep Ungroup…", "addon.cleanup.deepUngroup", &json!({"includeClipGroups": false})); + assert_eq!((target.as_str(), &p["command"]), ("ui.paramDialog", &json!("addon.cleanup.deepUngroup"))); +} + +#[test] +fn check_lists_what_it_found_and_fix_clears_it() { + let mut app = app(); + let text = painted_text(&mut app, show); + assert!(text.contains("Check Document") && !text.contains("Stray Points"), "{text}"); + let r = check(&mut app, None); + assert_eq!(r.scope, "document"); + assert_eq!(r.rows, [("strayPoints".to_string(), "Stray Points".to_string(), 1)]); + let shown = r.clone(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, shown.clone()); + show(app, ui); + }); + assert!(text.contains("Stray Points") && text.contains("Fix Selected") && text.contains("Fix All"), "{text}"); + let steps = app.session.doc().unwrap().history.undo.len(); + let after = fix(&mut app, &r, vec!["strayPoints".into()]); + assert!(after.rows.is_empty() && after.status.contains('1'), "{}", after.status); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, after.clone()); + show(app, ui); + }); + assert!(text.contains("No issues found."), "{text}"); +} diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs new file mode 100644 index 0000000000..c7dae8d491 --- /dev/null +++ b/crates/ui-egui/src/addons/color.rs @@ -0,0 +1,149 @@ +//! Color Effects' panel and submenu (Object › Plug-ins › Color Effects). The panel picks a colour +//! adjustment and its values, then adds it to the selection as a live effect or applies it as a +//! filter, into the colours themselves (`addon.color.filter`). The submenu applies the add-on's +//! live effects (Effect › Color Effects has them too) and opens the panel. + +use egui::Ui; +use serde_json::{Map, Value, json}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::{empty_state, pstate, set_pstate}; +use crate::widgets; + +/// The panel's id (`window.panel {panel: "colorEffects"}`). +pub const ID: &str = "colorEffects"; + +/// Where the panel keeps its choice and values (panel state). +const STATE: &str = "color-effects"; + +/// A value of an adjustment: (parameter, label, range, decimals, default). +type Field = (&'static str, &'static str, (f64, f64), usize, f64); + +/// The adjustments the panel offers: (effect, label, values). Curves and Shift to Color, which take +/// a curve or a colour, keep to their dialogs (Effect › Color Adjustments). +const ADJUSTMENTS: [(&str, &str, &[Field]); 7] = [ + ( + "adjust.brightnessContrast", + "Brightness/Contrast", + &[("brightness", "Brightness", (-100.0, 100.0), 0, 0.0), ("contrast", "Contrast", (-100.0, 100.0), 0, 0.0)], + ), + ( + "adjust.hueSaturation", + "Hue/Saturation", + &[ + ("hue", "Hue", (-180.0, 180.0), 0, 0.0), + ("saturation", "Saturation", (-100.0, 100.0), 0, 0.0), + ("lightness", "Lightness", (-100.0, 100.0), 0, 0.0), + ], + ), + ( + "adjust.levels", + "Levels", + &[ + ("inputBlack", "Input Black", (0.0, 255.0), 0, 0.0), + ("inputWhite", "Input White", (0.0, 255.0), 0, 255.0), + ("gamma", "Gamma", (0.1, 10.0), 2, 1.0), + ("outputBlack", "Output Black", (0.0, 255.0), 0, 0.0), + ("outputWhite", "Output White", (0.0, 255.0), 0, 255.0), + ], + ), + ( + "adjust.temperatureTint", + "Temperature/Tint", + &[("temperature", "Temperature", (-100.0, 100.0), 0, 0.0), ("tint", "Tint", (-100.0, 100.0), 0, 0.0)], + ), + ( + "addon.color.exposure", + "Exposure", + &[("exposure", "Exposure", (-20.0, 20.0), 2, 0.0), ("offset", "Offset", (-0.5, 0.5), 3, 0.0), ("gamma", "Gamma", (0.1, 10.0), 2, 1.0)], + ), + ("addon.color.desaturate", "Desaturate", &[]), + ("addon.color.invert", "Invert Colors", &[]), +]; + +/// Adjustment `i` of [`ADJUSTMENTS`] (the first past the end). +fn adjustment(i: usize) -> (&'static str, &'static str, &'static [Field]) { + ADJUSTMENTS.get(i).copied().unwrap_or(ADJUSTMENTS[0]) +} + +/// Object › Plug-ins › Color Effects. +pub fn menu() -> Vec { + vec![ + Item::Cmd("Color Effects Panel", "window.panel", json!({ "panel": ID })), + Item::Sep, + Item::Cmd("Exposure…", "effect.dialog", json!({ "effect": "addon.color.exposure" })), + Item::Cmd("Desaturate", "effect.apply", json!({ "effect": "addon.color.desaturate" })), + Item::Cmd("Invert Colors", "effect.apply", json!({ "effect": "addon.color.invert" })), + ] +} + +/// The panel's choice and the values set for each adjustment. +#[derive(Clone, Default)] +struct Picked { + /// Index in [`ADJUSTMENTS`]. + index: usize, + /// Values set, by effect id then parameter. + values: Map, +} + +impl Picked { + /// The params of the adjustment picked: its values, the defaults where none is set. + fn params(&self) -> (&'static str, Value) { + let (id, _, fields) = adjustment(self.index); + let set = self.values.get(id).and_then(Value::as_object); + let p: Map = + fields.iter().map(|(k, _, _, _, default)| (k.to_string(), set.and_then(|m| m.get(*k)).cloned().unwrap_or(json!(default)))).collect(); + (id, Value::Object(p)) + } +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + if app.session.active().is_none_or(|d| d.selection.is_empty()) { + empty_state(ui, "sun", tl!("No selection"), tl!("Select objects to adjust their colors.")); + return; + } + let mut st: Picked = pstate(ui.ctx(), STATE); + let labels: Vec<&str> = ADJUSTMENTS.iter().map(|a| a.1).collect(); + let (id, label, fields) = adjustment(st.index); + const LABEL_W: f32 = 84.0; + widgets::label_row(ui, tl!("Adjustment"), LABEL_W, |ui| { + if let Some(i) = widgets::dropdown(ui, "color-effects-pick", label, &labels, 150.0) { + st.index = i; + } + }); + let (_, params) = st.params(); + for (key, name, (min, max), decimals, _) in fields { + let v = params.get(*key).and_then(Value::as_f64); + widgets::label_row(ui, tl!(name), LABEL_W, |ui| { + if let Some(n) = widgets::range_field(ui, ("color-effects", id, key), v, *min..=*max, "", *decimals, 70.0) { + let set = st.values.entry(id).or_insert_with(|| json!({})); + if let Some(m) = set.as_object_mut() { + m.insert(key.to_string(), json!(n)); + } + } + }); + } + ui.add_space(4.0); + let (id, params) = st.params(); + ui.horizontal(|ui| { + let run = |app: &mut VectorcraftApp, cmd: &str| { + if let Err(e) = app.run(cmd, json!({ "effect": id, "params": params })) { + app.status(e); + } + }; + if widgets::flat_button(ui, tl!("Add as Effect"), 100.0).clicked() { + run(app, "effect.apply"); + } + if widgets::flat_button(ui, tl!("Apply as Filter"), 100.0).clicked() { + run(app, "addon.color.filter"); + } + if widgets::flat_button(ui, tl!("Reset"), 56.0).clicked() { + st.values.remove(id); + } + }); + set_pstate(ui.ctx(), STATE, st); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs new file mode 100644 index 0000000000..e05cacbfbd --- /dev/null +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -0,0 +1,61 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{ADJUSTMENTS, ID, Picked, STATE, show}; +use crate::panels::set_pstate; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with a selected red rectangle. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app +} + +#[test] +fn the_menus_list_the_effects_and_open_the_panel() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let at = |path: &[&str], label: &str| entries.iter().find(|e| e.path == path && e.label == label); + let plugins = ["Object", "Plug-ins", "Color Effects"]; + let item = at(&plugins, "Color Effects Panel").expect("listed"); + for label in ["Exposure…", "Desaturate", "Invert Colors"] { + assert!(at(&plugins, label).is_some(), "Object › Plug-ins › Color Effects › {label}"); + assert!(at(&["Effect", "Color Effects"], label).is_some(), "Effect › Color Effects › {label}"); + } + // The existing submenus are as they were. + assert!(at(&["Effect", "Color Adjustments"], "Exposure…").is_none()); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { + for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + assert!(vectorcraft_effects::is_adjustment(id), "{id}"); + let defaults = vectorcraft_effects::effect_info(id).unwrap().defaults; + let (picked, params) = Picked { index: i, ..Picked::default() }.params(); + assert_eq!(picked, *id); + for (key, ..) in fields.iter() { + assert_eq!(params[key], defaults[key], "{id} {key}"); + } + } +} + +#[test] +fn the_panel_shows_the_values_and_its_buttons() { + let mut app = app(); + let exposure = ADJUSTMENTS.iter().position(|a| a.0 == "addon.color.exposure").unwrap(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Picked { index: exposure, ..Picked::default() }); + show(app, ui); + }); + for s in ["Exposure", "Offset", "Gamma", "Add as Effect", "Apply as Filter"] { + assert!(text.contains(s), "{s} in {text}"); + } + app.run("select.none", json!({})).unwrap(); + assert!(painted_text(&mut app, show).contains("No selection")); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs new file mode 100644 index 0000000000..0ae31640a6 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -0,0 +1,216 @@ +//! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), +//! which selects its tools, opens the Anchor Inspector and runs Split / Add Points at Crossings; +//! the Anchor Inspector panel (the selected anchor's position and handles as numbers, and the +//! add-on's anchor edits); and its tools' options dialog (a double-click on the tool). Everything +//! acts through `addon.pathtools.*` and `tool.setOption`. + +use egui::Ui; +use serde_json::{Map, Value, json}; +use vectorcraft_geom::Point; +use vectorcraft_tools::addons::{anchor_eraser, extend_path, measure_inspect}; + +use crate::VectorcraftApp; +use crate::dialogs::DialogSpec; +use crate::menus::Item; +use crate::panels::{empty_state, pstate, set_pstate}; +use crate::state::Dialog; +use crate::widgets::{self, dim_label}; + +/// The Anchor Inspector panel's id (`window.panel {panel: "anchorInspector"}`). +pub const ID: &str = "anchorInspector"; +/// Where the panel keeps the count Add Points adds (panel state). +const COUNT: &str = "anchor-inspector-count"; +/// The tools' options dialog. +pub const KIND: &str = "pathToolOptions"; +/// The close modes, as `addon.pathtools.close` names them, and their labels. +const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; +const LABEL_W: f32 = 64.0; + +/// Object › Plug-ins › Path Precision Tools. +pub fn menu() -> Vec { + let tool = |label, id: &str| Item::Cmd(label, "tool.select", json!({ "tool": id })); + vec![ + tool("Anchor Eraser Brush", anchor_eraser::ID), + tool("Extend Path Tool", extend_path::ID), + tool("Measure & Inspect Tool", measure_inspect::ID), + Item::Sep, + Item::Cmd("Anchor Inspector", "window.panel", json!({ "panel": ID })), + Item::Sep, + Item::Cmd("Add Points at Crossings", "addon.pathtools.crossings", json!({})), + Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), + ] +} + +/// The first direct-selected anchor (path, subpath, anchor) and how many are selected. +fn first_anchor(app: &VectorcraftApp) -> Option<(vectorcraft_geom::Anchor, usize)> { + let st = app.session.active()?; + let count = st.selection.anchors.values().map(|a| a.len()).sum(); + let (id, set) = st.selection.anchors.iter().find(|(_, a)| !a.is_empty())?; + let (si, ai) = set.first()?; + let a = st.doc.node(*id)?.path_data()?.subpaths.get(*si)?.anchors.get(*ai)?; + Some((*a, count)) +} + +/// A handle's (length, direction in degrees counter-clockwise on the page); `None` for none. +fn polar(p: Point, h: Point) -> Option<(f64, f64)> { + let v = h - p; + (v.hypot() > 1e-9).then(|| (v.hypot(), (-v.y).atan2(v.x).to_degrees() + 0.0)) +} + +fn run(app: &mut VectorcraftApp, id: &str, p: Value) { + if let Err(e) = app.run(id, p) { + app.status(e); + } +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points.")); + return; + }; + let selected = !st.selection.is_empty(); + let unit = app.session.general_unit(); + let origin = app.ruler_origin(); + let anchor = first_anchor(app); + let mut set: Option = None; + match anchor { + Some((_, n)) => dim_label(ui, &crate::i18n::fmt(tl!("Anchors selected: {count}"), &[("count", &n.to_string())])), + None => dim_label(ui, tl!("Direct-select anchor points to edit them.")), + }; + ui.add_enabled_ui(anchor.is_some(), |ui| { + let a = anchor.map(|(a, _)| a); + egui::Grid::new("anchor-inspector-grid").num_columns(4).spacing([4.0, 6.0]).min_col_width(0.0).show(ui, |ui| { + for (label, key, v) in [("X:", "x", a.map(|a| a.p.x - origin.x)), ("Y:", "y", a.map(|a| a.p.y - origin.y))] { + dim_label(ui, label); + if let Some(v) = widgets::num_field_named(ui, ("anchor-inspector", key), Some(tl!(label)), v, unit, 72.0) { + let o = if key == "x" { origin.x } else { origin.y }; + set = Some(json!({ key: v + o })); + } + } + ui.end_row(); + for (name, out) in [("In:", false), ("Out:", true)] { + let h = a.and_then(|a| polar(a.p, if out { a.h_out } else { a.h_in })); + let side = if out { "out" } else { "in" }; + dim_label(ui, name); + let len = h.map(|h| h.0).or(a.map(|_| 0.0)); + if let Some(v) = widgets::size_field_named(ui, ("anchor-inspector-len", side), Some(tl!("Length")), len, unit, 72.0) { + set = Some(json!({ format!("{side}Length"): v })); + } + dim_label(ui, "∠"); + if let Some(v) = widgets::mixed_field_named(ui, ("anchor-inspector-angle", side), Some(tl!("Angle")), h.map(|h| h.1), "°", 1, 56.0) { + set = Some(json!({ format!("{side}Angle"): v })); + } + ui.end_row(); + } + }); + }); + widgets::divider(ui); + let width = ui.available_width(); + let mut action: Option<(&str, Value)> = None; + ui.add_enabled_ui(selected, |ui| { + for (label, id) in [ + ("Make Smooth", "addon.pathtools.smooth"), + ("Make Corner", "addon.pathtools.corner"), + ("Equalize Handles", "addon.pathtools.equalize"), + ("Remove Points, Keep Shape", "addon.pathtools.removeKeepShape"), + ] { + if widgets::flat_button(ui, tl!(label), width).clicked() { + action = Some((id, json!({}))); + } + } + let mut count: f64 = pstate::>(ui.ctx(), COUNT).unwrap_or(1.0); + ui.horizontal(|ui| { + if widgets::flat_button(ui, tl!("Add Points"), width - 70.0).clicked() { + action = Some(("addon.pathtools.addPoints", json!({ "count": count }))); + } + if let Some(v) = + widgets::range_field_named(ui, "anchor-inspector-count", Some(tl!("Points per segment")), count, 1.0..=100.0, "", 0, 60.0) + { + count = v; + } + }); + set_pstate(ui.ctx(), COUNT, Some(count)); + // The label above and the three ways sharing the row: beside the label they overflow a narrow dock. + widgets::subheader(ui, "Close Path:"); + ui.horizontal(|ui| { + let n = CLOSE_MODES.len() as f32; + let each = ((width - ui.spacing().item_spacing.x * (n - 1.0)) / n).max(40.0); + for (mode, label) in CLOSE_MODES { + if widgets::flat_button(ui, tl!(label), each).clicked() { + action = Some(("addon.pathtools.close", json!({ "mode": mode }))); + } + } + }); + }); + if let Some(p) = set { + run(app, "addon.pathtools.setAnchor", p); + } + if let Some((id, p)) = action { + run(app, id, p); + } +} + +// ---------- the tools' options ---------- + +/// Tools whose options the dialog edits. +pub fn has_options(tool: &str) -> bool { + [anchor_eraser::ID, extend_path::ID].contains(&tool) +} + +/// Open the options of add-on tool `tool` with its current values. +pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { + let mut fields: Map = app.session.tool_options_of(tool).as_object().cloned().unwrap_or_default(); + fields.insert("__tool".into(), json!(tool)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({ "dialog": KIND })) +} + +pub(crate) const OPTIONS_SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 280.0, ..DialogSpec::FORM }; + +fn heading(d: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(&d.str("__tool")).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + if d.str("__tool") == extend_path::ID { + let modes = [("straight", "Straight"), ("bezier", "Stretch Curve"), ("arc", "Arc")]; + let labels: Vec<&str> = modes.iter().map(|(_, l)| *l).collect(); + let current = modes.iter().find(|(m, _)| *m == d.str("mode")).map_or("Straight", |(_, l)| *l); + widgets::label_row(ui, tl!("Mode:"), LABEL_W, |ui| { + if let Some((m, _)) = widgets::dropdown(ui, "extend-path-mode", current, &labels, 140.0).and_then(|i| modes.get(i)) { + d.fields.insert("mode".into(), json!(m)); + } + }); + return false; + } + let rows = [ + ("size", "Size:", anchor_eraser::SIZE_RANGE, "px", anchor_eraser::SIZE), + ("tolerance", "Tolerance:", anchor_eraser::TOLERANCE_RANGE, "", anchor_eraser::TOLERANCE), + ]; + for (key, label, (lo, hi), suffix, default) in rows { + let v = d.f64(key, default); + widgets::label_row(ui, tl!(label), LABEL_W, |ui| { + if let Some(x) = widgets::range_field(ui, ("anchor-eraser", key), v, lo..=hi, suffix, 0, 72.0) { + d.fields.insert(key.into(), json!(x)); + } + }); + } + if widgets::check(ui, "Pressure", d.bool("pressure"), true) { + let on = !d.bool("pressure"); + d.fields.insert("pressure".into(), json!(on)); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let tool = d.str("__tool"); + let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); + let r = app.run("tool.setOption", json!({ "tool": tool, "values": values })); + app.ui.dialog = None; + r +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs new file mode 100644 index 0000000000..4e639d3292 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -0,0 +1,86 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{ID, KIND, show}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app +} + +#[test] +fn the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let under = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == label); + for (label, tool) in + [("Anchor Eraser Brush", "anchorEraserBrush"), ("Extend Path Tool", "extendPath"), ("Measure & Inspect Tool", "measureInspect")] + { + let e = under(label).expect(label); + assert_eq!((e.command.as_deref(), &e.params), (Some("tool.select"), &json!({ "tool": tool }))); + menus::invoke(&mut app, "tool.select", e.params.clone()); + assert_eq!(app.session.tool_id(), tool); + } + for (label, cut) in [("Add Points at Crossings", false), ("Split at Crossings", true)] { + let e = under(label).expect(label); + assert_eq!(e.command.as_deref(), Some("addon.pathtools.crossings")); + assert_eq!(e.params.get("cut").and_then(|v| v.as_bool()).unwrap_or(false), cut); + } + // Artwork Cleanup's submenu and Install Plug-in… are still there. + assert!(entries.iter().any(|e| e.path == ["Object", "Plug-ins", "Artwork Cleanup"])); + assert!(entries.iter().any(|e| e.path == ["Object", "Plug-ins"] && e.label == "Install Plug-in…")); + let inspector = under("Anchor Inspector").expect("listed"); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "window.panel", inspector.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() { + let mut app = app(); + let r = app.run("path.create", json!({"anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}], "closed": false})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + let text = painted_text(&mut app, show); + assert!(text.contains("Direct-select anchor points to edit them.") && text.contains("Make Smooth") && text.contains("Close Path:"), "{text}"); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let text = painted_text(&mut app, show); + assert!(text.contains("Anchors selected: 1"), "{text}"); + // The panel's buttons run the add-on's commands, each one undo step. + let steps = app.session.doc().unwrap().history.undo.len(); + app.run("addon.pathtools.smooth", json!({})).unwrap(); + let a = app.session.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[1]; + assert!(a.has_in() && a.has_out()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { + let mut app = app(); + app.run("tool.options", json!({"tool": "anchorEraserBrush"})).unwrap(); + let d = app.ui.dialog.as_mut().expect("the dialog"); + assert_eq!(d.kind, KIND); + assert_eq!((d.f64("size", 0.0), d.f64("tolerance", 0.0), d.bool("pressure")), (20.0, 10.0, false)); + let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(text.contains("Anchor Eraser Brush Options") && text.contains("Tolerance:") && text.contains("Pressure"), "{text}"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("size".into(), json!(64)); + d.fields.insert("pressure".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of("anchorEraserBrush"); + assert_eq!((o["size"].as_f64(), o["pressure"].as_bool()), (Some(64.0), Some(true))); + // The Extend Path tool's mode; the Measure & Inspect tool has none. + app.run("tool.options", json!({"tool": "extendPath"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("arc")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); + assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); +} diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 6d39883be8..6987dcb6d3 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -147,6 +147,9 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { | Cursor::Scissors | Cursor::ScissorsNotAllowed | Cursor::MeshAdd - | Cursor::PuppetPin => cursor_icon(c.stand_in().unwrap_or(Cursor::Crosshair)), + | Cursor::PuppetPin + | Cursor::AnchorEraser + | Cursor::ExtendPath + | Cursor::MeasureInspect => cursor_icon(c.stand_in().unwrap_or(Cursor::Crosshair)), } } diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index b87e68c7bf..5461767bd7 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -440,7 +440,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) { /// Every cursor with a glyph: its own, drawn here, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 81] = [ +const GLYPHS: [Cursor; 84] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -522,6 +522,9 @@ const GLYPHS: [Cursor; 81] = [ Cursor::Scissors, Cursor::MeshAdd, Cursor::PuppetPin, + Cursor::AnchorEraser, + Cursor::ExtendPath, + Cursor::MeasureInspect, ]; /// The shapes of cursor `c` with its hotspot at `p`; `None` for cursors that stay system cursors diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 659a2c793d..6f307d43ab 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -385,6 +385,7 @@ registry! { LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, + PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 02346ab1f7..9e00f0927b 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -161,7 +161,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { // Plug-in effects get fields from their parameter schema; colour adjustments their sliders. let changed = match vectorcraft_plugins::effect::installed(&id) { Some(plugin) => form::schema_fields(app, ui, d, plugin.manifest()), - None if vectorcraft_effects::is_adjustment(&id) => adjust_fields(ui, d), + // The Color Effects add-on's take the plain form of their parameters. + None if vectorcraft_effects::is_adjustment(&id) && !vectorcraft_effects::addons::color::is_color_effect(&id) => adjust_fields(ui, d), None if id == GLASS => glass_fields(app, ui, d, GLASS), None if id == TEXTURIZER => glass_fields(app, ui, d, TEXTURIZER), None if id == TRANSFORM => transform_fields(ui, d, app.session.general_unit()), diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index f61d19a557..8ec296aba1 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -349,6 +349,9 @@ fn heading(id: &str) -> &'static str { if let Some((cat, _)) = crate::toolbar::BASIC.iter().find(|(_, slots)| slots.iter().any(|s| s.contains(&id))) { return cat; } + if let Some(addon) = vectorcraft_tools::addons::heading(id) { + return addon; + } match id { _ if id.starts_with("symbol") => "Symbols", _ if id.ends_with("Graph") => "Graph", @@ -365,7 +368,7 @@ fn sections() -> &'static [(&'static str, Vec<&'static ToolInfo>)] { static SECTIONS: OnceLock)>> = OnceLock::new(); SECTIONS.get_or_init(|| { let mut out: Vec<(&'static str, Vec<&'static ToolInfo>)> = crate::toolbar::BASIC.iter().map(|(cat, _)| (*cat, vec![])).collect(); - for tool in TOOL_GROUPS.iter().flat_map(|g| g.iter()) { + for tool in vectorcraft_tools::catalog::all_tools() { let h = heading(tool.id); match out.iter_mut().find(|(c, _)| *c == h) { Some((_, tools)) => tools.push(tool), @@ -387,7 +390,7 @@ fn groups() -> &'static [Heading] { static GROUPS: OnceLock> = OnceLock::new(); GROUPS.get_or_init(|| { let mut out: Vec = sections().iter().map(|(cat, _)| (*cat, vec![])).collect(); - for g in TOOL_GROUPS { + for g in TOOL_GROUPS.iter().chain(vectorcraft_tools::addons::GROUPS) { let Some(first) = g.first() else { continue }; let count = |h: &str| g.iter().filter(|t| heading(t.id) == h).count(); let h = g.iter().map(|t| heading(t.id)).fold(heading(first.id), |best, h| if count(h) > count(best) { h } else { best }); diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 5a8f1ce948..4184e4e557 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -97,7 +97,7 @@ fn cell_at(shown: &[(String, Pos2, Color32)], drawer: Rect, name: &str) -> (Pos2 #[test] fn the_drawer_frames_every_flyout_group_once() { let listed: Vec<&str> = groups().iter().flat_map(|(_, gs)| gs.iter().flat_map(|g| g.iter().map(|t| t.id))).collect(); - let all: Vec<&str> = TOOL_GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); + let all: Vec<&str> = vectorcraft_tools::catalog::all_tools().map(|t| t.id).collect(); assert_eq!(listed.len(), all.len()); assert!(all.iter().all(|id| listed.contains(id))); let under = |id: &str| groups().iter().find(|(_, gs)| gs.iter().any(|g| g.iter().any(|t| t.id == id))).map(|(c, _)| *c); @@ -133,7 +133,7 @@ fn toolbar_show_turns_the_controls_under_the_tools_on_and_off() { fn every_tool_is_listed_once_under_a_heading() { let s = sections(); let listed: Vec<&str> = s.iter().flat_map(|(_, tools)| tools.iter().map(|t| t.id)).collect(); - let all: Vec<&str> = TOOL_GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); + let all: Vec<&str> = vectorcraft_tools::catalog::all_tools().map(|t| t.id).collect(); assert_eq!(listed.len(), all.len()); assert!(all.iter().all(|id| listed.contains(id))); let heads: Vec<&str> = s.iter().map(|(c, _)| *c).collect(); @@ -372,3 +372,23 @@ fn drop_targets_follow_the_buttons_edges() { assert_eq!(drop_target(&two, pos2(36.0, 10.0), 2), (Some(0), Place::After)); assert_eq!(drop_target(&[], pos2(0.0, 0.0), 1), (None, Place::Before)); } + +/// The add-ons' tools are in neither toolbar as they ship: the drawer lists them under their +/// add-on's heading, and they can be added from there. +#[test] +fn addon_tools_are_in_the_drawer_not_the_toolbars() { + let mut app = app(); + let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); + assert_eq!(addon, ["anchorEraserBrush", "extendPath", "measureInspect"]); + for advanced in [false, true] { + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + assert!(addon.iter().all(|id| slot_of(&app, id).is_none()), "advanced: {advanced}"); + } + let (heading, tools) = sections().iter().find(|(_, tools)| tools.iter().any(|t| t.id == "extendPath")).expect("listed"); + assert_eq!(*heading, "Path Precision Tools"); + assert_eq!(tools.iter().map(|t| t.id).collect::>(), addon); + app.run("toolbar.addTool", json!({"tool": "extendPath"})).unwrap(); + assert!(slot_of(&app, "extendPath").is_some()); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 60522f664b..82ab44160b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5590,3 +5590,100 @@ axis Y Axis Y ос Average & Join Усредняване и свързване anchor Points: Точки: @msg select two open path ends, or two open paths, to average and join изберете два края на отворени пътища или два отворени пътя за усредняване и свързване + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Почистване на графиката + Simplify Anchors (Keep Shape)… Опростяване на опорните точки (запазване на формата)… + Health Check Проверка на състоянието + Show Issue Показване на проблема + Fix All Issues Отстраняване на всички проблеми + Fix Issues Отстраняване на проблемите + Deep Ungroup… Разгрупиране на всички нива… + Rejoin Path Pieces… Повторно свързване на части от пътища… + Document Health Check Проверка на състоянието на документа + Check Selection Проверка на селекцията + Check Document Проверка на документа + No issues found. Не са открити проблеми. + Changed since the last check. Променено след последната проверка. + Fix Selected Отстраняване на избраните + Fix All Отстраняване на всички + Issues fixed: {count} Отстранени проблеми: {count} + Open a document to check it for issues. Отворете документ, за да го проверите за проблеми. + Empty Text Празен текст + Unpainted Objects Обекти без цвят + Zero-Opacity Objects Обекти с нулева непрозрачност + Duplicate Objects Дублирани обекти + Off-Artboard Art Графика извън работните области + Duplicate Anchors Дублирани опорни точки + Tiny Handles Миниатюрни дръжки + Collinear Anchors Колинеарни опорни точки + Nearly Coincident Anchors Почти съвпадащи опорни точки + Nearly Closed Paths Почти затворени пътища + Filled Open Paths Запълнени отворени пътища + Needless Clipping Groups Излишни групи за изрязване + Needless Compound Paths Излишни съставни пътища + Needless Groups Излишни групи + Empty Artboards Празни работни области + Protect Corners Защита на ъглите + Gap Разстояние + Include Clip Groups Включване на групите за изрязване +@msg `tolerance` must be from 1 to 100 `tolerance` трябва да е от 1 до 100 +@msg `gap` must be from 0 to 6 pt `gap` трябва да е от 0 до 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Опростяване на опорните точки: пътищата имат твърде много опорни точки, за да се опростят наведнъж +@msg Rejoin Path Pieces: too many paths to rejoin at once Повторно свързване на части от пътища: твърде много пътища за свързване наведнъж +@msg None of these issues are left: check again Не е останал нито един от тези проблеми: проверете отново +@msg `kinds` must be a list of issue kinds `kinds` трябва да е списък с видове проблеми +@msg missing `kind` липсва `kind` + Simplify Anchors (Keep Shape) Опростяване на опорните точки (запазване на формата) + Deep Ungroup Разгрупиране на всички нива + Rejoin Path Pieces Повторно свързване на части от пътища + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Цветови ефекти + Color Effects Panel Панел „Цветови ефекти“ + Exposure Експонация + Exposure… Експонация… + Desaturate Обезцветяване + Adjustment Корекция + Add as Effect Добавяне като ефект + Apply as Filter Прилагане като филтър + Select objects to adjust their colors. Изберете обекти, за да коригирате цветовете им. + Brightness/Contrast Яркост/Контраст + Hue/Saturation Оттенък/Наситеност + Temperature/Tint Температура/Нюанс +@msg `{id}` is not a colour adjustment `{id}` не е цветова корекция +@msg missing `effect` липсва `effect` +@msg `params` must be an object `params` трябва да бъде обект +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Инструменти за прецизни пътища + Anchor Eraser Brush Четка за изтриване на опорни точки + Extend Path Tool Инструмент „Удължаване на път“ + Measure & Inspect Tool Инструмент „Измерване и проверка“ + Anchor Inspector Инспектор на опорни точки + Add Points at Crossings Добавяне на точки в пресичанията + Split at Crossings Разделяне в пресичанията + Extend Path Удължаване на път + Measure & Inspect Измерване и проверка + Set Anchor Задаване на опорна точка + Make Smooth Направи гладка + Make Corner Направи ъглова + Equalize Handles Изравняване на дръжките + Remove Points, Keep Shape Премахване на точки, запазване на формата + Add Points to Segments… Добавяне на точки към сегменти… + Add Points to Segments Добавяне на точки към сегменти + Open a document to edit its anchor points. Отворете документ, за да редактирате опорните му точки. + Anchors selected: {count} Избрани опорни точки: {count} + Direct-select anchor points to edit them. Изберете опорните точки директно, за да ги редактирате. + In: Вход: + Out: Изход: + Add Points Добавяне на точки + Points per segment Точки на сегмент + Close Path: Затваряне на пътя: + Keep Handles Запазване на дръжките + Straight Прав + Stretch Curve Разтягане на кривата +@msg direct-select the anchor points to remove изберете директно опорните точки за премахване +@msg select segments, or paths, to add points to изберете сегменти или пътища, към които да се добавят точки +@msg select open paths to close изберете отворени пътища за затваряне +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) пътищата са твърде много или твърде заплетени, за да се намерят пресичанията им (най-много 10000 сегмента) +@msg the paths have too many anchors to edit at once пътищата имат твърде много опорни точки, за да се редактират наведнъж diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2148f134ec..f25027869f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5691,3 +5691,100 @@ theme Appearance Aparença Average & Join Mitjana i unió anchor Points: Punts: @msg select two open path ends, or two open paths, to average and join selecciona dos extrems de traçats oberts, o dos traçats oberts, per fer-ne la mitjana i unir-los + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Neteja de l’art + Simplify Anchors (Keep Shape)… Simplifica els punts d’ancoratge (mantén la forma)… + Health Check Revisió de l’estat + Show Issue Mostra el problema + Fix All Issues Corregeix tots els problemes + Fix Issues Corregeix els problemes + Deep Ungroup… Desagrupa tots els nivells… + Rejoin Path Pieces… Torna a unir els trossos de traçat… + Document Health Check Revisió de l’estat del document + Check Selection Revisa la selecció + Check Document Revisa el document + No issues found. No s’ha trobat cap problema. + Changed since the last check. Ha canviat des de l’última revisió. + Fix Selected Corregeix els seleccionats + Fix All Corregeix-ho tot + Issues fixed: {count} Problemes corregits: {count} + Open a document to check it for issues. Obriu un document per revisar-ne els problemes. + Empty Text Text buit + Unpainted Objects Objectes sense pintura + Zero-Opacity Objects Objectes amb opacitat zero + Duplicate Objects Objectes duplicats + Off-Artboard Art Art fora dels taulers + Duplicate Anchors Punts d’ancoratge duplicats + Tiny Handles Nanses minúscules + Collinear Anchors Punts d’ancoratge col·lineals + Nearly Coincident Anchors Punts d’ancoratge gairebé coincidents + Nearly Closed Paths Traçats gairebé tancats + Filled Open Paths Traçats oberts amb emplenament + Needless Clipping Groups Grups de retall innecessaris + Needless Compound Paths Traçats compostos innecessaris + Needless Groups Grups innecessaris + Empty Artboards Taulers buits + Protect Corners Protegeix les cantonades + Gap Separació + Include Clip Groups Inclou els grups de retall +@msg `tolerance` must be from 1 to 100 `tolerance` ha d’estar entre 1 i 100 +@msg `gap` must be from 0 to 6 pt `gap` ha d’estar entre 0 i 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Simplifica els punts d’ancoratge: els traçats tenen massa punts d’ancoratge per simplificar-los d’un cop +@msg Rejoin Path Pieces: too many paths to rejoin at once Torna a unir els trossos de traçat: massa traçats per unir-los d’un cop +@msg None of these issues are left: check again Ja no queda cap d’aquests problemes: torneu a revisar +@msg `kinds` must be a list of issue kinds `kinds` ha de ser una llista de tipus de problema +@msg missing `kind` falta `kind` + Simplify Anchors (Keep Shape) Simplifica els punts d’ancoratge (mantén la forma) + Deep Ungroup Desagrupa tots els nivells + Rejoin Path Pieces Torna a unir els trossos de traçat + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Efectes de color + Color Effects Panel Tauler Efectes de color + Exposure Exposició + Exposure… Exposició… + Desaturate Dessaturar + Adjustment Ajust + Add as Effect Afegeix com a efecte + Apply as Filter Aplica com a filtre + Select objects to adjust their colors. Seleccioneu objectes per ajustar-ne els colors. + Brightness/Contrast Lluentor/Contrast + Hue/Saturation To/saturació + Temperature/Tint Temperatura/To +@msg `{id}` is not a colour adjustment `{id}` no és un ajust de color +@msg missing `effect` falta `effect` +@msg `params` must be an object `params` ha de ser un objecte +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Eines de precisió de traçats + Anchor Eraser Brush Pinzell esborrador de punts d’ancoratge + Extend Path Tool Eina d’allargar el traçat + Measure & Inspect Tool Eina de mesurar i inspeccionar + Anchor Inspector Inspector de punts d’ancoratge + Add Points at Crossings Afegeix punts als encreuaments + Split at Crossings Divideix als encreuaments + Extend Path Allarga el traçat + Measure & Inspect Mesura i inspecciona + Set Anchor Defineix el punt d’ancoratge + Make Smooth Fes-lo suau + Make Corner Fes-lo vèrtex + Equalize Handles Iguala les nanses + Remove Points, Keep Shape Elimina punts, mantén la forma + Add Points to Segments… Afegeix punts als segments… + Add Points to Segments Afegeix punts als segments + Open a document to edit its anchor points. Obriu un document per editar-ne els punts d’ancoratge. + Anchors selected: {count} Punts d’ancoratge seleccionats: {count} + Direct-select anchor points to edit them. Seleccioneu directament punts d’ancoratge per editar-los. + In: Entrada: + Out: Sortida: + Add Points Afegeix punts + Points per segment Punts per segment + Close Path: Tanca el traçat: + Keep Handles Mantén les nanses + Straight Recte + Stretch Curve Estira la corba +@msg direct-select the anchor points to remove seleccioneu directament els punts d’ancoratge que voleu eliminar +@msg select segments, or paths, to add points to seleccioneu segments, o traçats, als quals afegir punts +@msg select open paths to close seleccioneu traçats oberts per tancar-los +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) massa traçats, o massa enredats, per trobar-ne els encreuaments (10000 segments com a màxim) +@msg the paths have too many anchors to edit at once els traçats tenen massa punts d’ancoratge per editar-los alhora diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 97082fd797..894d77f6e9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5700,3 +5700,100 @@ axis Y Axis osa Y Average & Join Zprůměrovat a spojit anchor Points: Body: @msg select two open path ends, or two open paths, to average and join vyberte dva konce otevřených cest nebo dvě otevřené cesty ke zprůměrování a spojení + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Vyčištění kresby + Simplify Anchors (Keep Shape)… Zjednodušit kotevní body (zachovat tvar)… + Health Check Kontrola stavu + Show Issue Zobrazit problém + Fix All Issues Opravit všechny problémy + Fix Issues Opravit problémy + Deep Ungroup… Oddělit všechny úrovně… + Rejoin Path Pieces… Znovu spojit části cest… + Document Health Check Kontrola stavu dokumentu + Check Selection Zkontrolovat výběr + Check Document Zkontrolovat dokument + No issues found. Nebyly nalezeny žádné problémy. + Changed since the last check. Změněno od poslední kontroly. + Fix Selected Opravit vybrané + Fix All Opravit vše + Issues fixed: {count} Opravené problémy: {count} + Open a document to check it for issues. Otevřete dokument a zkontrolujte jeho problémy. + Empty Text Prázdný text + Unpainted Objects Objekty bez barvy + Zero-Opacity Objects Objekty s nulovým krytím + Duplicate Objects Duplicitní objekty + Off-Artboard Art Kresba mimo pracovní plochy + Duplicate Anchors Duplicitní kotevní body + Tiny Handles Drobné úchyty + Collinear Anchors Kolineární kotevní body + Nearly Coincident Anchors Téměř shodné kotevní body + Nearly Closed Paths Téměř uzavřené cesty + Filled Open Paths Vyplněné otevřené cesty + Needless Clipping Groups Zbytečné ořezové skupiny + Needless Compound Paths Zbytečné složené cesty + Needless Groups Zbytečné skupiny + Empty Artboards Prázdné pracovní plochy + Protect Corners Chránit rohy + Gap Mezera + Include Clip Groups Zahrnout ořezové skupiny +@msg `tolerance` must be from 1 to 100 `tolerance` musí být od 1 do 100 +@msg `gap` must be from 0 to 6 pt `gap` musí být od 0 do 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Zjednodušit kotevní body: cesty mají příliš mnoho kotevních bodů, než aby je šlo zjednodušit najednou +@msg Rejoin Path Pieces: too many paths to rejoin at once Znovu spojit části cest: příliš mnoho cest ke spojení najednou +@msg None of these issues are left: check again Žádný z těchto problémů už nezůstal: zkontrolujte znovu +@msg `kinds` must be a list of issue kinds `kinds` musí být seznam druhů problémů +@msg missing `kind` chybí `kind` + Simplify Anchors (Keep Shape) Zjednodušit kotevní body (zachovat tvar) + Deep Ungroup Oddělit všechny úrovně + Rejoin Path Pieces Znovu spojit části cest + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Barevné efekty + Color Effects Panel Panel Barevné efekty + Exposure Expozice + Exposure… Expozice… + Desaturate Odbarvit + Adjustment Úprava + Add as Effect Přidat jako efekt + Apply as Filter Použít jako filtr + Select objects to adjust their colors. Vyberte objekty, jejichž barvy chcete upravit. + Brightness/Contrast Jas/kontrast + Hue/Saturation Odstín/sytost + Temperature/Tint Teplota/nádech +@msg `{id}` is not a colour adjustment `{id}` není úprava barev +@msg missing `effect` chybí `effect` +@msg `params` must be an object `params` musí být objekt +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Přesné nástroje pro cesty + Anchor Eraser Brush Štětec gumy kotevních bodů + Extend Path Tool Nástroj Prodloužit cestu + Measure & Inspect Tool Nástroj Měřit a zkoumat + Anchor Inspector Inspektor kotevních bodů + Add Points at Crossings Přidat body v křížení + Split at Crossings Rozdělit v křížení + Extend Path Prodloužit cestu + Measure & Inspect Měřit a zkoumat + Set Anchor Nastavit kotevní bod + Make Smooth Změnit na hladký + Make Corner Změnit na rohový + Equalize Handles Vyrovnat úchyty + Remove Points, Keep Shape Odstranit body, zachovat tvar + Add Points to Segments… Přidat body do segmentů… + Add Points to Segments Přidat body do segmentů + Open a document to edit its anchor points. Otevřete dokument a upravte jeho kotevní body. + Anchors selected: {count} Vybrané kotevní body: {count} + Direct-select anchor points to edit them. Kotevní body pro úpravy vyberte přímým výběrem. + In: Vstup: + Out: Výstup: + Add Points Přidat body + Points per segment Bodů na segment + Close Path: Uzavřít cestu: + Keep Handles Zachovat úchyty + Straight Přímý + Stretch Curve Natáhnout křivku +@msg direct-select the anchor points to remove přímým výběrem vyberte kotevní body k odstranění +@msg select segments, or paths, to add points to vyberte segmenty nebo cesty, do nichž přidat body +@msg select open paths to close vyberte otevřené cesty k uzavření +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) příliš mnoho nebo příliš spletených cest pro nalezení jejich křížení (nejvýše 10000 segmentů) +@msg the paths have too many anchors to edit at once cesty mají příliš mnoho kotevních bodů na úpravu najednou diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3ab958c4bb..bac02b2ad1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5605,3 +5605,100 @@ axis Y Axis Y-akse Average & Join Gennemsnit og forbind anchor Points: Punkter: @msg select two open path ends, or two open paths, to average and join markér to ender af åbne stier eller to åbne stier, der skal udlignes til gennemsnit og forbindes + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Oprydning i grafik + Simplify Anchors (Keep Shape)… Forenkl ankerpunkter (bevar form)… + Health Check Sundhedstjek + Show Issue Vis problem + Fix All Issues Ret alle problemer + Fix Issues Ret problemer + Deep Ungroup… Afgruppér alle niveauer… + Rejoin Path Pieces… Forbind kurvestykker igen… + Document Health Check Sundhedstjek af dokument + Check Selection Kontrollér markering + Check Document Kontrollér dokument + No issues found. Ingen problemer fundet. + Changed since the last check. Ændret siden sidste kontrol. + Fix Selected Ret valgte + Fix All Ret alle + Issues fixed: {count} Rettede problemer: {count} + Open a document to check it for issues. Åbn et dokument for at kontrollere det for problemer. + Empty Text Tom tekst + Unpainted Objects Objekter uden farve + Zero-Opacity Objects Objekter med 0 % opacitet + Duplicate Objects Dublerede objekter + Off-Artboard Art Grafik uden for kunstpladerne + Duplicate Anchors Dublerede ankerpunkter + Tiny Handles Små håndtag + Collinear Anchors Kollineære ankerpunkter + Nearly Coincident Anchors Næsten sammenfaldende ankerpunkter + Nearly Closed Paths Næsten lukkede kurver + Filled Open Paths Udfyldte åbne kurver + Needless Clipping Groups Unødvendige beskæringsgrupper + Needless Compound Paths Unødvendige sammensatte kurver + Needless Groups Unødvendige grupper + Empty Artboards Tomme kunstplader + Protect Corners Beskyt hjørner + Gap Afstand + Include Clip Groups Medtag beskæringsgrupper +@msg `tolerance` must be from 1 to 100 `tolerance` skal være fra 1 til 100 +@msg `gap` must be from 0 to 6 pt `gap` skal være fra 0 til 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Forenkl ankerpunkter: kurverne har for mange ankerpunkter til at blive forenklet på én gang +@msg Rejoin Path Pieces: too many paths to rejoin at once Forbind kurvestykker igen: for mange kurver til at forbinde på én gang +@msg None of these issues are left: check again Ingen af disse problemer er tilbage: kontrollér igen +@msg `kinds` must be a list of issue kinds `kinds` skal være en liste over problemtyper +@msg missing `kind` `kind` mangler + Simplify Anchors (Keep Shape) Forenkl ankerpunkter (bevar form) + Deep Ungroup Afgruppér alle niveauer + Rejoin Path Pieces Forbind kurvestykker igen + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Farveeffekter + Color Effects Panel Panelet Farveeffekter + Exposure Eksponering + Exposure… Eksponering… + Desaturate Afmæt + Adjustment Justering + Add as Effect Tilføj som effekt + Apply as Filter Anvend som filter + Select objects to adjust their colors. Markér objekter for at justere deres farver. + Brightness/Contrast Lysstyrke/kontrast + Hue/Saturation Farvetone/mætning + Temperature/Tint Temperatur/toning +@msg `{id}` is not a colour adjustment `{id}` er ikke en farvejustering +@msg missing `effect` `effect` mangler +@msg `params` must be an object `params` skal være et objekt +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Præcisionsværktøjer til stier + Anchor Eraser Brush Ankerpunktviskepensel + Extend Path Tool Forlæng sti-værktøj + Measure & Inspect Tool Mål og undersøg-værktøj + Anchor Inspector Ankerpunktinspektør + Add Points at Crossings Tilføj punkter ved krydsninger + Split at Crossings Opdel ved krydsninger + Extend Path Forlæng sti + Measure & Inspect Mål og undersøg + Set Anchor Angiv ankerpunkt + Make Smooth Gør blødt + Make Corner Gør til hjørne + Equalize Handles Udlign håndtag + Remove Points, Keep Shape Fjern punkter, bevar form + Add Points to Segments… Tilføj punkter til segmenter… + Add Points to Segments Tilføj punkter til segmenter + Open a document to edit its anchor points. Åbn et dokument for at redigere dets ankerpunkter. + Anchors selected: {count} Valgte ankerpunkter: {count} + Direct-select anchor points to edit them. Vælg ankerpunkter direkte for at redigere dem. + In: Ind: + Out: Ud: + Add Points Tilføj punkter + Points per segment Punkter pr. segment + Close Path: Luk sti: + Keep Handles Bevar håndtag + Straight Lige + Stretch Curve Stræk kurve +@msg direct-select the anchor points to remove vælg de ankerpunkter, der skal fjernes, direkte +@msg select segments, or paths, to add points to vælg segmenter eller stier at tilføje punkter til +@msg select open paths to close vælg åbne stier at lukke +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) for mange eller for sammenfiltrede stier til at finde deres krydsninger (højst 10000 segmenter) +@msg the paths have too many anchors to edit at once stierne har for mange ankerpunkter til at blive redigeret på én gang diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c3cd9d6375..6adaa3f3a7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5282,3 +5282,101 @@ axis Y Axis Y-Achse Average & Join Durchschnitt berechnen und zusammenfügen anchor Points: Punkte: @msg select two open path ends, or two open paths, to average and join wählen Sie zwei Enden offener Pfade oder zwei offene Pfade aus, um sie zu mitteln und zusammenzufügen + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Bildmaterial-Bereinigung + Simplify Anchors (Keep Shape)… Ankerpunkte vereinfachen (Form erhalten)… + Health Check Zustandsprüfung + Show Issue Problem anzeigen + Fix All Issues Alle Probleme beheben + Fix Issues Probleme beheben + Deep Ungroup… Alle Gruppierungsebenen aufheben… + Rejoin Path Pieces… Pfadstücke wieder zusammenfügen… + Document Health Check Dokument-Zustandsprüfung + Check Selection Auswahl prüfen + Check Document Dokument prüfen + No issues found. Keine Probleme gefunden. + Changed since the last check. Seit der letzten Prüfung geändert. + Fix Selected Ausgewählte beheben + Fix All Alle beheben + Issues fixed: {count} Behobene Probleme: {count} + Open a document to check it for issues. Öffnen Sie ein Dokument, um es auf Probleme zu prüfen. + Empty Text Leerer Text + Unpainted Objects Objekte ohne Farbe + Zero-Opacity Objects Objekte mit 0 % Deckkraft + Duplicate Objects Doppelte Objekte + Off-Artboard Art Bildmaterial außerhalb der Zeichenflächen + Duplicate Anchors Doppelte Ankerpunkte + Tiny Handles Winzige Griffe + Collinear Anchors Kollineare Ankerpunkte + Nearly Coincident Anchors Fast deckungsgleiche Ankerpunkte + Nearly Closed Paths Fast geschlossene Pfade + Filled Open Paths Gefüllte offene Pfade + Needless Clipping Groups Überflüssige Schnittgruppen + Needless Compound Paths Überflüssige zusammengesetzte Pfade + Needless Groups Überflüssige Gruppen + Empty Artboards Leere Zeichenflächen + Protect Corners Ecken schützen + Gap Abstand + Include Clip Groups Schnittgruppen einbeziehen +@msg `tolerance` must be from 1 to 100 `tolerance` muss zwischen 1 und 100 liegen +@msg `gap` must be from 0 to 6 pt `gap` muss zwischen 0 und 6 pt liegen +@msg Simplify Anchors: the paths have too many anchors to simplify at once Ankerpunkte vereinfachen: Die Pfade haben zu viele Ankerpunkte, um sie auf einmal zu vereinfachen +@msg Rejoin Path Pieces: too many paths to rejoin at once Pfadstücke wieder zusammenfügen: zu viele Pfade, um sie auf einmal zusammenzufügen +@msg None of these issues are left: check again Keines dieser Probleme ist mehr vorhanden: Prüfen Sie erneut +@msg `kinds` must be a list of issue kinds `kinds` muss eine Liste von Problemarten sein +@msg missing `kind` `kind` fehlt + Simplify Anchors (Keep Shape) Ankerpunkte vereinfachen (Form erhalten) + Deep Ungroup Alle Gruppierungsebenen aufheben + Rejoin Path Pieces Pfadstücke wieder zusammenfügen + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Farbeffekte + Color Effects Panel Farbeffekte-Bedienfeld + Exposure Belichtung + Exposure… Belichtung… + Desaturate Sättigung verringern + Adjustment Korrektur + Add as Effect Als Effekt hinzufügen + Apply as Filter Als Filter anwenden + Select objects to adjust their colors. Wählen Sie Objekte aus, um ihre Farben anzupassen. + Brightness/Contrast Helligkeit/Kontrast + Hue/Saturation Farbton/Sättigung + Temperature/Tint Temperatur/Farbstich +@msg `{id}` is not a colour adjustment `{id}` ist keine Farbkorrektur +@msg missing `effect` `effect` fehlt +@msg `params` must be an object `params` muss ein Objekt sein +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Pfad-Präzisionswerkzeuge + Anchor Eraser Brush Ankerpunkt-Radierpinsel + Extend Path Tool Pfad-verlängern-Werkzeug + Measure & Inspect Tool Messen-und-Prüfen-Werkzeug + Anchor Inspector Ankerpunkt-Inspektor + Add Points at Crossings Punkte an Kreuzungen hinzufügen + Split at Crossings An Kreuzungen teilen + Extend Path Pfad verlängern + Measure & Inspect Messen und prüfen + Set Anchor Ankerpunkt festlegen + Make Smooth Glätten + Make Corner Zu Eckpunkt machen + Equalize Handles Griffe angleichen + Remove Points, Keep Shape Punkte entfernen, Form erhalten + Add Points to Segments… Punkte zu Segmenten hinzufügen… + Add Points to Segments Punkte zu Segmenten hinzufügen + Open a document to edit its anchor points. Öffnen Sie ein Dokument, um seine Ankerpunkte zu bearbeiten. + Anchors selected: {count} Ausgewählte Ankerpunkte: {count} + Direct-select anchor points to edit them. Wählen Sie Ankerpunkte direkt aus, um sie zu bearbeiten. + Length Länge + In: Ein: + Out: Aus: + Add Points Punkte hinzufügen + Points per segment Punkte pro Segment + Close Path: Pfad schließen: + Keep Handles Griffe beibehalten + Straight Gerade + Stretch Curve Kurve strecken +@msg direct-select the anchor points to remove die zu entfernenden Ankerpunkte direkt auswählen +@msg select segments, or paths, to add points to Segmente oder Pfade auswählen, denen Punkte hinzugefügt werden sollen +@msg select open paths to close offene Pfade zum Schließen auswählen +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) zu viele oder zu verschlungene Pfade, um ihre Kreuzungen zu finden (höchstens 10000 Segmente) +@msg the paths have too many anchors to edit at once die Pfade haben zu viele Ankerpunkte, um sie auf einmal zu bearbeiten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b40a460def..d30ffaa194 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5652,3 +5652,100 @@ axis Y Axis Άξονας Y Average & Join Μέσος όρος και ένωση anchor Points: Σημεία: @msg select two open path ends, or two open paths, to average and join επιλέξτε δύο άκρα ανοιχτών διαδρομών ή δύο ανοιχτές διαδρομές για μέσο όρο και ένωση + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Εκκαθάριση γραφικών + Simplify Anchors (Keep Shape)… Απλοποίηση σημείων αγκύρωσης (διατήρηση σχήματος)… + Health Check Έλεγχος κατάστασης + Show Issue Εμφάνιση προβλήματος + Fix All Issues Διόρθωση όλων των προβλημάτων + Fix Issues Διόρθωση προβλημάτων + Deep Ungroup… Κατάργηση ομαδοποίησης σε όλα τα επίπεδα… + Rejoin Path Pieces… Επανένωση τμημάτων διαδρομών… + Document Health Check Έλεγχος κατάστασης εγγράφου + Check Selection Έλεγχος επιλογής + Check Document Έλεγχος εγγράφου + No issues found. Δεν βρέθηκαν προβλήματα. + Changed since the last check. Άλλαξε μετά τον τελευταίο έλεγχο. + Fix Selected Διόρθωση επιλεγμένων + Fix All Διόρθωση όλων + Issues fixed: {count} Διορθωμένα προβλήματα: {count} + Open a document to check it for issues. Ανοίξτε ένα έγγραφο για να το ελέγξετε για προβλήματα. + Empty Text Κενό κείμενο + Unpainted Objects Αντικείμενα χωρίς χρώμα + Zero-Opacity Objects Αντικείμενα με μηδενική αδιαφάνεια + Duplicate Objects Διπλότυπα αντικείμενα + Off-Artboard Art Γραφικά εκτός πινάκων σχεδίασης + Duplicate Anchors Διπλότυπα σημεία αγκύρωσης + Tiny Handles Μικροσκοπικές λαβές + Collinear Anchors Συγγραμμικά σημεία αγκύρωσης + Nearly Coincident Anchors Σχεδόν συμπίπτοντα σημεία αγκύρωσης + Nearly Closed Paths Σχεδόν κλειστές διαδρομές + Filled Open Paths Γεμισμένες ανοιχτές διαδρομές + Needless Clipping Groups Περιττές ομάδες αποκοπής + Needless Compound Paths Περιττές σύνθετες διαδρομές + Needless Groups Περιττές ομάδες + Empty Artboards Κενοί πίνακες σχεδίασης + Protect Corners Προστασία γωνιών + Gap Απόσταση + Include Clip Groups Συμπερίληψη ομάδων αποκοπής +@msg `tolerance` must be from 1 to 100 Το `tolerance` πρέπει να είναι από 1 έως 100 +@msg `gap` must be from 0 to 6 pt Το `gap` πρέπει να είναι από 0 έως 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Απλοποίηση σημείων αγκύρωσης: οι διαδρομές έχουν πάρα πολλά σημεία αγκύρωσης για να απλοποιηθούν μονομιάς +@msg Rejoin Path Pieces: too many paths to rejoin at once Επανένωση τμημάτων διαδρομών: πάρα πολλές διαδρομές για επανένωση μονομιάς +@msg None of these issues are left: check again Δεν έχει απομείνει κανένα από αυτά τα προβλήματα: ελέγξτε ξανά +@msg `kinds` must be a list of issue kinds Το `kinds` πρέπει να είναι λίστα ειδών προβλημάτων +@msg missing `kind` λείπει το `kind` + Simplify Anchors (Keep Shape) Απλοποίηση σημείων αγκύρωσης (διατήρηση σχήματος) + Deep Ungroup Κατάργηση ομαδοποίησης σε όλα τα επίπεδα + Rejoin Path Pieces Επανένωση τμημάτων διαδρομών + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Εφέ χρώματος + Color Effects Panel Πλαίσιο Εφέ χρώματος + Exposure Έκθεση + Exposure… Έκθεση… + Desaturate Αποκορεσμός + Adjustment Διόρθωση + Add as Effect Προσθήκη ως εφέ + Apply as Filter Εφαρμογή ως φίλτρο + Select objects to adjust their colors. Επιλέξτε αντικείμενα για να προσαρμόσετε τα χρώματά τους. + Brightness/Contrast Φωτεινότητα/Αντίθεση + Hue/Saturation Απόχρωση/Κορεσμός + Temperature/Tint Θερμοκρασία/Απόχρωση +@msg `{id}` is not a colour adjustment Το `{id}` δεν είναι διόρθωση χρώματος +@msg missing `effect` λείπει το `effect` +@msg `params` must be an object Το `params` πρέπει να είναι αντικείμενο +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Εργαλεία ακρίβειας διαδρομών + Anchor Eraser Brush Πινέλο διαγραφής σημείων αγκύρωσης (Anchor Eraser Brush) + Extend Path Tool Επέκταση διαδρομής (Extend Path Tool) + Measure & Inspect Tool Μέτρηση και επιθεώρηση (Measure & Inspect Tool) + Anchor Inspector Επιθεωρητής σημείων αγκύρωσης + Add Points at Crossings Προσθήκη σημείων στις διασταυρώσεις + Split at Crossings Διαχωρισμός στις διασταυρώσεις + Extend Path Επέκταση διαδρομής + Measure & Inspect Μέτρηση και επιθεώρηση + Set Anchor Ορισμός σημείου αγκύρωσης + Make Smooth Μετατροπή σε ομαλό + Make Corner Μετατροπή σε γωνία + Equalize Handles Εξίσωση λαβών + Remove Points, Keep Shape Αφαίρεση σημείων, διατήρηση σχήματος + Add Points to Segments… Προσθήκη σημείων σε τμήματα… + Add Points to Segments Προσθήκη σημείων σε τμήματα + Open a document to edit its anchor points. Ανοίξτε ένα έγγραφο για να επεξεργαστείτε τα σημεία αγκύρωσής του. + Anchors selected: {count} Επιλεγμένα σημεία αγκύρωσης: {count} + Direct-select anchor points to edit them. Επιλέξτε απευθείας σημεία αγκύρωσης για να τα επεξεργαστείτε. + In: Είσοδος: + Out: Έξοδος: + Add Points Προσθήκη σημείων + Points per segment Σημεία ανά τμήμα + Close Path: Κλείσιμο διαδρομής: + Keep Handles Διατήρηση λαβών + Straight Ευθύ + Stretch Curve Τέντωμα καμπύλης +@msg direct-select the anchor points to remove επιλέξτε απευθείας τα σημεία αγκύρωσης προς αφαίρεση +@msg select segments, or paths, to add points to επιλέξτε τμήματα ή διαδρομές στα οποία θα προστεθούν σημεία +@msg select open paths to close επιλέξτε ανοιχτές διαδρομές για κλείσιμο +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) οι διαδρομές είναι πάρα πολλές ή πολύ μπλεγμένες για να βρεθούν οι διασταυρώσεις τους (έως 10000 τμήματα) +@msg the paths have too many anchors to edit at once οι διαδρομές έχουν πάρα πολλά σημεία αγκύρωσης για επεξεργασία με μία φορά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 72b330091f..0fbc7da18f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5642,3 +5642,101 @@ axis Y Axis Eje Y Average & Join Promediar y unir anchor Points: Puntos: @msg select two open path ends, or two open paths, to average and join selecciona dos extremos de trazados abiertos, o dos trazados abiertos, para promediarlos y unirlos + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Limpieza de ilustraciones + Simplify Anchors (Keep Shape)… Simplificar puntos de ancla (mantener forma)… + Health Check Revisión de estado + Show Issue Mostrar problema + Fix All Issues Corregir todos los problemas + Fix Issues Corregir problemas + Deep Ungroup… Desagrupar todos los niveles… + Rejoin Path Pieces… Volver a unir fragmentos de trazado… + Document Health Check Revisión de estado del documento + Check Selection Revisar selección + Check Document Revisar documento + No issues found. No se encontraron problemas. + Changed since the last check. Ha cambiado desde la última revisión. + Fix Selected Corregir seleccionados + Fix All Corregir todo + Issues fixed: {count} Problemas corregidos: {count} + Open a document to check it for issues. Abra un documento para buscar problemas en él. + Empty Text Texto vacío + Unpainted Objects Objetos sin pintar + Zero-Opacity Objects Objetos con opacidad cero + Duplicate Objects Objetos duplicados + Off-Artboard Art Ilustración fuera de las mesas de trabajo + Duplicate Anchors Puntos de ancla duplicados + Tiny Handles Manejadores diminutos + Collinear Anchors Puntos de ancla colineales + Nearly Coincident Anchors Puntos de ancla casi coincidentes + Nearly Closed Paths Trazados casi cerrados + Filled Open Paths Trazados abiertos con relleno + Needless Clipping Groups Grupos de recorte innecesarios + Needless Compound Paths Trazados compuestos innecesarios + Needless Groups Grupos innecesarios + Empty Artboards Mesas de trabajo vacías + Protect Corners Proteger esquinas + Gap Separación + Include Clip Groups Incluir grupos de recorte +@msg `tolerance` must be from 1 to 100 `tolerance` debe estar entre 1 y 100 +@msg `gap` must be from 0 to 6 pt `gap` debe estar entre 0 y 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Simplificar puntos de ancla: los trazados tienen demasiados puntos de ancla para simplificarlos de una vez +@msg Rejoin Path Pieces: too many paths to rejoin at once Volver a unir fragmentos de trazado: demasiados trazados para unirlos de una vez +@msg None of these issues are left: check again Ya no queda ninguno de estos problemas: vuelva a revisar +@msg `kinds` must be a list of issue kinds `kinds` debe ser una lista de tipos de problema +@msg missing `kind` falta `kind` + Simplify Anchors (Keep Shape) Simplificar puntos de ancla (mantener forma) + Deep Ungroup Desagrupar todos los niveles + Rejoin Path Pieces Volver a unir fragmentos de trazado + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Efectos de color + Color Effects Panel Panel Efectos de color + Exposure Exposición + Exposure… Exposición… + Desaturate Desaturar + Adjustment Ajuste + Add as Effect Añadir como efecto + Apply as Filter Aplicar como filtro + Select objects to adjust their colors. Seleccione objetos para ajustar sus colores. + Brightness/Contrast Brillo/contraste + Hue/Saturation Tono/saturación + Temperature/Tint Temperatura/tinte +@msg `{id}` is not a colour adjustment `{id}` no es un ajuste de color +@msg missing `effect` falta `effect` +@msg `params` must be an object `params` debe ser un objeto +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Herramientas de precisión de trazados + Anchor Eraser Brush Pincel borrador de puntos de ancla + Extend Path Tool Herramienta Prolongar trazado + Measure & Inspect Tool Herramienta Medir e inspeccionar + Anchor Inspector Inspector de puntos de ancla + Add Points at Crossings Agregar puntos en los cruces + Split at Crossings Dividir en los cruces + Extend Path Prolongar trazado + Measure & Inspect Medir e inspeccionar + Set Anchor Definir punto de ancla + Make Smooth Suavizar punto + Make Corner Convertir en vértice + Equalize Handles Igualar manejadores + Remove Points, Keep Shape Quitar puntos, mantener forma + Add Points to Segments… Agregar puntos a segmentos… + Add Points to Segments Agregar puntos a segmentos + Open a document to edit its anchor points. Abra un documento para editar sus puntos de ancla. + Anchors selected: {count} Puntos de ancla seleccionados: {count} + Direct-select anchor points to edit them. Seleccione directamente puntos de ancla para editarlos. + Length Longitud + In: Entrada: + Out: Salida: + Add Points Agregar puntos + Points per segment Puntos por segmento + Close Path: Cerrar trazado: + Keep Handles Mantener manejadores + Straight Recto + Stretch Curve Estirar curva +@msg direct-select the anchor points to remove seleccione directamente los puntos de ancla que quitar +@msg select segments, or paths, to add points to seleccione segmentos, o trazados, a los que agregar puntos +@msg select open paths to close seleccione trazados abiertos que cerrar +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) hay demasiados trazados, o están demasiado enredados, para hallar sus cruces (10000 segmentos como máximo) +@msg the paths have too many anchors to edit at once los trazados tienen demasiados puntos de ancla para editarlos a la vez diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 62b0820c7b..2bd47a6ef3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5731,3 +5731,100 @@ axis Y Axis Y-akseli Average & Join Keskiarvota ja liitä anchor Points: Pisteet: @msg select two open path ends, or two open paths, to average and join valitse kaksi avoimen polun päätä tai kaksi avointa polkua keskiarvotettaviksi ja liitettäviksi + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Grafiikan siivous + Simplify Anchors (Keep Shape)… Yksinkertaista ankkuripisteet (säilytä muoto)… + Health Check Kuntotarkistus + Show Issue Näytä ongelma + Fix All Issues Korjaa kaikki ongelmat + Fix Issues Korjaa ongelmat + Deep Ungroup… Pura kaikki ryhmitystasot… + Rejoin Path Pieces… Yhdistä polun palat uudelleen… + Document Health Check Asiakirjan kuntotarkistus + Check Selection Tarkista valinta + Check Document Tarkista asiakirja + No issues found. Ongelmia ei löytynyt. + Changed since the last check. Muuttunut edellisen tarkistuksen jälkeen. + Fix Selected Korjaa valitut + Fix All Korjaa kaikki + Issues fixed: {count} Korjattuja ongelmia: {count} + Open a document to check it for issues. Avaa asiakirja tarkistaaksesi sen ongelmat. + Empty Text Tyhjä teksti + Unpainted Objects Värittömät objektit + Zero-Opacity Objects Täysin läpinäkyvät objektit + Duplicate Objects Objektien kaksoiskappaleet + Off-Artboard Art Piirtoalustojen ulkopuolinen grafiikka + Duplicate Anchors Kaksinkertaiset ankkuripisteet + Tiny Handles Pienet kahvat + Collinear Anchors Samalla suoralla olevat ankkuripisteet + Nearly Coincident Anchors Lähes yhtenevät ankkuripisteet + Nearly Closed Paths Lähes suljetut polut + Filled Open Paths Täytetyt avoimet polut + Needless Clipping Groups Tarpeettomat leikkausryhmät + Needless Compound Paths Tarpeettomat yhdistelmäpolut + Needless Groups Tarpeettomat ryhmät + Empty Artboards Tyhjät piirtoalustat + Protect Corners Suojaa kulmat + Gap Väli + Include Clip Groups Sisällytä leikkausryhmät +@msg `tolerance` must be from 1 to 100 `tolerance`-arvon on oltava 1–100 +@msg `gap` must be from 0 to 6 pt `gap`-arvon on oltava 0–6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Yksinkertaista ankkuripisteet: poluissa on liian monta ankkuripistettä yksinkertaistettavaksi kerralla +@msg Rejoin Path Pieces: too many paths to rejoin at once Yhdistä polun palat uudelleen: liian monta polkua yhdistettäväksi kerralla +@msg None of these issues are left: check again Yhtään näistä ongelmista ei ole enää jäljellä: tarkista uudelleen +@msg `kinds` must be a list of issue kinds `kinds`-arvon on oltava luettelo ongelmatyypeistä +@msg missing `kind` `kind` puuttuu + Simplify Anchors (Keep Shape) Yksinkertaista ankkuripisteet (säilytä muoto) + Deep Ungroup Pura kaikki ryhmitystasot + Rejoin Path Pieces Yhdistä polun palat uudelleen + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Väritehosteet + Color Effects Panel Väritehosteet-paneeli + Exposure Valotus + Exposure… Valotus… + Desaturate Poista värikylläisyys + Adjustment Säätö + Add as Effect Lisää tehosteena + Apply as Filter Käytä suodattimena + Select objects to adjust their colors. Valitse objektit, joiden värejä haluat säätää. + Brightness/Contrast Kirkkaus/kontrasti + Hue/Saturation Sävy/kylläisyys + Temperature/Tint Lämpötila/sävy +@msg `{id}` is not a colour adjustment `{id}` ei ole värisäätö +@msg missing `effect` `effect` puuttuu +@msg `params` must be an object `params` on oltava objekti +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Polkujen tarkkuustyökalut + Anchor Eraser Brush Ankkuripisteiden pyyhintäsivellin + Extend Path Tool Polun jatkamistyökalu + Measure & Inspect Tool Mittaus- ja tarkastelutyökalu + Anchor Inspector Ankkuripisteiden tarkastelu + Add Points at Crossings Lisää pisteet risteyskohtiin + Split at Crossings Jaa risteyskohdista + Extend Path Jatka polkua + Measure & Inspect Mittaa ja tarkastele + Set Anchor Aseta ankkuripiste + Make Smooth Tee tasaiseksi + Make Corner Tee kulmapisteeksi + Equalize Handles Tasaa kahvat + Remove Points, Keep Shape Poista pisteet, säilytä muoto + Add Points to Segments… Lisää pisteitä osiin… + Add Points to Segments Lisää pisteitä osiin + Open a document to edit its anchor points. Avaa asiakirja muokataksesi sen ankkuripisteitä. + Anchors selected: {count} Valittuja ankkuripisteitä: {count} + Direct-select anchor points to edit them. Valitse ankkuripisteet suoraan muokataksesi niitä. + In: Sisään: + Out: Ulos: + Add Points Lisää pisteitä + Points per segment Pisteitä osaa kohden + Close Path: Sulje polku: + Keep Handles Säilytä kahvat + Straight Suora + Stretch Curve Venytä käyrää +@msg direct-select the anchor points to remove valitse poistettavat ankkuripisteet suoraan +@msg select segments, or paths, to add points to valitse osat tai polut, joihin pisteitä lisätään +@msg select open paths to close valitse suljettavat avoimet polut +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) liian monta tai liian sotkuista polkua niiden risteyskohtien löytämiseen (enintään 10000 osaa) +@msg the paths have too many anchors to edit at once poluissa on liian monta ankkuripistettä muokattavaksi kerralla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0c9ddfc3d9..ae3f1b86a2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5699,3 +5699,100 @@ axis Y Axis Axe Y Average & Join Alignement et jonction anchor Points: Points : @msg select two open path ends, or two open paths, to average and join sélectionnez deux extrémités de tracés ouverts, ou deux tracés ouverts, à aligner et joindre + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Nettoyage des illustrations + Simplify Anchors (Keep Shape)… Simplifier les points d’ancrage (conserver la forme)… + Health Check Vérification de l’état + Show Issue Afficher le problème + Fix All Issues Corriger tous les problèmes + Fix Issues Corriger les problèmes + Deep Ungroup… Dissocier tous les niveaux… + Rejoin Path Pieces… Rejoindre les morceaux de tracé… + Document Health Check Vérification de l’état du document + Check Selection Vérifier la sélection + Check Document Vérifier le document + No issues found. Aucun problème trouvé. + Changed since the last check. Modifié depuis la dernière vérification. + Fix Selected Corriger la sélection + Fix All Tout corriger + Issues fixed: {count} Problèmes corrigés : {count} + Open a document to check it for issues. Ouvrez un document pour y rechercher des problèmes. + Empty Text Texte vide + Unpainted Objects Objets sans fond ni contour + Zero-Opacity Objects Objets à opacité nulle + Duplicate Objects Objets en double + Off-Artboard Art Illustration hors des plans de travail + Duplicate Anchors Points d’ancrage en double + Tiny Handles Poignées minuscules + Collinear Anchors Points d’ancrage alignés + Nearly Coincident Anchors Points d’ancrage presque confondus + Nearly Closed Paths Tracés presque fermés + Filled Open Paths Tracés ouverts avec fond + Needless Clipping Groups Groupes de découpe inutiles + Needless Compound Paths Tracés transparents inutiles + Needless Groups Groupes inutiles + Empty Artboards Plans de travail vides + Protect Corners Protéger les angles + Gap Écart + Include Clip Groups Inclure les groupes de découpe +@msg `tolerance` must be from 1 to 100 `tolerance` doit être compris entre 1 et 100 +@msg `gap` must be from 0 to 6 pt `gap` doit être compris entre 0 et 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Simplifier les points d’ancrage : les tracés ont trop de points d’ancrage pour être simplifiés en une fois +@msg Rejoin Path Pieces: too many paths to rejoin at once Rejoindre les morceaux de tracé : trop de tracés à rejoindre en une fois +@msg None of these issues are left: check again Aucun de ces problèmes ne subsiste : relancez la vérification +@msg `kinds` must be a list of issue kinds `kinds` doit être une liste de types de problèmes +@msg missing `kind` `kind` manquant + Simplify Anchors (Keep Shape) Simplifier les points d’ancrage (conserver la forme) + Deep Ungroup Dissocier tous les niveaux + Rejoin Path Pieces Rejoindre les morceaux de tracé + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Effets de couleur + Color Effects Panel Panneau Effets de couleur + Exposure Exposition + Exposure… Exposition… + Desaturate Désaturer + Adjustment Réglage + Add as Effect Ajouter comme effet + Apply as Filter Appliquer comme filtre + Select objects to adjust their colors. Sélectionnez des objets pour régler leurs couleurs. + Brightness/Contrast Luminosité/contraste + Hue/Saturation Teinte/saturation + Temperature/Tint Température/teinte +@msg `{id}` is not a colour adjustment `{id}` n'est pas un réglage de couleur +@msg missing `effect` `effect` manquant +@msg `params` must be an object `params` doit être un objet +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Outils de précision des tracés + Anchor Eraser Brush Pinceau effaceur de points d’ancrage + Extend Path Tool Outil Prolonger le tracé + Measure & Inspect Tool Outil Mesurer et inspecter + Anchor Inspector Inspecteur de points d’ancrage + Add Points at Crossings Ajouter des points aux croisements + Split at Crossings Scinder aux croisements + Extend Path Prolonger le tracé + Measure & Inspect Mesurer et inspecter + Set Anchor Définir le point d’ancrage + Make Smooth Rendre lisse + Make Corner Rendre angulaire + Equalize Handles Égaliser les poignées + Remove Points, Keep Shape Supprimer des points, conserver la forme + Add Points to Segments… Ajouter des points aux segments… + Add Points to Segments Ajouter des points aux segments + Open a document to edit its anchor points. Ouvrez un document pour modifier ses points d’ancrage. + Anchors selected: {count} Points d’ancrage sélectionnés : {count} + Direct-select anchor points to edit them. Sélectionnez directement des points d’ancrage pour les modifier. + In: Entrée : + Out: Sortie : + Add Points Ajouter des points + Points per segment Points par segment + Close Path: Fermer le tracé : + Keep Handles Conserver les poignées + Straight Droit + Stretch Curve Étirer la courbe +@msg direct-select the anchor points to remove sélectionnez directement les points d’ancrage à supprimer +@msg select segments, or paths, to add points to sélectionnez des segments, ou des tracés, auxquels ajouter des points +@msg select open paths to close sélectionnez des tracés ouverts à fermer +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) trop de tracés, ou trop enchevêtrés, pour trouver leurs croisements (10000 segments au plus) +@msg the paths have too many anchors to edit at once les tracés ont trop de points d’ancrage pour être modifiés en une fois diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4b6adc0ea4..55614e708c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5686,3 +5686,101 @@ axis Y Axis Y tengely Average & Join Átlagolás és összekapcsolás anchor Points: Pontok: @msg select two open path ends, or two open paths, to average and join jelölj ki két nyitott útvonalvéget vagy két nyitott útvonalat az átlagoláshoz és összekapcsoláshoz + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Grafika tisztítása + Simplify Anchors (Keep Shape)… Horgonypontok egyszerűsítése (alak megtartása)… + Health Check Állapotellenőrzés + Show Issue Probléma megjelenítése + Fix All Issues Minden probléma javítása + Fix Issues Problémák javítása + Deep Ungroup… Csoportbontás minden szinten… + Rejoin Path Pieces… Útvonaldarabok újraegyesítése… + Document Health Check Dokumentum állapotellenőrzése + Check Selection Kijelölés ellenőrzése + Check Document Dokumentum ellenőrzése + No issues found. Nem található probléma. + Changed since the last check. Módosult a legutóbbi ellenőrzés óta. + Fix Selected Kijelöltek javítása + Fix All Összes javítása + Issues fixed: {count} Javított problémák: {count} + Open a document to check it for issues. Nyisson meg egy dokumentumot a problémák ellenőrzéséhez. + Empty Text Üres szöveg + Unpainted Objects Festetlen objektumok + Zero-Opacity Objects Nulla átlátszatlanságú objektumok + Duplicate Objects Ismétlődő objektumok + Off-Artboard Art Rajztáblákon kívüli grafika + Duplicate Anchors Ismétlődő horgonypontok + Tiny Handles Apró fogantyúk + Collinear Anchors Egy egyenesre eső horgonypontok + Nearly Coincident Anchors Majdnem egybeeső horgonypontok + Nearly Closed Paths Majdnem zárt útvonalak + Filled Open Paths Kitöltött nyitott útvonalak + Needless Clipping Groups Szükségtelen vágócsoportok + Needless Compound Paths Szükségtelen összetett útvonalak + Needless Groups Szükségtelen csoportok + Empty Artboards Üres rajztáblák + Protect Corners Sarkok védelme + Gap Hézag + Include Clip Groups Vágócsoportokkal együtt +@msg `tolerance` must be from 1 to 100 A `tolerance` értéke 1 és 100 között lehet +@msg `gap` must be from 0 to 6 pt A `gap` értéke 0 és 6 pt között lehet +@msg Simplify Anchors: the paths have too many anchors to simplify at once Horgonypontok egyszerűsítése: az útvonalaknak túl sok horgonypontja van ahhoz, hogy egyszerre egyszerűsíthetők legyenek +@msg Rejoin Path Pieces: too many paths to rejoin at once Útvonaldarabok újraegyesítése: túl sok útvonal az egyszerre történő egyesítéshez +@msg None of these issues are left: check again Ezek közül a problémák közül már egy sem maradt: ellenőrizze újra +@msg `kinds` must be a list of issue kinds A `kinds` értékének problémafajták listájának kell lennie +@msg missing `kind` hiányzik a `kind` + Simplify Anchors (Keep Shape) Horgonypontok egyszerűsítése (alak megtartása) + Deep Ungroup Csoportbontás minden szinten + Rejoin Path Pieces Útvonaldarabok újraegyesítése + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Színeffektusok + Color Effects Panel Színeffektusok panel + Exposure Expozíció + Exposure… Expozíció… + Desaturate Telítettség csökkentése + Adjustment Korrekció + Add as Effect Hozzáadás effektusként + Apply as Filter Alkalmazás szűrőként + Select objects to adjust their colors. Jelöljön ki objektumokat a színeik módosításához. + Brightness/Contrast Fényesség/kontraszt + Hue/Saturation Színárnyalat/telítettség + Temperature/Tint Színhőmérséklet/tónus +@msg `{id}` is not a colour adjustment `{id}` nem színkorrekció +@msg missing `effect` hiányzik: `effect` +@msg `params` must be an object `params`: objektum kell +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Útvonal-precíziós eszközök + Anchor Eraser Brush Horgonypont-radírecset + Extend Path Tool Útvonal meghosszabbítása eszköz + Measure & Inspect Tool Mérés és vizsgálat eszköz + Anchor Inspector Horgonypont-vizsgáló + Add Points at Crossings Pontok hozzáadása a kereszteződésekben + Split at Crossings Felosztás a kereszteződésekben + Extend Path Útvonal meghosszabbítása + Measure & Inspect Mérés és vizsgálat + Set Anchor Horgonypont beállítása + Make Smooth Simává alakítás + Make Corner Sarokká alakítás + Equalize Handles Fogantyúk kiegyenlítése + Remove Points, Keep Shape Pontok eltávolítása, alak megtartása + Add Points to Segments… Pontok hozzáadása a szakaszokhoz… + Add Points to Segments Pontok hozzáadása a szakaszokhoz + Open a document to edit its anchor points. Nyisson meg egy dokumentumot a horgonypontjai szerkesztéséhez. + Anchors selected: {count} Kijelölt horgonypontok: {count} + Direct-select anchor points to edit them. A szerkesztéshez jelölje ki közvetlenül a horgonypontokat. + Length Hossz + In: Be: + Out: Ki: + Add Points Pontok hozzáadása + Points per segment Pont szakaszonként + Close Path: Útvonal lezárása: + Keep Handles Fogantyúk megtartása + Straight Egyenes + Stretch Curve Görbe nyújtása +@msg direct-select the anchor points to remove jelölje ki közvetlenül az eltávolítandó horgonypontokat +@msg select segments, or paths, to add points to jelöljön ki szakaszokat vagy útvonalakat, amelyekhez pontokat ad +@msg select open paths to close jelöljön ki lezárandó nyitott útvonalakat +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) túl sok vagy túl összegabalyodott útvonal a kereszteződések megtalálásához (legfeljebb 10000 szakasz) +@msg the paths have too many anchors to edit at once az útvonalaknak túl sok horgonypontjuk van az egyszerre szerkesztéshez diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 752637084d..99db664b51 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5605,3 +5605,100 @@ axis Y Axis Sumbu Y Average & Join Rata-rata dan sambungkan anchor Points: Titik: @msg select two open path ends, or two open paths, to average and join pilih dua ujung jalur terbuka, atau dua jalur terbuka, untuk dirata-ratakan dan disambungkan + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Pembersihan karya + Simplify Anchors (Keep Shape)… Sederhanakan titik jangkar (pertahankan bentuk)… + Health Check Pemeriksaan kesehatan + Show Issue Tampilkan masalah + Fix All Issues Perbaiki semua masalah + Fix Issues Perbaiki masalah + Deep Ungroup… Buka grup di semua tingkat… + Rejoin Path Pieces… Sambungkan kembali potongan jalur… + Document Health Check Pemeriksaan kesehatan dokumen + Check Selection Periksa seleksi + Check Document Periksa dokumen + No issues found. Tidak ada masalah yang ditemukan. + Changed since the last check. Berubah sejak pemeriksaan terakhir. + Fix Selected Perbaiki yang dipilih + Fix All Perbaiki semua + Issues fixed: {count} Masalah diperbaiki: {count} + Open a document to check it for issues. Buka dokumen untuk memeriksa masalahnya. + Empty Text Teks kosong + Unpainted Objects Objek tanpa warna + Zero-Opacity Objects Objek dengan opasitas nol + Duplicate Objects Objek duplikat + Off-Artboard Art Karya di luar artboard + Duplicate Anchors Titik jangkar duplikat + Tiny Handles Pegangan sangat kecil + Collinear Anchors Titik jangkar segaris + Nearly Coincident Anchors Titik jangkar yang hampir berimpit + Nearly Closed Paths Jalur yang hampir tertutup + Filled Open Paths Jalur terbuka berisi + Needless Clipping Groups Grup kliping yang tidak perlu + Needless Compound Paths Jalur majemuk yang tidak perlu + Needless Groups Grup yang tidak perlu + Empty Artboards Artboard kosong + Protect Corners Lindungi sudut + Gap Celah + Include Clip Groups Sertakan grup kliping +@msg `tolerance` must be from 1 to 100 `tolerance` harus antara 1 dan 100 +@msg `gap` must be from 0 to 6 pt `gap` harus antara 0 dan 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Sederhanakan titik jangkar: jalur memiliki terlalu banyak titik jangkar untuk disederhanakan sekaligus +@msg Rejoin Path Pieces: too many paths to rejoin at once Sambungkan kembali potongan jalur: terlalu banyak jalur untuk disambungkan sekaligus +@msg None of these issues are left: check again Tidak ada lagi masalah ini yang tersisa: periksa lagi +@msg `kinds` must be a list of issue kinds `kinds` harus berupa daftar jenis masalah +@msg missing `kind` `kind` tidak ada + Simplify Anchors (Keep Shape) Sederhanakan titik jangkar (pertahankan bentuk) + Deep Ungroup Buka grup di semua tingkat + Rejoin Path Pieces Sambungkan kembali potongan jalur + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Efek Warna + Color Effects Panel Panel Efek Warna + Exposure Eksposur + Exposure… Eksposur… + Desaturate Hilangkan Saturasi + Adjustment Penyesuaian + Add as Effect Tambahkan sebagai Efek + Apply as Filter Terapkan sebagai Filter + Select objects to adjust their colors. Pilih objek untuk menyesuaikan warnanya. + Brightness/Contrast Kecerahan/kontras + Hue/Saturation Rona/saturasi + Temperature/Tint Suhu/tint +@msg `{id}` is not a colour adjustment `{id}` bukan penyesuaian warna +@msg missing `effect` `effect` tidak ada +@msg `params` must be an object `params` harus berupa objek +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Alat presisi jalur + Anchor Eraser Brush Kuas penghapus titik jangkar + Extend Path Tool Alat perpanjang jalur + Measure & Inspect Tool Alat ukur dan periksa + Anchor Inspector Pemeriksa titik jangkar + Add Points at Crossings Tambahkan titik di persilangan + Split at Crossings Pisahkan di persilangan + Extend Path Perpanjang jalur + Measure & Inspect Ukur dan periksa + Set Anchor Atur titik jangkar + Make Smooth Jadikan halus + Make Corner Jadikan sudut + Equalize Handles Samakan pegangan + Remove Points, Keep Shape Hapus titik, pertahankan bentuk + Add Points to Segments… Tambahkan titik ke segmen… + Add Points to Segments Tambahkan titik ke segmen + Open a document to edit its anchor points. Buka dokumen untuk menyunting titik jangkarnya. + Anchors selected: {count} Titik jangkar terpilih: {count} + Direct-select anchor points to edit them. Pilih langsung titik jangkar untuk menyuntingnya. + In: Masuk: + Out: Keluar: + Add Points Tambahkan titik + Points per segment Titik per segmen + Close Path: Tutup jalur: + Keep Handles Pertahankan pegangan + Straight Lurus + Stretch Curve Regangkan kurva +@msg direct-select the anchor points to remove pilih langsung titik jangkar yang akan dihapus +@msg select segments, or paths, to add points to pilih segmen, atau jalur, untuk ditambahi titik +@msg select open paths to close pilih jalur terbuka untuk ditutup +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) jalur terlalu banyak atau terlalu kusut untuk menemukan persilangannya (paling banyak 10000 segmen) +@msg the paths have too many anchors to edit at once jalur memiliki terlalu banyak titik jangkar untuk disunting sekaligus diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4e27d545a5..eb91330e10 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5316,3 +5316,101 @@ axis Y Axis Asse Y Average & Join Media e unisci anchor Points: Punti: @msg select two open path ends, or two open paths, to average and join seleziona due estremità di tracciati aperti, o due tracciati aperti, da mediare e unire + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Pulizia grafica + Simplify Anchors (Keep Shape)… Semplifica punti di ancoraggio (mantieni forma)… + Health Check Controllo integrità + Show Issue Mostra problema + Fix All Issues Correggi tutti i problemi + Fix Issues Correggi problemi + Deep Ungroup… Separa tutti i livelli… + Rejoin Path Pieces… Ricongiungi parti di tracciato… + Document Health Check Controllo integrità documento + Check Selection Controlla selezione + Check Document Controlla documento + No issues found. Nessun problema trovato. + Changed since the last check. Modificato dall’ultimo controllo. + Fix Selected Correggi selezionati + Fix All Correggi tutto + Issues fixed: {count} Problemi corretti: {count} + Open a document to check it for issues. Apri un documento per controllarne i problemi. + Empty Text Testo vuoto + Unpainted Objects Oggetti senza colore + Zero-Opacity Objects Oggetti con opacità zero + Duplicate Objects Oggetti duplicati + Off-Artboard Art Grafica fuori dalle tavole da disegno + Duplicate Anchors Punti di ancoraggio duplicati + Tiny Handles Maniglie minuscole + Collinear Anchors Punti di ancoraggio allineati + Nearly Coincident Anchors Punti di ancoraggio quasi coincidenti + Nearly Closed Paths Tracciati quasi chiusi + Filled Open Paths Tracciati aperti con riempimento + Needless Clipping Groups Gruppi di ritaglio superflui + Needless Compound Paths Tracciati composti superflui + Needless Groups Gruppi superflui + Empty Artboards Tavole da disegno vuote + Protect Corners Proteggi angoli + Gap Distanza + Include Clip Groups Includi gruppi di ritaglio +@msg `tolerance` must be from 1 to 100 `tolerance` deve essere compreso tra 1 e 100 +@msg `gap` must be from 0 to 6 pt `gap` deve essere compreso tra 0 e 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Semplifica punti di ancoraggio: i tracciati hanno troppi punti di ancoraggio da semplificare in una volta +@msg Rejoin Path Pieces: too many paths to rejoin at once Ricongiungi parti di tracciato: troppi tracciati da ricongiungere in una volta +@msg None of these issues are left: check again Nessuno di questi problemi è ancora presente: controlla di nuovo +@msg `kinds` must be a list of issue kinds `kinds` deve essere un elenco di tipi di problema +@msg missing `kind` `kind` mancante + Simplify Anchors (Keep Shape) Semplifica punti di ancoraggio (mantieni forma) + Deep Ungroup Separa tutti i livelli + Rejoin Path Pieces Ricongiungi parti di tracciato + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Effetti colore + Color Effects Panel Pannello Effetti colore + Exposure Esposizione + Exposure… Esposizione… + Desaturate Desatura + Adjustment Regolazione + Add as Effect Aggiungi come effetto + Apply as Filter Applica come filtro + Select objects to adjust their colors. Seleziona gli oggetti per regolarne i colori. + Brightness/Contrast Luminosità/contrasto + Hue/Saturation Tonalità/saturazione + Temperature/Tint Temperatura/tinta +@msg `{id}` is not a colour adjustment `{id}` non è una regolazione del colore +@msg missing `effect` manca `effect` +@msg `params` must be an object `params` deve essere un oggetto +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Strumenti di precisione per tracciati + Anchor Eraser Brush Pennello gomma punti di ancoraggio + Extend Path Tool Strumento Estendi tracciato + Measure & Inspect Tool Strumento Misura e ispeziona + Anchor Inspector Ispettore punti di ancoraggio + Add Points at Crossings Aggiungi punti agli incroci + Split at Crossings Dividi agli incroci + Extend Path Estendi tracciato + Measure & Inspect Misura e ispeziona + Set Anchor Imposta punto di ancoraggio + Make Smooth Rendi arrotondato + Make Corner Rendi angolo + Equalize Handles Uguaglia maniglie + Remove Points, Keep Shape Rimuovi punti, mantieni forma + Add Points to Segments… Aggiungi punti ai segmenti… + Add Points to Segments Aggiungi punti ai segmenti + Open a document to edit its anchor points. Apri un documento per modificarne i punti di ancoraggio. + Anchors selected: {count} Punti di ancoraggio selezionati: {count} + Direct-select anchor points to edit them. Seleziona direttamente i punti di ancoraggio per modificarli. + Length Lunghezza + In: Entrata: + Out: Uscita: + Add Points Aggiungi punti + Points per segment Punti per segmento + Close Path: Chiudi tracciato: + Keep Handles Mantieni maniglie + Straight Diritto + Stretch Curve Allunga curva +@msg direct-select the anchor points to remove seleziona direttamente i punti di ancoraggio da rimuovere +@msg select segments, or paths, to add points to seleziona segmenti, o tracciati, a cui aggiungere punti +@msg select open paths to close seleziona tracciati aperti da chiudere +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) tracciati troppi o troppo intricati per trovarne gli incroci (al massimo 10000 segmenti) +@msg the paths have too many anchors to edit at once i tracciati hanno troppi punti di ancoraggio da modificare in una volta diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index bc8c797ff5..b9d63a54ab 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5385,3 +5385,101 @@ axis Y Axis Y 軸 Average & Join 平均と連結 anchor Points: ポイント: @msg select two open path ends, or two open paths, to average and join 平均と連結には、オープンパスの端点を 2 つ、またはオープンパスを 2 つ選択してください + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup アートワークのクリーンアップ + Simplify Anchors (Keep Shape)… アンカーポイントを単純化(形状を維持)… + Health Check ヘルスチェック + Show Issue 問題を表示 + Fix All Issues すべての問題を修正 + Fix Issues 問題を修正 + Deep Ungroup… すべての階層のグループ解除… + Rejoin Path Pieces… パスの断片を再連結… + Document Health Check ドキュメントのヘルスチェック + Check Selection 選択範囲をチェック + Check Document ドキュメントをチェック + No issues found. 問題は見つかりませんでした。 + Changed since the last check. 前回のチェック以降に変更されています。 + Fix Selected 選択した問題を修正 + Fix All すべて修正 + Issues fixed: {count} 修正した問題:{count} + Open a document to check it for issues. ドキュメントを開くと問題をチェックできます。 + Empty Text 空のテキスト + Unpainted Objects 塗りも線もないオブジェクト + Zero-Opacity Objects 不透明度 0% のオブジェクト + Duplicate Objects 重複したオブジェクト + Off-Artboard Art アートボード外のアートワーク + Duplicate Anchors 重複したアンカーポイント + Tiny Handles ごく短いハンドル + Collinear Anchors 同一直線上のアンカーポイント + Nearly Coincident Anchors ほぼ重なるアンカーポイント + Nearly Closed Paths ほぼ閉じたパス + Filled Open Paths 塗りのあるオープンパス + Needless Clipping Groups 不要なクリップグループ + Needless Compound Paths 不要な複合パス + Needless Groups 不要なグループ + Empty Artboards 空のアートボード + Protect Corners 角を保護 + Gap 間隔 + Include Clip Groups クリップグループを含める +@msg `tolerance` must be from 1 to 100 `tolerance` は 1~100 の範囲で指定してください +@msg `gap` must be from 0 to 6 pt `gap` は 0~6 pt の範囲で指定してください +@msg Simplify Anchors: the paths have too many anchors to simplify at once アンカーポイントを単純化:パスのアンカーポイントが多すぎて一度に単純化できません +@msg Rejoin Path Pieces: too many paths to rejoin at once パスの断片を再連結:パスが多すぎて一度に再連結できません +@msg None of these issues are left: check again これらの問題はもう残っていません:もう一度チェックしてください +@msg `kinds` must be a list of issue kinds `kinds` は問題の種類のリストで指定してください +@msg missing `kind` `kind` がありません + Simplify Anchors (Keep Shape) アンカーポイントを単純化(形状を維持) + Deep Ungroup すべての階層のグループ解除 + Rejoin Path Pieces パスの断片を再連結 + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects カラー効果 + Color Effects Panel カラー効果パネル + Exposure 露光量 + Exposure… 露光量… + Desaturate 彩度を下げる + Adjustment 補正 + Add as Effect 効果として追加 + Apply as Filter フィルターとして適用 + Select objects to adjust their colors. カラーを補正するオブジェクトを選択してください。 + Brightness/Contrast 明るさ・コントラスト + Hue/Saturation 色相・彩度 + Temperature/Tint 色温度・色かぶり +@msg `{id}` is not a colour adjustment `{id}` はカラー補正ではありません +@msg missing `effect` `effect` が指定されていません +@msg `params` must be an object `params` にはオブジェクトを指定してください +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools パス精密ツール + Anchor Eraser Brush アンカーポイント消去ブラシ + Extend Path Tool パス延長ツール + Measure & Inspect Tool 計測・検査ツール + Anchor Inspector アンカーポイントインスペクター + Add Points at Crossings 交差点にポイントを追加 + Split at Crossings 交差点で分割 + Extend Path パスを延長 + Measure & Inspect 計測・検査 + Set Anchor アンカーポイントを設定 + Make Smooth スムーズにする + Make Corner コーナーにする + Equalize Handles ハンドルの長さを揃える + Remove Points, Keep Shape ポイントを削除(形状を維持) + Add Points to Segments… セグメントにポイントを追加… + Add Points to Segments セグメントにポイントを追加 + Open a document to edit its anchor points. アンカーポイントを編集するにはドキュメントを開いてください。 + Anchors selected: {count} 選択中のアンカーポイント:{count} + Direct-select anchor points to edit them. 編集するアンカーポイントをダイレクト選択してください。 + Length 長さ + In: イン: + Out: アウト: + Add Points ポイントを追加 + Points per segment セグメントあたりのポイント数 + Close Path: パスを閉じる: + Keep Handles ハンドルを維持 + Straight 直線 + Stretch Curve カーブを延長 +@msg direct-select the anchor points to remove 削除するアンカーポイントをダイレクト選択してください +@msg select segments, or paths, to add points to ポイントを追加するセグメントまたはパスを選択してください +@msg select open paths to close 閉じるオープンパスを選択してください +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) パスが多すぎるか複雑すぎて交差点を見つけられません(最大 10000 セグメント) +@msg the paths have too many anchors to edit at once パスのアンカーポイントが多すぎて一度に編集できません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 20db589b7b..ebddec3e94 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5689,3 +5689,101 @@ swatch Bright Violet კაშკაშა იისფერი Average & Join საშუალო და შეერთება anchor Points: წერტილები: @msg select two open path ends, or two open paths, to average and join მონიშნეთ ღია ტრაექტორიების ორი ბოლო ან ორი ღია ტრაექტორია საშუალოსა და შეერთებისთვის + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup გრაფიკის გასუფთავება + Simplify Anchors (Keep Shape)… საყრდენი წერტილების გამარტივება (ფორმის შენარჩუნებით)… + Health Check მდგომარეობის შემოწმება + Show Issue პრობლემის ჩვენება + Fix All Issues ყველა პრობლემის გამოსწორება + Fix Issues პრობლემების გამოსწორება + Deep Ungroup… დაჯგუფების მოხსნა ყველა დონეზე… + Rejoin Path Pieces… ტრაექტორიის ნაწილების ხელახლა შეერთება… + Document Health Check დოკუმენტის მდგომარეობის შემოწმება + Check Selection მონიშნულის შემოწმება + Check Document დოკუმენტის შემოწმება + No issues found. პრობლემები ვერ მოიძებნა. + Changed since the last check. შეიცვალა ბოლო შემოწმების შემდეგ. + Fix Selected მონიშნულის გამოსწორება + Fix All ყველას გამოსწორება + Issues fixed: {count} გამოსწორებული პრობლემები: {count} + Open a document to check it for issues. გახსენით დოკუმენტი, რომ პრობლემებზე შეამოწმოთ. + Empty Text ცარიელი ტექსტი + Unpainted Objects შეუღებავი ობიექტები + Zero-Opacity Objects ნულოვანი გაუმჭვირვალობის ობიექტები + Duplicate Objects დუბლირებული ობიექტები + Off-Artboard Art სამუშაო დაფებს გარეთ მყოფი გრაფიკა + Duplicate Anchors დუბლირებული საყრდენი წერტილები + Tiny Handles პაწაწინა სახელურები + Collinear Anchors კოლინეარული საყრდენი წერტილები + Nearly Coincident Anchors თითქმის დამთხვეული საყრდენი წერტილები + Nearly Closed Paths თითქმის შეკრული ტრაექტორიები + Filled Open Paths შევსებული ღია ტრაექტორიები + Needless Clipping Groups ზედმეტი მომჭრელი ჯგუფები + Needless Compound Paths ზედმეტი შედგენილი ტრაექტორიები + Needless Groups ზედმეტი ჯგუფები + Empty Artboards ცარიელი სამუშაო დაფები + Protect Corners კუთხეების დაცვა + Gap ღრეჩო + Include Clip Groups მომჭრელი ჯგუფების ჩართვა +@msg `tolerance` must be from 1 to 100 `tolerance` უნდა იყოს 1-დან 100-მდე +@msg `gap` must be from 0 to 6 pt `gap` უნდა იყოს 0-დან 6 pt-მდე +@msg Simplify Anchors: the paths have too many anchors to simplify at once საყრდენი წერტილების გამარტივება: ტრაექტორიებს ძალიან ბევრი საყრდენი წერტილი აქვს ერთბაშად გასამარტივებლად +@msg Rejoin Path Pieces: too many paths to rejoin at once ტრაექტორიის ნაწილების ხელახლა შეერთება: ძალიან ბევრი ტრაექტორიაა ერთბაშად შესაერთებლად +@msg None of these issues are left: check again ამ პრობლემებიდან აღარცერთი დარჩა: შეამოწმეთ ხელახლა +@msg `kinds` must be a list of issue kinds `kinds` უნდა იყოს პრობლემის სახეების სია +@msg missing `kind` `kind` აკლია + Simplify Anchors (Keep Shape) საყრდენი წერტილების გამარტივება (ფორმის შენარჩუნებით) + Deep Ungroup დაჯგუფების მოხსნა ყველა დონეზე + Rejoin Path Pieces ტრაექტორიის ნაწილების ხელახლა შეერთება + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects ფერის ეფექტები + Color Effects Panel ფერის ეფექტების პანელი + Exposure ექსპოზიცია + Exposure… ექსპოზიცია… + Desaturate გაუფერულება + Adjustment კორექცია + Add as Effect ეფექტად დამატება + Apply as Filter ფილტრად გამოყენება + Select objects to adjust their colors. აირჩიეთ ობიექტები მათი ფერების დასარეგულირებლად. + Brightness/Contrast სიკაშკაშე/კონტრასტი + Hue/Saturation ფერის ტონი/გაჯერება + Temperature/Tint ტემპერატურა/ტონირება +@msg `{id}` is not a colour adjustment `{id}` ფერის კორექცია არ არის +@msg missing `effect` აკლია `effect` +@msg `params` must be an object `params` უნდა იყოს ობიექტი +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools ტრაექტორიების ზუსტი ხელსაწყოები + Anchor Eraser Brush საყრდენი წერტილების საშლელი ფუნჯი + Extend Path Tool ტრაექტორიის გაგრძელების ხელსაწყო + Measure & Inspect Tool გაზომვისა და შემოწმების ხელსაწყო + Anchor Inspector საყრდენი წერტილების ინსპექტორი + Add Points at Crossings წერტილების დამატება გადაკვეთებზე + Split at Crossings დაყოფა გადაკვეთებზე + Extend Path ტრაექტორიის გაგრძელება + Measure & Inspect გაზომვა და შემოწმება + Set Anchor საყრდენი წერტილის დაყენება + Make Smooth გლუვად ქცევა + Make Corner კუთხოვნად ქცევა + Equalize Handles სახელურების გათანაბრება + Remove Points, Keep Shape წერტილების მოცილება ფორმის შენარჩუნებით + Add Points to Segments… წერტილების დამატება სეგმენტებში… + Add Points to Segments წერტილების დამატება სეგმენტებში + Open a document to edit its anchor points. გახსენით დოკუმენტი მისი საყრდენი წერტილების დასარედაქტირებლად. + Anchors selected: {count} მონიშნული საყრდენი წერტილები: {count} + Direct-select anchor points to edit them. დასარედაქტირებლად საყრდენი წერტილები პირდაპირ მონიშნეთ. + Length სიგრძე + In: შესასვლელი: + Out: გამოსასვლელი: + Add Points წერტილების დამატება + Points per segment წერტილები სეგმენტზე + Close Path: ტრაექტორიის შეკვრა: + Keep Handles სახელურების შენარჩუნება + Straight სწორი + Stretch Curve მრუდის გაჭიმვა +@msg direct-select the anchor points to remove პირდაპირ მონიშნეთ მოსაცილებელი საყრდენი წერტილები +@msg select segments, or paths, to add points to მონიშნეთ სეგმენტები ან ტრაექტორიები წერტილების დასამატებლად +@msg select open paths to close მონიშნეთ შესაკრავი ღია ტრაექტორიები +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) ტრაექტორიები ზედმეტად ბევრი ან ჩახლართულია გადაკვეთების საპოვნელად (მაქსიმუმ 10000 სეგმენტი) +@msg the paths have too many anchors to edit at once ტრაექტორიებს ზედმეტად ბევრი საყრდენი წერტილი აქვს ერთბაშად დასარედაქტირებლად diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 266bbc0e7a..348baf15c9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5279,3 +5279,101 @@ axis Y Axis Y축 Average & Join 평균 및 결합 anchor Points: 포인트: @msg select two open path ends, or two open paths, to average and join 평균 및 결합할 열린 패스의 끝점 두 개 또는 열린 패스 두 개를 선택하세요 + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup 아트워크 정리 + Simplify Anchors (Keep Shape)… 앵커 포인트 단순화(모양 유지)… + Health Check 상태 점검 + Show Issue 문제 표시 + Fix All Issues 모든 문제 수정 + Fix Issues 문제 수정 + Deep Ungroup… 모든 단계 그룹 해제… + Rejoin Path Pieces… 패스 조각 다시 연결… + Document Health Check 문서 상태 점검 + Check Selection 선택 영역 점검 + Check Document 문서 점검 + No issues found. 문제가 없습니다. + Changed since the last check. 마지막 점검 이후 변경되었습니다. + Fix Selected 선택한 항목 수정 + Fix All 모두 수정 + Issues fixed: {count} 수정한 문제: {count} + Open a document to check it for issues. 문서를 열면 문제를 점검할 수 있습니다. + Empty Text 빈 텍스트 + Unpainted Objects 칠하지 않은 오브젝트 + Zero-Opacity Objects 불투명도 0% 오브젝트 + Duplicate Objects 중복 오브젝트 + Off-Artboard Art 아트보드 밖의 아트워크 + Duplicate Anchors 중복 앵커 포인트 + Tiny Handles 아주 짧은 핸들 + Collinear Anchors 일직선 위의 앵커 포인트 + Nearly Coincident Anchors 거의 겹치는 앵커 포인트 + Nearly Closed Paths 거의 닫힌 패스 + Filled Open Paths 칠한 열린 패스 + Needless Clipping Groups 불필요한 클리핑 그룹 + Needless Compound Paths 불필요한 컴파운드 패스 + Needless Groups 불필요한 그룹 + Empty Artboards 빈 아트보드 + Protect Corners 모서리 보호 + Gap 간격 + Include Clip Groups 클리핑 그룹 포함 +@msg `tolerance` must be from 1 to 100 `tolerance`는 1에서 100 사이여야 합니다 +@msg `gap` must be from 0 to 6 pt `gap`은 0에서 6pt 사이여야 합니다 +@msg Simplify Anchors: the paths have too many anchors to simplify at once 앵커 포인트 단순화: 패스의 앵커 포인트가 너무 많아 한 번에 단순화할 수 없습니다 +@msg Rejoin Path Pieces: too many paths to rejoin at once 패스 조각 다시 연결: 패스가 너무 많아 한 번에 연결할 수 없습니다 +@msg None of these issues are left: check again 이 문제가 더 이상 남아 있지 않습니다. 다시 점검하세요 +@msg `kinds` must be a list of issue kinds `kinds`는 문제 종류의 목록이어야 합니다 +@msg missing `kind` `kind`가 없습니다 + Simplify Anchors (Keep Shape) 앵커 포인트 단순화(모양 유지) + Deep Ungroup 모든 단계 그룹 해제 + Rejoin Path Pieces 패스 조각 다시 연결 + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects 색상 효과 + Color Effects Panel 색상 효과 패널 + Exposure 노출 + Exposure… 노출… + Desaturate 채도 감소 + Adjustment 조정 + Add as Effect 효과로 추가 + Apply as Filter 필터로 적용 + Select objects to adjust their colors. 색상을 조정할 개체를 선택하십시오. + Brightness/Contrast 밝기/대비 + Hue/Saturation 색조/채도 + Temperature/Tint 색온도/색조 +@msg `{id}` is not a colour adjustment `{id}`은(는) 색상 조정이 아닙니다 +@msg missing `effect` `effect`이 없습니다 +@msg `params` must be an object `params`는 개체여야 합니다 +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools 패스 정밀 도구 + Anchor Eraser Brush 앵커 포인트 지우개 브러시 + Extend Path Tool 패스 연장 도구 + Measure & Inspect Tool 측정 및 검사 도구 + Anchor Inspector 앵커 포인트 검사기 + Add Points at Crossings 교차점에 포인트 추가 + Split at Crossings 교차점에서 분할 + Extend Path 패스 연장 + Measure & Inspect 측정 및 검사 + Set Anchor 앵커 포인트 설정 + Make Smooth 매끄럽게 만들기 + Make Corner 모서리로 만들기 + Equalize Handles 핸들 길이 맞추기 + Remove Points, Keep Shape 포인트 제거(모양 유지) + Add Points to Segments… 세그먼트에 포인트 추가… + Add Points to Segments 세그먼트에 포인트 추가 + Open a document to edit its anchor points. 앵커 포인트를 편집하려면 문서를 여세요. + Anchors selected: {count} 선택한 앵커 포인트: {count} + Direct-select anchor points to edit them. 편집할 앵커 포인트를 직접 선택하세요. + Length 길이 + In: 들어옴: + Out: 나감: + Add Points 포인트 추가 + Points per segment 세그먼트당 포인트 + Close Path: 패스 닫기: + Keep Handles 핸들 유지 + Straight 직선 + Stretch Curve 곡선 늘이기 +@msg direct-select the anchor points to remove 제거할 앵커 포인트를 직접 선택하세요 +@msg select segments, or paths, to add points to 포인트를 추가할 세그먼트나 패스를 선택하세요 +@msg select open paths to close 닫을 열린 패스를 선택하세요 +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) 패스가 너무 많거나 너무 얽혀 교차점을 찾을 수 없습니다(최대 10000개 세그먼트) +@msg the paths have too many anchors to edit at once 패스의 앵커 포인트가 너무 많아 한 번에 편집할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7080aa48aa..956e2edd27 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5649,3 +5649,100 @@ axis Y Axis Y-as Average & Join Gemiddelde en verbinden anchor Points: Punten: @msg select two open path ends, or two open paths, to average and join selecteer twee uiteinden van open paden, of twee open paden, om te middelen en te verbinden + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Illustratie opschonen + Simplify Anchors (Keep Shape)… Ankerpunten vereenvoudigen (vorm behouden)… + Health Check Gezondheidscontrole + Show Issue Probleem tonen + Fix All Issues Alle problemen oplossen + Fix Issues Problemen oplossen + Deep Ungroup… Alle groeperingsniveaus opheffen… + Rejoin Path Pieces… Padstukken opnieuw verbinden… + Document Health Check Gezondheidscontrole van document + Check Selection Selectie controleren + Check Document Document controleren + No issues found. Geen problemen gevonden. + Changed since the last check. Gewijzigd sinds de laatste controle. + Fix Selected Geselecteerde oplossen + Fix All Alles oplossen + Issues fixed: {count} Opgeloste problemen: {count} + Open a document to check it for issues. Open een document om het op problemen te controleren. + Empty Text Lege tekst + Unpainted Objects Objecten zonder verf + Zero-Opacity Objects Objecten met 0% dekking + Duplicate Objects Dubbele objecten + Off-Artboard Art Illustraties buiten de tekenborden + Duplicate Anchors Dubbele ankerpunten + Tiny Handles Piepkleine grepen + Collinear Anchors Collineaire ankerpunten + Nearly Coincident Anchors Bijna samenvallende ankerpunten + Nearly Closed Paths Bijna gesloten paden + Filled Open Paths Gevulde open paden + Needless Clipping Groups Overbodige knipgroepen + Needless Compound Paths Overbodige samengestelde paden + Needless Groups Overbodige groepen + Empty Artboards Lege tekenborden + Protect Corners Hoeken beschermen + Gap Tussenruimte + Include Clip Groups Knipgroepen meenemen +@msg `tolerance` must be from 1 to 100 `tolerance` moet tussen 1 en 100 liggen +@msg `gap` must be from 0 to 6 pt `gap` moet tussen 0 en 6 pt liggen +@msg Simplify Anchors: the paths have too many anchors to simplify at once Ankerpunten vereenvoudigen: de paden hebben te veel ankerpunten om in één keer te vereenvoudigen +@msg Rejoin Path Pieces: too many paths to rejoin at once Padstukken opnieuw verbinden: te veel paden om in één keer te verbinden +@msg None of these issues are left: check again Geen van deze problemen is nog over: controleer opnieuw +@msg `kinds` must be a list of issue kinds `kinds` moet een lijst met soorten problemen zijn +@msg missing `kind` `kind` ontbreekt + Simplify Anchors (Keep Shape) Ankerpunten vereenvoudigen (vorm behouden) + Deep Ungroup Alle groeperingsniveaus opheffen + Rejoin Path Pieces Padstukken opnieuw verbinden + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Kleureffecten + Color Effects Panel Deelvenster Kleureffecten + Exposure Belichting + Exposure… Belichting… + Desaturate Desatureren + Adjustment Aanpassing + Add as Effect Toevoegen als effect + Apply as Filter Toepassen als filter + Select objects to adjust their colors. Selecteer objecten om hun kleuren aan te passen. + Brightness/Contrast Helderheid/contrast + Hue/Saturation Kleurtoon/verzadiging + Temperature/Tint Temperatuur/tint +@msg `{id}` is not a colour adjustment `{id}` is geen kleuraanpassing +@msg missing `effect` `effect` ontbreekt +@msg `params` must be an object `params` moet een object zijn +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Precisiegereedschappen voor paden + Anchor Eraser Brush Ankerpunt-gumpenseel + Extend Path Tool Pad verlengen-gereedschap + Measure & Inspect Tool Meten en inspecteren-gereedschap + Anchor Inspector Ankerpuntinspecteur + Add Points at Crossings Punten toevoegen bij kruisingen + Split at Crossings Splitsen bij kruisingen + Extend Path Pad verlengen + Measure & Inspect Meten en inspecteren + Set Anchor Ankerpunt instellen + Make Smooth Vloeiend maken + Make Corner Hoekpunt maken + Equalize Handles Grepen gelijkmaken + Remove Points, Keep Shape Punten verwijderen, vorm behouden + Add Points to Segments… Punten aan segmenten toevoegen… + Add Points to Segments Punten aan segmenten toevoegen + Open a document to edit its anchor points. Open een document om de ankerpunten ervan te bewerken. + Anchors selected: {count} Geselecteerde ankerpunten: {count} + Direct-select anchor points to edit them. Selecteer ankerpunten direct om ze te bewerken. + In: In: + Out: Uit: + Add Points Punten toevoegen + Points per segment Punten per segment + Close Path: Pad sluiten: + Keep Handles Grepen behouden + Straight Recht + Stretch Curve Curve uitrekken +@msg direct-select the anchor points to remove selecteer de te verwijderen ankerpunten direct +@msg select segments, or paths, to add points to selecteer segmenten, of paden, om punten aan toe te voegen +@msg select open paths to close selecteer open paden om te sluiten +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) te veel of te verwarde paden om hun kruisingen te vinden (hoogstens 10000 segmenten) +@msg the paths have too many anchors to edit at once de paden hebben te veel ankerpunten om in één keer te bewerken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 56fb73b651..9292990c49 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5554,3 +5554,101 @@ axis Y Axis Oś Y Average & Join Uśrednij i połącz anchor Points: Punkty: @msg select two open path ends, or two open paths, to average and join zaznacz dwa końce otwartych ścieżek lub dwie otwarte ścieżki do uśrednienia i połączenia + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Porządkowanie grafiki + Simplify Anchors (Keep Shape)… Uprość punkty kontrolne (zachowaj kształt)… + Health Check Kontrola stanu + Show Issue Pokaż problem + Fix All Issues Napraw wszystkie problemy + Fix Issues Napraw problemy + Deep Ungroup… Rozgrupuj wszystkie poziomy… + Rejoin Path Pieces… Ponownie połącz fragmenty ścieżek… + Document Health Check Kontrola stanu dokumentu + Check Selection Sprawdź zaznaczenie + Check Document Sprawdź dokument + No issues found. Nie znaleziono problemów. + Changed since the last check. Zmieniono od ostatniego sprawdzenia. + Fix Selected Napraw zaznaczone + Fix All Napraw wszystko + Issues fixed: {count} Naprawione problemy: {count} + Open a document to check it for issues. Otwórz dokument, aby sprawdzić go pod kątem problemów. + Empty Text Pusty tekst + Unpainted Objects Obiekty bez koloru + Zero-Opacity Objects Obiekty o zerowym kryciu + Duplicate Objects Zduplikowane obiekty + Off-Artboard Art Grafika poza obszarami kompozycji + Duplicate Anchors Zduplikowane punkty kontrolne + Tiny Handles Bardzo krótkie uchwyty + Collinear Anchors Współliniowe punkty kontrolne + Nearly Coincident Anchors Prawie pokrywające się punkty kontrolne + Nearly Closed Paths Prawie zamknięte ścieżki + Filled Open Paths Wypełnione otwarte ścieżki + Needless Clipping Groups Zbędne grupy przycinające + Needless Compound Paths Zbędne ścieżki złożone + Needless Groups Zbędne grupy + Empty Artboards Puste obszary kompozycji + Protect Corners Chroń narożniki + Gap Odstęp + Include Clip Groups Uwzględnij grupy przycinające +@msg `tolerance` must be from 1 to 100 `tolerance` musi mieścić się w zakresie od 1 do 100 +@msg `gap` must be from 0 to 6 pt `gap` musi mieścić się w zakresie od 0 do 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Uprość punkty kontrolne: ścieżki mają zbyt wiele punktów kontrolnych, aby uprościć je naraz +@msg Rejoin Path Pieces: too many paths to rejoin at once Ponownie połącz fragmenty ścieżek: zbyt wiele ścieżek do połączenia naraz +@msg None of these issues are left: check again Żaden z tych problemów już nie występuje: sprawdź ponownie +@msg `kinds` must be a list of issue kinds `kinds` musi być listą rodzajów problemów +@msg missing `kind` brak `kind` + Simplify Anchors (Keep Shape) Uprość punkty kontrolne (zachowaj kształt) + Deep Ungroup Rozgrupuj wszystkie poziomy + Rejoin Path Pieces Ponownie połącz fragmenty ścieżek + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Efekty koloru + Color Effects Panel Panel Efekty koloru + Exposure Ekspozycja + Exposure… Ekspozycja… + Desaturate Usuń nasycenie + Adjustment Korekta + Add as Effect Dodaj jako efekt + Apply as Filter Zastosuj jako filtr + Select objects to adjust their colors. Zaznacz obiekty, aby skorygować ich kolory. + Brightness/Contrast Jasność/kontrast + Hue/Saturation Barwa/nasycenie + Temperature/Tint Temperatura/odcień +@msg `{id}` is not a colour adjustment `{id}` nie jest korektą koloru +@msg missing `effect` brak `effect` +@msg `params` must be an object `params` musi być obiektem +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Precyzyjne narzędzia ścieżek + Anchor Eraser Brush Pędzel gumki punktów kontrolnych + Extend Path Tool Narzędzie Przedłuż ścieżkę + Measure & Inspect Tool Narzędzie Mierz i badaj + Anchor Inspector Inspektor punktów kontrolnych + Add Points at Crossings Dodaj punkty na skrzyżowaniach + Split at Crossings Podziel na skrzyżowaniach + Extend Path Przedłuż ścieżkę + Measure & Inspect Mierz i badaj + Set Anchor Ustaw punkt kontrolny + Make Smooth Zmień na gładki + Make Corner Zmień na narożny + Equalize Handles Wyrównaj uchwyty + Remove Points, Keep Shape Usuń punkty, zachowaj kształt + Add Points to Segments… Dodaj punkty do segmentów… + Add Points to Segments Dodaj punkty do segmentów + Open a document to edit its anchor points. Otwórz dokument, aby edytować jego punkty kontrolne. + Anchors selected: {count} Zaznaczone punkty kontrolne: {count} + Direct-select anchor points to edit them. Zaznacz bezpośrednio punkty kontrolne, aby je edytować. + Length Długość + In: Wejście: + Out: Wyjście: + Add Points Dodaj punkty + Points per segment Punkty na segment + Close Path: Zamknij ścieżkę: + Keep Handles Zachowaj uchwyty + Straight Prosty + Stretch Curve Rozciągnij krzywą +@msg direct-select the anchor points to remove zaznacz bezpośrednio punkty kontrolne do usunięcia +@msg select segments, or paths, to add points to zaznacz segmenty lub ścieżki, do których dodać punkty +@msg select open paths to close zaznacz otwarte ścieżki do zamknięcia +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) za dużo ścieżek lub są zbyt splątane, by znaleźć ich skrzyżowania (najwyżej 10000 segmentów) +@msg the paths have too many anchors to edit at once ścieżki mają za dużo punktów kontrolnych, by edytować je naraz diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 91217099c4..b850a0796d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5617,3 +5617,101 @@ axis Y Axis Eixo Y Average & Join Média e união anchor Points: Pontos: @msg select two open path ends, or two open paths, to average and join selecione duas extremidades de traçados abertos, ou dois traçados abertos, para calcular a média e unir + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Limpeza de Arte + Simplify Anchors (Keep Shape)… Simplificar Pontos de Ancoragem (Manter Forma)… + Health Check Verificação de Integridade + Show Issue Mostrar Problema + Fix All Issues Corrigir Todos os Problemas + Fix Issues Corrigir Problemas + Deep Ungroup… Desagrupar Todos os Níveis… + Rejoin Path Pieces… Reunir Partes de Caminho… + Document Health Check Verificação de Integridade do Documento + Check Selection Verificar Seleção + Check Document Verificar Documento + No issues found. Nenhum problema encontrado. + Changed since the last check. Alterado desde a última verificação. + Fix Selected Corrigir Selecionados + Fix All Corrigir Tudo + Issues fixed: {count} Problemas corrigidos: {count} + Open a document to check it for issues. Abra um documento para verificar se há problemas. + Empty Text Texto Vazio + Unpainted Objects Objetos sem Pintura + Zero-Opacity Objects Objetos com Opacidade Zero + Duplicate Objects Objetos Duplicados + Off-Artboard Art Arte Fora das Pranchetas + Duplicate Anchors Pontos de Ancoragem Duplicados + Tiny Handles Alças Minúsculas + Collinear Anchors Pontos de Ancoragem Colineares + Nearly Coincident Anchors Pontos de Ancoragem Quase Coincidentes + Nearly Closed Paths Caminhos Quase Fechados + Filled Open Paths Caminhos Abertos Preenchidos + Needless Clipping Groups Grupos de Recorte Desnecessários + Needless Compound Paths Caminhos Compostos Desnecessários + Needless Groups Grupos Desnecessários + Empty Artboards Pranchetas Vazias + Protect Corners Proteger Cantos + Gap Distância + Include Clip Groups Incluir Grupos de Recorte +@msg `tolerance` must be from 1 to 100 `tolerance` deve estar entre 1 e 100 +@msg `gap` must be from 0 to 6 pt `gap` deve estar entre 0 e 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Simplificar Pontos de Ancoragem: os caminhos têm pontos de ancoragem demais para simplificar de uma vez +@msg Rejoin Path Pieces: too many paths to rejoin at once Reunir Partes de Caminho: caminhos demais para reunir de uma vez +@msg None of these issues are left: check again Nenhum desses problemas permanece: verifique novamente +@msg `kinds` must be a list of issue kinds `kinds` deve ser uma lista de tipos de problema +@msg missing `kind` `kind` ausente + Simplify Anchors (Keep Shape) Simplificar Pontos de Ancoragem (Manter Forma) + Deep Ungroup Desagrupar Todos os Níveis + Rejoin Path Pieces Reunir Partes de Caminho + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Efeitos de cor + Color Effects Panel Painel Efeitos de cor + Exposure Exposição + Exposure… Exposição… + Desaturate Dessaturar + Adjustment Ajuste + Add as Effect Adicionar como efeito + Apply as Filter Aplicar como filtro + Select objects to adjust their colors. Selecione objetos para ajustar suas cores. + Brightness/Contrast Brilho/Contraste + Hue/Saturation Matiz/Saturação + Temperature/Tint Temperatura/Tom +@msg `{id}` is not a colour adjustment `{id}` não é um ajuste de cor +@msg missing `effect` falta `effect` +@msg `params` must be an object `params` deve ser um objeto +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Ferramentas de Precisão de Caminhos + Anchor Eraser Brush Pincel Apagador de Pontos de Ancoragem + Extend Path Tool Ferramenta Estender Caminho + Measure & Inspect Tool Ferramenta Medir e Inspecionar + Anchor Inspector Inspetor de Pontos de Ancoragem + Add Points at Crossings Adicionar Pontos nos Cruzamentos + Split at Crossings Dividir nos Cruzamentos + Extend Path Estender Caminho + Measure & Inspect Medir e Inspecionar + Set Anchor Definir Ponto de Ancoragem + Make Smooth Tornar Suave + Make Corner Tornar Canto + Equalize Handles Igualar Alças + Remove Points, Keep Shape Remover Pontos, Manter Forma + Add Points to Segments… Adicionar Pontos aos Segmentos… + Add Points to Segments Adicionar Pontos aos Segmentos + Open a document to edit its anchor points. Abra um documento para editar seus pontos de ancoragem. + Anchors selected: {count} Pontos de ancoragem selecionados: {count} + Direct-select anchor points to edit them. Selecione diretamente pontos de ancoragem para editá-los. + Length Comprimento + In: Entrada: + Out: Saída: + Add Points Adicionar Pontos + Points per segment Pontos por segmento + Close Path: Fechar Caminho: + Keep Handles Manter Alças + Straight Reto + Stretch Curve Esticar Curva +@msg direct-select the anchor points to remove selecione diretamente os pontos de ancoragem a remover +@msg select segments, or paths, to add points to selecione segmentos, ou caminhos, aos quais adicionar pontos +@msg select open paths to close selecione caminhos abertos para fechar +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) caminhos demais, ou emaranhados demais, para encontrar seus cruzamentos (no máximo 10000 segmentos) +@msg the paths have too many anchors to edit at once os caminhos têm pontos de ancoragem demais para editar de uma vez diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 48d428b206..cf222a0af9 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5678,3 +5678,100 @@ theme Appearance Оформление Average & Join Усреднить и соединить anchor Points: Точки: @msg select two open path ends, or two open paths, to average and join выделите два конца открытых контуров или два открытых контура для усреднения и соединения + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Очистка графики + Simplify Anchors (Keep Shape)… Упростить опорные точки (сохранить форму)… + Health Check Проверка состояния + Show Issue Показать проблему + Fix All Issues Исправить все проблемы + Fix Issues Исправить проблемы + Deep Ungroup… Разгруппировать все уровни… + Rejoin Path Pieces… Соединить части контуров… + Document Health Check Проверка состояния документа + Check Selection Проверить выделение + Check Document Проверить документ + No issues found. Проблем не найдено. + Changed since the last check. Изменено после последней проверки. + Fix Selected Исправить выбранные + Fix All Исправить все + Issues fixed: {count} Исправлено проблем: {count} + Open a document to check it for issues. Откройте документ, чтобы проверить его на проблемы. + Empty Text Пустой текст + Unpainted Objects Объекты без заливки и обводки + Zero-Opacity Objects Объекты с нулевой непрозрачностью + Duplicate Objects Дублирующиеся объекты + Off-Artboard Art Графика за пределами монтажных областей + Duplicate Anchors Дублирующиеся опорные точки + Tiny Handles Крошечные маркеры + Collinear Anchors Коллинеарные опорные точки + Nearly Coincident Anchors Почти совпадающие опорные точки + Nearly Closed Paths Почти замкнутые контуры + Filled Open Paths Открытые контуры с заливкой + Needless Clipping Groups Лишние группы обрезки + Needless Compound Paths Лишние составные контуры + Needless Groups Лишние группы + Empty Artboards Пустые монтажные области + Protect Corners Защищать углы + Gap Зазор + Include Clip Groups Включить группы обрезки +@msg `tolerance` must be from 1 to 100 `tolerance` должно быть от 1 до 100 +@msg `gap` must be from 0 to 6 pt `gap` должно быть от 0 до 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Упростить опорные точки: у контуров слишком много опорных точек, чтобы упростить их за один раз +@msg Rejoin Path Pieces: too many paths to rejoin at once Соединить части контуров: слишком много контуров, чтобы соединить их за один раз +@msg None of these issues are left: check again Ни одной из этих проблем больше нет: проверьте снова +@msg `kinds` must be a list of issue kinds `kinds` должно быть списком видов проблем +@msg missing `kind` не указан `kind` + Simplify Anchors (Keep Shape) Упростить опорные точки (сохранить форму) + Deep Ungroup Разгруппировать все уровни + Rejoin Path Pieces Соединить части контуров + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Цветовые эффекты + Color Effects Panel Панель «Цветовые эффекты» + Exposure Экспозиция + Exposure… Экспозиция… + Desaturate Обесцветить + Adjustment Коррекция + Add as Effect Добавить как эффект + Apply as Filter Применить как фильтр + Select objects to adjust their colors. Выделите объекты, чтобы настроить их цвета. + Brightness/Contrast Яркость/контраст + Hue/Saturation Оттенок/насыщенность + Temperature/Tint Температура/оттенок +@msg `{id}` is not a colour adjustment `{id}` не является цветокоррекцией +@msg missing `effect` отсутствует `effect` +@msg `params` must be an object `params` должно быть объектом +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Инструменты точной правки контуров + Anchor Eraser Brush Кисть-ластик опорных точек + Extend Path Tool Инструмент «Продление контура» + Measure & Inspect Tool Инструмент «Измерение и анализ» + Anchor Inspector Инспектор опорных точек + Add Points at Crossings Добавить точки на пересечениях + Split at Crossings Разрезать на пересечениях + Extend Path Продлить контур + Measure & Inspect Измерение и анализ + Set Anchor Задать опорную точку + Make Smooth Сделать гладкой + Make Corner Сделать угловой + Equalize Handles Выровнять длину маркеров + Remove Points, Keep Shape Убрать точки, сохранить форму + Add Points to Segments… Добавить точки в сегменты… + Add Points to Segments Добавить точки в сегменты + Open a document to edit its anchor points. Откройте документ, чтобы править его опорные точки. + Anchors selected: {count} Выбрано опорных точек: {count} + Direct-select anchor points to edit them. Выделите опорные точки напрямую, чтобы править их. + In: Вход: + Out: Выход: + Add Points Добавить точки + Points per segment Точек на сегмент + Close Path: Замкнуть контур: + Keep Handles Сохранить маркеры + Straight Прямой + Stretch Curve Растянуть кривую +@msg direct-select the anchor points to remove выделите напрямую опорные точки, которые нужно убрать +@msg select segments, or paths, to add points to выделите сегменты или контуры, в которые нужно добавить точки +@msg select open paths to close выделите незамкнутые контуры, чтобы замкнуть их +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) контуров слишком много или они слишком запутаны, чтобы найти их пересечения (не более 10000 сегментов) +@msg the paths have too many anchors to edit at once у контуров слишком много опорных точек, чтобы править их за раз diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 27bf1d75a4..965c0f8d6f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5724,3 +5724,100 @@ axis Y Axis Y-axel Average & Join Medelvärde och foga samman anchor Points: Punkter: @msg select two open path ends, or two open paths, to average and join markera två ändar av öppna banor, eller två öppna banor, att medelvärdesberäkna och foga samman + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Upprensning av grafik + Simplify Anchors (Keep Shape)… Förenkla ankarpunkter (behåll formen)… + Health Check Hälsokontroll + Show Issue Visa problem + Fix All Issues Åtgärda alla problem + Fix Issues Åtgärda problem + Deep Ungroup… Dela upp grupper på alla nivåer… + Rejoin Path Pieces… Foga samman banbitar igen… + Document Health Check Hälsokontroll av dokument + Check Selection Kontrollera markering + Check Document Kontrollera dokument + No issues found. Inga problem hittades. + Changed since the last check. Ändrat sedan den senaste kontrollen. + Fix Selected Åtgärda markerade + Fix All Åtgärda alla + Issues fixed: {count} Åtgärdade problem: {count} + Open a document to check it for issues. Öppna ett dokument för att kontrollera det efter problem. + Empty Text Tom text + Unpainted Objects Ofärgade objekt + Zero-Opacity Objects Objekt med 0 % opacitet + Duplicate Objects Dubblettobjekt + Off-Artboard Art Grafik utanför ritytorna + Duplicate Anchors Dubbletter av ankarpunkter + Tiny Handles Små handtag + Collinear Anchors Kollineära ankarpunkter + Nearly Coincident Anchors Nästan sammanfallande ankarpunkter + Nearly Closed Paths Nästan slutna banor + Filled Open Paths Fyllda öppna banor + Needless Clipping Groups Onödiga klippgrupper + Needless Compound Paths Onödiga sammansatta banor + Needless Groups Onödiga grupper + Empty Artboards Tomma ritytor + Protect Corners Skydda hörn + Gap Mellanrum + Include Clip Groups Ta med klippgrupper +@msg `tolerance` must be from 1 to 100 `tolerance` måste vara från 1 till 100 +@msg `gap` must be from 0 to 6 pt `gap` måste vara från 0 till 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Förenkla ankarpunkter: banorna har för många ankarpunkter för att förenklas på en gång +@msg Rejoin Path Pieces: too many paths to rejoin at once Foga samman banbitar igen: för många banor för att foga samman på en gång +@msg None of these issues are left: check again Inget av dessa problem finns kvar: kontrollera igen +@msg `kinds` must be a list of issue kinds `kinds` måste vara en lista med problemtyper +@msg missing `kind` `kind` saknas + Simplify Anchors (Keep Shape) Förenkla ankarpunkter (behåll formen) + Deep Ungroup Dela upp grupper på alla nivåer + Rejoin Path Pieces Foga samman banbitar igen + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Färgeffekter + Color Effects Panel Panelen Färgeffekter + Exposure Exponering + Exposure… Exponering… + Desaturate Avmätta + Adjustment Justering + Add as Effect Lägg till som effekt + Apply as Filter Använd som filter + Select objects to adjust their colors. Markera objekt för att justera deras färger. + Brightness/Contrast Ljusstyrka/kontrast + Hue/Saturation Nyans/mättnad + Temperature/Tint Temperatur/färgton +@msg `{id}` is not a colour adjustment `{id}` är ingen färgjustering +@msg missing `effect` `effect` saknas +@msg `params` must be an object `params` måste vara ett objekt +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Precisionsverktyg för banor + Anchor Eraser Brush Ankarpunktsraderpensel + Extend Path Tool Förläng bana-verktyget + Measure & Inspect Tool Mät och granska-verktyget + Anchor Inspector Ankarpunktsgranskare + Add Points at Crossings Lägg till punkter vid korsningar + Split at Crossings Dela vid korsningar + Extend Path Förläng bana + Measure & Inspect Mät och granska + Set Anchor Ange ankarpunkt + Make Smooth Gör mjuk + Make Corner Gör till hörn + Equalize Handles Utjämna handtag + Remove Points, Keep Shape Ta bort punkter, behåll formen + Add Points to Segments… Lägg till punkter i segment… + Add Points to Segments Lägg till punkter i segment + Open a document to edit its anchor points. Öppna ett dokument för att redigera dess ankarpunkter. + Anchors selected: {count} Valda ankarpunkter: {count} + Direct-select anchor points to edit them. Direktmarkera ankarpunkter för att redigera dem. + In: In: + Out: Ut: + Add Points Lägg till punkter + Points per segment Punkter per segment + Close Path: Stäng bana: + Keep Handles Behåll handtag + Straight Rak + Stretch Curve Sträck kurvan +@msg direct-select the anchor points to remove direktmarkera ankarpunkterna som ska tas bort +@msg select segments, or paths, to add points to markera segment, eller banor, att lägga till punkter i +@msg select open paths to close markera öppna banor att stänga +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) för många eller för trassliga banor för att hitta deras korsningar (högst 10000 segment) +@msg the paths have too many anchors to edit at once banorna har för många ankarpunkter för att redigeras på en gång diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7c7cc5ec8c..ee0fcd1404 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5658,3 +5658,100 @@ axis Y Axis Y ekseni Average & Join Ortalama ve katıl anchor Points: Noktalar: @msg select two open path ends, or two open paths, to average and join ortalaması alınıp katılmak için iki açık yol ucu veya iki açık yol seçin + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Çizim Temizliği + Simplify Anchors (Keep Shape)… Bağlantı Noktalarını Basitleştir (Şekli Koru)… + Health Check Sağlık Denetimi + Show Issue Sorunu Göster + Fix All Issues Tüm Sorunları Düzelt + Fix Issues Sorunları Düzelt + Deep Ungroup… Tüm Düzeylerde Grubu Çöz… + Rejoin Path Pieces… Yol Parçalarını Yeniden Birleştir… + Document Health Check Belge Sağlık Denetimi + Check Selection Seçimi Denetle + Check Document Belgeyi Denetle + No issues found. Sorun bulunamadı. + Changed since the last check. Son denetimden bu yana değişti. + Fix Selected Seçilenleri Düzelt + Fix All Tümünü Düzelt + Issues fixed: {count} Düzeltilen sorunlar: {count} + Open a document to check it for issues. Sorunlar için denetlemek üzere bir belge açın. + Empty Text Boş Metin + Unpainted Objects Boyanmamış Nesneler + Zero-Opacity Objects Sıfır Opaklıklı Nesneler + Duplicate Objects Yinelenen Nesneler + Off-Artboard Art Çalışma Yüzeyi Dışındaki Çizimler + Duplicate Anchors Yinelenen Bağlantı Noktaları + Tiny Handles Çok Kısa Kollar + Collinear Anchors Doğrusal Bağlantı Noktaları + Nearly Coincident Anchors Neredeyse Çakışan Bağlantı Noktaları + Nearly Closed Paths Neredeyse Kapalı Yollar + Filled Open Paths Dolgulu Açık Yollar + Needless Clipping Groups Gereksiz Kırpma Grupları + Needless Compound Paths Gereksiz Bileşik Yollar + Needless Groups Gereksiz Gruplar + Empty Artboards Boş Çalışma Yüzeyleri + Protect Corners Köşeleri Koru + Gap Boşluk + Include Clip Groups Kırpma Gruplarını Dahil Et +@msg `tolerance` must be from 1 to 100 `tolerance` 1 ile 100 arasında olmalıdır +@msg `gap` must be from 0 to 6 pt `gap` 0 ile 6 pt arasında olmalıdır +@msg Simplify Anchors: the paths have too many anchors to simplify at once Bağlantı Noktalarını Basitleştir: yollarda bir kerede basitleştirilemeyecek kadar çok bağlantı noktası var +@msg Rejoin Path Pieces: too many paths to rejoin at once Yol Parçalarını Yeniden Birleştir: bir kerede birleştirilemeyecek kadar çok yol var +@msg None of these issues are left: check again Bu sorunların hiçbiri kalmadı: yeniden denetleyin +@msg `kinds` must be a list of issue kinds `kinds` bir sorun türleri listesi olmalıdır +@msg missing `kind` `kind` eksik + Simplify Anchors (Keep Shape) Bağlantı Noktalarını Basitleştir (Şekli Koru) + Deep Ungroup Tüm Düzeylerde Grubu Çöz + Rejoin Path Pieces Yol Parçalarını Yeniden Birleştir + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Renk Efektleri + Color Effects Panel Renk Efektleri Paneli + Exposure Pozlama + Exposure… Pozlama… + Desaturate Doygunluğu Kaldır + Adjustment Ayar + Add as Effect Efekt Olarak Ekle + Apply as Filter Filtre Olarak Uygula + Select objects to adjust their colors. Renklerini ayarlamak için nesneleri seçin. + Brightness/Contrast Parlaklık/Kontrast + Hue/Saturation Ton/Doygunluk + Temperature/Tint Sıcaklık/Renk Tonu +@msg `{id}` is not a colour adjustment `{id}` bir renk ayarı değil +@msg missing `effect` "isim" eksik +@msg `params` must be an object "gradyan" bir nesne olmalıdır +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Yol Hassasiyet Araçları + Anchor Eraser Brush Bağlantı Noktası Silgi Fırçası + Extend Path Tool Yolu Uzat Aracı + Measure & Inspect Tool Ölç ve İncele Aracı + Anchor Inspector Bağlantı Noktası Denetçisi + Add Points at Crossings Kesişimlere Nokta Ekle + Split at Crossings Kesişimlerden Böl + Extend Path Yolu Uzat + Measure & Inspect Ölç ve İncele + Set Anchor Bağlantı Noktasını Ayarla + Make Smooth Yumuşak Yap + Make Corner Köşe Yap + Equalize Handles Kolları Eşitle + Remove Points, Keep Shape Noktaları Kaldır, Şekli Koru + Add Points to Segments… Bölümlere Nokta Ekle… + Add Points to Segments Bölümlere Nokta Ekle + Open a document to edit its anchor points. Bağlantı noktalarını düzenlemek için bir belge açın. + Anchors selected: {count} Seçili bağlantı noktaları: {count} + Direct-select anchor points to edit them. Düzenlemek için bağlantı noktalarını doğrudan seçin. + In: Giriş: + Out: Çıkış: + Add Points Nokta Ekle + Points per segment Bölüm başına nokta + Close Path: Yolu Kapat: + Keep Handles Kolları Koru + Straight Düz + Stretch Curve Eğriyi Uzat +@msg direct-select the anchor points to remove kaldırılacak bağlantı noktalarını doğrudan seçin +@msg select segments, or paths, to add points to nokta eklenecek bölümleri veya yolları seçin +@msg select open paths to close kapatılacak açık yolları seçin +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) kesişimlerini bulmak için yollar çok fazla veya çok karışık (en fazla 10000 bölüm) +@msg the paths have too many anchors to edit at once yolların aynı anda düzenlenemeyecek kadar çok bağlantı noktası var diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 217fad0759..a9264ddd2e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5296,3 +5296,101 @@ axis Y Axis Вісь Y Average & Join Усереднити і з’єднати anchor Points: Точки: @msg select two open path ends, or two open paths, to average and join виділіть два кінці відкритих контурів або два відкриті контури для усереднення і з’єднання + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Очищення графіки + Simplify Anchors (Keep Shape)… Спростити опорні точки (зберегти форму)… + Health Check Перевірка стану + Show Issue Показати проблему + Fix All Issues Виправити всі проблеми + Fix Issues Виправити проблеми + Deep Ungroup… Розгрупувати всі рівні… + Rejoin Path Pieces… З’єднати частини контурів… + Document Health Check Перевірка стану документа + Check Selection Перевірити виділення + Check Document Перевірити документ + No issues found. Проблем не знайдено. + Changed since the last check. Змінено після останньої перевірки. + Fix Selected Виправити вибрані + Fix All Виправити все + Issues fixed: {count} Виправлено проблем: {count} + Open a document to check it for issues. Відкрийте документ, щоб перевірити його на проблеми. + Empty Text Порожній текст + Unpainted Objects Об’єкти без заливки й обведення + Zero-Opacity Objects Об’єкти з нульовою непрозорістю + Duplicate Objects Дублікати об’єктів + Off-Artboard Art Графіка поза монтажними областями + Duplicate Anchors Дублікати опорних точок + Tiny Handles Крихітні маркери + Collinear Anchors Колінеарні опорні точки + Nearly Coincident Anchors Майже збіжні опорні точки + Nearly Closed Paths Майже замкнені контури + Filled Open Paths Відкриті контури із заливкою + Needless Clipping Groups Зайві групи відсікання + Needless Compound Paths Зайві складені контури + Needless Groups Зайві групи + Empty Artboards Порожні монтажні області + Protect Corners Захищати кути + Gap Проміжок + Include Clip Groups Включити групи відсікання +@msg `tolerance` must be from 1 to 100 `tolerance` має бути від 1 до 100 +@msg `gap` must be from 0 to 6 pt `gap` має бути від 0 до 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Спростити опорні точки: контури мають забагато опорних точок, щоб спростити їх за один раз +@msg Rejoin Path Pieces: too many paths to rejoin at once З’єднати частини контурів: забагато контурів, щоб з’єднати їх за один раз +@msg None of these issues are left: check again Жодної з цих проблем більше немає: перевірте знову +@msg `kinds` must be a list of issue kinds `kinds` має бути списком видів проблем +@msg missing `kind` не вказано `kind` + Simplify Anchors (Keep Shape) Спростити опорні точки (зберегти форму) + Deep Ungroup Розгрупувати всі рівні + Rejoin Path Pieces З’єднати частини контурів + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Колірні ефекти + Color Effects Panel Панель «Колірні ефекти» + Exposure Експозиція + Exposure… Експозиція… + Desaturate Знебарвити + Adjustment Корекція + Add as Effect Додати як ефект + Apply as Filter Застосувати як фільтр + Select objects to adjust their colors. Виділіть об’єкти, щоб налаштувати їхні кольори. + Brightness/Contrast Яскравість/контраст + Hue/Saturation Відтінок/насиченість + Temperature/Tint Температура/відтінок +@msg `{id}` is not a colour adjustment `{id}` не є корекцією кольору +@msg missing `effect` відсутня `effect` +@msg `params` must be an object `params` має бути об’єктом +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Інструменти точного редагування контурів + Anchor Eraser Brush Пензель-гумка опорних точок + Extend Path Tool Інструмент «Подовження контуру» + Measure & Inspect Tool Інструмент «Вимірювання й аналіз» + Anchor Inspector Інспектор опорних точок + Add Points at Crossings Додати точки на перетинах + Split at Crossings Розрізати на перетинах + Extend Path Подовжити контур + Measure & Inspect Вимірювання й аналіз + Set Anchor Задати опорну точку + Make Smooth Зробити гладкою + Make Corner Зробити кутовою + Equalize Handles Вирівняти довжину маркерів + Remove Points, Keep Shape Забрати точки, зберегти форму + Add Points to Segments… Додати точки до сегментів… + Add Points to Segments Додати точки до сегментів + Open a document to edit its anchor points. Відкрийте документ, щоб редагувати його опорні точки. + Anchors selected: {count} Вибрано опорних точок: {count} + Direct-select anchor points to edit them. Виділіть опорні точки напряму, щоб редагувати їх. + Length Довжина + In: Вхід: + Out: Вихід: + Add Points Додати точки + Points per segment Точок на сегмент + Close Path: Замкнути контур: + Keep Handles Зберегти маркери + Straight Прямий + Stretch Curve Розтягнути криву +@msg direct-select the anchor points to remove виділіть напряму опорні точки, які треба забрати +@msg select segments, or paths, to add points to виділіть сегменти або контури, до яких треба додати точки +@msg select open paths to close виділіть незамкнені контури, щоб замкнути їх +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) контурів забагато або вони надто заплутані, щоб знайти їхні перетини (не більше 10000 сегментів) +@msg the paths have too many anchors to edit at once у контурів забагато опорних точок, щоб редагувати їх за раз diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f30176f575..d471be738b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5298,3 +5298,101 @@ axis Y Axis Trục Y Average & Join Trung bình và nối anchor Points: Điểm: @msg select two open path ends, or two open paths, to average and join hãy chọn hai đầu của đường dẫn mở, hoặc hai đường dẫn mở, để lấy trung bình và nối + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup Dọn dẹp tác phẩm + Simplify Anchors (Keep Shape)… Đơn giản hóa điểm neo (giữ hình dạng)… + Health Check Kiểm tra tình trạng + Show Issue Hiện vấn đề + Fix All Issues Sửa mọi vấn đề + Fix Issues Sửa vấn đề + Deep Ungroup… Bỏ nhóm mọi cấp… + Rejoin Path Pieces… Nối lại các mảnh đường dẫn… + Document Health Check Kiểm tra tình trạng tài liệu + Check Selection Kiểm tra vùng chọn + Check Document Kiểm tra tài liệu + No issues found. Không tìm thấy vấn đề nào. + Changed since the last check. Đã thay đổi kể từ lần kiểm tra trước. + Fix Selected Sửa mục đã chọn + Fix All Sửa tất cả + Issues fixed: {count} Vấn đề đã sửa: {count} + Open a document to check it for issues. Mở một tài liệu để kiểm tra vấn đề. + Empty Text Văn bản trống + Unpainted Objects Đối tượng không tô màu + Zero-Opacity Objects Đối tượng có độ mờ đục bằng 0 + Duplicate Objects Đối tượng trùng lặp + Off-Artboard Art Hình vẽ ngoài bảng vẽ + Duplicate Anchors Điểm neo trùng lặp + Tiny Handles Tay nắm rất ngắn + Collinear Anchors Điểm neo thẳng hàng + Nearly Coincident Anchors Điểm neo gần trùng nhau + Nearly Closed Paths Đường dẫn gần khép kín + Filled Open Paths Đường dẫn mở có tô + Needless Clipping Groups Nhóm cắt không cần thiết + Needless Compound Paths Đường dẫn phức không cần thiết + Needless Groups Nhóm không cần thiết + Empty Artboards Bảng vẽ trống + Protect Corners Bảo vệ góc + Gap Khoảng hở + Include Clip Groups Bao gồm nhóm cắt +@msg `tolerance` must be from 1 to 100 `tolerance` phải từ 1 đến 100 +@msg `gap` must be from 0 to 6 pt `gap` phải từ 0 đến 6 pt +@msg Simplify Anchors: the paths have too many anchors to simplify at once Đơn giản hóa điểm neo: các đường dẫn có quá nhiều điểm neo để đơn giản hóa một lần +@msg Rejoin Path Pieces: too many paths to rejoin at once Nối lại các mảnh đường dẫn: quá nhiều đường dẫn để nối một lần +@msg None of these issues are left: check again Không còn vấn đề nào trong số này: hãy kiểm tra lại +@msg `kinds` must be a list of issue kinds `kinds` phải là danh sách các loại vấn đề +@msg missing `kind` thiếu `kind` + Simplify Anchors (Keep Shape) Đơn giản hóa điểm neo (giữ hình dạng) + Deep Ungroup Bỏ nhóm mọi cấp + Rejoin Path Pieces Nối lại các mảnh đường dẫn + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects Hiệu ứng màu + Color Effects Panel Bảng Hiệu ứng màu + Exposure Phơi sáng + Exposure… Phơi sáng… + Desaturate Khử bão hòa + Adjustment Điều chỉnh + Add as Effect Thêm làm hiệu ứng + Apply as Filter Áp dụng làm bộ lọc + Select objects to adjust their colors. Chọn đối tượng để điều chỉnh màu của chúng. + Brightness/Contrast Độ sáng/Tương phản + Hue/Saturation Sắc độ/Độ bão hòa + Temperature/Tint Nhiệt độ màu/Tông +@msg `{id}` is not a colour adjustment `{id}` không phải là điều chỉnh màu +@msg missing `effect` thiếu `effect` +@msg `params` must be an object `params` phải là một đối tượng +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools Công cụ chính xác cho đường dẫn + Anchor Eraser Brush Cọ tẩy điểm neo + Extend Path Tool Công cụ Kéo dài đường dẫn + Measure & Inspect Tool Công cụ Đo và kiểm tra + Anchor Inspector Trình kiểm tra điểm neo + Add Points at Crossings Thêm điểm tại chỗ giao nhau + Split at Crossings Tách tại chỗ giao nhau + Extend Path Kéo dài đường dẫn + Measure & Inspect Đo và kiểm tra + Set Anchor Đặt điểm neo + Make Smooth Làm mượt + Make Corner Chuyển thành góc + Equalize Handles Cân bằng tay nắm + Remove Points, Keep Shape Gỡ điểm, giữ hình dạng + Add Points to Segments… Thêm điểm vào đoạn… + Add Points to Segments Thêm điểm vào đoạn + Open a document to edit its anchor points. Mở một tài liệu để sửa các điểm neo của nó. + Anchors selected: {count} Điểm neo đã chọn: {count} + Direct-select anchor points to edit them. Chọn trực tiếp các điểm neo để sửa chúng. + Length Độ dài + In: Vào: + Out: Ra: + Add Points Thêm điểm + Points per segment Số điểm mỗi đoạn + Close Path: Đóng đường dẫn: + Keep Handles Giữ tay nắm + Straight Thẳng + Stretch Curve Kéo giãn đường cong +@msg direct-select the anchor points to remove chọn trực tiếp các điểm neo cần gỡ +@msg select segments, or paths, to add points to chọn các đoạn hoặc đường dẫn để thêm điểm +@msg select open paths to close chọn các đường dẫn mở để đóng +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) quá nhiều đường dẫn hoặc chúng quá rối để tìm chỗ giao nhau (tối đa 10000 đoạn) +@msg the paths have too many anchors to edit at once các đường dẫn có quá nhiều điểm neo để sửa cùng lúc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4b241917dc..dd7d0037a7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5539,3 +5539,101 @@ axis Y Axis Y 轴 Average & Join 平均并连接 anchor Points: 点: @msg select two open path ends, or two open paths, to average and join 请选择两个开放路径的端点或两条开放路径以进行平均并连接 + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup 图稿清理 + Simplify Anchors (Keep Shape)… 简化锚点(保持形状)… + Health Check 健康检查 + Show Issue 显示问题 + Fix All Issues 修复所有问题 + Fix Issues 修复问题 + Deep Ungroup… 取消所有层级编组… + Rejoin Path Pieces… 重新连接路径片段… + Document Health Check 文档健康检查 + Check Selection 检查所选对象 + Check Document 检查文档 + No issues found. 未发现问题。 + Changed since the last check. 自上次检查后已更改。 + Fix Selected 修复所选 + Fix All 全部修复 + Issues fixed: {count} 已修复的问题:{count} + Open a document to check it for issues. 打开文档以检查其中的问题。 + Empty Text 空文本 + Unpainted Objects 无上色对象 + Zero-Opacity Objects 不透明度为零的对象 + Duplicate Objects 重复对象 + Off-Artboard Art 画板外的图稿 + Duplicate Anchors 重复锚点 + Tiny Handles 极短手柄 + Collinear Anchors 共线锚点 + Nearly Coincident Anchors 几乎重合的锚点 + Nearly Closed Paths 几乎闭合的路径 + Filled Open Paths 填色的开放路径 + Needless Clipping Groups 多余的剪切组 + Needless Compound Paths 多余的复合路径 + Needless Groups 多余的编组 + Empty Artboards 空白画板 + Protect Corners 保护尖角 + Gap 间隙 + Include Clip Groups 包括剪切组 +@msg `tolerance` must be from 1 to 100 `tolerance` 必须介于 1 到 100 之间 +@msg `gap` must be from 0 to 6 pt `gap` 必须介于 0 到 6 pt 之间 +@msg Simplify Anchors: the paths have too many anchors to simplify at once 简化锚点:路径的锚点太多,无法一次简化 +@msg Rejoin Path Pieces: too many paths to rejoin at once 重新连接路径片段:路径太多,无法一次连接 +@msg None of these issues are left: check again 这些问题都已不存在:请重新检查 +@msg `kinds` must be a list of issue kinds `kinds` 必须是问题类型的列表 +@msg missing `kind` 缺少 `kind` + Simplify Anchors (Keep Shape) 简化锚点(保持形状) + Deep Ungroup 取消所有层级编组 + Rejoin Path Pieces 重新连接路径片段 + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects 颜色效果 + Color Effects Panel 颜色效果面板 + Exposure 曝光度 + Exposure… 曝光度… + Desaturate 去色 + Adjustment 调整 + Add as Effect 添加为效果 + Apply as Filter 作为滤镜应用 + Select objects to adjust their colors. 选择对象以调整其颜色。 + Brightness/Contrast 亮度/对比 + Hue/Saturation 色相/饱和度 + Temperature/Tint 色温/色调 +@msg `{id}` is not a colour adjustment `{id}` 不是颜色调整 +@msg missing `effect` 缺少 `effect` +@msg `params` must be an object `params` 必须是对象 +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools 路径精确工具 + Anchor Eraser Brush 锚点橡皮擦画笔 + Extend Path Tool 延长路径工具 + Measure & Inspect Tool 测量与检查工具 + Anchor Inspector 锚点检查器 + Add Points at Crossings 在交叉处添加锚点 + Split at Crossings 在交叉处分割 + Extend Path 延长路径 + Measure & Inspect 测量与检查 + Set Anchor 设置锚点 + Make Smooth 转为平滑 + Make Corner 转为尖角 + Equalize Handles 等长手柄 + Remove Points, Keep Shape 删除锚点并保持形状 + Add Points to Segments… 在线段中添加锚点… + Add Points to Segments 在线段中添加锚点 + Open a document to edit its anchor points. 打开文档以编辑其锚点。 + Anchors selected: {count} 已选锚点:{count} + Direct-select anchor points to edit them. 直接选择锚点以编辑它们。 + Length 长度 + In: 入: + Out: 出: + Add Points 添加锚点 + Points per segment 每段锚点数 + Close Path: 闭合路径: + Keep Handles 保留手柄 + Straight 直线 + Stretch Curve 拉伸曲线 +@msg direct-select the anchor points to remove 请直接选择要删除的锚点 +@msg select segments, or paths, to add points to 请选择要添加锚点的线段或路径 +@msg select open paths to close 请选择要闭合的开放路径 +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) 路径太多或太复杂,无法找到交叉处(最多 10000 段) +@msg the paths have too many anchors to edit at once 路径的锚点太多,无法一次编辑 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 98026e0fb6..0847e3b6c1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5335,3 +5335,101 @@ axis Y Axis Y 軸 Average & Join 平均並連接 anchor Points: 點: @msg select two open path ends, or two open paths, to average and join 請選取兩個開放路徑的端點或兩條開放路徑以進行平均並連接 + +# Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. + Artwork Cleanup 圖稿清理 + Simplify Anchors (Keep Shape)… 簡化錨點(保持形狀)… + Health Check 健康檢查 + Show Issue 顯示問題 + Fix All Issues 修正所有問題 + Fix Issues 修正問題 + Deep Ungroup… 解散所有層級群組… + Rejoin Path Pieces… 重新連接路徑片段… + Document Health Check 文件健康檢查 + Check Selection 檢查選取範圍 + Check Document 檢查文件 + No issues found. 未發現問題。 + Changed since the last check. 自上次檢查後已變更。 + Fix Selected 修正選取項目 + Fix All 全部修正 + Issues fixed: {count} 已修正的問題:{count} + Open a document to check it for issues. 開啟文件以檢查其中的問題。 + Empty Text 空白文字 + Unpainted Objects 未上色物件 + Zero-Opacity Objects 不透明度為零的物件 + Duplicate Objects 重複物件 + Off-Artboard Art 工作區域外的圖稿 + Duplicate Anchors 重複錨點 + Tiny Handles 極短控制把手 + Collinear Anchors 共線錨點 + Nearly Coincident Anchors 幾乎重合的錨點 + Nearly Closed Paths 幾乎封閉的路徑 + Filled Open Paths 有填色的開放路徑 + Needless Clipping Groups 多餘的剪裁群組 + Needless Compound Paths 多餘的複合路徑 + Needless Groups 多餘的群組 + Empty Artboards 空白工作區域 + Protect Corners 保護尖角 + Gap 間隙 + Include Clip Groups 包含剪裁群組 +@msg `tolerance` must be from 1 to 100 `tolerance` 必須介於 1 到 100 之間 +@msg `gap` must be from 0 to 6 pt `gap` 必須介於 0 到 6 pt 之間 +@msg Simplify Anchors: the paths have too many anchors to simplify at once 簡化錨點:路徑的錨點太多,無法一次簡化 +@msg Rejoin Path Pieces: too many paths to rejoin at once 重新連接路徑片段:路徑太多,無法一次連接 +@msg None of these issues are left: check again 這些問題都已不存在:請重新檢查 +@msg `kinds` must be a list of issue kinds `kinds` 必須是問題類型的清單 +@msg missing `kind` 未指定 `kind` + Simplify Anchors (Keep Shape) 簡化錨點(保持形狀) + Deep Ungroup 解散所有層級群組 + Rejoin Path Pieces 重新連接路徑片段 + +# Color Effects add-on (Object › Plug-ins › Color Effects, Effect › Color Effects): its effects, panel and messages. + Color Effects 顏色效果 + Color Effects Panel 顏色效果面板 + Exposure 曝光度 + Exposure… 曝光度… + Desaturate 去除飽和度 + Adjustment 調整 + Add as Effect 加入為效果 + Apply as Filter 套用為濾鏡 + Select objects to adjust their colors. 選取物件以調整其顏色。 + Brightness/Contrast 亮度/對比 + Hue/Saturation 色相/飽和度 + Temperature/Tint 色溫/色調 +@msg `{id}` is not a colour adjustment `{id}` 不是顏色調整 +@msg missing `effect` 未提供 `effect` +@msg `params` must be an object `params` 必須是物件 +# Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. + Path Precision Tools 路徑精確工具 + Anchor Eraser Brush 錨點橡皮擦筆刷 + Extend Path Tool 延長路徑工具 + Measure & Inspect Tool 測量與檢查工具 + Anchor Inspector 錨點檢查器 + Add Points at Crossings 在交叉處增加錨點 + Split at Crossings 在交叉處分割 + Extend Path 延長路徑 + Measure & Inspect 測量與檢查 + Set Anchor 設定錨點 + Make Smooth 轉為平滑 + Make Corner 轉為角點 + Equalize Handles 等長控制把手 + Remove Points, Keep Shape 刪除錨點並保持形狀 + Add Points to Segments… 在線段中增加錨點… + Add Points to Segments 在線段中增加錨點 + Open a document to edit its anchor points. 開啟文件以編輯其錨點。 + Anchors selected: {count} 已選取錨點:{count} + Direct-select anchor points to edit them. 直接選取錨點以編輯它們。 + Length 長度 + In: 入: + Out: 出: + Add Points 增加錨點 + Points per segment 每段錨點數 + Close Path: 封閉路徑: + Keep Handles 保留控制把手 + Straight 直線 + Stretch Curve 延展曲線 +@msg direct-select the anchor points to remove 請直接選取要刪除的錨點 +@msg select segments, or paths, to add points to 請選取要增加錨點的線段或路徑 +@msg select open paths to close 請選取要封閉的開放路徑 +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) 路徑太多或太複雜,無法找到交叉處(最多 10000 段) +@msg the paths have too many anchors to edit at once 路徑的錨點太多,無法一次編輯 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fe7b87c36e..27551cae20 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -22,6 +22,7 @@ macro_rules! tl { }; } +pub mod addons; pub mod background; mod brand; pub mod canvas; diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index 00637705eb..9cb1a2aa6b 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -134,6 +134,7 @@ pub(super) fn effect_menu() -> Vec { let order = [ "3D and Materials", "Color Adjustments", + "Color Effects", "Convert to Shape", "Crop Marks", "Distort & Transform", diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4ce87a6dd0..a64821a011 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -367,7 +367,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ], ), Sep, - sub("Plug-ins", crate::dialogs::plugin::object_menu()), + sub("Plug-ins", [crate::addons::plugin_menu(), crate::dialogs::plugin::object_menu()].concat()), ], ), ( diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 6015dbaa67..3760594c8f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -179,6 +179,9 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { links::ID => links::show(app, ui), asset_export::ID => asset_export::show(app, ui), css_properties::ID => css_properties::show(app, ui), + crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), + crate::addons::color::ID => crate::addons::color::show(app, ui), + crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), id if library_panel::parse(id).is_some() => library_panel::show(app, ui, id), _ => { dim_label(ui, tl!("This panel is on the roadmap (see the parity plan).")); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 843915bbdc..e41af01cd7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -197,6 +197,9 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::asset_export::ID, "Asset Export", "share-2"), (crate::panels::css_properties::ID, "CSS Properties", "globe"), (crate::panels::variables::ID, "Variables", "chart-column"), + (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), + (crate::addons::color::ID, "Color Effects", "sun"), + (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), ]; /// Groups of icon panels separated by dividers in the collapsed column. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 65b21a797d..d58102761d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -389,6 +389,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::addons::pathtools::open_options(app, tool), _ if vectorcraft_tools::tool_info(tool).is_none() => Err(format!("unknown tool `{tool}`")), _ => Err(format!("the {tool} tool has no options")), } diff --git a/docs/mcp.md b/docs/mcp.md index 466ecd0fa7..a04a7abbd4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5652,3 +5652,137 @@ the entry names and decodes the codes that VectorCraft's default shortcuts agree {"name":"run_command","arguments":{"command":"shortcutSet.read","params":{"path":"/Users/me/Studio.kys"}}} {"name":"run_command","arguments":{"command":"importMatches.set","params":{"matches":[{"kind":"name","name":"Group","target":"object.group"},{"kind":"key","name":"901","target":"G"}]}}} ``` + +## Artwork Cleanup add-on + +Artwork Cleanup is a built-in add-on: its commands are `addon.cleanup.*`, and in the desktop app it lives in Object › +Plug-ins › Artwork Cleanup and in its panel (`window.panel {panel: "artworkCleanup"}`). + +`addon.cleanup.simplify {tolerance?, protectCorners?, ids?}` removes the anchors each selected path can do without and +refits the handles beside each one, so the outline keeps its shape. `tolerance` runs from 1 to 100 (20 by default); the +outline stays within tolerance × 0.02 pt of where it was, measured against the original outline, so removals don't add +up. With `protectCorners`, anchors where the path turns by more than 30° stay. Open ends always stay. It reports the +anchor counts `before` and `after`, as one undo step. + +The health check looks for issues in the selection, or in the whole document while nothing is selected (`scope: +"selection"|"document"` picks one). Locked and hidden objects, and the insides of live or generated art (blends, +envelopes, graphs, symbols), are left out. + +- `addon.cleanup.check {scope?, kinds?}` changes nothing and lists `findings`: for each kind found, its `count`, the + `ids` of the objects it is on (at most 1,000) and, for empty artboards, their indexes. +- `addon.cleanup.show {kind, scope?}` selects the objects with that issue. +- `addon.cleanup.fix {scope?, kinds?}` fixes the issues as one undo step and reports how many of each kind it fixed. + The kinds run in a fixed order, so art removed by one kind can leave a group that a later kind unwraps, and they + run again (three rounds at most) while a round still fixes something. + +| Kind | Finds | Fix | +|---|---|---| +| `emptyText` | Text with no characters, or only spaces | Removes it | +| `strayPoints` | Paths of one anchor (not clipping paths) | Removes them | +| `unpainted` | Paths and compound paths with no fill and no stroke | Removes them | +| `zeroOpacity` | Objects at 0 % opacity | Removes them | +| `duplicateObjects` | A path stacked directly on an identical one (geometry, paint, opacity) | Removes the upper one | +| `offArtboard` | Top-level objects that touch no artboard | Removes them | +| `duplicateAnchors` | Neighbouring anchors within 0.01 pt | Merges them | +| `tinyHandles` | Handles shorter than 0.01 pt | Retracts them | +| `collinearAnchors` | Corner anchors on a straight run (turning by a sine of 0.005 or less) | Removes them | +| `nearPoints` | Anchors within 0.01 pt of anchors of other paths | Snaps them together | +| `nearlyClosed` | Open paths whose ends lie within 0.01 pt | Closes them | +| `filledOpenPaths` | Open paths with a fill and no stroke | Closes them | +| `needlessClipGroups` | Clipping groups whose unpainted clip clips nothing, hides all their art, or is a rectangle round all of it | Removes the group (and the art it hides), or leaves the art | +| `needlessCompounds` | Compound paths of one path or none | Leaves the path, painted as the compound was | +| `needlessGroups` | Groups of one member or none, with no paint, effects or transparency of their own | Leaves the member | +| `emptyArtboards` | Artboards with no art (document scope only; one artboard always stays) | Deletes them | + +`addon.cleanup.deepUngroup {includeClipGroups?, ids?}` takes apart every level of grouping in the selection. Clipping +groups stay whole unless `includeClipGroups` is true; their clipping paths then become plain paths. Objects keep the +opacity of the groups they were in. + +`addon.cleanup.rejoin {gap?, ids?}` welds the selected open paths whose ends lie within `gap` (0 to 6 pt, 0.1 by +default) back into paths. Each end joins one other end: where several are in reach, the one the path turns least to go +on into. Pieces may run either way, and a chain whose ends meet closes. Each new path takes the place and paint of its +topmost piece. + +```json +{"name":"run_command","arguments":{"command":"addon.cleanup.check","params":{"scope":"document"}}} +{"name":"run_command","arguments":{"command":"addon.cleanup.fix","params":{"kinds":["strayPoints","needlessGroups"]}}} +{"name":"run_command","arguments":{"command":"addon.cleanup.simplify","params":{"tolerance":40,"protectCorners":true}}} +``` + +## Path Precision Tools add-on + +Path Precision Tools is a built-in add-on for exact anchor and path work: its commands are `addon.pathtools.*`, and in +the desktop app it lives in Object › Plug-ins › Path Precision Tools, in its Anchor Inspector panel +(`window.panel {panel: "anchorInspector"}`) and in three tools that the toolbars don't show until they are added from the +All Tools drawer (or chosen with `tool.select`): `anchorEraserBrush`, `extendPath` and `measureInspect`. Each edit is one +undo step, and an edit that changes nothing makes no step. + +Tools: + +- **Anchor Eraser Brush** (`anchorEraserBrush`): a drag over selected paths runs `addon.pathtools.erase` with the + stroke. Options (`tool.setOption`, or a double-click on the tool): `size` (screen pixels, 1 to 2500, 20), `tolerance` + (1 to 100, 10) and `pressure` (a pen's pressure scales the brush). Alt removes every anchor under the brush that can + go whatever the tolerance; Cmd/Ctrl deletes them without refitting; `[` and `]` resize the brush. +- **Extend Path tool** (`extendPath`): a drag from an end of an open path runs `addon.pathtools.extend` with the length + the pointer asks for: forward carries the path on, back along it shortens it. Option `mode`: `straight` (default), + `bezier` or `arc`; E cycles it. Shift steps the length by the keyboard increment. +- **Measure & Inspect tool** (`measureInspect`): a drag measures distance, angle and offsets, as the Measure tool does + (`tool.options` reports the last one); hovering a path reads it, as `addon.pathtools.inspect` does. Nothing goes into + the document. + +Commands: + +- `addon.pathtools.erase {points, diameter?, tolerance?, ignoreTolerance?, plain?, ids?}` removes the anchors of the + selected paths that a round brush of `diameter` pt (20 by default), swept through `points` (`[x, y]`, or `[x, y, + pressure]` to scale it), passes over, wherever the outline stays within tolerance × 0.02 pt of where it was (the + scale `addon.cleanup.simplify` uses), refitting the handles beside each. Open ends stay. → `{ids, removed}`. +- `addon.pathtools.extend {id, subpath?, end, length | to, mode?}` lengthens an open path at `end` (`"start"` or + `"end"`) by `length` pt, or shortens it by a negative length (never all of it). With `to: [x, y]` instead, the length + is the one that brings the end nearest that point. `mode`: `straight` (along the end's direction), `bezier` (the last + segment's curve stretched on, no anchor added) or `arc` (along the circle the end curves on, at most half way round; + a straight end goes on straight). +- `addon.pathtools.inspect {id, x, y, tolerance?}` (a query) reads the path at its point nearest `(x, y)`: open or + closed, anchor count, the subpath's length and enclosed area (an open one closed by a straight line), the segment's + length, the direction the path runs there and its radius of curvature (`null` where straight), and, within + `tolerance` (3 pt) of an anchor, that anchor's angle (90 at a square's corner, 180 where the path runs straight on; + `null` at an open end) and its handles' lengths and directions. +- The Anchor Inspector's edits act on the direct-selected anchors, or on every anchor of a path selected whole: + `addon.pathtools.setAnchor {x?, y?, inLength?, inAngle?, outLength?, outAngle?}` (page coordinates; angles in + degrees counter-clockwise; a length of 0 retracts), `addon.pathtools.smooth {ratio?}`, `addon.pathtools.corner + {retract?}` and `addon.pathtools.equalize {}`. Make Smooth mirrors a lone handle; an anchor without handles gets two + at right angles to the bisector of the angle its neighbours make at it, each `ratio` (0.1 to 0.5, 0.3905 by default: + the ratio that makes a square's corners a circle) × the nearer neighbour's distance long; an open end aims its handle + at its neighbour's. Equalize gives both handles their average length and makes a missing one opposite the other. +- `addon.pathtools.removeKeepShape {}` removes the direct-selected anchors, refitting the handles beside each. +- `addon.pathtools.addPoints {count?}` splits each selected segment (between two selected anchors, or every segment of + a path selected whole) into `count + 1` (1 to 100) pieces of equal length. +- `addon.pathtools.close {mode?, ratio?}` closes the selected open paths keeping the ends' handles (`handles`), with a + straight segment (`straight`) or with both ends made smooth (`smooth`). +- `addon.pathtools.crossings {cut?, selfCrossings?, ids?}` adds anchors where the selected paths cross one another (and + where each crosses itself, with `selfCrossings`), or with `cut` also cuts them there: a path of one subpath becomes a + path per piece. Paths that meet at a shared anchor don't cross there; at most 10,000 segments at once. + +```json +{"name":"run_command","arguments":{"command":"addon.pathtools.extend","params":{"id":12,"end":"end","length":40,"mode":"arc"}}} +{"name":"run_command","arguments":{"command":"addon.pathtools.erase","params":{"points":[[100,40],[100,160]],"diameter":30}}} +{"name":"run_command","arguments":{"command":"addon.pathtools.crossings","params":{"cut":true}}} +``` +## Color Effects add-on +Color Effects is a built-in add-on: its effects are colour adjustments in Effect › Color Effects, its command is +`addon.color.filter`, and in the desktop app it also lives in Object › Plug-ins › Color Effects and in its panel +(`window.panel {panel: "colorEffects"}`). +Its live effects go on through `effect.apply` like any other and recolour what the object paints, in stack order with +the other colour adjustments (Effect › Color Adjustments); each colour keeps its colour model: +| Effect | Parameters | Does | +|---|---|---| +| `addon.color.exposure` (Exposure…) | `exposure` stops −20…20 (0), `offset` −0.5…0.5 (0), `gamma` 0.1…10 (1) | Scales the light in linear light (each stop doubles or halves it, mostly in the highlights), adds the offset (shadows and midtones) and applies the gamma | +| `addon.color.desaturate` (Desaturate) | none | Turns every colour to the grey of its lightness | +| `addon.color.invert` (Invert Colors) | none | Turns every colour to its RGB inverse | +`addon.color.filter {effect, params?, fill?, stroke?, includeImages?, includePatterns?, ids?}` applies any colour +adjustment, the add-on's or one of Effect › Color Adjustments', to the colours themselves instead of as a live effect: +fills, strokes, type, gradient meshes, embedded images and pattern tiles, as `edit.colors.invert` reaches them, as one +undo step. Missing `params` take the effect's dialog defaults; the objects' own effects stay as they are. +{"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"addon.color.exposure","params":{"exposure":1.5}}}} +{"name":"run_command","arguments":{"command":"addon.color.filter","params":{"effect":"adjust.hueSaturation","params":{"hue":120}}}} +The panel picks an adjustment (Brightness/Contrast, Hue/Saturation, Levels, Temperature/Tint, Exposure, Desaturate or +Invert Colors), sets its values, and then Add as Effect (`effect.apply`) or Apply as Filter (`addon.color.filter`). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d8eb717bb7..edc203bfc2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Pencil: Edit Selected Paths follows strokes lifted away, carves, loops, closes and redraws compound paths (#3793), scores unchanged; previously: Hardware: a second finger cancels the tool press the first finger began, so a pinch only navigates (#4198); scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Pencil: Edit Selected Paths follows strokes lifted away, carves, loops, closes and redraws compound paths (#3793), scores unchanged; previously: Path Precision Tools, a built-in add-on beyond Illustrator; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1207,10 +1207,45 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi `pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's `the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged. +## Artwork Cleanup add-on (2026-10-30) + +A VectorCraft addition, not an Illustrator feature, so no area score moves. Object › Plug-ins › Artwork Cleanup and its +panel run `addon.cleanup.*`: Simplify Anchors (Keep Shape) on the shared kernel +`vectorcraft_pathops::addons::keep_shape`, a health check of 16 kinds of issue on the selection or the document with +Show, Fix Selected and Fix All (each one undo step), Deep Ungroup and Rejoin Path Pieces. Tests: `addons::` in +`vectorcraft-pathops`, `cmd::addons::cleanup::tests` in `vectorcraft-engine` (each kind found, fixed and clean art left +alone; Fix All as one step; scopes; rejoin within the gap only) and `addons::cleanup::tests` in `vectorcraft-ui-egui` +(the submenu opens the panel; Check lists what it finds). Commands: `docs/mcp.md` › Artwork Cleanup add-on. + +## Path Precision Tools add-on (2026-10-30) + +A VectorCraft addition, not an Illustrator feature, so no area score moves. Object › Plug-ins › Path Precision Tools, +its Anchor Inspector panel and three tools kept out of the shipped toolbars (listed in the All Tools drawer) run +`addon.pathtools.*`: an Anchor Eraser Brush on the shared keep-shape kernel, an Extend Path tool (straight, stretched +curve or arc; shortening back along the path), a Measure & Inspect tool with hover readouts (lengths, area, curvature, +angles), the Anchor Inspector's numeric anchor and handle fields with Make Smooth (auto-smooth rule), Make Corner, +Equalize Handles, Remove Points Keep Shape, Add Points and three ways to close, and Add Points at / Split at Crossings. +Kernels in `vectorcraft_pathops::addons::pathtools`. Tests: `addons::pathtools` in `vectorcraft-pathops`, +`vectorcraft-tools` and `vectorcraft-ui-egui`, `cmd::addons::pathtools::tests` in `vectorcraft-engine` (each command one +undo step, bad params refused, the brush's stroke one step) and `edit_toolbar::tests::addon_tools_are_in_the_drawer_not_the_toolbars`. +Commands: `docs/mcp.md` › Path Precision Tools add-on. + +## Color Effects add-on (2026-10-30) +A VectorCraft addition, not an Illustrator feature, so no area score moves. Effect › Color Effects adds live Exposure +(stops of linear light, offset and gamma), Desaturate and Invert Colors as colour adjustments evaluated with those of +Effect › Color Adjustments (`vectorcraft_effects::addons::color`), and `addon.color.filter` applies any colour adjustment +to the colours themselves through the Edit Colors pass. Object › Plug-ins › Color Effects and its panel reach them. +Tests: `addons::color` in `vectorcraft-effects` (exposure in stops, desaturate keeps lightness, invert twice is +identity), `cmd::addons::color::tests` in `vectorcraft-engine` (drawn live without changing the colours; a filter as one +undo step, with any adjustment and its params; bad requests refused) and `addons::color::tests` in +`vectorcraft-ui-egui` (the menus and the panel). Commands: `docs/mcp.md` › Color Effects add-on. ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Path Precision Tools add-on (a VectorCraft addition): evidence added; scores unchanged. | +| 2026-10-30 | minor | Color Effects, a built-in add-on beyond Illustrator; scores and estimates unchanged | +| 2026-10-30 | minor | Artwork Cleanup add-on (a VectorCraft addition): evidence added; scores unchanged. | | 2026-10-30 | minor | Hardware: a second finger cancels the tool press the first finger began, and a finger landing while another is down presses nothing, so a pinch only navigates (#4198); evidence added; scores unchanged (estimated). | | 2026-10-30 | minor | File formats: SVG export writes axis-aligned rectangles as ``, circles and ellipses as ``/``, straight lines as `` and other straight-segment paths as ``/``, keeping `` where a shape element would draw differently (#4652); evidence added; scores and hours unchanged (estimated). | | 2026-10-30 | minor | UI chrome: with Preferences › Performance › Real-time Drawing and Editing off, a ruler guide dragged out of a ruler or moved shows while it is dragged (#4646); evidence added; score and hours unchanged (estimated). | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c60653e17d..12a4a1dbda 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Pencil Edit Selected Paths: strokes lifted away, carving, loops, closing over open ends, compound paths, a preview of the stroke as drawn (#3793); scores and estimates unchanged; previously: Spinners: a held arrow repeats after a pause (#4267); scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Pencil Edit Selected Paths: strokes lifted away, carving, loops, closing over open ends, compound paths, a preview of the stroke as drawn (#3793); scores and estimates unchanged; previously: Path Precision Tools add-on: its tools, Anchor Inspector panel and Object › Plug-ins submenu; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -321,6 +321,9 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and runs Add Points at / Split at Crossings; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not an Illustrator feature, so it is not scored | +| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not an Illustrator feature, so it is not scored | +| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not an Illustrator feature, so it is not scored | ## Look and feel @@ -361,6 +364,9 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Path Precision Tools add-on (a VectorCraft addition): its tools, Anchor Inspector panel and Object › Plug-ins › Path Precision Tools; scores and estimates unchanged | +| 2026-10-30 | minor | Color Effects add-on: its effects, panel and Object › Plug-ins submenu; scores and estimates unchanged | +| 2026-10-30 | minor | Artwork Cleanup add-on (a VectorCraft addition): its panel and Object › Plug-ins › Artwork Cleanup; scores and estimates unchanged | | 2026-10-30 | minor | Spinners: a held arrow repeats after a pause (#4267); scores and estimates unchanged | | 2026-10-30 | minor | Control bar: a Replace menu swaps the selected symbol instances' symbol (#4121); scores and estimates unchanged | | 2026-10-30 | minor | Color Mixer popover: the Color panel's menu with its color modes (#4249); scores and estimates unchanged |