diff --git a/ROADMAP.md b/ROADMAP.md index 04eb95f38f..6471505555 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -147,6 +147,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 4d578b8dcc..2213190df6 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -491,6 +491,10 @@ pub struct GraphSpec { pub first_column_in_front: bool, #[serde(skip_serializing_if = "std::ops::Not::not")] pub filled_lines: bool, + /// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws + /// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub line_width: Option, /// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the /// legend in rows above the plot instead of a column on its right). #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -565,6 +569,21 @@ fn is_zero(n: &usize) -> bool { *n == 0 } +/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and +/// greatest widths a graph takes, in points. +pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0; +pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01; +pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0; + +impl GraphSpec { + /// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A + /// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the + /// default. + pub fn filled_line_width(&self) -> f64 { + self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH) + } +} + /// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then. fn edge_to_edge_before_the_option() -> bool { true @@ -704,6 +723,7 @@ impl Default for GraphSpec { first_row_in_front: false, first_column_in_front: false, filled_lines: false, + line_width: None, drop_shadow: false, legend_across_top: false, pie_legend_in_wedges: false, diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 902d29e7c5..2d956ed30a 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -96,8 +96,8 @@ pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ - ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, - PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, + ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH, + MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, }; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 541e7801c2..e97a4b0cc1 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -50,10 +50,10 @@ pub struct Selection { #[serde(default, skip_serializing_if = "Option::is_none")] pub key_guide: Option, /// The key anchor for Align: one of two or more anchor points selected with Direct Selection, - /// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute - /// move the other selected points relative to it, and it stays in place. Never set with `key` - /// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or - /// fewer than two points are selected. + /// designated by clicking an already-selected anchor point without modifiers (path, anchor in + /// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and + /// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the + /// point is no longer a selected anchor, or fewer than two points are selected. #[serde(default, skip_serializing_if = "Option::is_none")] pub key_anchor: Option<(NodeId, AnchorRef)>, /// The new art on a locked artboard that this selection keeps editable @@ -311,7 +311,7 @@ impl Selection { let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| { self.objects.contains(&id) && !self.segments.contains_key(&id) - && self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) + && (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id)) && found .get(&id) .and_then(|p| doc.node_at(p)) diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 9af57f8e02..f84fb20f57 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,7 +3,8 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths, Trim at Crossings ([`trim`]) and Tangent Circle ([`tangent_circle`]). +//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle +//! ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -13,6 +14,7 @@ mod effect_tests; mod shape; mod shared_edge; mod tangent_circle; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -182,6 +184,7 @@ pub fn specs() -> Vec { v.extend(shared_edge::specs()); v.extend(trim::specs()); v.extend(tangent_circle::specs()); + v.extend(tangents::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..4376cbe791 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -0,0 +1,130 @@ +//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected +//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without +//! crossing into either, added as separate open paths, with the line joining their centers if +//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Affine; +use vectorcraft_geom::{FillRule, PathData, Point, SubPath}; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::object::choice; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The command's id. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The undo step's name. +const LABEL: &str = "Common Tangents"; +/// The kinds of tangent `tangents` picks. +const KINDS: [&str; 3] = ["external", "internal", "all"]; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.commonTangents", + "Common Tangents", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + has_selection, + common_tangents + )] +} + +/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, +/// else the path's one closed convex subpath. +fn outline_of(d: &Document, id: NodeId) -> Result { + const C: &str = COMMON_TANGENTS; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; + let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { + let span = (pie.1 - pie.0).rem_euclid(360.0); + if span < 1e-9 || 360.0 - span < 1e-9 { + let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]); + return pt::Outline::ellipse(unit).map_err(refusal); + } + } + pt::Outline::convex(sp).map_err(refusal) +} + +fn refusal(e: pt::OutlineError) -> EngineError { + bad( + COMMON_TANGENTS, + match e { + pt::OutlineError::Open => "a selected path is open", + pt::OutlineError::NotConvex => "a selected path is not convex", + pt::OutlineError::Empty => "a selected path has no area", + pt::OutlineError::TooComplex => "a selected path has more than 10000 segments", + }, + ) +} + +fn common_tangents(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMON_TANGENTS; + let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let centerline = switch_or(p, "centerline", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ordered = d.paint_order(roots.iter().copied()); + let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; + let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; + let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); + let keep = |t: &&pt::Tangent| match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + }; + let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); + let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); + let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() { + // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one + // external tangent means one path lies inside the other and touches it there; paths that + // overlap without one inside the other have at least two. + let warning = match external { + 0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()), + 1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()), + _ => EngineError::Other("The paths overlap, so they have no internal tangents".into()), + }; + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + let fill = Paint::None; + let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; + let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); + // The new art's look may carry more fills than the top one: none of them is kept. + look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + let top = *second; + let (ids, center_id) = s.edit(LABEL, |d, sel| { + let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; + let mut ids = vec![]; + let mut center_id = None; + for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let id = d.alloc_id(); + let path = PathData::single(SubPath::polyline(&[from, to], false)); + let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + look.apply(d, &mut n); + d.insert(parent, idx + 1 + k, n)?; + if k == lines.len() { + center_id = Some(id); + } + ids.push(id); + } + sel.set(ids.iter().copied()); + Ok((ids, center_id)) + })?; + Ok(json!({ + "ids": ids.iter().map(|i| i.0).collect::>(), + "external": external_kept, + "internal": internal_kept, + "centerline": center_id.map(|i| i.0), + })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..5ed6e2b0d6 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -0,0 +1,265 @@ +//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline, +//! the paint, one undo step, the cases with no tangent, and refused selections and params. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; +use vectorcraft_geom::{Point, Vec2}; + +use crate::Session; + +const C: &str = super::COMMON_TANGENTS; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId { + id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The ends of each new line, as `ids` lists them. +fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> { + let d = &s.doc().unwrap().doc; + r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + (sp.anchors[0].p, sp.anchors[1].p) + }) + .collect() +} + +fn near(p: Point, q: Point) -> bool { + p.distance(q) < 1e-6 +} + +fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool { + found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p))) +} + +#[test] +fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 200.0, 20.0); + let b = circle(&mut s, 300.0, 200.0, 40.0); + select(&mut s, &[a, b]); + let before = steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 4); + let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3. + for (nx, external) in [(-0.1f64, true), (0.3, false)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 }; + assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}"); + } + } + // The lines are the selection, above the two circles. + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 4); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied())); + assert_eq!(&order[..2], &[a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all"); +} + +#[test] +fn turned_ellipses_are_measured_exactly() { + let mut s = session(); + let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap()); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap(); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap()); + select(&mut s, &[b]); + s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(C, &json!({"tangents": "all"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + // Each end lies on its ellipse, where the ellipse runs along the line: turned back about the + // center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line. + let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| { + let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians()); + // `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms. + let page = |v: Vec2| Vec2::new(v.x, -v.y); + let q = page((turn * page(p - center).to_point()).to_vec2()); + let d = page((turn * page(dir).to_point()).to_vec2()); + let value = (q.x / rx).powi(2) + (q.y / ry).powi(2); + let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry)); + (value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7 + }; + for (p, q) in lines(&s, &r) { + let dir = q - p; + assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse"); + assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse"); + } +} + +#[test] +fn a_convex_bezier_path_and_the_centerline() { + let mut s = session(); + let anchors = json!([ + {"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]}, + {"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]}, + {"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]}, + {"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]} + ]); + let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()); + let round = circle(&mut s, 300.0, 200.0, 30.0); + let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 5, "four tangents and the centerline"); + // The centerline is the last line and its id is given: from the blob's center of area to the + // circle's center. + assert_eq!(r["centerline"], r["ids"][4]); + let (from, to) = found[4]; + assert!(near(to, Point::new(300.0, 200.0)), "{to:?}"); + assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}"); + // A tangent touches without crossing: every point of both paths is on one side of it. + let d = &s.doc().unwrap().doc; + let points = |id: NodeId| { + let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect(); + segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::>() + }; + let (pa, pb) = (points(blob), points(round)); + for (p, q) in &found[..4] { + let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize(); + for pts in [&pa, &pb] { + let side: Vec = pts.iter().map(|x| (*x - *p).dot(n)).collect(); + let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + // The circle is measured as an exact circle, which its four curves follow to within + // about 0.03% of the radius. + assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}"); + } + } +} + +#[test] +fn the_lines_take_the_current_stroke_and_no_fill() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let d = &s.doc().unwrap().doc; + for v in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill"); + let st = n.appearance.stroke().expect("stroked"); + assert!(!st.paint.is_none(), "black when the stroke is None"); + } + // A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill. + let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0); + let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap(); + look.items.push(fill); + s.paint.appearance = Some(look); + s.paint.inherited = false; + let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + let d2 = &s.doc().unwrap().doc; + for v in r2["ids"].as_array().unwrap() { + let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all"); + assert!(n.appearance.stroke().is_some()); + } + // Two equal circles: the external tangents run along their tops and bottoms. + assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0))); + assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0))); +} + +#[test] +fn nested_and_overlapping_paths_change_nothing_and_say_why() { + let mut s = session(); + let big = circle(&mut s, 200.0, 200.0, 100.0); + let small = circle(&mut s, 220.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Overlapping circles have external tangents only. + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 140.0, 100.0, 30.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap(); + assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + // Circles that touch share the tangent where they touch. + let c = circle(&mut s, 100.0, 300.0, 10.0); + let e = circle(&mut s, 130.0, 300.0, 20.0); + let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["internal"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}"); + // A circle touching the inside of a larger one: no internal tangent, and the message says the + // one lies inside the other rather than that they overlap. + let outer = circle(&mut s, 400.0, 200.0, 50.0); + let inner = circle(&mut s, 430.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); +} + +#[test] +fn bad_selections_and_params_are_refused() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap()); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + let group_of = |s: &mut Session, ids: &[NodeId]| { + select(s, ids); + id_of(&s.execute("object.group", &json!({})).unwrap()) + }; + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused"); + assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex")); + assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open")); + assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()); + assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline")); + let g = group_of(&mut s, &[b]); + assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); +} diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index ddb74ef445..5d2374c72a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -74,7 +74,7 @@ pub fn specs() -> Vec { "Split Path", [], None, - "{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}", + "{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes", has_doc, split ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 63051297e3..e3ee153744 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -197,6 +197,9 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) { return Err(bad(C, "invalid t")); } + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } let ids = s.edit("Split Path", |d, sel| { let path = path_mut(d, id)?; let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?; @@ -296,7 +299,13 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { let samples = samples_param(p, "points", C)?; let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; + if !(-180.0..=180.0).contains(&angle) { + return Err(bad(C, "`angle` must be from -180 to 180 degrees")); + } let roundness = number_or(p, "roundness", 100.0, C)?; + if !(1.0..=100.0).contains(&roundness) { + return Err(bad(C, "`roundness` must be from 1 to 100%")); + } let vary = eraser_variations(p, C)?; if varies_beyond_size_pressure(&vary) { return erase_varied(s, &samples, [angle, roundness, size], vary); @@ -306,7 +315,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { let r = size / 2.0; // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0)); - let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0; + let short = narrowest * roundness / 100.0; let st = s.doc()?; // A point is under the tip when, with the tip squashed back into a circle, it is within the // circle's radius of the squashed drag. diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 2429d5763f..acd25aea28 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption { name: "layers", ty: "boolean", default: "true", - description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent", + description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way", }; const MAX_EDITABILITY: FormatOption = FormatOption { diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 85fa6ae7e9..cc210ffa2a 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -511,3 +511,75 @@ fn damaged_slices_never_panic() { } } } + +/// The PSD file `document.export` writes from `s`, with its layers or flat. +fn export(s: &mut Session, layers: bool) -> Vec { + let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +#[test] +fn an_opened_files_slices_survive_a_psd_export() { + let link = + S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) }; + let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) }; + let html = S { kind: 0, html: true, cell: "Hi", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) }; + let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) }; + let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[])); + let (mut s, _) = open(&f, json!({})); + let opened = slices(&s); + assert_eq!(opened.len(), 3); + for layers in [true, false] { + let out = export(&mut s, layers); + let (again, r) = open(&out, json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + // The same rectangles and options; the auto slices are laid out again around them. + let mut got = slices(&again); + let mut want = opened.clone(); + let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0))); + order(&mut got); + order(&mut want); + assert_eq!(got, want); + let layout = again.doc().unwrap().doc.slice_layout(); + assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto)); + assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3)); + } +} + +#[test] +fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + let rect = r["id"].as_u64().unwrap(); + s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "x", "background": "#00ff00"})).unwrap(); + let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.slice.make", &json!({"ids": [t]})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap(); + let (again, _) = open(&export(&mut s, false), json!({})); + let got = slices(&again); + assert_eq!(got.len(), 2, "{got:?}"); + let doc = &s.doc().unwrap().doc; + let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap(); + let boxed = got.iter().find(|g| g.1.name == "box").unwrap(); + // Within a pixel of the object's bounds. + for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] { + assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0); + } + assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "x", "#00ff00")); + let text = got.iter().find(|g| g.1.name.is_empty()).unwrap(); + assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A & B")); +} + +#[test] +fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() { + let columns: Vec = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect(); + let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({})); + assert_eq!(slices(&s).len(), 20); + let (again, r) = open(&export(&mut s, true), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&again), slices(&s)); +} diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 7084fe19f6..27da7936a8 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Type…", ["Object", "Graph"], None, - "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", + "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as bands `lineWidth` wide filled with the series colour), lineWidth?: pt (Line Width of Draw Filled Lines: 0.01–1000; 3), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; options that leave the graph as it is record no step of history; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", has_selection, set_type ), diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 378a8e3745..728eff6427 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -230,6 +230,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value "prefix": one_line(&spec.prefix), "suffix": one_line(&spec.suffix), "rightPrefix": one_line(&spec.right_prefix), "rightSuffix": one_line(&spec.right_suffix), "dropShadow": spec.drop_shadow, "legendAcrossTop": spec.legend_across_top, "firstRowInFront": spec.first_row_in_front, "firstColumnInFront": spec.first_column_in_front, "filledLines": spec.filled_lines, + "lineWidth": spec.filled_line_width(), }); // Only the options this graph's types use: overlap order for columns and bars, filled lines for lines. let kinds: Vec = (0..count.max(1)).map(|i| spec.series_kind(i)).collect(); @@ -241,6 +242,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value } if !has(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]) { o.remove("filledLines"); + o.remove("lineWidth"); } } // Pie graphs: Legend, Position and Sort (their Legend stands for the legend checkbox). @@ -266,6 +268,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { const C: &str = "graph.setType"; let id = target(s, p, C)?; let mut spec = spec_of(s, id)?; + let stored = spec.clone(); // The series to retype: `seriesIndexes`, else, with no `id`, a selection made only of this graph's series (Group // Selection). Anything else selected, the graph itself for one, is the whole graph. let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); @@ -311,6 +314,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { "firstRowInFront", "firstColumnInFront", "filledLines", + "lineWidth", "pieLegend", "piePosition", "pieSort", @@ -404,6 +408,15 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?; spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?; spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?; + if let Some(w) = p.get("lineWidth").filter(|v| !v.is_null()) { + let w = w.as_f64().ok_or_else(|| bad(C, format!("`lineWidth` must be a number, not {w}")))?; + let (min, max) = (vectorcraft_doc::MIN_FILLED_LINE_WIDTH, vectorcraft_doc::MAX_FILLED_LINE_WIDTH); + if !(min..=max).contains(&w) { + return Err(bad(C, format!("`lineWidth` must be from {min} to {max} pt, not {w}"))); + } + // The default width is stored as no width. + spec.line_width = (w != vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH).then_some(w); + } spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?; // After `legend`, which the Graph Type dialog sends too. if let Some(v) = text_param(p, "pieLegend", C)? { @@ -418,6 +431,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result { spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?; spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?; spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks); + // Options that leave the graph as it is record no step of history. + if spec == stored { + return Ok(json!({ "id": id.0 })); + } let label = format!("{} Graph", spec.kind.label()); s.edit("Graph Type", |d, sel| { regenerate(d, id, spec)?; diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 8d0ea64e45..e6b9a6711b 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -230,10 +230,11 @@ impl Gen<'_> { Arc::new(g) } /// A series' line joining its data points (Connect Data Points): a 1 pt stroke in the series colour, or with Draw - /// Filled Lines a band FILLED_LINE_WIDTH wide filled with it and outlined in black. + /// Filled Lines a band as wide as the graph's Line Width ([`GraphSpec::filled_line_width`]) filled with it and outlined + /// in black. pub(super) fn data_line(&mut self, g: &GraphSpec, s: usize, pd: PathData, filled: bool) -> Arc { let band = if filled { - vectorcraft_pathops::outline_stroke(&pd, FILLED_LINE_WIDTH, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0) + vectorcraft_pathops::outline_stroke(&pd, g.filled_line_width(), vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0) } else { PathData::default() }; @@ -287,9 +288,6 @@ const SHADOW_OFFSET: f64 = 2.0; pub(super) const SHADOW_OPACITY: f32 = 0.35; -/// Draw Filled Lines: how wide a filled line is. -const FILLED_LINE_WIDTH: f64 = 3.0; - const FILLED_LINE_BUDGET: usize = 20_000; /// Does graph `g`, with `series` series, draw Filled Lines (up to FILLED_LINE_BUDGET data points)? diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c1a59c30e5..d7000d5c68 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6700,6 +6700,54 @@ fn filled_lines_keep_the_line_colour_and_fall_back_to_thin_lines() { assert!(series_parts(&s, big, 0)[0].appearance.fill_paint().is_none()); } +/// Line Width sets how wide Draw Filled Lines draws the bands and is kept through save and open. A width outside 0.01 +/// to 1000 pt is refused, the same width again records no undo step, and the default 3 pt is stored as no width. +#[test] +fn filled_lines_take_a_line_width() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "line", ",a\nQ1,2\nQ2,2\nQ3,2"); + s.execute("graph.setType", &json!({"id": id.0, "filledLines": true})).unwrap(); + let height = |s: &Session| series_parts(s, id, 0)[0].geometric_bounds().unwrap().height(); + assert!((height(&s) - 3.0).abs() < 1e-6, "3 pt by default: {}", height(&s)); + assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(3.0)); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 8})).unwrap(); + assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s)); + assert_eq!(s.execute("graph.setType", &json!({"id": id.0})).unwrap()["lineWidth"], json!(8.0)); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + for p in [json!({"id": id.0, "lineWidth": 8}), json!({"id": id.0, "lineWidth": 8.0, "filledLines": true}), json!({"id": id.0, "lineWidth": null})] + { + s.execute("graph.setType", &p).unwrap(); + assert_eq!(steps(&s), before, "nothing changed: {p}"); + } + for w in [json!(0), json!(-2), json!(0.005), json!(1000.5)] { + let e = s.execute("graph.setType", &json!({"id": id.0, "lineWidth": w})).unwrap_err().to_string(); + assert!(e.contains(&format!("`lineWidth` must be from 0.01 to 1000 pt, not {}", w.as_f64().unwrap())), "{e}"); + assert_eq!((steps(&s), spec(&s, id).line_width), (before, Some(8.0)), "{w}"); + } + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 0.01})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(0.01)); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 1000})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(1000.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(8.0)); + // Kept through save and open. + let dir = vectorcraft_testkit::TempDir::new("graph-line-width"); + let path = dir.join("width.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + assert_eq!(spec(&s, id).line_width, Some(8.0)); + assert!((height(&s) - 8.0).abs() < 1e-6, "{}", height(&s)); + // The default width is stored as no width, so the file keeps no `lineWidth`. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setType", &json!({"id": id.0, "lineWidth": 3})).unwrap(); + assert_eq!(spec(&s, id).line_width, None); + assert!(serde_json::to_value(spec(&s, id)).unwrap().get("lineWidth").is_none()); + assert!((height(&s) - 3.0).abs() < 1e-6, "{}", height(&s)); +} + #[test] fn overlapping_columns_keep_clear_of_the_legend_and_options_follow_the_graph_type() { let mut s = Session::new(); @@ -9216,6 +9264,7 @@ fn graph_commands_refuse_params_of_the_wrong_type() { ("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"), ("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"), ("filledLines", json!("on"), "`filledLines` must be true or false"), + ("lineWidth", json!("4"), "`lineWidth` must be a number, not \"4\""), ("dropShadow", json!(1), "`dropShadow` must be true or false"), ("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"), ("type", json!(5), "`type` must be a string"), diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index dae66f1a1b..b0d313fbf5 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -260,7 +260,7 @@ pub fn specs() -> Vec { "Align", ["Window", "Align"], None, - "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put", + "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put", has_selection_or_guides, align ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c15ef6d0c4..75313d4e4c 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -45,6 +45,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", "addon.pathtools.close", + "addon.pathtools.commonTangents", "addon.pathtools.corner", "addon.pathtools.cornerRemove", "addon.pathtools.cornerSet", diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index e5fa5f75b3..791aa47f39 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -82,19 +82,11 @@ pub fn specs() -> Vec { "Cancel Key Object", [], None, - "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)", + "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; a click without modifiers on an already-selected anchor point makes it the key anchor)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)", has_doc, key ), - cmd!( - "select.anchors", - "Select Anchors", - [], - None, - "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)", - has_doc, - anchors - ), + cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors), cmd!( "select.segments", "Select Segments", @@ -734,17 +726,32 @@ fn key_anchor(s: &mut Session, id: Option, guide: Option, v: &Val let st = s.doc()?; let sel = &st.selection; let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len())); - if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) { + let is_selected_anchor = on_path + && !sel.segments.contains_key(&id) + && (sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) || (!sel.anchors.contains_key(&id) && sel.contains(id))); + if !is_selected_anchor { return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1))); } // Check the new key on a copy first, so a request that fails leaves the key as it was. let mut trial = sel.clone(); + if !trial.anchors.contains_key(&id) + && let Some(p) = st.doc.node(id).and_then(|n| n.path_data()) + { + trial.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect()); + } trial.key_anchor = Some((id, r)); trial.prune(&st.doc); if trial.key_anchor.is_none() { return Err(bad(C, "select another anchor point to align to the key anchor")); } - s.select(|_, sel| sel.key_anchor = Some((id, r)))?; + s.select(|d, sel| { + if !sel.anchors.contains_key(&id) + && let Some(p) = d.node(id).and_then(|n| n.path_data()) + { + sel.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect()); + } + sel.key_anchor = Some((id, r)); + })?; key_result(s) } @@ -891,23 +898,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result { if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) { e.extend(path.anchors().map(|(s, i, _)| (s, i))); } - // One point that add or toggle selects becomes the key anchor (a Shift-click with Direct - // Selection); `prune` drops it unless another point is selected too. - let single = refs.len() == 1; - let mut newest = None; for r in refs { if mode == "toggle" && e.contains(&r) { e.remove(&r); - } else if e.insert(r) && single { - newest = Some(r); + } else { + e.insert(r); } } if e.is_empty() { sel.remove(id); - } else if mode != "set" - && let Some(r) = newest - { - sel.key_anchor = Some((id, r)); } })?; ok() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 64a551e872..fbd2eb71e7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -196,6 +196,7 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbollib; +mod tangent_line; mod targeting; mod textcombos; mod textedit; diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index d049698222..f041a7426c 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -596,8 +596,8 @@ fn a_graph_pasted_without_formatting_keeps_plain_labels_when_drawn_again() { let r = node(&s, p).extras().graph.as_deref().unwrap().rect; let off = [r.x0 - plot.x0 - 10.0, r.y0 - plot.y0 - 20.0, r.x1 - plot.x1 - 10.0, r.y1 - plot.y1 - 20.0]; assert!(off.iter().all(|d| d.abs() < 1e-6), "the plot moves by the offset and keeps its size: {plot:?} → {r:?}"); - s.execute("graph.setType", &json!({"id": p.0, "type": "column"})).unwrap(); - assert_eq!(graph_label_looks(&s, p), pasted, "a change of type draws them the same way"); + s.execute("graph.setType", &json!({"id": p.0, "type": "column", "dropShadow": true})).unwrap(); + assert_eq!(graph_label_looks(&s, p), pasted, "a change of graph type options draws them the same way"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 54364915da..8674750c19 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1504,9 +1504,76 @@ fn the_eraser_tip_takes_its_angle_and_roundness() { // At 45°, half axes 10 and 2.5: the band is 2·√((10² + 2.5²) / 2), about 14.58 pt, and the // chord 2 / √(0.5 / 10² + 0.5 / 2.5²), about 6.86 pt. close(erase(json!({"angle": 45, "roundness": 25})), 2.0 * ((100.0f64 + 6.25) / 2.0).sqrt(), 2.0 / (0.5f64 / 100.0 + 0.5 / 6.25).sqrt()); - // A roundness past 100 is kept to 100, and one below 1 to 1. - close(erase(json!({"angle": 90, "roundness": 400})), 20.0, 20.0); - close(erase(json!({"angle": 90, "roundness": 0})), 0.2, 0.2); + // The ends of the Roundness range: 100% is round, and 1% leaves a tip 0.2 pt across. + close(erase(json!({"angle": 90, "roundness": 100})), 20.0, 20.0); + close(erase(json!({"angle": 90, "roundness": 1})), 0.2, 0.2); +} + +/// The Eraser refuses an `angle` outside -180 to 180 degrees and a `roundness` outside 1 to 100%, +/// naming the key and the range, and erases nothing. The ends of each range erase, and a key left +/// out or null takes its default: 0 degrees and 100%. +#[test] +fn the_eraser_refuses_an_angle_or_roundness_outside_its_range() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + let stroke = json!({"points": [[90, 150], [210, 150]], "size": 10}); + for angle in [json!(-181), json!(-180.001), json!(180.001), json!(200), json!(1e300), json!(-1e300)] { + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": angle})), "`angle` must be from -180 to 180 degrees"); + } + for roundness in [json!(0), json!(0.999), json!(-25), json!(100.001), json!(400), json!(1e300)] { + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"roundness": roundness})), "`roundness` must be from 1 to 100%"); + } + // A key out of its range is refused when the other key is in range. + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 90, "roundness": 400})), "`roundness` must be from 1 to 100%"); + refuses_with(&mut s, "path.eraseRegion", &with(&stroke, json!({"angle": 540, "roundness": 25})), "`angle` must be from -180 to 180 degrees"); + // The pieces a stroke leaves, undone again. + let mut erased = |tip: serde_json::Value| { + let r = s.execute("path.eraseRegion", &with(&stroke, tip.clone())).unwrap(); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(2), "{tip}: the stroke cuts the square in two: {r}"); + let pieces: Vec = paths(&s).into_iter().map(|p| p.1).collect(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + pieces + }; + // Both ends of each range are inside it. + for tip in [json!({"angle": -180}), json!({"angle": 180}), json!({"angle": 90, "roundness": 1}), json!({"roundness": 100})] { + erased(tip); + } + let default = erased(json!({})); + assert_eq!(erased(json!({"angle": 0, "roundness": 100})), default, "left out, the tip is round at 0 degrees"); + assert_eq!(erased(json!({"angle": null, "roundness": null})), default, "null is read as a key left out"); + assert!(erased(json!({"angle": 0, "roundness": 25})) != default, "a quarter-round level tip erases a narrower band"); +} + +/// The Scissors command refuses a `t` outside 0 to 1 instead of cutting at the nearer end of the +/// segment, with or without an `anchor` beside it; 0 and 1 cut at the segment's two anchors. +#[test] +fn scissors_refuse_a_t_outside_the_segment() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let before = path(&s, id); + for t in [json!(-0.1), json!(-1e-9), json!(1.000001), json!(1.1), json!(1e300), json!(-1e300)] { + refuses_with(&mut s, "path.split", &json!({"id": id.0, "segment": 0, "t": t}), "`t` must be from 0 to 1"); + refuses_with(&mut s, "path.split", &json!({"id": id.0, "anchor": 1, "t": t}), "`t` must be from 0 to 1"); + } + // 0 opens the square at the segment's first anchor, 1 at its second, and 0.5 at a new anchor + // between them. + for (t, anchors, start) in [ + (json!(0), 5, before.subpaths[0].anchors[0].p), + (json!(1), 5, before.subpaths[0].anchors[1].p), + (json!(0.5), 6, before.subpaths[0].anchors[0].p.midpoint(before.subpaths[0].anchors[1].p)), + ] { + s.execute("path.split", &json!({"id": id.0, "segment": 0, "t": t})).unwrap(); + let cut = path(&s, id); + assert!(!cut.subpaths[0].closed && cut.subpaths[0].anchors.len() == anchors, "t {t}: {cut:?}"); + assert!((cut.subpaths[0].anchors[0].p - start).hypot() < 1e-9, "t {t}: the cut starts at {:?}", cut.subpaths[0].anchors[0].p); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), before, "t {t}: undo"); + } + // Left out, `t` is 0.5. + s.execute("path.split", &json!({"id": id.0, "segment": 0})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 6); } #[test] diff --git a/crates/engine/src/tests/keyanchor.rs b/crates/engine/src/tests/keyanchor.rs index 0dc6675f2a..fb5e319bb9 100644 --- a/crates/engine/src/tests/keyanchor.rs +++ b/crates/engine/src/tests/keyanchor.rs @@ -1,6 +1,7 @@ -//! #1636: the key anchor. With Direct Selection, the point a Shift-click adds to two or more -//! selected anchor points is the key anchor; Align moves the other points to it, Distribute with a -//! spacing places them from it, and it stays in place. +//! #1636: the key anchor. When multiple anchors are selected with Direct Selection, +//! clicking an already-selected anchor point without modifiers designates it as the key anchor; +//! Align moves the other points to it, Distribute with a spacing places them from it, and it stays in place. +//! Deselecting, pressing Escape, or clicking canvas clears the key anchor designation. use serde_json::json; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -34,56 +35,148 @@ fn click(s: &mut Session, x: f64, y: f64, shift: bool) { } #[test] -fn a_shift_click_makes_the_key_anchor_and_a_plain_click_narrows_the_selection() { +fn clicking_an_already_selected_anchor_makes_it_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M100 40 L200 60 L150 160 Z"); s.select_tool("directSelection", ViewInfo::default()).unwrap(); + // 1st click selects point (0, 0) alone. click(&mut s, 100.0, 40.0, false); assert_eq!(key_anchor(&s), None, "one point: no key anchor"); + // Shift-click adds point (0, 2) to selection. No key anchor yet. click(&mut s, 150.0, 160.0, true); - assert_eq!(key_anchor(&s), Some((id, (0, 2))), "the point the Shift-click added"); + assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection"); + // Shift-click adds point (0, 1) to selection. No key anchor yet. click(&mut s, 200.0, 60.0, true); - assert_eq!(key_anchor(&s), Some((id, (0, 1))), "the last point added"); + assert_eq!(key_anchor(&s), None, "Shift-click only adds to selection"); + + // Clicking an already-selected anchor without modifiers designates it as the Key Anchor. + click(&mut s, 200.0, 60.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 1))), "clicking selected anchor designates key anchor"); let inspect = s.execute("document.inspect", &json!({})).unwrap(); assert_eq!(inspect["keyAnchor"], json!({"id": id.0, "anchor": [0, 1]})); - // A Shift-click on the key anchor deselects it, and there is no key anchor. - click(&mut s, 200.0, 60.0, true); - assert_eq!(key_anchor(&s), None); - click(&mut s, 200.0, 60.0, true); - // A plain click on one of the selected points selects that point alone. - click(&mut s, 100.0, 40.0, false); + + // Clicking the key anchor again cancels the key anchor. + click(&mut s, 200.0, 60.0, false); + assert_eq!(key_anchor(&s), None, "clicking key anchor again cancels it"); + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + assert!(inspect["keyAnchor"].is_null()); + + // Clicking another selected anchor designates that one as the key anchor. + click(&mut s, 150.0, 160.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Pressing Escape cancels the key anchor designation while keeping points selected. + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), ViewInfo::default()).unwrap(); + assert_eq!(key_anchor(&s), None, "Escape cancels key anchor"); let sel = &s.doc().unwrap().selection; - assert_eq!(sel.anchors.get(&id).map(|a| a.iter().copied().collect::>()), Some(vec![(0, 0)])); - assert_eq!(sel.key_anchor, None); + assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(3), "points remain selected"); + + // Designate key anchor: + click(&mut s, 150.0, 160.0, false); + assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Canvas click clears selection and key anchor. + click(&mut s, 500.0, 500.0, false); // canvas click + assert_eq!(key_anchor(&s), None, "canvas click clears key anchor"); + assert!(s.doc().unwrap().selection.is_empty(), "canvas click clears selection"); + + // Re-select multiple anchors: + click(&mut s, 100.0, 40.0, false); // select (0, 0) + click(&mut s, 200.0, 60.0, true); // add (0, 1) + assert_eq!(key_anchor(&s), None); + click(&mut s, 200.0, 60.0, false); // make (0, 1) key anchor + assert_eq!(key_anchor(&s), Some((id, (0, 1)))); + + // Shift-click on the key anchor deselects it, clearing the key anchor. + click(&mut s, 200.0, 60.0, true); + assert_eq!(key_anchor(&s), None, "deselecting key anchor clears it"); } #[test] fn align_moves_the_other_points_to_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M100 40 L200 60 L150 160 L60 120 Z"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - assert_eq!(key_anchor(&s), None, "a set selects no key anchor"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + assert_eq!(key_anchor(&s), None, "set selects no key anchor"); + s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap(); assert_eq!(key_anchor(&s), Some((id, (0, 2)))); + + // Horizontal Left aligns other selected points to key anchor's x (150). s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); assert_eq!(pts(&s, id), [(150.0, 40.0), (150.0, 60.0), (150.0, 160.0), (60.0, 120.0)], "to the key anchor's x"); + + // Vertical Bottom aligns other selected points to key anchor's y (160). s.execute("object.align", &json!({"vertical": "bottom"})).unwrap(); assert_eq!(pts(&s, id), [(150.0, 160.0), (150.0, 160.0), (150.0, 160.0), (60.0, 120.0)], "the key anchor stays"); + let steps = super::history(&s); s.execute("object.align", &json!({"vertical": "top"})).unwrap(); assert_eq!(super::history(&s), steps, "nothing moved: no undo step"); - // `to: "selection"` aligns to the points' bounds instead. + + // `to: "selection"` aligns to the points' collective bounds instead. s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]], "mode": "add"})).unwrap(); s.execute("object.align", &json!({"horizontal": "left", "to": "selection"})).unwrap(); assert_eq!(pts(&s, id).iter().map(|p| p.0).collect::>(), [60.0; 4]); } +#[test] +fn align_commands_across_paths_without_moving_key_anchor() { + let mut s = session(); + let a = path(&mut s, "M100 100 L200 100 L200 200 Z"); + let b = path(&mut s, "M300 300 L400 350 Z"); + // Select point (0, 1) on path a (at 200, 100) and point (0, 0) on path b (at 300, 300). + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + // Set point (0, 1) of a as the key anchor. + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + assert_eq!(key_anchor(&s), Some((a, (0, 1)))); + + // Align Horizontal Center: point (0, 0) of b moves to x=200, while point on a does not move! + s.execute("object.align", &json!({"horizontal": "center"})).unwrap(); + assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a does not move"); + assert_eq!(pts(&s, b)[0].0, 200.0, "survivor point on b aligned to key anchor x"); + assert_eq!(pts(&s, b)[1], (400.0, 350.0), "unselected point on b was not moved"); + + // Align Vertical Center / Middle: point (0, 0) of b moves to y=100. + s.execute("object.align", &json!({"vertical": "center"})).unwrap(); + assert_eq!(pts(&s, a)[1], (200.0, 100.0), "key anchor on a still did not move"); + assert_eq!(pts(&s, b)[0].1, 100.0, "survivor point on b aligned to key anchor y"); +} + +#[test] +fn single_step_undo_redo_for_key_anchor_alignment() { + let mut s = session(); + let a = path(&mut s, "M100 100 L200 150 Z"); + let b = path(&mut s, "M300 300 L400 350 Z"); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 0]})).unwrap(); + + let initial_a = pts(&s, a); + let initial_b = pts(&s, b); + + // Run align: + s.execute("object.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!(pts(&s, a)[0], (100.0, 100.0), "key anchor did not move"); + assert_eq!(pts(&s, b)[0].0, 100.0, "survivor moved to key anchor x"); + + // Undo reverts to initial in one step: + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(pts(&s, a), initial_a, "undo restored a"); + assert_eq!(pts(&s, b), initial_b, "undo restored b"); + + // Redo re-aligns in one step: + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(pts(&s, a)[0], (100.0, 100.0)); + assert_eq!(pts(&s, b)[0].0, 100.0); +} + #[test] fn distribute_with_a_spacing_places_the_points_from_the_key_anchor() { let mut s = session(); let id = path(&mut s, "M10 10 L20 50 L100 30 L60 90"); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": id.0, "anchor": [0, 2]})).unwrap(); s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 20})).unwrap(); assert_eq!(pts(&s, id), [(60.0, 10.0), (80.0, 50.0), (100.0, 30.0), (60.0, 90.0)], "20 apart, outward from the key anchor"); s.execute("object.distribute", &json!({"vertical": "center", "spacing": 5})).unwrap(); @@ -100,6 +193,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() { let b = path(&mut s, "M300 300 L400 300"); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": b.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((b, (0, 1))), "a point of another path"); assert!(s.doc().unwrap().selection.has_key()); let r = s.execute("select.key", &json!({})).unwrap(); @@ -114,6 +208,7 @@ fn the_key_anchor_goes_when_it_can_no_longer_be_one() { let c = path(&mut s, "M500 500 L600 500"); s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((a, (0, 1))), "beside a path selected whole"); s.execute("select.key", &json!({"id": c.0})).unwrap(); let sel = &s.doc().unwrap().selection; @@ -154,6 +249,7 @@ fn a_rejected_select_key_keeps_the_key_anchor() { let a = path(&mut s, "M100 40 L200 60 L150 160 Z"); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 9]], "mode": "set"})).unwrap(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); assert_eq!(key_anchor(&s), Some((a, (0, 1)))); // [0, 9] is in the selection but not on the path. let err = s.execute("select.key", &json!({"id": a.0, "anchor": [0, 9]})).expect_err("a point the path does not have").to_string(); diff --git a/crates/engine/src/tests/tangent_line.rs b/crates/engine/src/tests/tangent_line.rs new file mode 100644 index 0000000000..78511d766b --- /dev/null +++ b/crates/engine/src/tests/tangent_line.rs @@ -0,0 +1,40 @@ +//! Snap to Tangent with the Line Segment tool: a line dragged from one circle to another lands on +//! their common tangent, drawn by `shape.line` as one undo step. + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::*; + +use PointerKind::{Down, Drag, Up}; + +#[test] +fn a_line_segment_drag_draws_the_common_tangent_as_one_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 210, "width": 80, "height": 80})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 240, "y": 190, "width": 120, "height": 120})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + assert_eq!(count(&s), 2); + // Circles about (100, 250), radius 40, and (300, 250), radius 60: the outer tangent above them + // has the normal (-0.1, -√0.99) and touches them at center + radius × normal. + let n = Vec2::new(-0.1, -(0.99f64).sqrt()); + let (on_a, on_b) = (Point::new(100.0, 250.0) + n * 40.0, Point::new(300.0, 250.0) + n * 60.0); + s.select_tool("lineSegment", ViewInfo::default()).unwrap(); + let to = on_b + Vec2::new(0.5, 0.7); + for (k, x, y) in [(Down, 100.0, 210.0), (Drag, 200.0, 200.0), (Drag, to.x, to.y), (Up, to.x, to.y)] { + s.pointer(&PointerEvent::new(k, x, y), ViewInfo::default()).unwrap(); + } + assert_eq!(count(&s), 3); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") }; + let ends: Vec = path.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends.len(), 2); + // Within what the drawn circles' 0.03% radius error allows. + assert!((ends[0] - on_a).hypot() < 0.15 && (ends[1] - on_b).hypot() < 0.15, "{ends:?}, want {on_a:?} {on_b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(count(&s), 2, "one undo removes the line"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b661478e0f..a4c6c1af40 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -991,6 +991,10 @@ fn structured_junk() { ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), + ("addon.pathtools.commonTangents", json!({"tangents": "all", "centerline": true})), + ("addon.pathtools.commonTangents", json!({"tangents": "x", "centerline": "y", "ids": [u64::MAX, -1]})), + ("addon.pathtools.commonTangents", json!({"tangents": null, "ids": [1, 2, 3, 4], "centerline": null})), + ("addon.pathtools.commonTangents", json!({"tangents": ["external"], "ids": "all"})), ("addon.pathtools.expandDashes", json!({})), ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), diff --git a/crates/eps/src/ai_graph.rs b/crates/eps/src/ai_graph.rs index 3e1cebd9f9..d2db08229f 100644 --- a/crates/eps/src/ai_graph.rs +++ b/crates/eps/src/ai_graph.rs @@ -233,7 +233,8 @@ fn tick(t: TickLength) -> u8 { } /// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across -/// the top, every series of the graph's type, one value axis on the left, lines not filled, no graph +/// the top, every series of the graph's type, one value axis on the left, lines not filled and no +/// Line Width of their own, no graph /// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most /// [`MAX_TICK_MARKS`] tick marks a division. fn settings_kept(g: &GraphSpec) -> bool { @@ -244,6 +245,7 @@ fn settings_kept(g: &GraphSpec) -> bool { && !g.separate_scales && g.right_series.is_empty() && !g.filled_lines + && g.line_width.is_none() && g.series_markers.iter().all(Option::is_none) && g.series_columns.iter().all(Option::is_none) && g.label_styles == LabelStyles::default() @@ -514,6 +516,7 @@ pub(crate) mod sample { cases.extend([ ("no legend", with(&|g| g.legend = false)), ("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))), + ("a filled line width", with(&|g| (g.kind, g.line_width) = (GraphKind::Line, Some(8.0)))), ("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])), ("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])), ("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b3db2cfc88..ad97330005 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -979,7 +979,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 516cfe6235..87cc5ba56f 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,8 +4,9 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch -//! two or three shapes ([`tangent_circles`]). +//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]), the +//! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes +//! ([`tangent_circles`]). mod crossings; mod dashes; @@ -14,6 +15,7 @@ pub mod shapes; mod shared_edge; mod slide; mod tangent_circle; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -31,6 +33,7 @@ pub use shared_edge::{ }; pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at}; pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLES, TangentCircleError, tangent_circle_segments, tangent_circles}; +pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents}; pub use trim::{Span, slice, span_at, spans, without_spans}; use crate::fit::{end_tangent, start_tangent}; diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..2059932aa2 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -0,0 +1,895 @@ +//! Common Tangents: the straight lines that touch two convex closed outlines (ellipses at any +//! rotation and scale, and convex Bézier paths) without crossing into either. An external tangent +//! has both outlines on the same side of it; an internal one runs between them. +//! +//! A line with unit normal `n` touches an outline from outside where `p · n` reaches the +//! outline's support value `h(n)`, the largest `p · n` over its points. External tangents are the +//! normals where both outlines have the same support value, internal ones where `h₁(n) = -h₂(-n)`. +//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with +//! sampled minima refined too so that a double root (outlines that touch) or two roots between +//! neighboring samples are kept. + +use std::f64::consts::TAU; + +use kurbo::{Affine, CubicBez, ParamCurve, Point, Vec2}; +use vectorcraft_geom::SubPath; + +/// Most segments one outline may have. +pub const MAX_TANGENT_SEGMENTS: usize = 10_000; +/// Normal directions sampled around the circle before refining. +const SAMPLES: usize = 720; +/// Steps of bisection or golden-section search for each root. +const STEPS: usize = 64; +/// Straight pieces each segment is cut into to check that a path is convex and to find its center. +const FLATTEN: usize = 32; + +/// Which side of a tangent the two outlines lie on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TangentKind { + /// Both on the same side. + External, + /// One on each side. + Internal, +} + +/// One common tangent: the stretch of the line from where it touches the first outline to where +/// it touches the second. Where the outlines touch each other at one point, the stretch is +/// centered on that point and as long as the narrower outline is wide along the line, and `from` +/// is the end with the lower position along the line. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tangent { + pub kind: TangentKind, + pub from: Point, + pub to: Point, +} + +/// Why [`Outline::convex`] or [`Outline::ellipse`] cannot take a shape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineError { + /// The path is open. + Open, + /// The path bends inward somewhere, or winds around more than once. + NotConvex, + /// No area, or not finite. + Empty, + /// More than [`MAX_TANGENT_SEGMENTS`] segments. + TooComplex, +} + +/// The two outlines are the same, so every line touching one touches the other. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Coincide; + +/// A convex closed outline that [`common_tangents`] takes. +#[derive(Clone, Debug)] +pub enum Outline { + /// The unit circle under an affine map: the center is the map's translation, `m` its linear + /// part (`[a, b, c, d]`, as kurbo orders them). + Ellipse { center: Point, m: [f64; 4] }, + /// A convex closed path's segments, its center of area and the diagonal of its bounds. `ccw` + /// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then + /// comes later in the list as the angle of `n` grows. + Convex { segments: Vec, center: Point, size: f64, ccw: bool }, +} + +impl Outline { + /// The ellipse that `unit` maps the unit circle onto. + pub fn ellipse(unit: Affine) -> Result { + let [a, b, c, d, e, f] = unit.as_coeffs(); + let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm { + return Err(OutlineError::Empty); + } + Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) + } + + /// A closed subpath that bends one way all around and winds around once. + pub fn convex(sp: &SubPath) -> Result { + if !sp.closed { + return Err(OutlineError::Open); + } + let n = sp.segment_count(); + if n > MAX_TANGENT_SEGMENTS { + return Err(OutlineError::TooComplex); + } + let segments: Vec = (0..n).map(|k| sp.segment(k)).collect(); + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if segments.iter().any(|s| ![s.p0, s.p1, s.p2, s.p3].into_iter().all(finite)) { + return Err(OutlineError::Empty); + } + let mut pts: Vec = Vec::with_capacity(n * FLATTEN); + for s in &segments { + pts.extend((0..FLATTEN).map(|k| s.eval(k as f64 / FLATTEN as f64))); + } + let (lo, hi) = pts.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| { + (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))) + }); + let size = (hi - lo).hypot(); + if !size.is_finite() || size <= 0.0 { + return Err(OutlineError::Empty); + } + // Points closer than this to the one before are dropped: a retracted handle or a segment + // of no length gives no direction. + pts.dedup_by(|b, a| (*b - *a).hypot() <= 1e-9 * size); + while pts.len() > 1 && pts.first().zip(pts.last()).is_some_and(|(f, l)| (*f - *l).hypot() <= 1e-9 * size) { + pts.pop(); + } + let m = pts.len(); + if m < 3 { + return Err(OutlineError::Empty); + } + // Area, center and turns are worked out on the points taken about the first one and + // divided by the size. + let origin = pts[0].to_vec2(); + let unit: Vec = pts.iter().map(|p| (p.to_vec2() - origin) / size).collect(); + let (mut area2, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..m { + let (p, q) = (unit[i], unit[(i + 1) % m]); + let cross = p.cross(q); + area2 += cross; + cx += (p.x + q.x) * cross; + cy += (p.y + q.y) * cross; + } + if area2.abs() <= 1e-12 { + return Err(OutlineError::Empty); + } + let sign = area2.signum(); + // Every turn the same way (straight runs allowed), and one turn in all. + let mut turning = 0.0; + for i in 0..m { + let (p, q, r) = (unit[(i + m - 1) % m], unit[i], unit[(i + 1) % m]); + let (u, v) = (q - p, r - q); + let cross = u.cross(v) * sign; + if cross < -1e-12 { + return Err(OutlineError::NotConvex); + } + turning += cross.atan2(u.dot(v)); + } + if (turning - TAU).abs() > 1e-6 { + return Err(OutlineError::NotConvex); + } + // A short bend the other way can lie between two of the points: each segment is checked + // whole. + if segments.iter().any(|s| bends_against(s, sign)) { + return Err(OutlineError::NotConvex); + } + let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); + if !center.x.is_finite() || !center.y.is_finite() { + return Err(OutlineError::Empty); + } + Ok(Outline::Convex { segments, center, size, ccw: sign > 0.0 }) + } + + /// The outline moved by `d`. + fn shifted(&self, d: Vec2) -> Self { + match self { + Outline::Ellipse { center, m } => Outline::Ellipse { center: *center + d, m: *m }, + Outline::Convex { segments, center, size, ccw } => Outline::Convex { + segments: segments.iter().map(|s| CubicBez::new(s.p0 + d, s.p1 + d, s.p2 + d, s.p3 + d)).collect(), + center: *center + d, + size: *size, + ccw: *ccw, + }, + } + } + + /// Adds to `out` the normal angles where the point of largest `p · n` can pass from one + /// segment to the next: square to each segment's direction at its ends, on both sides. + fn breaks(&self, out: &mut Vec) { + let Outline::Convex { segments, .. } = self else { return }; + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot2() > 0.0); + for s in segments { + let ends = [nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]), nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])]; + for d in ends.into_iter().flatten() { + let a = d.y.atan2(d.x); + out.extend([a + TAU / 4.0, a - TAU / 4.0]); + } + } + } + + /// The support value at `n` and the segment it is reached on, from every segment. + fn support_scan(&self, n: Vec2) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, .. } => { + let mut best = (f64::MIN, 0); + for (i, s) in segments.iter().enumerate() { + each_extreme(s, n, |_, v| { + if v > best.0 { + best = (v, i); + } + }); + } + best + } + } + } + + /// The support value at `n` and the segment it is reached on, walking on from segment `from`, + /// where the support value was reached at a normal angle a little less than `n`'s. + fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, ccw, .. } => { + let len = segments.len(); + if len == 0 { + return (f64::MIN, 0); + } + let step = if *ccw { 1 } else { len - 1 }; + let value = |i: usize| { + let mut best = f64::MIN; + if let Some(s) = segments.get(i) { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + }; + let mut i = from % len; + let mut v = value(i); + for _ in 0..len { + let j = (i + step) % len; + let w = value(j); + if w < v { + break; + } + (i, v) = (j, w); + } + (v, i) + } + } + } + + /// The center: an ellipse's, or a path's center of area. + pub fn center(&self) -> Point { + match self { + Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center, + } + } + + /// The diagonal of the bounds (an ellipse's: of the box its axes span). + fn size(&self) -> f64 { + match self { + Outline::Ellipse { m, .. } => { + let [a, b, c, d] = *m; + 2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt() + } + Outline::Convex { size, .. } => *size, + } + } + + /// The support value: the largest `p · n` over the outline's points. + fn support(&self, n: Vec2) -> f64 { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => center.to_vec2().dot(n) + Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y).hypot(), + Outline::Convex { segments, .. } => { + let mut best = f64::MIN; + for s in segments { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + } + } + } + + /// The points of the outline on the line `p · n = h`, its support value: the point where + /// `p · n` is largest, and the ends of any straight side along the line. Another point counts + /// when it lies within `tol` of the line plus `slope` times its distance from that largest + /// point, where `slope` is how far off the normal's angle may be. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => { + let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); + let w = w / w.hypot(); + vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] + } + Outline::Convex { segments, .. } => { + let mut all = vec![]; + for s in segments { + each_extreme(s, n, |p, v| all.push((p, v))); + } + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() + } + } + } +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. +/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product +/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared +/// with the segment's control polygon length squared. +fn bends_against(s: &CubicBez, sign: f64) -> bool { + let (a, b, c) = (s.p1 - s.p0, s.p2 - s.p1, s.p3 - s.p2); + let q = |t: f64| { + let u = 1.0 - t; + let d1 = a * (u * u) + b * (2.0 * u * t) + c * (t * t); + let d2 = (b - a) * u + (c - b) * t; + d1.cross(d2) * sign + }; + let (q0, half, q1) = (q(0.0), q(0.5), q(1.0)); + // q(t) = q0 + k1 t + k2 t². + let k2 = 2.0 * (q0 + q1 - 2.0 * half); + let k1 = q1 - q0 - k2; + let mut low = q0.min(q1); + if k2 > 0.0 { + let t = -k1 / (2.0 * k2); + if t > 0.0 && t < 1.0 { + low = low.min(q(t)); + } + } + let scale = (a.hypot() + b.hypot() + c.hypot()).powi(2); + low < -1e-9 * scale +} + +fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); + f(s.p0, v0); + f(s.p3, v3); + // The derivative of p(t) · n, divided by 3: a quadratic in t. + let (d0, d1, d2) = (v1 - v0, v2 - v1, v3 - v2); + let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); + let mut root = |t: f64| { + if t > 0.0 && t < 1.0 { + let p = s.eval(t); + f(p, p.to_vec2().dot(n)); + } + }; + let scale = qa.abs().max(qb.abs()).max(qc.abs()); + if !scale.is_finite() || scale <= 0.0 { + return; + } + if qa.abs() <= 1e-12 * scale { + if qb != 0.0 { + root(-qc / qb); + } + return; + } + let disc = qb * qb - 4.0 * qa * qc; + if disc < 0.0 { + return; + } + // The stable form of the two roots; with `qb` zero the sign is taken as positive, so `q` is + // not zero. + let sign = if qb < 0.0 { -1.0 } else { 1.0 }; + let q = -0.5 * (qb + sign * disc.sqrt()); + root(q / qa); + if q != 0.0 { + root(qc / q); + } +} + +/// The unit vector at `angle` radians. +fn dir(angle: f64) -> Vec2 { + Vec2::new(angle.cos(), angle.sin()) +} + +/// The common tangents of `a` and `b`: the external ones, then the internal ones, each in order of +/// the angle of its normal. Separate outlines have two of each; overlapping ones only external +/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the +/// other none; outlines that touch share one tangent where they touch. +pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincide> { + // Worked out about the point between the two centers. + let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0; + let (a, b) = (&a.shifted(-origin), &b.shifted(-origin)); + let size = a.size().max(b.size()).max((a.center() - b.center()).hypot()); + let tol = 1e-9 * size; + // The normal angles sampled: evenly spaced ones, and every angle where the support value of + // either outline passes to another segment. Between two neighboring samples each outline is + // then touched on one segment. + let mut at: Vec = (0..SAMPLES).map(|k| k as f64 * TAU / SAMPLES as f64).collect(); + a.breaks(&mut at); + b.breaks(&mut at); + let mut at: Vec = at.into_iter().map(|t| t.rem_euclid(TAU)).map(|t| if t < TAU { t } else { 0.0 }).collect(); + at.sort_by(f64::total_cmp); + at.dedup_by(|y, x| *y - *x <= 1e-12); + // The segment each outline is touched on at each sample, found by walking around once. + let hints = |o: &Outline, sign: f64| -> Vec { + let mut out = Vec::with_capacity(at.len()); + let mut i = at.first().map_or(0, |t| o.support_scan(dir(*t) * sign).1); + for t in &at { + i = o.support_from(dir(*t) * sign, i).1; + out.push(i); + } + out + }; + let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0)); + let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); + let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; + let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let mut out = Vec::with_capacity(external.len() + internal.len()); + for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { + for root in list { + let t = tangent_at(a, b, kind, dir(root.angle), root.double, size); + out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); + } + } + Ok(out) +} + +/// A zero of a support-value difference: the normal's angle, and whether the difference only +/// touches zero there (outlines that touch) rather than crossing it. +#[derive(Clone, Copy, Debug)] +struct Root { + angle: f64, + double: bool, +} + +/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value, +/// and `b` on the same side (external) or the other side (internal). `double` when the outlines +/// touch there. +fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent { + // The rounding allowed in `p · n` grows with each outline's own size and its distance from the + // origin. + let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); + let (tol_a, tol_b) = (rounding(a), rounding(b)); + // Bisection finds a simple root's angle to about the rounding of the support values; the + // golden-section search finds a double root's to about 1e-8 radians. + let slope = if double { 1e-7 } else { 1e-10 }; + let ha = a.support(n); + let (on_a, on_b) = match kind { + TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)), + TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)), + }; + // Positions along the line, which runs square to `n` through `n * ha`. + let t = Vec2::new(-n.y, n.x); + let along = |p: &Point| p.to_vec2().dot(t); + let mean = |v: &[Point]| v.iter().map(along).sum::() / v.len().max(1) as f64; + let all = on_a.iter().chain(&on_b).map(along); + let (lo, hi) = all.fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(s), hi.max(s))); + let at = |s: f64| (n * ha + t * s).to_point(); + // A double root's angle is found less exactly than a simple one's, so touching points may + // stand a little apart. + let (from, to) = if double && hi - lo <= 1e-6 * size { + // Touching at one point: the narrower outline's width along the line, centered there. + let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min); + let mid = (lo + hi) / 2.0; + (mid - width / 2.0, mid + width / 2.0) + } else if mean(&on_a) <= mean(&on_b) { + (lo, hi) + } else { + (hi, lo) + }; + Tangent { kind, from: at(from), to: at(to) } +} + +/// The angles in `[0, 2π)` where `f` (periodic) is zero, within `tol`. An interval where it stays +/// zero (outlines that meet at a corner or along a shared stretch) gives the angle at its middle, +/// as a double root. +/// +/// `at` holds the sampled angles in increasing order, in `[0, 2π)`; `f(t, k)` is `f` at an angle +/// `t` at or after sample `k` and before the sample two on. +fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result, Coincide> { + let n = at.len(); + if n < 3 { + return Err(Coincide); + } + // The angle of sample `k + j`, counted on from sample `k` past 2π. + let ang = |k: usize, j: usize| at.get((k + j) % n).copied().unwrap_or(0.0) + TAU * ((k + j) / n) as f64; + let v: Vec = (0..n).map(|k| f(ang(k, 0), k)).collect(); + let val = |k: usize| v.get(k % n).copied().unwrap_or(0.0); + let zero = |x: f64| x.abs() <= tol; + let Some(start) = v.iter().position(|x| !zero(*x)) else { return Err(Coincide) }; + let simple = |angle: f64| Root { angle, double: false }; + let mut out = vec![]; + // Between `lo` (sample `k`) and `hi`, where `s * f` is positive at both ends: the least of + // `s * f`, a double root where it reaches zero, two roots where it goes past it, none where it + // stays above. + let dip = |out: &mut Vec, s: f64, k: usize, lo: f64, hi: f64| { + let g = |t: f64| f(t, k); + let (t, least) = golden(&|t| s * g(t), lo, hi); + if least < -tol { + out.push(simple(bisect(&g, lo, t))); + out.push(simple(bisect(&g, t, hi))); + } else if least <= tol { + out.push(Root { angle: t, double: true }); + } + }; + for i in 0..n { + let k = (start + i) % n; + let (prev, next) = ((k + n - 1) % n, k + 1); + let theta = ang(k, 0); + if zero(val(k)) { + continue; + } + if zero(val(next)) { + let len = (1..n).take_while(|j| zero(val(k + j))).count(); + if len == 1 { + // One sample on zero: a crossing when the samples beside it differ in sign, else a + // dip between them. + let (lo, hi) = (theta, ang(k, 2)); + let s = val(k).signum(); + if val(k + 2).signum() == s { + dip(&mut out, s, k, lo, hi); + } else { + out.push(simple(bisect(&|t| f(t, k), lo, hi))); + } + } else { + out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true }); + } + continue; + } + if val(k).signum() != val(next).signum() { + out.push(simple(bisect(&|t| f(t, k), theta, ang(k, 1)))); + continue; + } + // A sampled minimum of |f|: the curve may dip to zero (a double root), or across it and + // back (two roots), between the neighboring samples. + let (vp, vk, vn) = (val(prev), val(k), val(next)); + if !zero(vp) && vp.signum() == vk.signum() && vk.abs() < vp.abs() && vk.abs() <= vn.abs() { + let lo = if k == 0 { ang(prev, 0) - TAU } else { ang(prev, 0) }; + dip(&mut out, vk.signum(), prev, lo, ang(k, 1)); + } + } + let mut out: Vec = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect(); + out.sort_by(|a, b| a.angle.total_cmp(&b.angle)); + out.dedup_by(|b, a| { + let same = (b.angle - a.angle).abs() < 1e-7; + a.double |= same && b.double; + same + }); + if out.len() > 1 + && out.first().zip(out.last()).is_some_and(|(f, l)| f.angle + TAU - l.angle < 1e-7) + && let Some(last) = out.pop() + && let Some(first) = out.first_mut() + { + first.double |= last.double; + } + Ok(out) +} + +/// A root of `f` between `lo` and `hi`, where it has opposite signs. +fn bisect(f: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> f64 { + let s = f(lo).signum(); + for _ in 0..STEPS { + let mid = (lo + hi) / 2.0; + if f(mid).signum() == s { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 +} + +/// Where `g` is least between `lo` and `hi` (taken as having one minimum there), and its value. +fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { + let r = (5f64.sqrt() - 1.0) / 2.0; + let (mut x1, mut x2) = (hi - r * (hi - lo), lo + r * (hi - lo)); + let (mut g1, mut g2) = (g(x1), g(x2)); + for _ in 0..STEPS { + if g1 < g2 { + hi = x2; + (x2, g2) = (x1, g1); + x1 = hi - r * (hi - lo); + g1 = g(x1); + } else { + lo = x1; + (x1, g1) = (x2, g2); + x2 = lo + r * (hi - lo); + g2 = g(x2); + } + } + let t = (lo + hi) / 2.0; + (t, g(t)) +} + +#[cfg(test)] +mod tests { + use kurbo::Rect; + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(cx: f64, cy: f64, r: f64) -> Outline { + Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() + } + + /// An ellipse with semi-axes `rx`, `ry`, turned `deg` degrees, centered at (`cx`, `cy`). + fn ellipse_map(cx: f64, cy: f64, rx: f64, ry: f64, deg: f64) -> Affine { + Affine::translate((cx, cy)) * Affine::rotate(deg.to_radians()) * Affine::scale_non_uniform(rx, ry) + } + + /// Whether `t` has its two ends at `p` and `q`, in either order. + fn ends_at(t: &Tangent, p: Point, q: Point) -> bool { + ends_within(t, p, q, 1e-7) + } + + /// [`ends_at`] within `eps`: the angle of a tangent where outlines touch (a double root) is + /// found to about 1e-8 radians. + fn ends_within(t: &Tangent, p: Point, q: Point, eps: f64) -> bool { + let near = |a: Point, b: Point| (a - b).hypot() < eps; + (near(t.from, p) && near(t.to, q)) || (near(t.from, q) && near(t.to, p)) + } + + /// Checks `t` against dense samples of the two outlines, without support values: each lies on + /// one side of the line (the same side for an external tangent, opposite ones for an internal + /// one) and comes within `eps` of it. + fn check_against_samples(t: &Tangent, a: &[Point], b: &[Point], eps: f64) { + let d = t.to - t.from; + let n = Vec2::new(-d.y, d.x) / d.hypot(); + let side = |pts: &[Point]| { + let dist: Vec = pts.iter().map(|p| (*p - t.from).dot(n)).collect(); + let (lo, hi) = dist.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s))); + assert!(lo > -eps || hi < eps, "the line crosses the outline: {lo} .. {hi} ({t:?})"); + assert!(lo.abs() < eps || hi.abs() < eps, "the line misses the outline: {lo} .. {hi} ({t:?})"); + if hi < eps { -1.0 } else { 1.0 } + }; + let (sa, sb) = (side(a), side(b)); + match t.kind { + TangentKind::External => assert_eq!(sa, sb, "{t:?}"), + TangentKind::Internal => assert_ne!(sa, sb, "{t:?}"), + } + } + + fn sample_ellipse(m: Affine, count: usize) -> Vec { + (0..count).map(|k| m * Point::new((TAU * k as f64 / count as f64).cos(), (TAU * k as f64 / count as f64).sin())).collect() + } + + fn sample_path(sp: &SubPath, per_segment: usize) -> Vec { + (0..sp.segment_count()).flat_map(|k| (0..per_segment).map(move |j| sp.segment(k).eval(j as f64 / per_segment as f64))).collect() + } + + #[test] + fn two_circles_have_four_tangents_at_the_closed_form_points() { + let (c1, r1, c2, r2) = (Point::new(0.0, 0.0), 10.0, Point::new(100.0, 0.0), 20.0); + let all = common_tangents(&circle(c1.x, c1.y, r1), &circle(c2.x, c2.y, r2)).unwrap(); + assert_eq!(all.len(), 4, "{all:?}"); + // External: (c1 - c2) · n = r2 - r1, so n.x = -0.1; the points are c + r n on each. + // Internal: (c1 - c2) · n = -(r1 + r2), so n.x = 0.3; c1 + r1 n and c2 - r2 n. + for (kind, nx) in [(TangentKind::External, -0.1f64), (TangentKind::Internal, 0.3)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if kind == TangentKind::External { c2 + n * r2 } else { c2 - n * r2 }; + let found = all.iter().filter(|t| t.kind == kind && ends_at(t, c1 + n * r1, far)).count(); + assert_eq!(found, 1, "{kind:?} {n:?} in {all:?}"); + } + } + // Each runs from the first outline to the second. + assert!(all.iter().all(|t| (t.from - c1).hypot() < (t.to - c1).hypot())); + } + + #[test] + fn turned_ellipses_match_an_independent_numeric_solution() { + let (ma, mb) = (ellipse_map(0.0, 0.0, 40.0, 15.0, 30.0), ellipse_map(150.0, 60.0, 25.0, 60.0, -70.0)); + let all = common_tangents(&Outline::ellipse(ma).unwrap(), &Outline::ellipse(mb).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(ma, 5_000), sample_ellipse(mb, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // A brute-force scan of the normal's angle with support values read off the samples finds + // the same normals. + let support = |pts: &[Point], n: Vec2| pts.iter().map(|p| p.to_vec2().dot(n)).fold(f64::MIN, f64::max); + let scan = |f: &dyn Fn(Vec2) -> f64| { + let steps = 7_200; + let g = |k: usize| f(dir(TAU * k as f64 / steps as f64)); + (0..steps).filter(|&k| g(k).signum() != g((k + 1) % steps).signum()).map(|k| TAU * (k as f64 + 0.5) / steps as f64).collect::>() + }; + let ext = scan(&|n| support(&sa, n) - support(&sb, n)); + let int = scan(&|n| support(&sa, n) + support(&sb, -n)); + for (kind, expected) in [(TangentKind::External, ext), (TangentKind::Internal, int)] { + assert_eq!(expected.len(), 2); + for angle in expected { + let n = dir(angle); + let hit = all.iter().filter(|t| t.kind == kind).any(|t| { + let d = t.to - t.from; + let m = Vec2::new(d.y, -d.x) / d.hypot(); + m.dot(n).abs() > 1.0 - 1e-6 + }); + assert!(hit, "{kind:?} normal at {angle} in {all:?}"); + } + } + } + + #[test] + fn nested_overlapping_and_touching_circles() { + // One inside the other: none. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(5.0, 0.0, 10.0)).unwrap().is_empty()); + // Overlapping: the two external ones only. + let over = common_tangents(&circle(0.0, 0.0, 30.0), &circle(40.0, 0.0, 30.0)).unwrap(); + assert_eq!(over.len(), 2); + assert!(over.iter().all(|t| t.kind == TangentKind::External)); + assert!(over.iter().any(|t| ends_at(t, Point::new(0.0, 30.0), Point::new(40.0, 30.0)))); + // Touching from outside at (10, 0): two external ones and one shared internal one, square to + // the line of centers, as long as the smaller circle is wide. + let touch = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0, 0.0, 20.0)).unwrap(); + assert_eq!(touch.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{touch:?}"); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(ends_within(shared[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{shared:?}"); + // Touching along a direction between two sampled normals: the sampled minimum is refined + // down to the double root. + let along = dir(0.1234); + let off = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0 * along.x, 30.0 * along.y, 20.0)).unwrap(); + assert_eq!(off.iter().filter(|t| t.kind == TangentKind::Internal).count(), 1, "{off:?}"); + // A hair apart: two internal tangents less than a sample apart, both kept. + let d = 30.000_01; + let near_miss = common_tangents(&circle(0.0, 0.0, 10.0), &circle(d * along.x, d * along.y, 20.0)).unwrap(); + assert_eq!(near_miss.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{near_miss:?}"); + // Inside with a clearance of 1e-6: no tangent. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0 - 1e-6, 0.0, 10.0)).unwrap().is_empty()); + // Equal circles a hair apart: the two external tangents run between their real contact + // points, that hair apart, not as a touching tangent. + let hair = common_tangents(&circle(0.0, 0.0, 30.0), &circle(1e-5, 0.0, 30.0)).unwrap(); + assert_eq!(hair.len(), 2, "{hair:?}"); + assert!(hair.iter().all(|t| ((t.to - t.from).hypot() - 1e-5).abs() < 1e-9), "{hair:?}"); + // Touching from inside at (50, 0): the one shared external tangent. + let inside = common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0, 0.0, 10.0)).unwrap(); + assert_eq!(inside.len(), 1, "{inside:?}"); + assert!(ends_within(&inside[0], Point::new(50.0, -10.0), Point::new(50.0, 10.0), 1e-5), "{inside:?}"); + } + + #[test] + fn a_convex_bezier_blob_and_an_ellipse_path() { + // A lopsided convex blob of four curves. + let a = |x: f64, y: f64, ix: f64, iy: f64, ox: f64, oy: f64| { + vectorcraft_geom::Anchor::with_handles(Point::new(x, y), Point::new(ix, iy), Point::new(ox, oy)) + }; + let blob = SubPath::new( + vec![ + a(0.0, 40.0, 0.0, 70.0, 0.0, 10.0), + a(50.0, 0.0, 20.0, 0.0, 90.0, 0.0), + a(110.0, 50.0, 110.0, 20.0, 110.0, 90.0), + a(40.0, 100.0, 80.0, 100.0, 10.0, 100.0), + ], + true, + ); + let round = shapes::ellipse(Rect::new(200.0, 150.0, 260.0, 230.0)).subpaths[0].clone(); + let (oa, ob) = (Outline::convex(&blob).unwrap(), Outline::convex(&round).unwrap()); + let all = common_tangents(&oa, &ob).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_path(&blob, 4000), sample_path(&round, 4000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // The path's center is its center of area: the ellipse path's is its box's center. + assert!((ob.center() - Point::new(230.0, 190.0)).hypot() < 1e-6, "{:?}", ob.center()); + } + + #[test] + fn flat_sides_give_the_whole_stretch_they_touch() { + let square = + |x: f64| SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)], true); + let all = common_tangents(&Outline::convex(&square(0.0)).unwrap(), &Outline::convex(&square(30.0)).unwrap()).unwrap(); + let ext: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{all:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 0.0), Point::new(40.0, 0.0))), "{ext:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 10.0), Point::new(40.0, 10.0))), "{ext:?}"); + // Far apart, each diamond is still touched only at its top corner. + let diamond = + |x: f64| SubPath::polyline(&[Point::new(x - 5.0, 0.0), Point::new(x, -5.0), Point::new(x + 5.0, 0.0), Point::new(x, 5.0)], true); + let far = common_tangents(&Outline::convex(&diamond(0.0)).unwrap(), &Outline::convex(&diamond(1e9)).unwrap()).unwrap(); + let top = far.iter().find(|t| t.kind == TangentKind::External && t.from.y > 0.0).unwrap(); + assert!(ends_within(top, Point::new(0.0, 5.0), Point::new(1e9, 5.0), 1e-3), "{far:?}"); + // Far from the origin the center of area and the tangents come out as near it. + let o = 1e9; + let away = |x: f64| SubPath::polyline(&[(x, o), (x + 10.0, o), (x + 10.0, o + 10.0), (x, o + 10.0)].map(Point::from), true); + let (sa, sb) = (Outline::convex(&away(o)).unwrap(), Outline::convex(&away(o + 30.0)).unwrap()); + assert!((sa.center() - Point::new(o + 5.0, o + 5.0)).hypot() < 1e-6, "{:?}", sa.center()); + let shifted = common_tangents(&sa, &sb).unwrap(); + assert!(shifted.iter().any(|t| ends_within(t, Point::new(o, o), Point::new(o + 40.0, o), 1e-6)), "{shifted:?}"); + // The internal ones are the diagonals between the near corners. + let int: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(int.len(), 2, "{all:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 0.0), Point::new(30.0, 10.0))), "{int:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 10.0), Point::new(30.0, 0.0))), "{int:?}"); + // Squares meeting at the corner (10, 10): every line through the corner between their + // sides touches both, and the one internal line drawn is the one at the middle of those + // directions, as long as a square is wide along it. + let box_at = |x: f64, y: f64| { + SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y), Point::new(x + 10.0, y + 10.0), Point::new(x, y + 10.0)], true) + }; + let corner = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(10.0, 10.0)).unwrap()).unwrap(); + let shared: Vec<_> = corner.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{corner:?}"); + assert!(ends_within(shared[0], Point::new(5.0, 15.0), Point::new(15.0, 5.0), 1e-6), "{shared:?}"); + // Sides 1e-6 off parallel: each line ends at the corners it touches, not at the corners + // of the sides it nearly lies along. + let tilted = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(30.0, -1e-6)).unwrap()).unwrap(); + let ext: Vec<_> = tilted.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{tilted:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(10.0, 10.0), Point::new(40.0, 10.0 - 1e-6), 1e-6)), "{ext:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(0.0, 0.0), Point::new(30.0, -1e-6), 1e-6)), "{ext:?}"); + } + + /// A circle path of four curves, radius 100 about the origin, with an anchor at (100, 0). + fn circle_path() -> SubPath { + shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).subpaths[0].clone() + } + + /// The point of `sp` where `p · n` is largest. + fn peak(sp: &SubPath, n: Vec2) -> Point { + let mut best = (Point::ORIGIN, f64::MIN); + for k in 0..sp.segment_count() { + each_extreme(&sp.segment(k), n, |p, v| { + if v > best.1 { + best = (p, v); + } + }); + } + best.0 + } + + #[test] + fn a_curve_is_touched_only_at_its_peak_beside_an_anchor() { + // The line touches the circle path 5e-4 radians from its anchor at (100, 0), where the + // anchor lies about 1.25e-5 inside the line: the line still ends at the peak, not at the + // anchor 0.05 along it. + let path = circle_path(); + let n = dir(5e-4); + let away = Vec2::new(n.y, -n.x) * 300.0; + let a = Outline::convex(&path).unwrap(); + let all = common_tangents(&a, &a.shifted(away)).unwrap(); + let top = all.iter().find(|t| t.kind == TangentKind::External && (t.from.to_vec2().dot(n) - 100.0).abs() < 1e-3).unwrap(); + let p = peak(&path, n); + assert!(ends_within(top, p, p + away, 1e-6), "{top:?} {p:?}"); + // An exact circle touching the path there from outside: one shared internal line, as long + // as that circle is wide, not a stub running to the anchor. + let b = circle(p.x + 20.0 * n.x, p.y + 20.0 * n.y, 20.0); + let touch = common_tangents(&a, &b).unwrap(); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(((shared[0].to - shared[0].from).hypot() - 40.0).abs() < 1e-3, "{shared:?}"); + assert!(((shared[0].from.midpoint(shared[0].to)) - p).hypot() < 1e-3, "{shared:?}"); + } + + #[test] + fn outlines_crossing_more_often_than_the_even_samples_keep_every_tangent() { + // Two regular 400-gons about one center, one turned half a step: their outlines cross 800 + // times, and an external tangent runs across each crossing. + let gon = |turn: f64| { + let pts: Vec = (0..400).map(|k| (dir(turn + TAU * k as f64 / 400.0) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let all = common_tangents(&Outline::convex(&gon(0.0)).unwrap(), &Outline::convex(&gon(TAU / 800.0)).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 800); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 0); + // Each runs between a corner of one and the next corner of the other, about 0.785 apart. + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { + // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is + // zero, and the peak, 0.25 at t = 0.5, lies inside the segment. + let s = CubicBez::new((0.0, 0.0), (1.0, 0.25), (2.0, 0.5), (3.0, -0.25)); + let mut best = f64::MIN; + each_extreme(&s, Vec2::new(0.0, 1.0), |_, v| best = best.max(v)); + assert!((best - 0.25).abs() < 1e-12, "{best}"); + } + + #[test] + fn open_concave_empty_and_identical_outlines_are_refused() { + let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); + assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open)); + let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone(); + assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex)); + // A half disk whose straight side is a cubic with crossed handles: it bends the other way + // for a short stretch between two of the points the outline is checked at. + let mut bp = vectorcraft_geom::BezPath::new(); + let k = 0.5523 * 50.0; + bp.move_to((0.0, 0.0)); + bp.curve_to((62.4, 43.4), (60.3, 44.2), (100.0, 0.0)); + bp.curve_to((100.0, -k), (50.0 + k, -50.0), (50.0, -50.0)); + bp.curve_to((50.0 - k, -50.0), (0.0, -k), (0.0, 0.0)); + bp.close_path(); + let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); + // A square traced twice around winds around twice. + let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); + let flat = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(20.0, 0.0)], true); + assert_eq!(Outline::convex(&flat).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::scale_non_uniform(10.0, 0.0)).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + let many: Vec = (0..=MAX_TANGENT_SEGMENTS).map(|k| dir(TAU * k as f64 / (MAX_TANGENT_SEGMENTS + 1) as f64).to_point()).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&many, true)).err(), Some(OutlineError::TooComplex)); + // A square 1e110 wide has a finite center. + let huge = SubPath::polyline(&[(0.0, 0.0), (1e110, 0.0), (1e110, 1e110), (0.0, 1e110)].map(Point::from), true); + let center = Outline::convex(&huge).unwrap().center(); + assert!((center - Point::new(5e109, 5e109)).hypot() < 1e98, "{center:?}"); + assert_eq!(common_tangents(&circle(1.0, 2.0, 3.0), &circle(1.0, 2.0, 3.0)), Err(Coincide)); + } +} diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 1dec0423e4..c1fa1a2a5f 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -1,14 +1,15 @@ //! PSD export: a layered bitmap at 8 bits per channel, written from the format's public -//! specification. The file holds the header, the resolution and colour profile resources, the -//! layer records and their channels (PackBits row by row; groups as section dividers), then the +//! specification. The file holds the header, the resolution, colour profile and slices resources, +//! the layer records and their channels (PackBits row by row; groups as section dividers), then the //! merged image, which readers that skip layers show. RGB, CMYK (stored as 255 − ink, as the //! format keeps inks) or grayscale. +use std::collections::HashMap; use std::sync::Arc; use vectorcraft_color::{BlendMode, cms}; use vectorcraft_doc::text::TypeAntiAlias; -use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind}; +use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource}; use vectorcraft_geom::{Point, Rect}; use super::jpeg::{self, ColorModel}; @@ -302,6 +303,8 @@ struct File { records: Vec, ppi: f64, icc: Option>, + /// Image resource 1050's data, when the file has slices. + slices: Option>, } /// Refuse a size the format can't store. @@ -332,7 +335,8 @@ impl File { out.extend(mode(self.model).to_be_bytes()); // No colour mode data. out.extend(0u32.to_be_bytes()); - // Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the profile. + // Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the + // profile, the slices. let ppi = if self.ppi.is_finite() && self.ppi > 0.0 { self.ppi } else { 72.0 }; let fixed = (ppi.min(30_000.0) * 65536.0).round() as u32; let res = [fixed.to_be_bytes(), [0, 1, 0, 1], fixed.to_be_bytes(), [0, 1, 0, 1]].concat(); @@ -341,6 +345,9 @@ impl File { if let Some(icc) = &self.icc { resource(&mut resources, 1039, icc)?; } + if let Some(slices) = &self.slices { + resource(&mut resources, SLICES, slices)?; + } out.extend(len32(resources.len())?.to_be_bytes()); out.extend(resources); self.write_layers(&mut out)?; @@ -390,17 +397,20 @@ fn icc(o: &PsdOptions) -> Result>, String> { pub fn encode(img: &Rendered, ppi: f64, o: &PsdOptions) -> Result, String> { let inks = (o.color_model == ColorModel::Cmyk).then(|| jpeg::separated(img)); let merged = planes(o.color_model, &img.to_straight(), inks.as_deref(), true, false); - File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)? }.write() + File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)?, slices: None } + .write() } /// `region` of `doc` as a PSD with `opts` (see [`PsdOptions`]). The merged image is the export's /// render; with Write Layers each part is also drawn alone as its own layer, cropped to what it -/// paints, its opacity and blend mode in the layer's record. +/// paints, its opacity and blend mode in the layer's record. The user and object slices that reach +/// into `region` are written with or without layers ([`slices`]). pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &RasterExportOptions) -> Result, String> { let o = &opts.psd; let scale = opts.scale(); let (width, height) = crate::region_pixels(region, scale); check_size(width, height)?; + let slices = slices(doc, region, scale, (width, height))?; let ro = opts.render_options(RasterFormat::Psd); let (mut merged, mut alpha) = { let px = r.render_region_with(doc, region, scale, &ro).to_straight(); @@ -426,7 +436,156 @@ pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &Rast merged.pop(); alpha = false; } - File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)? }.write() + File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)?, slices }.write() +} + +/// The image resource that holds the slices. +const SLICES: u16 = 1050; + +/// The most slices one file holds (as many as `document.open` reads). +pub(crate) const MAX_SLICES: usize = 10_000; + +/// The longest text of a slice, in UTF-16 units (as long as `document.open` reads). +pub(crate) const MAX_SLICE_TEXT: usize = 65_536; + +/// Resource 1050's data for the user and object slices of `doc` that reach into `region`, in the +/// "Slices resource format" of the Photoshop File Formats Specification +/// (), version 6: the bounds of all +/// the slices, the group's name, the count, then one record per slice. `None` when no slice +/// reaches into `region`. Each rectangle is the slice as laid out ([`Document::slice_layout`]), +/// clipped to `region` and given in the `size` canvas's pixels at `scale`, at least one pixel +/// each way. Every slice is written as one the user made (origin 2): an object slice keeps its +/// rectangle and options. Auto slices aren't written; a reader lays them out again. An HTML Text +/// slice is written as No Image with its type's text as HTML. Text alignment is written as the +/// default. An error when a slice's bounds aren't finite, or there are more than [`MAX_SLICES`] +/// slices, a text longer than [`MAX_SLICE_TEXT`], or more than 4 GB of slices ([`room`]). +fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Result>, String> { + let users: HashMap = doc.slices.iter().map(|s| (s.id, &s.options)).collect(); + let mut found = vec![]; + for area in doc.slice_layout().iter().filter(|a| a.source != SliceSource::Auto) { + let Some(id) = area.id else { continue }; + let r = area.rect; + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + let number = area.number; + return Err(format!("slice {number} has no finite bounds and can't be written to PSD")); + } + let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue }; + // The part inside `region`, found before the region is rounded to whole pixels. + let (x0, y0, x1, y1) = (r.x0.max(region.x0), r.y0.max(region.y0), r.x1.min(region.x1), r.y1.min(region.y1)); + if !(x0 < x1 && y0 < y1) { + continue; + } + let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max)); + let (l, t, r, b) = (edge(x0, region.x0, w), edge(y0, region.y0, h), edge(x1, region.x0, w), edge(y1, region.y0, h)); + // Whole pixels, at least one each way. + let span = |a: f64, b: f64, max: u32| { + let max = i64::from(max); + let (mut a, mut b) = ((a.round() as i64).clamp(0, max), (b.round() as i64).clamp(0, max)); + if b <= a { + a = a.min(max - 1); + b = a + 1; + } + (a as i32, b as i32) + }; + let ((l, r), (t, b)) = (span(l, r, w), span(t, b, h)); + let text = match options.kind { + SliceKind::HtmlText => doc.node(id).map(html_text).unwrap_or_default(), + _ => options.text.clone(), + }; + found.push(([l, t, r, b], options, text)); + } + if found.is_empty() { + return Ok(None); + } + if found.len() > MAX_SLICES { + let count = found.len(); + return Err(format!("the document has {count} slices, more than the {MAX_SLICES} a PSD file holds")); + } + let (mut top, mut left, mut bottom, mut right) = (i32::MAX, i32::MAX, 0, 0); + for ([l, t, r, b], _, _) in &found { + (left, top, right, bottom) = (left.min(*l), top.min(*t), right.max(*r), bottom.max(*b)); + } + let mut out = 6u32.to_be_bytes().to_vec(); + for v in [top, left, bottom, right] { + out.extend(v.to_be_bytes()); + } + let stem = doc.title.rsplit_once('.').map_or(doc.title.as_str(), |(s, _)| s); + unicode(&mut out, stem)?; + out.extend((found.len() as u32).to_be_bytes()); + // IDs from 1. + for ((rect, o, text), id) in found.into_iter().zip(1u32..) { + out.extend(id.to_be_bytes()); + // Group 0; made by the user. + out.extend(0u32.to_be_bytes()); + out.extend(2u32.to_be_bytes()); + unicode(&mut out, &o.name)?; + out.extend(u32::from(o.kind == SliceKind::Image).to_be_bytes()); + for v in rect { + out.extend(v.to_be_bytes()); + } + for s in [&o.url, &o.target, &o.message, &o.alt] { + unicode(&mut out, s)?; + } + // The cell text is HTML, as a No Image slice shows it. + out.push(1); + unicode(&mut out, &text)?; + // The default horizontal and vertical alignment. + out.extend([0; 8]); + out.extend(background(o)); + } + Ok(Some(out)) +} + +/// A slice's background as alpha, red, green and blue: none (all 0), the matte (alpha 0 over a +/// colour) or an opaque `#rrggbb`. +fn background(o: &SliceOptions) -> [u8; 4] { + let bg = o.background.trim(); + if bg.eq_ignore_ascii_case("matte") { + return [0, 255, 255, 255]; + } + let hex = bg.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit())); + match hex.and_then(|h| u32::from_str_radix(h, 16).ok()) { + Some(c) => { + let [_, r, g, b] = c.to_be_bytes(); + [255, r, g, b] + } + None => [0; 4], + } +} + +/// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a +/// line break as `
` (CR LF is one break). Empty for anything but type. +fn html_text(n: &Node) -> String { + let NodeKind::Text(t) = &n.kind else { return String::new() }; + t.plain_text() + .replace("\r\n", "\n") + .split(['\n', '\r', '\u{2029}']) + .map(|l| l.replace('&', "&").replace('<', "<").replace('>', ">")) + .collect::>() + .join("
") +} + +/// `s` as a Unicode string: a count of UTF-16 units, then the units. An error past +/// [`MAX_SLICE_TEXT`] units, or when the string would take `out` past [`room`]. +fn unicode(out: &mut Vec, s: &str) -> Result<(), String> { + let units = s.encode_utf16().count(); + if units > MAX_SLICE_TEXT { + return Err(format!("a slice's text has more than the {MAX_SLICE_TEXT} characters a PSD file holds")); + } + room(out.len(), units)?; + out.extend((units as u32).to_be_bytes()); + out.extend(s.encode_utf16().flat_map(|u| u.to_be_bytes())); + Ok(()) +} + +/// An error when `units` UTF-16 units and their count, added to a slices resource of `len` bytes, +/// make it longer than the 4 GB a PSD resource holds. +pub(crate) fn room(len: usize, units: usize) -> Result<(), String> { + let end = units.checked_mul(2).and_then(|n| n.checked_add(4)).and_then(|n| n.checked_add(len)); + match end.map(u32::try_from) { + Some(Ok(_)) => Ok(()), + _ => Err("the slices are too large for PSD (at most 4 GB)".into()), + } } /// Draws the parts of a document as layer records, bottom first. diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index ae8836aa66..012921cb37 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -1,15 +1,16 @@ //! PSD export: the header, the layer records (names, bounds, opacity, blend modes, groups, -//! hidden layers), the merged image, the colour models, and a reader's view of the file. +//! hidden layers), the merged image, the colour models, the slices, and a reader's view of the +//! file. use std::sync::Arc; use vectorcraft_color::{BlendMode, Color}; -use vectorcraft_doc::{Document, LayerColor, Node}; +use vectorcraft_doc::{Document, LayerColor, Node, NodeId, Slice, SliceKind, SliceOptions}; use vectorcraft_geom::Rect; use vectorcraft_testkit::fixtures::DocBuilder; use super::jpeg::ColorModel; -use super::psd::{MAX_SIDE, PsdOptions}; +use super::psd::{MAX_SIDE, MAX_SLICE_TEXT, MAX_SLICES, PsdOptions, room}; use super::*; /// A 100 × 60 pt document: a red square on Layer 1, and on "Top" a half-opaque blue multiply @@ -735,3 +736,145 @@ fn long_unicode_name_is_cut_on_a_character_boundary() { let file = export(&b.build(), &opts(PsdOptions::default())); assert_eq!(parse(&file).records.last().unwrap().name, "a".repeat(254)); } + +/// `doc()` with a user slice over (20, 5)–(50, 15) and the red square made an object slice. +fn sliced() -> Document { + let mut d = doc(); + let red = d.layers[0].children().unwrap()[0].id; + let user = SliceOptions { + name: "banner".into(), + url: "https://example.com/".into(), + target: "_blank".into(), + message: "Go".into(), + alt: "Banner".into(), + background: "#123456".into(), + ..SliceOptions::default() + }; + let id = d.alloc_id(); + d.slices.push(Slice { id, rect: Rect::new(20.0, 5.0, 50.0, 15.0), options: user }); + let cell = SliceOptions { kind: SliceKind::NoImage, text: "Hi".into(), background: "matte".into(), ..SliceOptions::default() }; + d.node_mut(red).unwrap().extras_mut().slice = Some(Box::new(cell)); + d +} + +/// The slices resource of `file` as an independent reader reads it. +fn slices_of(file: &[u8]) -> Option { + let psd = craft_psd::PsdFile::from_bytes(file).expect("a PSD a reader takes"); + psd.resource(1050).map(|r| craft_psd::slices::SlicesResource::from_bytes(&r.data).expect("a slices resource a reader takes")) +} + +#[test] +fn slices_are_written_with_or_without_layers() { + let d = sliced(); + for layers in [true, false] { + let file = export(&d, &opts(PsdOptions { layers, ..PsdOptions::default() })); + let res = slices_of(&file).expect("the slices resource"); + assert_eq!((res.version, res.bounds, res.group_name.as_str()), (6, [5, 10, 40, 50], "Untitled-1")); + let s = &res.slices; + assert_eq!(s.len(), 2, "{s:?}"); + // Laid out top to bottom: the user slice, then the object slice, both written as made by + // the user. + let user = &s[0]; + assert_eq!((user.id, user.origin, user.layer_id, user.kind, user.rect), (1, 2, None, 1, [20, 5, 50, 15])); + assert_eq!( + (user.name.as_str(), user.url.as_str(), user.target.as_str(), user.message.as_str(), user.alt.as_str()), + ("banner", "https://example.com/", "_blank", "Go", "Banner") + ); + assert_eq!(user.color, [255, 0x12, 0x34, 0x56]); + let cell = &s[1]; + assert_eq!((cell.id, cell.origin, cell.kind, cell.rect), (2, 2, 0, [10, 10, 40, 40])); + assert_eq!((cell.name.as_str(), cell.cell_text.as_str(), cell.cell_text_is_html), ("", "Hi", true)); + assert_eq!((cell.color[0], cell.color[1..].iter().any(|c| *c != 0)), (0, true), "the matte"); + assert_eq!((cell.horizontal_align, cell.vertical_align), (0, 0)); + } + // A document without slices has no slices resource. + assert!(slices_of(&export(&doc(), &opts(PsdOptions::default()))).is_none()); +} + +#[test] +fn slices_are_cut_to_the_exported_region_in_its_pixels() { + let doc = sliced(); + // The right part at 2 px a point: the user slice is cut at the region's left edge, and the red + // square's slice ends at that edge. + let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) }; + let file = Renderer::new().export_region(&doc, Rect::new(40.0, 0.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap(); + let res = slices_of(&file).unwrap(); + assert_eq!(res.slices.iter().map(|s| s.rect).collect::>(), [[0, 10, 20, 30]]); + assert_eq!(res.bounds, [10, 0, 30, 20]); + // A region no slice reaches has none. + let file = Renderer::new().export_region(&doc, Rect::new(60.0, 30.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap(); + assert!(slices_of(&file).is_none()); + // A slice thinner than a pixel keeps one pixel. + let mut thin = doc.clone(); + thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0); + let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap(); + assert_eq!(res.slices[0].rect, [20, 5, 21, 15]); + // The overlap is found before the region is rounded to whole pixels: a slice inside a region + // that ends at 10.4 keeps its last pixel, and one past a region that ends at 10.6 isn't written. + let o = opts(PsdOptions::default()); + let mut edge = doc.clone(); + edge.slices[0].rect = Rect::new(10.1, 5.0, 10.3, 15.0); + edge.node_mut(edge.layers[0].children().unwrap()[0].id).unwrap().extras_mut().slice = None; + let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.4, 60.0), RasterFormat::Psd, &o).unwrap(); + assert_eq!(slices_of(&file).unwrap().slices.iter().map(|s| s.rect).collect::>(), [[9, 5, 10, 15]]); + edge.slices[0].rect = Rect::new(10.7, 5.0, 10.9, 15.0); + let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.6, 60.0), RasterFormat::Psd, &o).unwrap(); + assert!(slices_of(&file).is_none()); +} + +#[test] +fn an_html_text_slice_writes_one_break_for_each_line_ending() { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + use vectorcraft_geom::Point; + let mut d = DocBuilder::new(100.0, 60.0).build(); + let t = TextObject::point(Point::new(10.0, 30.0), "A\r\nB\rC\nD\u{2029}E", CharStyle { size: 12.0, ..CharStyle::default() }); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.extras_mut().slice = Some(Box::new(SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() })); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let res = slices_of(&export(&d, &opts(PsdOptions::default()))).unwrap(); + assert_eq!(res.slices[0].cell_text, "A
B
C
D
E"); +} + +#[test] +fn slice_ids_count_from_1_and_the_limits_are_errors() { + let mut doc = doc(); + for i in 0..20 { + let id = doc.alloc_id(); + let x = f64::from(i) * 5.0; + doc.slices.push(Slice { id, rect: Rect::new(x, 0.0, x + 5.0, 5.0), options: SliceOptions::default() }); + } + let res = slices_of(&export(&doc, &opts(PsdOptions::default()))).unwrap(); + let ids: Vec = res.slices.iter().map(|s| s.id).collect(); + assert_eq!(ids, (1..=20).collect::>()); + let export_err = |d: &Document| { + Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::Psd, &opts(PsdOptions::default())).err().unwrap_or_default() + }; + let mut long = doc.clone(); + long.slices[0].options.alt = "a".repeat(MAX_SLICE_TEXT + 1); + let e = export_err(&long); + assert!(e.contains("characters"), "{e}"); + let mut many = doc.clone(); + many.slices = (0..=MAX_SLICES as u64) + .map(|i| Slice { id: NodeId(1_000_000 + i), rect: Rect::new(0.0, 0.0, 5.0, 5.0), options: SliceOptions::default() }) + .collect(); + let e = export_err(&many); + assert!(e.contains("slices"), "{e}"); + // Not clipped to the artboard, a slice keeps bounds that aren't finite. + let mut bad = doc; + bad.slices_clip_to_artboard = false; + bad.slices[0].rect = Rect::new(f64::NAN, 0.0, 5.0, 5.0); + let e = export_err(&bad); + assert!(e.contains("finite"), "{e}"); +} + +#[test] +fn slices_past_4_gb_are_an_error_before_they_are_written() { + let max = u32::MAX as usize; + assert_eq!(room(0, MAX_SLICE_TEXT), Ok(())); + assert_eq!(room(max - 4 - 2 * 10, 10), Ok(())); + let e = room(max - 4 - 2 * 10, 11).err().unwrap_or_default(); + assert!(e.contains("4 GB"), "{e}"); + assert!(room(max, 0).is_err()); + assert!(room(0, usize::MAX).is_err()); +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 0e7280ae9a..0946ad7a2d 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -209,9 +209,11 @@ pub struct ToolContext<'a> { /// [`Self::snap_tolerance`]. pub snap_to_point: bool, /// View → Snapping → Snap to Tangent: with Smart Guides on, a line drawn - /// from an anchor lands where it touches a nearby curve. + /// from an anchor lands where it touches a nearby curve, and a Line Segment + /// drag from one convex curved path to another lands on their common tangent. pub snap_tangent: bool, - /// View → Snapping → Snap to Perpendicular: likewise where it meets a nearby segment square. + /// View → Snapping → Snap to Perpendicular: with Smart Guides on, a line drawn from an anchor + /// lands where it meets a nearby segment square. pub snap_perpendicular: bool, /// View → Snap to Glyph: drawn points snap to live-text glyph bounds, and on a single line of type /// to its baseline, x-height, character widths and glyph anchor points (with Smart Guides). diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index d6620894ed..5a5c951548 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -713,6 +713,23 @@ fn part_picked(cx: &ToolContext, id: NodeId) -> bool { cx.selection.symbol_part.as_ref().is_some_and(|sp| sp.instance == id) } +/// Whether multiple anchor points are selected (across one or more paths) with Direct Selection. +fn has_multiple_selected_anchors(cx: &ToolContext) -> bool { + let direct_count: usize = cx.selection.anchors.values().map(|s| s.len()).sum(); + if direct_count >= 2 { + return true; + } + if direct_count >= 1 { + let has_whole_path = cx.selection.objects.iter().any(|id| { + !cx.selection.anchors.contains_key(id) && cx.doc.node(*id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().next().is_some()) + }); + if has_whole_path { + return true; + } + } + false +} + /// The segment of path `id` nearest to `p`, where the hit test found its stroke. fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option { let pd = cx.doc.node(id)?.path_data()?; @@ -769,6 +786,9 @@ impl Tool for DirectSelectionTool { if key == ToolKey::Escape && self.guide.busy() { return self.guide.cancel(); } + if key == ToolKey::Escape && matches!(self.state, State::Idle) && cx.selection.key_anchor.is_some() { + return vec![Action::Exec("select.key".into(), json!({}))]; + } if key != ToolKey::Escape || matches!(self.state, State::Idle) { return vec![]; } @@ -788,6 +808,7 @@ impl Tool for DirectSelectionTool { || self.claims_letter(key) || self.mesh_nudge(cx, key, Mods::default()).is_some() || self.frame_nudge(cx, key, Mods::default()).is_some() + || (key == ToolKey::Escape && (cx.selection.key_anchor.is_some() || !matches!(self.state, State::Idle))) } fn notify(&mut self, cx: &ToolContext, what: &str) { if what == FRAME_PICKED { @@ -1596,7 +1617,15 @@ impl DirectSelectionTool { (true, ..) => vec![Action::Commit], (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], (false, None, Some((id, si, ai)), _) => { - vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + if has_multiple_selected_anchors(cx) { + if cx.selection.key_anchor == Some((id, (si, ai))) { + vec![Action::Exec("select.key".into(), json!({}))] + } else { + vec![Action::Exec("select.key".into(), json!({"id": id.0, "anchor": [si, ai]}))] + } + } else { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } } (false, None, None, Some((id, si, seg))) => { vec![Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]]}))] diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 32229158af..1a7cb68a55 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -661,10 +661,9 @@ fn an_anchor_drag_follows_the_while_moving_option() { assert!((m - Vec2::new(5.7, 4.6)).hypot() < 1e-9, "{m:?}"); } -/// A click (no drag) on an anchor that is selected with others, whether the whole path is or -/// some of its anchors, selects that anchor alone, as in Illustrator: a press keeps the -/// selection so a drag moves it all, the release without a drag narrows it. Shift still -/// toggles, and a click on a path's only selected anchor changes nothing visible. +/// A click (no drag) on an anchor of a path selected whole selects that anchor alone, as in +/// Illustrator: a press keeps the selection so a drag moves it all, the release without a drag +/// narrows it. An anchor not yet selected is selected on the press. #[test] fn a_click_on_a_selected_anchor_selects_it_alone() { let (d, id) = doc_with_rect(); @@ -672,22 +671,65 @@ fn a_click_on_a_selected_anchor_selects_it_alone() { let alone = vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))]; let mut whole = Selection::default(); whole.set([id]); - for s in [whole, anchors_of(id, &[(0, 0), (0, 1)])] { - let cx = cx(&d, &s, &p); - let mut t = DirectSelectionTool::new(false); - assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty(), "{s:?}"); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), alone, "{s:?}"); - // Dragged instead: moved, selection kept. - assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); - t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 120.0, 100.0)), vec![Action::Commit], "{s:?}"); - } + let cx_whole = cx(&d, &whole, &p); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert_eq!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), alone); + // Dragged instead: moved, selection kept. + assert!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.pointer(&cx_whole, &PointerEvent::new(PointerKind::Up, 120.0, 100.0)), vec![Action::Commit]); + // An anchor not yet selected is selected on the press, and the release adds nothing. let none = Selection::default(); - let cx = cx(&d, &none, &p); + let cx_none = cx(&d, &none, &p); let mut t = DirectSelectionTool::new(false); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)), alone); - assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)).is_empty()); + assert_eq!(t.pointer(&cx_none, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)), alone); + assert!(t.pointer(&cx_none, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)).is_empty()); +} + +/// #1636: when multiple anchors are selected with Direct Selection, clicking an already-selected +/// anchor without modifiers designates it as the key anchor. Clicking it again, or pressing Escape, +/// clears the key anchor designation. +#[test] +fn clicking_selected_anchor_designates_and_clears_key_anchor() { + let (d, id) = doc_with_rect(); + let p = paint(); + let s = anchors_of(id, &[(0, 0), (0, 1)]); + let cx_base = cx(&d, &s, &p); + + // Clicking already-selected anchor (0, 0) designates it as Key Anchor. + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&cx_base, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert_eq!( + t.pointer(&cx_base, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.key".into(), json!({"id": id.0, "anchor": [0, 0]}))] + ); + + // Dragging instead moves anchors, committing the move. + assert!(t.pointer(&cx_base, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + t.pointer(&cx_base, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.pointer(&cx_base, &PointerEvent::new(PointerKind::Up, 120.0, 100.0)), vec![Action::Commit]); + + // When the anchor is already designated as the key anchor: + let mut with_key = s.clone(); + with_key.key_anchor = Some((id, (0, 0))); + let cx_key = cx(&d, &with_key, &p); + + // Clicking it again cancels the key anchor. + let mut t2 = DirectSelectionTool::new(false); + assert!(t2.pointer(&cx_key, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)).is_empty()); + assert_eq!(t2.pointer(&cx_key, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), vec![Action::Exec("select.key".into(), json!({}))]); + + // Pressing Escape cancels the key anchor. + let mut t3 = DirectSelectionTool::new(false); + assert!(t3.claims_key(&cx_key, ToolKey::Escape)); + assert_eq!(t3.key(&cx_key, ToolKey::Escape, Mods::default()), vec![Action::Exec("select.key".into(), json!({}))]); + + // Clicking canvas clears selection and key anchor. + let mut t4 = DirectSelectionTool::new(false); + assert!(t4.pointer(&cx_key, &PointerEvent::new(PointerKind::Down, 500.0, 500.0)).is_empty()); + assert_eq!(t4.pointer(&cx_key, &PointerEvent::new(PointerKind::Up, 500.0, 500.0)), vec![Action::Exec("select.none".into(), json!({}))]); } /// Alt-pressing an anchor picks the whole path, as Alt on a segment does, and the drag copies diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index 614df68917..e9f7bf7318 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -20,9 +20,11 @@ use vectorcraft_text::{FontDb, layout as layout_text}; use crate::bbox::Handle; use crate::{GlyphSnap, Overlay, ScreenFrame, ToolContext}; +mod bitangent; mod snap; mod targets; +pub(crate) use bitangent::TangentLine; pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, diff --git a/crates/tools/src/guides/bitangent.rs b/crates/tools/src/guides/bitangent.rs new file mode 100644 index 0000000000..9d4f9fa05c --- /dev/null +++ b/crates/tools/src/guides/bitangent.rs @@ -0,0 +1,271 @@ +//! Snap to Tangent for a line drawn from one curve to another (the Line Segment tool): when the +//! press lands on a convex closed path with curves and the pointer comes near another one, both +//! ends of the line move onto a common tangent of the two, the start sliding along the first path. +//! The tangents are [`vectorcraft_pathops::addons::pathtools::common_tangents`]'s. +//! +//! The closed subpaths in the window the line may end on are listed once, at the press, by their +//! bounds, up to as many segments as Smart Guides gather. Each pointer move looks only at the +//! [`MAX_NEAR`] nearest of them whose outline lies within the snapping tolerance of the pointer. +//! The tangents of each pair are worked out once, and the last [`MAX_KEPT`] pairs' are kept for +//! the rest of the drag. + +use std::collections::HashSet; + +use vectorcraft_pathops::addons::pathtools::{Outline, Tangent, common_tangents}; + +use super::snap::visible; +use super::targets::{BUDGET, walk_but}; +use super::{Node, NodeId, NodeKind, Overlay, ParamCurveNearest, Point, Rect, SubPath, ToolContext}; +use crate::PixelOp; + +/// Most subpaths a pointer move takes tangents from: the nearest ones whose outline lies within +/// the snapping tolerance of the pointer. +const MAX_NEAR: usize = 16; +/// Most pairs whose tangents are kept during one drag. +const MAX_KEPT: usize = 64; +/// Most segments a subpath the line starts or ends on may have: the tangents of two paths take +/// time that grows with both paths' segment counts, and they are worked out during the drag. +const MAX_SEGMENTS: usize = 512; + +/// A closed subpath with a curve the line may end on: its path, its index in the path, and the +/// bounds of its control points. +#[derive(Clone, Copy)] +struct Listed { + key: (NodeId, usize), + bounds: Rect, +} + +/// The two-ended tangent snap of one Line Segment drag. +#[derive(Default)] +pub(crate) struct TangentLine { + /// The subpath the press landed on and its outline: none when the press was not on a convex + /// closed path with a curve, or the snap is off. + from: Option<((NodeId, usize), Outline)>, + /// The closed subpaths with a curve, listed at the press (none when it found no subpath to + /// start from). + listed: Vec, + /// The common tangents of the press's subpath and each subpath the pointer came near. + kept: Vec<((NodeId, usize), Vec)>, + /// The line of the last snap. + line: Option<(Point, Point)>, +} + +/// The snap applies: Smart Guides and Snap to Tangent on, and neither pixels nor the grid +/// snapping drawn points instead. +fn applies(cx: &ToolContext) -> bool { + cx.smart_guides && cx.snap_tangent && !cx.snaps_to_pixel(PixelOp::Drawing) && !cx.snap_to_grid +} + +/// The subpath `key` of the document in `cx`. +fn subpath<'a>(cx: &'a ToolContext, key: (NodeId, usize)) -> Option<&'a SubPath> { + match &cx.doc.node(key.0)?.kind { + NodeKind::Path { path, .. } => path.subpaths.get(key.1), + _ => None, + } +} + +/// The subpaths of path `id` a line may start or end on, with their indexes: closed, with at most +/// [`MAX_SEGMENTS`] segments. +fn closed_subpaths<'a>(cx: &'a ToolContext, id: NodeId) -> impl Iterator { + let subpaths = match cx.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, .. }) => path.subpaths.as_slice(), + _ => &[], + }; + subpaths.iter().enumerate().filter(|(_, sp)| sp.closed && sp.segment_count() <= MAX_SEGMENTS) +} + +/// How far `p` lies from `sp` (its segments whose control bounds come within `reach` of `p`); none +/// when no segment comes that near. +fn distance(sp: &SubPath, p: Point, reach: f64) -> Option { + let mut best: Option = None; + for k in 0..sp.segment_count() { + let c = sp.segment(k); + let b = Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2); + if !b.inflate(reach, reach).contains(p) { + continue; + } + let d = c.nearest(p, 1e-9).distance_sq.sqrt(); + if best.is_none_or(|e| d < e) { + best = Some(d); + } + } + best +} + +/// Whether `sp` has a curved segment. +fn curved(sp: &SubPath) -> bool { + (0..sp.segment_count()).any(|k| !sp.segment_is_line(k)) +} + +impl TangentLine { + /// Start a drag pressed at `start` (where the pointer went down): the subpath under it, when it + /// is a convex closed path with a curve, and then the closed subpaths with a curve in the window + /// the line may end on, by their bounds. The press looks at the segments of the paths whose + /// bounds reach it only, and lists nothing when it lands on no such subpath, or when `held` (an + /// anchor, center or crossing the press snapped to) lies off that subpath. + pub(crate) fn press(&mut self, cx: &ToolContext, start: Point, held: Option) { + *self = Self::default(); + if !applies(cx) || !start.x.is_finite() || !start.y.is_finite() { + return; + } + let tol = cx.snap_tol(); + // The paths with a closed subpath, by their finite bounds. + let closed = |n: &Node| match &n.kind { + NodeKind::Path { path, .. } if path.subpaths.iter().any(|sp| sp.closed) => { + n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) + } + _ => None, + }; + // The subpaths under the press: at most as many segments as Smart Guides gather. + let mut on: Option<(f64, (NodeId, usize))> = None; + let mut budget = BUDGET; + walk_but(&cx.doc.layers, &HashSet::new(), &mut |n| { + if budget == 0 || !closed(n).is_some_and(|b| b.inflate(tol, tol).contains(start)) { + return; + } + for (si, sp) in closed_subpaths(cx, n.id) { + let Some(left) = budget.checked_sub(sp.segment_count()) else { return }; + budget = left; + if let Some(d) = distance(sp, start, tol) + && d <= tol + && curved(sp) + && on.is_none_or(|(e, _)| d < e) + { + on = Some((d, (n.id, si))); + } + } + }); + // A path that bends inward somewhere has no tangent of this kind: the line keeps its start. + let Some(from) = on.and_then(|(_, key)| Some((key, Outline::convex(subpath(cx, key)?).ok()?))) else { return }; + // A press held by an anchor, center or crossing off that path starts the line there. + if let Some(q) = held + && !subpath(cx, from.0).and_then(|sp| distance(sp, q, tol)).is_some_and(|d| d <= 1e-6 * tol.max(1.0)) + { + return; + } + let from_key = from.0; + self.from = Some(from); + // The subpaths the line may end on: closed ones with a curve, of the paths in the window, + // at most as many segments as Smart Guides gather. + let window = visible(cx); + let listed = &mut self.listed; + let mut budget = BUDGET; + walk_but(&cx.doc.layers, &HashSet::new(), &mut |n| { + if budget == 0 || !closed(n).is_some_and(|b| window.is_none_or(|v| b.intersect(v).area() > 0.0 || v.contains(b.center()))) { + return; + } + for (si, sp) in closed_subpaths(cx, n.id) { + let Some(left) = budget.checked_sub(sp.segment_count()) else { return }; + budget = left; + let mut bounds: Option = None; + for k in 0..sp.segment_count() { + let c = sp.segment(k); + let b = Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2); + bounds = Some(bounds.map_or(b, |r| r.union(b))); + } + if let Some(bounds) = + bounds.filter(|b| curved(sp) && (n.id, si) != from_key && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) + { + listed.push(Listed { key: (n.id, si), bounds }); + } + } + }); + } + + /// The line for the pointer at `p`: on the nearest subpath whose outline lies within the + /// snapping tolerance of `p` and that has a common tangent with the press's subpath, the + /// tangent whose touch point on it is nearest `p`; none when there is none. A subpath farther + /// from `p` than `rival` (an anchor, center or crossing the pointer snaps to otherwise) gives + /// way to it; its own anchors, which lie on its outline, do not. + pub(crate) fn snap(&mut self, cx: &ToolContext, p: Point, rival: Option) -> Option<(Point, Point)> { + let line = self.find(cx, p, rival); + self.line = line; + line + } + + fn find(&mut self, cx: &ToolContext, p: Point, rival: Option) -> Option<(Point, Point)> { + if self.from.is_none() || !applies(cx) || !p.x.is_finite() || !p.y.is_finite() { + return None; + } + let tol = cx.snap_tol(); + let mut near: Vec<(f64, (NodeId, usize))> = vec![]; + for l in self.listed.iter().filter(|l| l.bounds.inflate(tol, tol).contains(p)) { + // The nearest `MAX_NEAR`, in order, kept while scanning. + if let Some(d) = subpath(cx, l.key).and_then(|sp| distance(sp, p, tol)).filter(|d| *d <= tol) { + let at = near.partition_point(|(e, _)| *e <= d); + if at < MAX_NEAR { + near.insert(at, (d, l.key)); + near.truncate(MAX_NEAR); + } + } + } + for (d, key) in near { + if rival.is_some_and(|r| r < d - 1e-6 * tol) { + return None; + } + let Some(sp) = subpath(cx, key) else { continue }; + let mut best: Option<(f64, Point, Point)> = None; + for t in self.tangents(cx, key) { + // Where the paths touch each other, the tangent's ends are not both on the paths. + let on_b = distance(sp, t.to, tol).is_some_and(|e| e <= 1e-6 * tol.max(1.0)); + if !on_b || t.from.distance(t.to) <= tol { + continue; + } + let dist = t.to.distance(p); + // On a tie the line of the last move stays, so it does not flicker. + let same = self.line == Some((t.from, t.to)); + if best.is_none_or(|(e, ..)| dist < e - 1e-9 || (same && dist <= e + 1e-9)) { + best = Some((dist, t.from, t.to)); + } + } + if let Some((_, a, b)) = best { + return Some((a, b)); + } + } + None + } + + /// The common tangents of the press's subpath and subpath `key`, worked out on first use. + fn tangents(&mut self, cx: &ToolContext, key: (NodeId, usize)) -> Vec { + if let Some((_, t)) = self.kept.iter().find(|(k, _)| *k == key) { + return t.clone(); + } + let Some((_, from)) = &self.from else { return vec![] }; + let all = subpath(cx, key).and_then(|sp| Outline::convex(sp).ok()).and_then(|o| common_tangents(from, &o).ok()).unwrap_or_default(); + if self.kept.len() >= MAX_KEPT { + self.kept.remove(0); + } + self.kept.push((key, all.clone())); + all + } + + /// The line of the last snap, if it found one. + pub(crate) fn line(&self) -> Option<(Point, Point)> { + self.line + } + + /// Forget the last snap's line for a move that does not snap this way (a modifier is held), + /// keeping the press's subpath for the moves after it. + pub(crate) fn drop_line(&mut self) { + self.line = None; + } + + /// End the drag. + pub(crate) fn clear(&mut self) { + *self = Self::default(); + } + + /// The guides of the last snap: the line, and the "tangent" label at both ends. + pub(crate) fn guides(&self, cx: &ToolContext) -> Vec { + let Some((a, b)) = self.line else { return vec![] }; + let color = cx.smart_guide_color; + let mut out = vec![]; + if cx.alignment_guides { + out.push(Overlay::Line { a, b, color, dashed: false }); + } + if cx.anchor_path_labels { + out.extend([a, b].map(|p| Overlay::Label { p, text: "tangent".into(), color })); + } + out + } +} diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 36bea9b231..0c3ca94625 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -365,7 +365,7 @@ impl SnapKey { } /// The part of the document the window shows (none headless: all of it). -fn visible(cx: &ToolContext) -> Option { +pub(super) fn visible(cx: &ToolContext) -> Option { let s = cx.screen?; let (w, h) = s.size; Some(Rect::from_points(s.at(0.0, 0.0), s.at(w, h)).union_pt(s.at(w, 0.0)).union_pt(s.at(0.0, h))) @@ -446,6 +446,35 @@ impl DrawSnap { self.snap(cx, p, from) } + /// How far from `p` the nearest Smart Guides point (an anchor or a center) or crossing of the + /// targets lies, when one is within the snapping tolerance: none otherwise, and none while + /// pixels or the grid snap instead. + pub(crate) fn point_within_reach(&self, cx: &ToolContext, p: Point) -> Option { + let Some((_, PointSnap { targets: Some((t, tol)), .. })) = &self.targets else { return None }; + if !cx.smart_guides { + return None; + } + let tol = cx.tol(*tol); + let point = t.nearest_point(p, tol).map(|(q, _)| q.distance(p)); + let crossing = t.crossing(p, tol).map(|q| q.distance(p)); + match (point, crossing) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } + } + + /// Whether `q`, where a point at `p` snapped to, is the nearest Smart Guides point (an anchor or + /// a center) or the nearest crossing of the targets within the snapping tolerance of `p`. + pub(crate) fn snapped_to_point(&self, cx: &ToolContext, p: Point, q: Point) -> bool { + let Some((_, PointSnap { targets: Some((t, tol)), .. })) = &self.targets else { return false }; + if !cx.smart_guides { + return false; + } + let tol = cx.tol(*tol); + let at = |a: Point| a.distance(q) <= 1e-9 * tol.max(1.0); + t.nearest_point(p, tol).is_some_and(|(a, _)| at(a)) || t.crossing(p, tol).is_some_and(at) + } + /// The guides of the last snap. pub fn guides(&self) -> &[Overlay] { &self.guides diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 7341cf2713..37499b8354 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -64,7 +64,7 @@ pub struct Targets { } /// How many anchors, and how many segments, the targets gather at most. -const BUDGET: usize = 20_000; +pub(super) const BUDGET: usize = 20_000; /// What [`Targets::collect_inner`] gathers from each path besides its anchors and bounds. #[derive(Clone, Copy, PartialEq)] @@ -88,7 +88,7 @@ fn within(sorted: &[T], key: impl Fn(&T) -> f64, v: f64, tol: f64) -> &[T] { /// Visit `nodes` and everything inside them, but the nodes in `skip`, the hidden nodes and /// everything inside those: one pass, however many are skipped. A Shaper Group's original /// shapes, its first child, are not shown and are skipped too. -fn walk_but<'a>(nodes: &'a [Arc], skip: &HashSet, f: &mut impl FnMut(&'a Node)) { +pub(super) fn walk_but<'a>(nodes: &'a [Arc], skip: &HashSet, f: &mut impl FnMut(&'a Node)) { for n in nodes.iter().filter(|n| n.visible && !skip.contains(&n.id)) { f(n); if let Some(ch) = n.children() { @@ -1049,7 +1049,7 @@ impl Targets { /// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing /// nearest `p` within `tol` ("intersect", #1602). - fn crossing(&self, p: Point, tol: f64) -> Option { + pub(super) fn crossing(&self, p: Point, tol: f64) -> Option { self.crossing_with(p, tol, &self.rulers) } diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 0743036fb6..5a4bb93cb7 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -5,7 +5,9 @@ //! Illustrator). ↑/↓ during a polygon/star drag change the side/point count; during a star drag, //! Ctrl/Cmd keeps the inner radius where it is while the outer one follows the pointer, and Alt //! keeps the star's shoulders straight (#812). The start point and -//! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. +//! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. With Snap +//! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a +//! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]). //! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed. //! //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, @@ -26,7 +28,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag}; -use crate::guides::{DrawSnap, Leave, PointSnap, Targets, square}; +use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square}; use crate::pie::{self, PieDrag}; use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -106,6 +108,8 @@ pub struct ShapeTool { pub line_angle: f64, pub fill_line: bool, snap: DrawSnap, + /// Snap to Tangent for a line from one curve to another: both ends on a common tangent. + tangent_line: TangentLine, /// The options a drag's keys and Ctrl/Cmd change, as they were when the drag began: Escape /// puts them back. before_drag: Option, @@ -163,6 +167,7 @@ impl ShapeTool { inner: None, tangent_corner: None, snap: DrawSnap::default(), + tangent_line: TangentLine::default(), line_length: 100.0, line_angle: 0.0, fill_line: false, @@ -581,6 +586,12 @@ impl Tool for ShapeTool { return out; } let p = self.snap.press(cx, ev.pos, &[], None); + if self.id == "lineSegment" { + // The pressed spot finds the curve; a press that snapped to an anchor, center + // or crossing off that curve keeps the line's start there. + let held = self.snap.snapped_to_point(cx, ev.pos, p).then_some(p); + self.tangent_line.press(cx, ev.pos, held); + } self.start = Some(p); self.last = ev.pos; self.began = false; @@ -607,6 +618,10 @@ impl Tool for ShapeTool { self.last = s + d; } space_moves(&mut s, &mut self.last, ev, self.began); + if ev.mods.space && self.began { + // The start no longer lies on the pressed path. + self.tangent_line.clear(); + } self.start = Some(s); self.mods = ev.mods; if self.id == "star" { @@ -626,13 +641,25 @@ impl Tool for ShapeTool { self.before_drag = Some(self.drag_options()); out.push(Action::Begin(self.label().into())); } - let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); + // Snap to Tangent: a line pressed on one curve and ending near another moves both + // its ends onto a common tangent of the two, unless Shift, Alt or Space is held or + // an anchor or crossing nearer the pointer pulls it. + let tangent = if self.id == "lineSegment" && !(ev.mods.shift || ev.mods.alt || ev.mods.space) { + let rival = self.snap.point_within_reach(cx, raw); + self.tangent_line.snap(cx, raw, rival) + } else { + self.tangent_line.drop_line(); + None + }; + let (a, b) = tangent.unwrap_or((s, ev.pos)); + let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle); out.push(Action::Preview(c, v)); out } PointerKind::Up => { let Some(s) = self.start.take() else { return vec![] }; self.snap.clear(); + self.tangent_line.clear(); self.inner = None; self.before_drag = None; if self.began { @@ -706,6 +733,7 @@ impl Tool for ShapeTool { self.restore_drag_options(o); } self.snap.clear(); + self.tangent_line.clear(); vec![Action::Cancel] } else { vec![] @@ -754,7 +782,9 @@ impl Tool for ShapeTool { Some(WidgetDrag::Pie(d)) => return d.overlays(cx), None => {} } - let mut o = self.snap.guides().to_vec(); + // A line on a common tangent shows that snap's guides, and its length and angle. + let tangent = self.tangent_line.line().filter(|_| self.start.is_some()); + let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() }; o.extend(self.guides.iter().cloned()); if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); @@ -762,7 +792,8 @@ impl Tool for ShapeTool { if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); let text = if self.id == "lineSegment" { - cx.segment_measure_label(s, self.last) + let (a, b) = tangent.unwrap_or((s, self.last)); + cx.segment_measure_label(a, b) } else { // A box's size as drawn (from its centre with Alt, square with Shift). match self.id { diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 4e0ee1d1dc..1aadbf7dee 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -780,6 +780,259 @@ fn line_segment_options_and_fill_line() { assert_eq!(t.command(a, b, Mods::default()).1["fill"], json!(true)); } +/// A document holding the closed paths `paths`, unselected. +fn doc_with_paths(paths: Vec) -> vectorcraft_doc::Document { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + d +} + +/// The circle of radius `r` about `c`, as the Ellipse tool draws it. +fn circle(c: Point, r: f64) -> vectorcraft_geom::PathData { + vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)) +} + +/// The ends of the line a Line Segment drag from `press` through `drag` to `to` (with `mods`) +/// previews last, and the drag's actions. +fn line_drag(c: &ToolContext, press: Point, drag: Point, to: Point, mods: Mods) -> ((Point, Point), Vec) { + let mut t = ShapeTool::new("lineSegment"); + t.pointer(c, &PointerEvent::new(PointerKind::Down, press.x, press.y).with_mods(mods)); + let mut all = t.pointer(c, &PointerEvent::new(PointerKind::Drag, drag.x, drag.y).with_mods(mods)); + all.extend(t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods))); + let Some(Action::Preview(cmd, v)) = all.last().cloned() else { panic!("a preview: {all:?}") }; + assert_eq!(cmd, "shape.line"); + let f = |k: &str| v[k].as_f64().unwrap(); + let line = (Point::new(f("x1"), f("y1")), Point::new(f("x2"), f("y2"))); + all.extend(t.pointer(c, &PointerEvent::new(PointerKind::Up, to.x, to.y).with_mods(mods))); + (line, all) +} + +/// Snap to Tangent: a line pressed on one circle and dragged near another lands on a common +/// tangent of the two, both ends moving to where it touches them. Near the second circle's top it +/// is the outer tangent, near its bottom left the one crossing between them, each against the +/// closed form (the drawn circles are within 0.03% of round). The guides show the line and a +/// "tangent" label at each end, and the length label measures the tangent line. +#[test] +fn a_line_from_one_circle_to_another_lands_on_their_common_tangent() { + let (c1, r1, c2, r2) = (Point::new(100.0, 250.0), 40.0, Point::new(300.0, 250.0), 60.0); + let d = doc_with_paths(vec![circle(c1, r1), circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + // A drawn circle's radius is off by up to 0.03%, which moves the touch points along the line by + // up to about 0.1 pt here; the line's distance from each center stays within 0.03 pt. + let near = |a: Point, b: Point| (a - b).hypot() < 0.15; + let off_by = |(a, b): (Point, Point), c: Point| ((b - a).cross(c - a) / (b - a).hypot()).abs(); + let touches = |line: (Point, Point)| (off_by(line, c1) - r1).abs() < 0.03 && (off_by(line, c2) - r2).abs() < 0.03; + // A normal n with n · (c2 - c1) / |c2 - c1| = k: the line touches the first circle at + // c1 + r1 n, and the second at c2 + r2 n (outer, k = (r1 - r2) / d) or c2 - r2 n (crossing, + // k = (r1 + r2) / d). + let normal = |k: f64, up: bool| Vec2::new(k, if up { -1.0 } else { 1.0 } * (1.0 - k * k).sqrt()); + let outer = normal((r1 - r2) / 200.0, true); + let (on_a, on_b) = (c1 + outer * r1, c2 + outer * r2); + let press = Point::new(100.0, 210.0); + let ((a, b), actions) = line_drag(&c, press, Point::new(200.0, 200.0), on_b + Vec2::new(0.5, 0.7), Mods::default()); + assert!(near(a, on_a) && near(b, on_b) && touches((a, b)), "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + // One gesture: one undo step. + assert_eq!(actions.iter().filter(|a| matches!(a, Action::Begin(_))).count(), 1, "{actions:?}"); + assert_eq!(actions.last(), Some(&Action::Commit)); + let crossing = normal((r1 + r2) / 200.0, false); + let (on_a, on_b) = (c1 + crossing * r1, c2 - crossing * r2); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 260.0), on_b + Vec2::new(-0.6, 0.4), Mods::default()); + assert!(near(a, on_a) && near(b, on_b) && touches((a, b)), "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + // The guides and the length label while dragging. + let mut t = ShapeTool::new("lineSegment"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, press.x, press.y)); + let to = on_b + Vec2::new(-0.6, 0.4); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let o = t.overlays(&c); + let tangents: Vec = o + .iter() + .filter_map(|o| match o { + Overlay::Label { p, text, .. } if text == "tangent" => Some(*p), + _ => None, + }) + .collect(); + assert_eq!(tangents.len(), 2, "{o:?}"); + assert!(near(tangents[0], on_a) && near(tangents[1], on_b), "{o:?}"); + let (a, b) = t.tangent_line.line().unwrap(); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.segment_measure_label(a, b))), "{o:?}"); + // Escape ends it. + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.tangent_line.line().is_none() && t.overlays(&c).is_empty()); +} + +/// The tangent of a turned ellipse and a circle, against the ellipse's own closed form: the +/// support value of the ellipse x = c + M u (|u| = 1) along n is c · n + |Mᵀ n|, touched at +/// c + M Mᵀ n / |Mᵀ n|; the outer tangents are the n where it equals the circle's c₂ · n + r. +#[test] +fn a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle() { + let ce = Point::new(100.0, 250.0); + let turn = Affine::rotate_about(30f64.to_radians(), ce); + let ellipse = vectorcraft_geom::shapes::ellipse(Rect::new(40.0, 220.0, 160.0, 280.0)).transformed(turn); + let (c2, r2) = (Point::new(320.0, 260.0), 40.0); + let d = doc_with_paths(vec![ellipse, circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + // M maps the unit circle onto the ellipse's axes: 60 and 30 long, turned 30°. + let (cos, sin) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let m = [[60.0 * cos, -30.0 * sin], [60.0 * sin, 30.0 * cos]]; + let mt_n = |n: Vec2| Vec2::new(m[0][0] * n.x + m[1][0] * n.y, m[0][1] * n.x + m[1][1] * n.y); + let g = |a: f64| { + let n = Vec2::new(a.cos(), a.sin()); + ce.to_vec2().dot(n) + mt_n(n).hypot() - c2.to_vec2().dot(n) - r2 + }; + // The roots of g over the angle, by sampling and bisection; the one with n pointing up. + let mut roots = vec![]; + let steps = 3600; + for k in 0..steps { + let (mut lo, mut hi) = (k as f64 * std::f64::consts::TAU / steps as f64, (k + 1) as f64 * std::f64::consts::TAU / steps as f64); + if g(lo).signum() == g(hi).signum() { + continue; + } + for _ in 0..80 { + let mid = (lo + hi) / 2.0; + if g(mid).signum() == g(lo).signum() { lo = mid } else { hi = mid } + } + roots.push(lo); + } + let n = roots.iter().map(|a| Vec2::new(a.cos(), a.sin())).find(|n| n.y < 0.0).unwrap(); + let w = mt_n(n); + let on_a = ce + Vec2::new(m[0][0] * w.x + m[0][1] * w.y, m[1][0] * w.x + m[1][1] * w.y) / w.hypot(); + let on_b = c2 + n * r2; + // The press on the ellipse's turned top anchor. + let press = turn * Point::new(100.0, 220.0); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 200.0), on_b + Vec2::new(0.4, -0.5), Mods::default()); + assert!((a - on_a).hypot() < 0.05 && (b - on_b).hypot() < 0.05, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); +} + +/// The line keeps its start where it was pressed, as before, when Snap to Tangent is off, Smart +/// Guides are off, Shift or Alt is held, or the pressed path bends inward somewhere (it has no +/// tangent of this kind). Where the tangent touches the second circle at one of its anchors, the +/// tangent still wins over that anchor. +#[test] +fn a_line_keeps_its_start_without_a_tangent_snap() { + use vectorcraft_geom::{BezPath, PathData}; + let (c1, c2, r) = (Point::new(100.0, 250.0), Point::new(300.0, 250.0), 50.0); + let d = doc_with_paths(vec![circle(c1, r), circle(c2, r)]); + let (s, p) = (Selection::default(), paint()); + let on = cx(&d, &s, &p); + // The pointer next to the second circle's top anchor, where the outer tangent touches it. + let to = Point::new(300.6, 200.4); + // A press on the first circle 30° round from its top, away from its anchors. + let pressed = c1 + Vec2::new(r * 0.5, -r * 3f64.sqrt() / 2.0); + // With Snap to Tangent on, the start moves to the first circle's top. + let ((a, b), _) = line_drag(&on, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - Point::new(100.0, 200.0)).hypot() < 0.05 && (b - Point::new(300.0, 200.0)).hypot() < 0.05, "{a:?} {b:?}"); + let off = [ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }, ToolContext { smart_guides: false, ..cx(&d, &s, &p) }]; + for c in &off { + let ((a, _), _) = line_drag(c, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - pressed).hypot() < 0.05, "{a:?}"); + } + for mods in [Mods { shift: true, ..Mods::default() }, Mods { alt: true, ..Mods::default() }] { + let ((a, b), _) = line_drag(&on, pressed, Point::new(200.0, 190.0), to, mods); + // Alt draws the line from its middle. + let start = if mods.alt { a.midpoint(b) } else { a }; + assert!((start - pressed).hypot() < 0.05, "{a:?} {b:?}"); + } + // Space moves the line being drawn, its start off the pressed circle: the snap lets go. + let mut t = ShapeTool::new("lineSegment"); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&on, &PointerEvent::new(PointerKind::Down, pressed.x, pressed.y)); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 200.0, 170.0)); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 210.0, 160.0).with_mods(space)); + let a = t.pointer(&on, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("a preview: {a:?}") }; + let start = Point::new(v["x1"].as_f64().unwrap(), v["y1"].as_f64().unwrap()); + assert!((start - (pressed + Vec2::new(10.0, -10.0))).hypot() < 1.0, "{start:?}"); + // A crescent: closed and curved, but its lower side bends inward. The press on its top + // keeps its start. + let mut bp = BezPath::new(); + bp.move_to((60.0, 250.0)); + bp.curve_to((60.0, 190.0), (140.0, 190.0), (140.0, 250.0)); + bp.curve_to((120.0, 220.0), (80.0, 220.0), (60.0, 250.0)); + bp.close_path(); + let d = doc_with_paths(vec![PathData::from_bezpath(&bp), circle(c2, r)]); + let c = cx(&d, &s, &p); + let crest = Point::new(100.0, 205.0); + let ((a, _), _) = line_drag(&c, crest, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - crest).hypot() < 1e-6, "{a:?}"); +} + +/// The upper outer common tangent of the circles about `c1` and `c2` with radii `r1` and `r2` +/// (`c2` to the right): where it touches each. +fn upper_outer_tangent(c1: Point, r1: f64, c2: Point, r2: f64) -> (Point, Point) { + let d = c2 - c1; + let u = d / d.hypot(); + let k = (r1 - r2) / d.hypot(); + // n · u = k, with n pointing up (y down). + let n = u * k + Vec2::new(u.y, -u.x) * (1.0 - k * k).sqrt(); + (c1 + n * r1, c2 + n * r2) +} + +/// The pointer only has to come near the second path's outline: anywhere along it, the line takes +/// the tangent whose touch point is nearest the pointer, here one about 30 pt away. A press on a +/// straight side of a convex path with curves (a rounded rectangle's top edge) moves the start +/// onto the corner the tangent touches. +#[test] +fn a_line_near_the_second_path_takes_the_tangent_touching_it_nearest() { + let (c1, r1, c2, r2) = (Point::new(100.0, 250.0), 40.0, Point::new(300.0, 250.0), 60.0); + let d = doc_with_paths(vec![circle(c1, r1), circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (on_a, on_b) = upper_outer_tangent(c1, r1, c2, r2); + // On the second circle's outline, 25° round from its top. + let to = c2 + Vec2::new(r2 * 25f64.to_radians().sin(), -r2 * 25f64.to_radians().cos()); + assert!((to - on_b).hypot() > 25.0); + let ((a, b), _) = line_drag(&c, Point::new(100.0, 210.0), Point::new(200.0, 200.0), to, Mods::default()); + assert!((a - on_a).hypot() < 0.15 && (b - on_b).hypot() < 0.15, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + + // A rounded rectangle whose top right corner is a quarter circle of radius 20 about (140, 220). + let rounded = vectorcraft_geom::shapes::rounded_rectangle(Rect::new(40.0, 200.0, 160.0, 300.0), 20.0); + let (c2, r2) = (Point::new(320.0, 260.0), 40.0); + let d = doc_with_paths(vec![rounded, circle(c2, r2)]); + let c = cx(&d, &s, &p); + let (on_a, on_b) = upper_outer_tangent(Point::new(140.0, 220.0), 20.0, c2, r2); + let press = Point::new(90.0, 200.0); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 200.0), Point::new(320.0, 220.5), Mods::default()); + assert!((a - on_a).hypot() < 0.15 && (b - on_b).hypot() < 0.15, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); +} + +/// No tangent snap when the second path bends inward somewhere (a crescent), or when the press +/// snapped to an anchor of other art lying beside the first circle: the start stays where the +/// press put it. +#[test] +fn a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start() { + use vectorcraft_geom::{BezPath, PathData}; + let (c1, r) = (Point::new(100.0, 250.0), 50.0); + let mut bp = BezPath::new(); + bp.move_to((260.0, 250.0)); + bp.curve_to((260.0, 190.0), (340.0, 190.0), (340.0, 250.0)); + bp.curve_to((320.0, 220.0), (280.0, 220.0), (260.0, 250.0)); + bp.close_path(); + let d = doc_with_paths(vec![circle(c1, r), PathData::from_bezpath(&bp)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let pressed = c1 + Vec2::new(r * 0.5, -r * 3f64.sqrt() / 2.0); + // Beside the crescent's top, which lies at (300, 205). + let to = Point::new(300.4, 205.3); + let ((a, b), _) = line_drag(&c, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - pressed).hypot() < 0.05 && (b - to).hypot() < 1.0, "{a:?} {b:?}"); + + // A square whose corner (99, 199) lies about 1 pt outside the first circle's top; a second + // circle to the right. The press snaps to that corner and the line starts there. + let (c2, r2) = (Point::new(300.0, 250.0), 50.0); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(80.0, 180.0, 99.0, 199.0)); + let d = doc_with_paths(vec![circle(c1, r), square, circle(c2, r2)]); + let c = cx(&d, &s, &p); + let corner = Point::new(99.0, 199.0); + let ((a, _), _) = line_drag(&c, Point::new(99.3, 199.3), Point::new(200.0, 190.0), Point::new(300.6, 200.4), Mods::default()); + assert!((a - corner).hypot() < 1e-6, "{a:?}"); +} + /// #5477: with a shape tool, a drag on a selected live rectangle's corner widget rounds its /// corners (one undo step) and a drag on a live ellipse's pie widget sets its pie angle, as with /// the Selection tool; the pointer over a widget is the Selection tool's. A press anywhere else, or diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index b5dfb3eee0..011af4b171 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -31,6 +31,10 @@ pub const ID: &str = "anchorInspector"; const COUNT: &str = "anchor-inspector-count"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; +/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The kinds of tangent Common Tangents' `tangents` picks, and their labels. +pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; /// 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; @@ -72,6 +76,7 @@ pub fn menu() -> Vec { Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null), + Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index db4b39b6fc..de01be5b7d 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -258,3 +258,73 @@ fn effect_path_effects_lists_the_live_effects_and_their_dialogs_pick_from_their_ assert!(options.iter().all(|(_, value)| doc.params.contains(&format!("\"{value}\""))), "{effect} {key}"); } } + +/// Object › Plug-ins › Path Precision Tools › Common Tangents… opens the command dialog on all +/// tangents without the centerline, Preview off. With Preview on the lines show on the canvas; +/// Cancel takes them away with no step of history, and OK keeps them as one step. Nested circles +/// change nothing and say why. +#[test] +fn common_tangents_previews_cancels_and_runs_on_ok() { + let mut app = app(); + let circle = |app: &mut VectorcraftApp, x: f64, r: f64| { + app.run("shape.ellipse", json!({"x": x - r, "y": 150.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (circle(&mut app, 60.0, 20.0), circle(&mut app, 220.0, 40.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), steps(&app), count(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::COMMON_TANGENTS.to_string(), "Common Tangents".to_string())); + assert_eq!((d.str("tangents"), d.bool("centerline"), d.bool("preview")), ("all".to_string(), false, false)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Common Tangents", "Tangents", "All", "Centerline", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + // Each kind the list offers is one the command takes. + for (_, kind) in super::TANGENT_KINDS { + assert!(vectorcraft_engine::check_params(super::COMMON_TANGENTS, &json!({"tangents": kind})).is_ok(), "{kind}"); + } + assert_eq!(count(&app), nodes, "no preview without the checkbox"); + + // Preview on: the four lines are on the canvas. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 4, "previewed"); + // External only, with the centerline: two lines and the centerline. + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "tangents".into(), json!("external")); + crate::dialogs::set_field(d, "centerline".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 3, "previewed again"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel takes the preview away"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + // OK: one step. + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(count(&app), nodes + 4); + + // A circle inside another: nothing changes, and a message says why. + let inner = circle(&mut app, 220.0, 10.0); + app.run("select.set", json!({"ids": [b, inner]})).unwrap(); + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes)); + assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 7afe37ec0b..9e918fe092 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -66,8 +66,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and -/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes. (Cancel rolls a -/// preview back whichever dialog started it.) +/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path +/// Precision Tools › Common Tangents. (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -77,7 +77,8 @@ fn previews(d: &Dialog) -> bool { | crate::addons::image::COLOR_MASK | crate::addons::cutting::WEED | crate::addons::cutting::BANNER - | crate::addons::cutting::NEST => true, + | crate::addons::cutting::NEST + | crate::addons::pathtools::COMMON_TANGENTS => true, _ => false, } } @@ -163,6 +164,7 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], + crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], _ => &[], } } @@ -179,6 +181,7 @@ fn choices(command: &str, key: &str) -> Option { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), + (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), _ => None, diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 083adfacb6..838ba066d9 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -10,8 +10,8 @@ //! without a step of history. //! //! Fields: the options `graph.setType {}` returns under the command's names for them, with -//! `legend`, `pieLegend`, `piePosition`, `pieSort`, `firstRowInFront`, `firstColumnInFront` and -//! `filledLines` held for every type, and `type` or `valueAxis` null while the picked series +//! `legend`, `pieLegend`, `piePosition`, `pieSort`, `firstRowInFront`, `firstColumnInFront`, +//! `filledLines` and `lineWidth` held for every type, and `type` or `valueAxis` null while the picked series //! differ in it (OK then leaves each series as it is); `overrideValues` and `rightOverrideValues` (Override //! Calculated Values of the left or only value axis and of the right one: while one is on, OK //! sends `axisMin`, `axisMax` and `ticks`, or `rightAxisMin`, `rightAxisMax` and `rightTicks`); and @@ -60,6 +60,8 @@ const WIDTHS: RangeInclusive = 1.0..=1000.0; /// The divisions it takes for a value axis, and the tick marks it takes per division. const DIVISIONS: RangeInclusive = 1.0..=100.0; const TICK_MARKS: RangeInclusive = 1.0..=20.0; +/// The Line Width it takes for Draw Filled Lines, in points. +const LINE_WIDTHS: RangeInclusive = vectorcraft_doc::MIN_FILLED_LINE_WIDTH..=vectorcraft_doc::MAX_FILLED_LINE_WIDTH; /// The characters it keeps of a prefix or suffix. const AFFIX_CHARS: usize = 64; /// The divisions it draws an overridden value axis in while the axis has no count of its own. @@ -86,7 +88,7 @@ const PIE_SORTS: [(&str, &str); 3] = [("all", "All"), ("first", "First"), ("none /// The options OK always sends. `valueAxis` is left out while the picked series are on both axes, /// and the legend and the tick values follow the type and Override Calculated Values. -const SENT: [&str; 24] = [ +const SENT: [&str; 25] = [ "type", "valueAxis", "separateScales", @@ -100,6 +102,7 @@ const SENT: [&str; 24] = [ "connectPoints", "edgeToEdge", "filledLines", + "lineWidth", "tickLength", "tickMarks", "rightTickLength", @@ -183,6 +186,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ("firstRowInFront", json!(spec.first_row_in_front)), ("firstColumnInFront", json!(spec.first_column_in_front)), ("filledLines", json!(spec.filled_lines)), + ("lineWidth", json!(spec.filled_line_width())), ("legend", json!(spec.legend)), ("pieLegend", json!(pie_legend)), ("piePosition", json!(spec.pie_position.id())), @@ -672,6 +676,11 @@ fn type_options(ui: &mut egui::Ui, d: &mut Dialog, kind: GraphKind) { check(ui, d, "filledLines", tl!("Draw Filled Lines"), connected); ui.end_row(); }); + // Line Width sets how wide Draw Filled Lines draws the lines. + let shown = number(d, "lineWidth").unwrap_or(vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH); + ui.add_enabled_ui(connected && d.bool("filledLines"), |ui| { + ranged(ui, d, "lineWidth", &colon(tl!("Line Width")), shown, (LINE_WIDTHS, " pt", 2)); + }); } if pie { choice(ui, d, "pieLegend", &colon(tl!("Legend")), &PIE_LEGENDS); @@ -1062,6 +1071,32 @@ mod tests { assert!(!field(&h, "Column Width:") && !checkbox(&h, "Mark Data Points") && !menu(&h, "Legend:") && h.query_by_label("Options").is_none()); } + /// Line Width next to Draw Filled Lines shows the graph's width, is available only while Draw + /// Filled Lines and Connect Data Points are on, and OK gives the graph the width typed. + #[test] + fn line_width_goes_with_draw_filled_lines() { + let mut app = app_with_graph("line"); + open(&mut app).unwrap(); + assert_eq!(number(app.ui.dialog.as_ref().unwrap(), "lineWidth"), Some(vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH)); + let mut h = harness(app); + let dimmed = |h: &Harness| h.get_by_role_and_label(Role::TextInput, "Line Width:").accesskit_node().is_disabled(); + assert!(dimmed(&h), "Draw Filled Lines is off"); + h.get_by_role_and_label(Role::CheckBox, "Draw Filled Lines").click(); + h.run_steps(3); + assert!(!dimmed(&h)); + h.check_accessibility(); + set(h.state_mut(), "connectPoints", json!(false)); + h.run_steps(3); + assert!(dimmed(&h), "no lines to fill"); + set(h.state_mut(), "connectPoints", json!(true)); + set(h.state_mut(), "lineWidth", json!(6.5)); + let app = h.state_mut(); + let before = steps(app); + crate::dialogs::confirm(app).unwrap(); + assert_eq!((query(app)["filledLines"].clone(), query(app)["lineWidth"].clone()), (json!(true), json!(6.5))); + assert_eq!(steps(app), before + 1, "one step of history"); + } + /// The menu at the top lists a page per axis of the type picked, and a second value axis page /// while the value axis is on both sides. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d6729a36e8..faf6180840 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1405,6 +1405,7 @@ font-technology Variable Променливи Connect Data Points Свързване на точките от данни Edge-to-Edge Lines Линии от край до край Draw Filled Lines Чертане на запълнени линии + Line Width Ширина на линията Tick Values Стойности на отметките Override Calculated Values Замяна на изчислените стойности Divisions Деления @@ -6756,6 +6757,22 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Общи допирателни… + Common Tangents Общи допирателни + Tangents Допирателни + Centerline Централна линия + External Външни + Internal Вътрешни +@msg select two closed paths изберете два затворени пътя +@msg a selected path is open избран път е отворен +@msg a selected path is not convex избран път не е изпъкнал +@msg a selected path has no area избран път няма площ +@msg a selected path has more than 10000 segments избран път има повече от 10000 сегмента +@msg the two paths have the same outline двата пътя имат еднакъв контур +@msg One path lies inside the other, so they have no common tangents Единият път е вътре в другия, затова нямат общи допирателни +@msg The paths overlap, so they have no internal tangents Пътищата се припокриват, затова нямат вътрешни допирателни +@msg One path lies inside the other, so they have no internal tangents Единият път е вътре в другия, затова нямат вътрешни допирателни # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разширяване на тиретата в пътища @msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a52f3e4834..db9e97f9bc 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3635,6 +3635,7 @@ theme Appearance Izgled Connect Data Points Poveži tačke podataka Edge-to-Edge Lines Linije od ivice do ivice Draw Filled Lines Crtaj ispunjene linije + Line Width Širina linije Tick Values Vrijednosti crtica Override Calculated Values Zamijeni izračunate vrijednosti Divisions Podioci @@ -6808,6 +6809,22 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Zajedničke tangente… + Common Tangents Zajedničke tangente + Tangents Tangente + Centerline Središnja linija + External Vanjske + Internal Unutrašnje +@msg select two closed paths odaberite dvije zatvorene putanje +@msg a selected path is open odabrana putanja je otvorena +@msg a selected path is not convex odabrana putanja nije konveksna +@msg a selected path has no area odabrana putanja nema površinu +@msg a selected path has more than 10000 segments odabrana putanja ima više od 10000 segmenata +@msg the two paths have the same outline obje putanje imaju isti obris +@msg One path lies inside the other, so they have no common tangents Jedna putanja leži unutar druge, pa nemaju zajedničkih tangenti +@msg The paths overlap, so they have no internal tangents Putanje se preklapaju, pa nemaju unutrašnjih tangenti +@msg One path lies inside the other, so they have no internal tangents Jedna putanja leži unutar druge, pa nemaju unutrašnjih tangenti # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Proširi crtice u putanje @msg select paths with dashed strokes to expand odaberite putanje s isprekidanim potezom za proširivanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index eaebd2fca2..1705aa6811 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1945,6 +1945,7 @@ digits Malayalam Malaiàlam Connect Data Points Connecta els punts de dades Edge-to-Edge Lines Línies de vora a vora Draw Filled Lines Dibuixa línies emplenades + Line Width Amplada de línia Tick Values Valors de les marques Override Calculated Values Substitueix els valors calculats Divisions Divisions @@ -7459,6 +7460,22 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangents comunes… + Common Tangents Tangents comunes + Tangents Tangents + Centerline Línia central + External Externes + Internal Internes +@msg select two closed paths seleccioneu dos camins tancats +@msg a selected path is open un camí seleccionat és obert +@msg a selected path is not convex un camí seleccionat no és convex +@msg a selected path has no area un camí seleccionat no té àrea +@msg a selected path has more than 10000 segments un camí seleccionat té més de 10000 segments +@msg the two paths have the same outline els dos camins tenen el mateix contorn +@msg One path lies inside the other, so they have no common tangents Un camí és dins de l’altre, per tant no tenen tangents comunes +@msg The paths overlap, so they have no internal tangents Els camins se superposen, per tant no tenen tangents internes +@msg One path lies inside the other, so they have no internal tangents Un camí és dins de l’altre, per tant no tenen tangents internes # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandeix els guions en camins @msg select paths with dashed strokes to expand seleccioneu camins amb traç discontinu per expandir @@ -7773,6 +7790,8 @@ breakText Glyphs Glifs @msg No bridge of this width fits across the selected art Cap pont d’aquesta amplada no cap a la il·lustració seleccionada @msg Some islands could not be joined to the area around the art Algunes illes no s’han pogut unir a l’àrea que envolta la il·lustració @msg `width` must be from {lo} to {hi} pt `width` ha d’estar entre {lo} i {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` ha d’estar entre -180 i 180 graus +@msg `roundness` must be from 1 to 100% `roundness` ha d’estar entre 1 i 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` ha de ser un nombre enter d’1 a {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caixa i línies de pelat… Weed Box and Lines Caixa i línies de pelat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 645a8756fc..3ce4d6f0a5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3738,6 +3738,7 @@ theme Appearance Motiv Connect Data Points Spojit datové body Edge-to-Edge Lines Čáry od okraje k okraji Draw Filled Lines Kreslit vyplněné čáry + Line Width Šířka čáry Tick Values Hodnoty značek Override Calculated Values Přepsat vypočítané hodnoty Divisions Dílky @@ -7450,6 +7451,22 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Společné tečny… + Common Tangents Společné tečny + Tangents Tečny + Centerline Středová čára + External Vnější + Internal Vnitřní +@msg select two closed paths vyberte dvě uzavřené cesty +@msg a selected path is open vybraná cesta je otevřená +@msg a selected path is not convex vybraná cesta není konvexní +@msg a selected path has no area vybraná cesta nemá žádnou plochu +@msg a selected path has more than 10000 segments vybraná cesta má více než 10000 segmentů +@msg the two paths have the same outline obě cesty mají stejný obrys +@msg One path lies inside the other, so they have no common tangents Jedna cesta leží uvnitř druhé, takže nemají žádné společné tečny +@msg The paths overlap, so they have no internal tangents Cesty se překrývají, takže nemají žádné vnitřní tečny +@msg One path lies inside the other, so they have no internal tangents Jedna cesta leží uvnitř druhé, takže nemají žádné vnitřní tečny # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozložit čárky na cesty @msg select paths with dashed strokes to expand vyberte cesty s čárkovaným tahem k rozložení @@ -7867,6 +7884,8 @@ breakText Glyphs Glyfy @msg No bridge of this width fits across the selected art Přes vybranou kresbu se nevejde žádný můstek této šířky @msg Some islands could not be joined to the area around the art Některé ostrůvky nebylo možné připojit k oblasti kolem kresby @msg `width` must be from {lo} to {hi} pt `width` musí být od {lo} do {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` musí být od -180 do 180 stupňů +@msg `roundness` must be from 1 to 100% `roundness` musí být od 1 do 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musí být celé číslo od 1 do {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Rámeček a linie pro vybírání… Weed Box and Lines Rámeček a linie pro vybírání diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 32cc2fe80d..69db2c7136 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -706,6 +706,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg No bridge of this width fits across the selected art Ingen bro med denne bredde passer hen over den markerede grafik @msg Some islands could not be joined to the area around the art Nogle øer kunne ikke forbindes med området omkring grafikken @msg `width` must be from {lo} to {hi} pt `width` skal være fra {lo} til {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` skal være fra -180 til 180 grader +@msg `roundness` must be from 1 to 100% `roundness` skal være fra 1 til 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` skal være et heltal fra 1 til {MAX_BRIDGES_PER_ISLAND} File Filer @@ -6133,6 +6135,7 @@ theme Appearance Udseende Connect Data Points Forbind datapunkter Edge-to-Edge Lines Linjer fra kant til kant Draw Filled Lines Tegn udfyldte linjer + Line Width Linjebredde Tick Values Afmærkningsværdier Override Calculated Values Tilsidesæt beregnede værdier Divisions Inddelinger @@ -9501,6 +9504,22 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Fælles tangenter… + Common Tangents Fælles tangenter + Tangents Tangenter + Centerline Midterlinje + External Ydre + Internal Indre +@msg select two closed paths vælg to lukkede stier +@msg a selected path is open en valgt sti er åben +@msg a selected path is not convex en valgt sti er ikke konveks +@msg a selected path has no area en valgt sti har intet areal +@msg a selected path has more than 10000 segments en valgt sti har mere end 10000 segmenter +@msg the two paths have the same outline de to stier har samme omrids +@msg One path lies inside the other, so they have no common tangents Den ene sti ligger inden i den anden, så de har ingen fælles tangenter +@msg The paths overlap, so they have no internal tangents Stierne overlapper, så de har ingen indre tangenter +@msg One path lies inside the other, so they have no internal tangents Den ene sti ligger inden i den anden, så de har ingen indre tangenter # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Udvid streger til stier @msg select paths with dashed strokes to expand vælg stier med stiplet streg, der skal udvides diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8309c120bd..9adc5e4da1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1455,6 +1455,7 @@ file-filter Templates Vorlagen Connect Data Points Datenpunkte verbinden Edge-to-Edge Lines Linien von Kante zu Kante Draw Filled Lines Gefüllte Linien zeichnen + Line Width Linienbreite Tick Values Teilstrichwerte Override Calculated Values Berechnete Werte überschreiben Divisions Teilungen @@ -7041,6 +7042,22 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemeinsame Tangenten… + Common Tangents Gemeinsame Tangenten + Tangents Tangenten + Centerline Mittellinie + External Äußere + Internal Innere +@msg select two closed paths wählen Sie zwei geschlossene Pfade aus +@msg a selected path is open ein ausgewählter Pfad ist offen +@msg a selected path is not convex ein ausgewählter Pfad ist nicht konvex +@msg a selected path has no area ein ausgewählter Pfad hat keine Fläche +@msg a selected path has more than 10000 segments ein ausgewählter Pfad hat mehr als 10000 Segmente +@msg the two paths have the same outline die beiden Pfade haben denselben Umriss +@msg One path lies inside the other, so they have no common tangents Ein Pfad liegt im anderen, daher haben sie keine gemeinsamen Tangenten +@msg The paths overlap, so they have no internal tangents Die Pfade überlappen sich, daher haben sie keine inneren Tangenten +@msg One path lies inside the other, so they have no internal tangents Ein Pfad liegt im anderen, daher haben sie keine inneren Tangenten # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Striche in Pfade umwandeln @msg select paths with dashed strokes to expand wählen Sie Pfade mit gestrichelter Kontur zum Umwandeln aus @@ -7342,6 +7359,8 @@ breakText Glyphs Glyphen @msg No bridge of this width fits across the selected art Kein Steg dieser Breite passt über das ausgewählte Bildmaterial @msg Some islands could not be joined to the area around the art Einige Inseln konnten nicht mit der Fläche um das Bildmaterial verbunden werden @msg `width` must be from {lo} to {hi} pt `width` muss zwischen {lo} und {hi} pt liegen +@msg `angle` must be from -180 to 180 degrees `angle` muss zwischen -180 und 180 Grad liegen +@msg `roundness` must be from 1 to 100% `roundness` muss zwischen 1 und 100 % liegen @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` muss eine ganze Zahl von 1 bis {MAX_BRIDGES_PER_ISLAND} sein Weed Box and Lines… Entgitterrahmen und -linien… Weed Box and Lines Entgitterrahmen und -linien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2897534171..2bb03c51e9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1387,6 +1387,7 @@ font-technology Variable Μεταβλητές Connect Data Points Σύνδεση σημείων δεδομένων Edge-to-Edge Lines Γραμμές από άκρη σε άκρη Draw Filled Lines Σχεδίαση γεμισμένων γραμμών + Line Width Πλάτος γραμμής Tick Values Τιμές υποδιαιρέσεων Override Calculated Values Αντικατάσταση υπολογισμένων τιμών Divisions Διαιρέσεις @@ -7432,6 +7433,22 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Κοινές εφαπτόμενες… + Common Tangents Κοινές εφαπτόμενες + Tangents Εφαπτόμενες + Centerline Κεντρική γραμμή + External Εξωτερικές + Internal Εσωτερικές +@msg select two closed paths επιλέξτε δύο κλειστές διαδρομές +@msg a selected path is open μια επιλεγμένη διαδρομή είναι ανοιχτή +@msg a selected path is not convex μια επιλεγμένη διαδρομή δεν είναι κυρτή +@msg a selected path has no area μια επιλεγμένη διαδρομή δεν έχει εμβαδόν +@msg a selected path has more than 10000 segments μια επιλεγμένη διαδρομή έχει περισσότερα από 10000 τμήματα +@msg the two paths have the same outline οι δύο διαδρομές έχουν το ίδιο περίγραμμα +@msg One path lies inside the other, so they have no common tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν κοινές εφαπτόμενες +@msg The paths overlap, so they have no internal tangents Οι διαδρομές επικαλύπτονται, επομένως δεν έχουν εσωτερικές εφαπτόμενες +@msg One path lies inside the other, so they have no internal tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν εσωτερικές εφαπτόμενες # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Επέκταση παυλών σε διαδρομές @msg select paths with dashed strokes to expand επιλέξτε διαδρομές με διακεκομμένο περίγραμμα για επέκταση @@ -7746,6 +7763,8 @@ breakText Glyphs Γλύφοι @msg No bridge of this width fits across the selected art Καμία γέφυρα αυτού του πλάτους δεν χωράει στο επιλεγμένο γραφικό @msg Some islands could not be joined to the area around the art Ορισμένες νησίδες δεν ήταν δυνατό να συνδεθούν με την περιοχή γύρω από το γραφικό @msg `width` must be from {lo} to {hi} pt Το `width` πρέπει να είναι από {lo} έως {hi} pt +@msg `angle` must be from -180 to 180 degrees Το `angle` πρέπει να είναι από -180 έως 180 μοίρες +@msg `roundness` must be from 1 to 100% Το `roundness` πρέπει να είναι από 1 έως 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} Το `count` πρέπει να είναι ακέραιος από 1 έως {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Πλαίσιο και γραμμές αφαίρεσης περισσευμάτων… Weed Box and Lines Πλαίσιο και γραμμές αφαίρεσης περισσευμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 05ef523598..fc63c72e93 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1470,6 +1470,7 @@ font-technology Variable Variables Connect Data Points Conectar puntos de datos Edge-to-Edge Lines Líneas de borde a borde Draw Filled Lines Dibujar líneas rellenas + Line Width Ancho de línea Tick Values Valores de marcas Override Calculated Values Sustituir valores calculados Divisions Divisiones @@ -7420,6 +7421,22 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes comunes… + Common Tangents Tangentes comunes + Tangents Tangentes + Centerline Línea central + External Externas + Internal Internas +@msg select two closed paths seleccione dos trazados cerrados +@msg a selected path is open un trazado seleccionado está abierto +@msg a selected path is not convex un trazado seleccionado no es convexo +@msg a selected path has no area un trazado seleccionado no tiene área +@msg a selected path has more than 10000 segments un trazado seleccionado tiene más de 10000 segmentos +@msg the two paths have the same outline los dos trazados tienen el mismo contorno +@msg One path lies inside the other, so they have no common tangents Un trazado está dentro del otro, por lo que no tienen tangentes comunes +@msg The paths overlap, so they have no internal tangents Los trazados se superponen, por lo que no tienen tangentes internas +@msg One path lies inside the other, so they have no internal tangents Un trazado está dentro del otro, por lo que no tienen tangentes internas # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir guiones en trazados @msg select paths with dashed strokes to expand seleccione trazados con trazo discontinuo para expandir @@ -7850,6 +7867,8 @@ breakText Glyphs Glifos @msg No bridge of this width fits across the selected art Ningún puente de este ancho cabe en la ilustración seleccionada @msg Some islands could not be joined to the area around the art Algunas islas no se pudieron unir al área que rodea la ilustración @msg `width` must be from {lo} to {hi} pt `width` debe estar entre {lo} y {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` debe estar entre -180 y 180 grados +@msg `roundness` must be from 1 to 100% `roundness` debe estar entre 1 y 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` debe ser un número entero entre 1 y {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caja y líneas de pelado… Weed Box and Lines Caja y líneas de pelado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index df5805199a..59aa73a6b8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3676,6 +3676,7 @@ theme Appearance Ulkoasu Connect Data Points Yhdistä arvopisteet Edge-to-Edge Lines Viivat reunasta reunaan Draw Filled Lines Piirrä täytetyt viivat + Line Width Viivan leveys Tick Values Asteikon arvot Override Calculated Values Ohita lasketut arvot Divisions Jaot @@ -7508,6 +7509,22 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Yhteiset tangentit… + Common Tangents Yhteiset tangentit + Tangents Tangentit + Centerline Keskilinja + External Ulkoiset + Internal Sisäiset +@msg select two closed paths valitse kaksi suljettua polkua +@msg a selected path is open valittu polku on avoin +@msg a selected path is not convex valittu polku ei ole kupera +@msg a selected path has no area valitulla polulla ei ole pinta-alaa +@msg a selected path has more than 10000 segments valitussa polussa on yli 10000 segmenttiä +@msg the two paths have the same outline kahdella polulla on sama ääriviiva +@msg One path lies inside the other, so they have no common tangents Toinen polku on toisen sisällä, joten niillä ei ole yhteisiä tangentteja +@msg The paths overlap, so they have no internal tangents Polut ovat päällekkäin, joten niillä ei ole sisäisiä tangentteja +@msg One path lies inside the other, so they have no internal tangents Toinen polku on toisen sisällä, joten niillä ei ole sisäisiä tangentteja # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Laajenna viivat poluiksi @msg select paths with dashed strokes to expand valitse laajennettavat polut, joissa on katkoviiva @@ -7827,6 +7844,8 @@ breakText Glyphs Merkit @msg No bridge of this width fits across the selected art Näin leveä silta ei mahdu valitun grafiikan poikki @msg Some islands could not be joined to the area around the art Joitakin saarekkeita ei voitu yhdistää grafiikkaa ympäröivään alueeseen @msg `width` must be from {lo} to {hi} pt `width`-arvon on oltava {lo}–{hi} pt +@msg `angle` must be from -180 to 180 degrees `angle`-arvon on oltava -180–180 astetta +@msg `roundness` must be from 1 to 100% `roundness`-arvon on oltava 1–100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` on oltava kokonaisluku 1–{MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Karsintakehys ja -viivat… Weed Box and Lines Karsintakehys ja -viivat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4b427005e4..14a0be4478 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1460,6 +1460,7 @@ font-technology Variable Variables Connect Data Points Relier les points de données Edge-to-Edge Lines Lignes bord à bord Draw Filled Lines Tracer des lignes pleines + Line Width Épaisseur de ligne Tick Values Valeurs des graduations Override Calculated Values Remplacer les valeurs calculées Divisions Divisions @@ -7445,6 +7446,22 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes communes… + Common Tangents Tangentes communes + Tangents Tangentes + Centerline Ligne médiane + External Externes + Internal Internes +@msg select two closed paths sélectionnez deux tracés fermés +@msg a selected path is open un tracé sélectionné est ouvert +@msg a selected path is not convex un tracé sélectionné n’est pas convexe +@msg a selected path has no area un tracé sélectionné n’a pas de surface +@msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments +@msg the two paths have the same outline les deux tracés ont le même contour +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer @@ -7746,6 +7763,8 @@ breakText Glyphs Glyphes @msg No bridge of this width fits across the selected art Aucun pont de cette largeur ne tient en travers de l’illustration sélectionnée @msg Some islands could not be joined to the area around the art Certains îlots n’ont pas pu être reliés à la zone autour de l’illustration @msg `width` must be from {lo} to {hi} pt `width` doit être compris entre {lo} et {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` doit être compris entre -180 et 180 degrés +@msg `roundness` must be from 1 to 100% `roundness` doit être compris entre 1 et 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` doit être un nombre entier compris entre 1 et {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Cadre et lignes d’échenillage… Weed Box and Lines Cadre et lignes d’échenillage diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index a04afa99ad..3d04ff79a9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1577,6 +1577,7 @@ Connect Data Points ડેટા પોઇન્ટ જોડો Edge-to-Edge Lines કિનારીથી કિનારી સુધી રેખાઓ Draw Filled Lines ભરેલી રેખાઓ દોરો + Line Width રેખાની પહોળાઈ Tick Values ટિક મૂલ્યો Override Calculated Values ગણતરી કરેલાં મૂલ્યો બદલો Divisions વિભાગો @@ -2992,6 +2993,22 @@ Remove Effect ઇફેક્ટ દૂર કરો Remove Effects ઇફેક્ટ્સ દૂર કરો Remove Gaps ગેપ દૂર કરો +# Path Precision Tools add-on: Common Tangents. + Common Tangents… સામાન્ય સ્પર્શરેખાઓ… + Common Tangents સામાન્ય સ્પર્શરેખાઓ + Tangents સ્પર્શરેખાઓ + Centerline કેન્દ્ર રેખા + External બાહ્ય + Internal આંતરિક +@msg select two closed paths બે બંધ પાથ પસંદ કરો +@msg a selected path is open પસંદ કરેલો એક પાથ ખુલ્લો છે +@msg a selected path is not convex પસંદ કરેલો એક પાથ બહિર્ગોળ નથી +@msg a selected path has no area પસંદ કરેલા એક પાથનું કોઈ ક્ષેત્રફળ નથી +@msg a selected path has more than 10000 segments પસંદ કરેલા એક પાથમાં 10000 થી વધુ ખંડ છે +@msg the two paths have the same outline બંને પાથની રૂપરેખા સમાન છે +@msg One path lies inside the other, so they have no common tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ સામાન્ય સ્પર્શરેખા નથી +@msg The paths overlap, so they have no internal tangents પાથ એકબીજા પર ચઢેલા છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી +@msg One path lies inside the other, so they have no internal tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી Remove Guide ગાઇડ દૂર કરો Remove Item આઇટમ દૂર કરો Remove JavaScript File JavaScript ફાઇલ દૂર કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2c27a763eb..447b652288 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2161,6 +2161,7 @@ antiAlias Sharp शार्प Connect Data Points डेटा पॉइंट जोड़ें Edge-to-Edge Lines किनारे से किनारे तक रेखाएँ Draw Filled Lines भरी हुई रेखाएँ बनाएँ + Line Width रेखा की चौड़ाई Tick Values टिक मान Override Calculated Values परिकलित मानों को बदलें Divisions विभाजन @@ -8140,6 +8141,22 @@ liquify-list-end {0}, {1} {0} और {1} @msg select paths to join जोड़ने के लिए पाथ सिलेक्ट करें @msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें @msg select paths, or segments, to divide विभाजित करने के लिए पाथ, या खंड चुनें +# Path Precision Tools add-on: Common Tangents. + Common Tangents… उभयनिष्ठ स्पर्शरेखाएँ… + Common Tangents उभयनिष्ठ स्पर्शरेखाएँ + Tangents स्पर्शरेखाएँ + Centerline केंद्र रेखा + External बाहरी + Internal आंतरिक +@msg select two closed paths दो बंद पाथ चुनें +@msg a selected path is open चुना गया एक पाथ खुला है +@msg a selected path is not convex चुना गया एक पाथ उत्तल नहीं है +@msg a selected path has no area चुने गए एक पाथ का कोई क्षेत्रफल नहीं है +@msg a selected path has more than 10000 segments चुने गए एक पाथ में 10000 से अधिक खंड हैं +@msg the two paths have the same outline दोनों पाथ की रूपरेखा एक जैसी है +@msg One path lies inside the other, so they have no common tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई उभयनिष्ठ स्पर्शरेखा नहीं है +@msg The paths overlap, so they have no internal tangents पाथ एक-दूसरे पर चढ़े हुए हैं, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है +@msg One path lies inside the other, so they have no internal tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select two or three paths or compound paths दो या तीन पाथ या यौगिक पाथ सिलेक्ट करें @@ -9173,6 +9190,8 @@ theme Appearance अपीयरेंस @msg No bridge of this width fits across the selected art इस चौड़ाई का कोई ब्रिज चुने गए आर्टवर्क के पार नहीं आता @msg Some islands could not be joined to the area around the art कुछ आइलैंड आर्टवर्क के आसपास के क्षेत्र से नहीं जोड़े जा सके @msg `width` must be from {lo} to {hi} pt `width` {lo} से {hi} pt तक होना चाहिए +@msg `angle` must be from -180 to 180 degrees `angle` -180 से 180 डिग्री तक होना चाहिए +@msg `roundness` must be from 1 to 100% `roundness` 1 से 100% तक होना चाहिए @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 से {MAX_BRIDGES_PER_ISLAND} तक पूरी संख्या होना चाहिए Weed Box and Lines… वीड बॉक्स और लाइनें… Weed Box and Lines वीड बॉक्स और लाइनें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d703efb0b2..e081c882b6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1819,6 +1819,7 @@ file-filter Templates Sablonok Connect Data Points Adatpontok összekötése Edge-to-Edge Lines Széltől szélig érő vonalak Draw Filled Lines Kitöltött vonalak rajzolása + Line Width Vonalvastagság Tick Values Osztásértékek Override Calculated Values Számított értékek felülírása Divisions Osztások @@ -7435,6 +7436,22 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Közös érintők… + Common Tangents Közös érintők + Tangents Érintők + Centerline Középvonal + External Külső + Internal Belső +@msg select two closed paths jelöljön ki két zárt útvonalat +@msg a selected path is open egy kijelölt útvonal nyitott +@msg a selected path is not convex egy kijelölt útvonal nem konvex +@msg a selected path has no area egy kijelölt útvonalnak nincs területe +@msg a selected path has more than 10000 segments egy kijelölt útvonalnak több mint 10000 szakasza van +@msg the two paths have the same outline a két útvonal körvonala azonos +@msg One path lies inside the other, so they have no common tangents Az egyik útvonal a másikon belül van, így nincsenek közös érintőik +@msg The paths overlap, so they have no internal tangents Az útvonalak átfedik egymást, így nincsenek belső érintőik +@msg One path lies inside the other, so they have no internal tangents Az egyik útvonal a másikon belül van, így nincsenek belső érintőik # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Szaggatások kibontása útvonalakká @msg select paths with dashed strokes to expand jelöljön ki szaggatott körvonalú útvonalakat a kibontáshoz @@ -7736,6 +7753,8 @@ breakText Glyphs Glifák @msg No bridge of this width fits across the selected art Ilyen széles híd nem fér el a kijelölt grafikán @msg Some islands could not be joined to the area around the art Egyes szigeteket nem sikerült összekötni a grafikát körülvevő területtel @msg `width` must be from {lo} to {hi} pt A `width` értéke {lo} és {hi} pt között lehet +@msg `angle` must be from -180 to 180 degrees Az `angle` értéke -180 és 180 fok között lehet +@msg `roundness` must be from 1 to 100% A `roundness` értéke 1 és 100% között lehet @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`: 1 és {MAX_BRIDGES_PER_ISLAND} közötti egész szám kell Weed Box and Lines… Gyomláló keret és vonalak… Weed Box and Lines Gyomláló keret és vonalak diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b4d8beb213..9f27f50e03 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3412,6 +3412,7 @@ theme Appearance Tampilan Connect Data Points Hubungkan titik data Edge-to-Edge Lines Garis dari tepi ke tepi Draw Filled Lines Gambar garis terisi + Line Width Lebar garis Tick Values Nilai tanda skala Override Calculated Values Timpa nilai terhitung Divisions Pembagian @@ -6771,6 +6772,22 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Garis Singgung Persekutuan… + Common Tangents Garis Singgung Persekutuan + Tangents Garis Singgung + Centerline Garis Tengah + External Luar + Internal Dalam +@msg select two closed paths pilih dua jalur tertutup +@msg a selected path is open jalur yang dipilih terbuka +@msg a selected path is not convex jalur yang dipilih tidak cembung +@msg a selected path has no area jalur yang dipilih tidak memiliki luas +@msg a selected path has more than 10000 segments jalur yang dipilih memiliki lebih dari 10000 segmen +@msg the two paths have the same outline kedua jalur memiliki garis luar yang sama +@msg One path lies inside the other, so they have no common tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung persekutuan +@msg The paths overlap, so they have no internal tangents Jalur-jalur saling tumpang tindih, sehingga tidak ada garis singgung dalam +@msg One path lies inside the other, so they have no internal tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung dalam # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Perluas garis putus menjadi jalur @msg select paths with dashed strokes to expand pilih jalur dengan stroke putus-putus yang akan diperluas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 554d12fbb1..b294b7da3a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1489,6 +1489,7 @@ file-filter Templates Modelli Connect Data Points Collega punti dati Edge-to-Edge Lines Linee da bordo a bordo Draw Filled Lines Disegna linee piene + Line Width Spessore linea Tick Values Valori delle tacche Override Calculated Values Sostituisci valori calcolati Divisions Divisioni @@ -7077,6 +7078,22 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangenti comuni… + Common Tangents Tangenti comuni + Tangents Tangenti + Centerline Linea centrale + External Esterne + Internal Interne +@msg select two closed paths seleziona due tracciati chiusi +@msg a selected path is open un tracciato selezionato è aperto +@msg a selected path is not convex un tracciato selezionato non è convesso +@msg a selected path has no area un tracciato selezionato non ha area +@msg a selected path has more than 10000 segments un tracciato selezionato ha più di 10000 segmenti +@msg the two paths have the same outline i due tracciati hanno lo stesso contorno +@msg One path lies inside the other, so they have no common tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti comuni +@msg The paths overlap, so they have no internal tangents I tracciati si sovrappongono, quindi non hanno tangenti interne +@msg One path lies inside the other, so they have no internal tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Espandi trattini in tracciati @msg select paths with dashed strokes to expand seleziona tracciati con traccia tratteggiata da espandere @@ -7378,6 +7395,8 @@ breakText Glyphs Glifi @msg No bridge of this width fits across the selected art Nessun ponte di questa larghezza entra nella grafica selezionata @msg Some islands could not be joined to the area around the art Non è stato possibile collegare alcune isole all’area intorno alla grafica @msg `width` must be from {lo} to {hi} pt `width` deve essere compreso tra {lo} e {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` deve essere compreso tra -180 e 180 gradi +@msg `roundness` must be from 1 to 100% `roundness` deve essere compreso tra 1 e 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve essere un numero intero compreso tra 1 e {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Riquadro e linee di spellicolatura… Weed Box and Lines Riquadro e linee di spellicolatura diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 66f0a85572..56c1c1e5ec 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3924,6 +3924,7 @@ file-filter Templates テンプレート Connect Data Points データポイントを線でつなぐ Edge-to-Edge Lines 端から端までの線 Draw Filled Lines 線を塗りつぶして描く + Line Width 線幅 Tick Values 目盛りの値 Override Calculated Values 計算値を上書き Divisions 分割数 @@ -8956,6 +8957,22 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 共通接線… + Common Tangents 共通接線 + Tangents 接線 + Centerline 中心線 + External 外側 + Internal 内側 +@msg select two closed paths 閉じたパスを 2 つ選択してください +@msg a selected path is open 選択したパスが開いています +@msg a selected path is not convex 選択したパスが凸形ではありません +@msg a selected path has no area 選択したパスに面積がありません +@msg a selected path has more than 10000 segments 選択したパスのセグメントが 10000 を超えています +@msg the two paths have the same outline 2 つのパスの輪郭が同じです +@msg One path lies inside the other, so they have no common tangents 一方のパスがもう一方の内側にあるため、共通接線はありません +@msg The paths overlap, so they have no internal tangents パスが重なっているため、内側の接線はありません +@msg One path lies inside the other, so they have no internal tangents 一方のパスがもう一方の内側にあるため、内側の接線はありません # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 破線をパスに拡張 @msg select paths with dashed strokes to expand 拡張する破線のパスを選択してください @@ -9257,6 +9274,8 @@ breakText Glyphs 字形 @msg No bridge of this width fits across the selected art この幅のブリッジは選択したアートワークに収まりません @msg Some islands could not be joined to the area around the art 一部のアイランドをアートワークの周囲の領域につなげられませんでした @msg `width` must be from {lo} to {hi} pt `width` は {lo}~{hi} pt の範囲で指定してください +@msg `angle` must be from -180 to 180 degrees `angle` は -180~180 度の範囲で指定してください +@msg `roundness` must be from 1 to 100% `roundness` は 1~100% の範囲で指定してください @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` には 1 から {MAX_BRIDGES_PER_ISLAND} の整数を指定してください Weed Box and Lines… カス取り枠とライン… Weed Box and Lines カス取り枠とライン diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 190dd2cce6..0f18e63a1a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5392,6 +5392,7 @@ theme Appearance იერსახე Connect Data Points მონაცემთა წერტილების შეერთება Edge-to-Edge Lines ხაზები კიდიდან კიდემდე Draw Filled Lines შევსებული ხაზების დახატვა + Line Width ხაზის სიგანე Tick Values დანაყოფების მნიშვნელობები Override Calculated Values გამოთვლილი მნიშვნელობების შეცვლა Divisions დანაყოფები @@ -9565,6 +9566,22 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი ტრაექტორიები ან სეგმენტები +# Path Precision Tools add-on: Common Tangents. + Common Tangents… საერთო მხებები… + Common Tangents საერთო მხებები + Tangents მხებები + Centerline ცენტრალური ხაზი + External გარე + Internal შიდა +@msg select two closed paths აირჩიეთ ორი დახურული ტრაექტორია +@msg a selected path is open არჩეული ტრაექტორია ღიაა +@msg a selected path is not convex არჩეული ტრაექტორია არ არის ამოზნექილი +@msg a selected path has no area არჩეულ ტრაექტორიას ფართობი არ აქვს +@msg a selected path has more than 10000 segments არჩეულ ტრაექტორიას 10000-ზე მეტი სეგმენტი აქვს +@msg the two paths have the same outline ორივე ტრაექტორიას ერთნაირი კონტური აქვს +@msg One path lies inside the other, so they have no common tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ საერთო მხებები არ აქვთ +@msg The paths overlap, so they have no internal tangents ტრაექტორიები ერთმანეთს ფარავს, ამიტომ მათ შიდა მხებები არ აქვთ +@msg One path lies inside the other, so they have no internal tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ შიდა მხებები არ აქვთ # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths ტირეების ტრაექტორიებად გაშლა @msg select paths with dashed strokes to expand აირჩიეთ გასაშლელი ტირეებიანი ხაზის კონტურები @@ -9954,6 +9971,8 @@ font-script Japanese იაპონური @msg No bridge of this width fits across the selected art ამ სიგანის ხიდი მონიშნულ ნახატზე არ ეტევა @msg Some islands could not be joined to the area around the art ზოგიერთი კუნძული ვერ დაუკავშირდა ნახატის გარშემო არეს @msg `width` must be from {lo} to {hi} pt `width` უნდა იყოს {lo}-დან {hi} pt-მდე +@msg `angle` must be from -180 to 180 degrees `angle` უნდა იყოს -180-დან 180 გრადუსამდე +@msg `roundness` must be from 1 to 100% `roundness` უნდა იყოს 1-დან 100%-მდე @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` უნდა იყოს მთელი რიცხვი 1-დან {MAX_BRIDGES_PER_ISLAND}-მდე Weed Box and Lines… ნარჩენის მოსაცილებელი ჩარჩო და ხაზები… Weed Box and Lines ნარჩენის მოსაცილებელი ჩარჩო და ხაზები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4e06535d45..8e5a3799a5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3912,6 +3912,7 @@ file-filter Templates 템플릿 Connect Data Points 데이터 요소 연결 Edge-to-Edge Lines 가장자리 간 선 Draw Filled Lines 채워진 선 그리기 + Line Width 선 너비 Tick Values 눈금 값 Override Calculated Values 계산된 값 재정의 Divisions 구간 @@ -7041,6 +7042,22 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 공통 접선… + Common Tangents 공통 접선 + Tangents 접선 + Centerline 중심선 + External 외부 + Internal 내부 +@msg select two closed paths 닫힌 패스 2개를 선택하십시오 +@msg a selected path is open 선택한 패스가 열려 있습니다 +@msg a selected path is not convex 선택한 패스가 볼록하지 않습니다 +@msg a selected path has no area 선택한 패스에 면적이 없습니다 +@msg a selected path has more than 10000 segments 선택한 패스의 세그먼트가 10000개를 넘습니다 +@msg the two paths have the same outline 두 패스의 윤곽선이 같습니다 +@msg One path lies inside the other, so they have no common tangents 한 패스가 다른 패스 안에 있어 공통 접선이 없습니다 +@msg The paths overlap, so they have no internal tangents 패스가 겹쳐 있어 내부 접선이 없습니다 +@msg One path lies inside the other, so they have no internal tangents 한 패스가 다른 패스 안에 있어 내부 접선이 없습니다 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 대시를 패스로 확장 @msg select paths with dashed strokes to expand 확장할 점선 획의 패스를 선택하십시오 @@ -7342,6 +7359,8 @@ breakText Glyphs 글리프 @msg No bridge of this width fits across the selected art 이 너비의 브리지가 선택한 아트워크에 들어가지 않습니다 @msg Some islands could not be joined to the area around the art 일부 섬을 아트워크 주변 영역에 연결할 수 없습니다 @msg `width` must be from {lo} to {hi} pt `width`는 {lo}에서 {hi}pt 사이여야 합니다 +@msg `angle` must be from -180 to 180 degrees `angle`는 -180도에서 180도 사이여야 합니다 +@msg `roundness` must be from 1 to 100% `roundness`는 1%에서 100% 사이여야 합니다 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`는 1에서 {MAX_BRIDGES_PER_ISLAND} 사이의 정수여야 합니다 Weed Box and Lines… 위딩 상자 및 선… Weed Box and Lines 위딩 상자 및 선 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c3c4f15335..96e9e6a985 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -575,6 +575,8 @@ liquify-list-end {0}, {1} {0} en {1} @msg No bridge of this width fits across the selected art Geen brug van deze breedte past over de geselecteerde illustratie @msg Some islands could not be joined to the area around the art Sommige eilanden konden niet worden verbonden met het gebied rond de illustratie @msg `width` must be from {lo} to {hi} pt `width` moet van {lo} tot {hi} pt zijn +@msg `angle` must be from -180 to 180 degrees `angle` moet van -180 tot 180 graden zijn +@msg `roundness` must be from 1 to 100% `roundness` moet van 1 tot 100% zijn @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` moet een geheel getal van 1 tot {MAX_BRIDGES_PER_ISLAND} zijn File Bestand @@ -4027,6 +4029,7 @@ theme Appearance Vormgeving Connect Data Points Gegevenspunten verbinden Edge-to-Edge Lines Lijnen van rand tot rand Draw Filled Lines Gevulde lijnen tekenen + Line Width Lijndikte Tick Values Maatstreepwaarden Override Calculated Values Berekende waarden negeren Divisions Verdelingen @@ -9326,6 +9329,22 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemeenschappelijke raaklijnen… + Common Tangents Gemeenschappelijke raaklijnen + Tangents Raaklijnen + Centerline Middellijn + External Uitwendige + Internal Inwendige +@msg select two closed paths selecteer twee gesloten paden +@msg a selected path is open een geselecteerd pad is open +@msg a selected path is not convex een geselecteerd pad is niet convex +@msg a selected path has no area een geselecteerd pad heeft geen oppervlak +@msg a selected path has more than 10000 segments een geselecteerd pad heeft meer dan 10000 segmenten +@msg the two paths have the same outline de twee paden hebben dezelfde omtrek +@msg One path lies inside the other, so they have no common tangents Het ene pad ligt binnen het andere, dus ze hebben geen gemeenschappelijke raaklijnen +@msg The paths overlap, so they have no internal tangents De paden overlappen, dus ze hebben geen inwendige raaklijnen +@msg One path lies inside the other, so they have no internal tangents Het ene pad ligt binnen het andere, dus ze hebben geen inwendige raaklijnen # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Streepjes uitbreiden tot paden @msg select paths with dashed strokes to expand selecteer paden met een streepjeslijn om uit te breiden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ed2cb8a062..487283e406 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3617,6 +3617,7 @@ theme Appearance Wygląd Connect Data Points Połącz punkty danych Edge-to-Edge Lines Linie od krawędzi do krawędzi Draw Filled Lines Rysuj wypełnione linie + Line Width Szerokość linii Tick Values Wartości podziałki Override Calculated Values Zastąp obliczone wartości Divisions Podziały @@ -7306,6 +7307,22 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Wspólne styczne… + Common Tangents Wspólne styczne + Tangents Styczne + Centerline Linia środkowa + External Zewnętrzne + Internal Wewnętrzne +@msg select two closed paths zaznacz dwie zamknięte ścieżki +@msg a selected path is open zaznaczona ścieżka jest otwarta +@msg a selected path is not convex zaznaczona ścieżka nie jest wypukła +@msg a selected path has no area zaznaczona ścieżka nie ma pola +@msg a selected path has more than 10000 segments zaznaczona ścieżka ma więcej niż 10000 segmentów +@msg the two paths have the same outline obie ścieżki mają ten sam kontur +@msg One path lies inside the other, so they have no common tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają wspólnych stycznych +@msg The paths overlap, so they have no internal tangents Ścieżki nachodzą na siebie, więc nie mają stycznych wewnętrznych +@msg One path lies inside the other, so they have no internal tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają stycznych wewnętrznych # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozszerz kreski na ścieżki @msg select paths with dashed strokes to expand zaznacz ścieżki z przerywanym konturem do rozszerzenia @@ -7607,6 +7624,8 @@ breakText Glyphs Glify @msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej grafice @msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół grafiki @msg `width` must be from {lo} to {hi} pt `width` musi mieścić się w zakresie od {lo} do {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` musi mieścić się w zakresie od -180 do 180 stopni +@msg `roundness` must be from 1 to 100% `roundness` musi mieścić się w zakresie od 1 do 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musi być liczbą całkowitą od 1 do {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Ramka i linie do wybierania… Weed Box and Lines Ramka i linie do wybierania diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 18f3f358e2..e1a8bcb11c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5048,6 +5048,7 @@ axis Both Ambos Connect Data Points Conectar Pontos de Dados Edge-to-Edge Lines Linhas de Borda a Borda Draw Filled Lines Desenhar Linhas Preenchidas + Line Width Largura da Linha Tick Values Valores das Marcas Override Calculated Values Substituir Valores Calculados Divisions Divisões @@ -7481,6 +7482,22 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes comuns… + Common Tangents Tangentes comuns + Tangents Tangentes + Centerline Linha central + External Externas + Internal Internas +@msg select two closed paths selecione dois demarcadores fechados +@msg a selected path is open um demarcador selecionado está aberto +@msg a selected path is not convex um demarcador selecionado não é convexo +@msg a selected path has no area um demarcador selecionado não tem área +@msg a selected path has more than 10000 segments um demarcador selecionado tem mais de 10000 segmentos +@msg the two paths have the same outline os dois demarcadores têm o mesmo contorno +@msg One path lies inside the other, so they have no common tangents Um demarcador está dentro do outro, então eles não têm tangentes comuns +@msg The paths overlap, so they have no internal tangents Os demarcadores se sobrepõem, então eles não têm tangentes internas +@msg One path lies inside the other, so they have no internal tangents Um demarcador está dentro do outro, então eles não têm tangentes internas # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir traços em demarcadores @msg select paths with dashed strokes to expand selecione demarcadores com traçado tracejado para expandir @@ -7937,6 +7954,8 @@ swatch Yellow Green Verde-amarelado @msg No bridge of this width fits across the selected art Nenhuma ponte desta largura cabe na arte selecionada @msg Some islands could not be joined to the area around the art Algumas ilhas não puderam ser unidas à área ao redor da arte @msg `width` must be from {lo} to {hi} pt `width` deve estar entre {lo} e {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` deve estar entre -180 e 180 graus +@msg `roundness` must be from 1 to 100% `roundness` deve estar entre 1 e 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve ser um número inteiro de 1 a {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Caixa e Linhas de Descasque… Weed Box and Lines Caixa e Linhas de Descasque diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index da4d50e2dd..f443922dd7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1480,6 +1480,7 @@ file-filter Templates Шаблоны Connect Data Points Соединять точки данных Edge-to-Edge Lines Линии от края до края Draw Filled Lines Рисовать заполненные линии + Line Width Ширина линии Tick Values Значения делений Override Calculated Values Заменить вычисленные значения Divisions Деления @@ -7440,6 +7441,22 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Общие касательные… + Common Tangents Общие касательные + Tangents Касательные + Centerline Осевая линия + External Внешние + Internal Внутренние +@msg select two closed paths выделите два замкнутых контура +@msg a selected path is open выделенный контур открыт +@msg a selected path is not convex выделенный контур не выпуклый +@msg a selected path has no area выделенный контур не имеет площади +@msg a selected path has more than 10000 segments выделенный контур содержит более 10000 сегментов +@msg the two paths have the same outline у обоих контуров одинаковая форма +@msg One path lies inside the other, so they have no common tangents Один контур лежит внутри другого, поэтому у них нет общих касательных +@msg The paths overlap, so they have no internal tangents Контуры перекрываются, поэтому у них нет внутренних касательных +@msg One path lies inside the other, so they have no internal tangents Один контур лежит внутри другого, поэтому у них нет внутренних касательных # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разобрать штрихи на контуры @msg select paths with dashed strokes to expand выделите контуры со штриховой обводкой для разбора @@ -7853,6 +7870,8 @@ shape Open Открытый @msg No bridge of this width fits across the selected art Мостик такой ширины не помещается поперёк выделенной графики @msg Some islands could not be joined to the area around the art Некоторые островки не удалось соединить с областью вокруг графики @msg `width` must be from {lo} to {hi} pt `width` должно быть от {lo} до {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` должно быть от -180 до 180 градусов +@msg `roundness` must be from 1 to 100% `roundness` должно быть от 1 до 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` должно быть целым числом от 1 до {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Рамка и линии выборки… Weed Box and Lines Рамка и линии выборки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6817cb0608..f4277b7fd6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1423,6 +1423,7 @@ font-technology Variable Variabla Connect Data Points Förbind datapunkter Edge-to-Edge Lines Linjer från kant till kant Draw Filled Lines Rita fyllda linjer + Line Width Linjebredd Tick Values Skalstrecksvärden Override Calculated Values Åsidosätt beräknade värden Divisions Indelningar @@ -7478,6 +7479,22 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemensamma tangenter… + Common Tangents Gemensamma tangenter + Tangents Tangenter + Centerline Mittlinje + External Yttre + Internal Inre +@msg select two closed paths markera två slutna banor +@msg a selected path is open en markerad bana är öppen +@msg a selected path is not convex en markerad bana är inte konvex +@msg a selected path has no area en markerad bana har ingen yta +@msg a selected path has more than 10000 segments en markerad bana har fler än 10000 segment +@msg the two paths have the same outline de två banorna har samma kontur +@msg One path lies inside the other, so they have no common tangents Den ena banan ligger inuti den andra, så de har inga gemensamma tangenter +@msg The paths overlap, so they have no internal tangents Banorna överlappar, så de har inga inre tangenter +@msg One path lies inside the other, so they have no internal tangents Den ena banan ligger inuti den andra, så de har inga inre tangenter # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandera streck till banor @msg select paths with dashed strokes to expand markera banor med streckad kontur att expandera @@ -9217,6 +9234,8 @@ digits Hindi Hindi @msg No bridge of this width fits across the selected art Ingen brygga med den här bredden får plats över den markerade teckningen @msg Some islands could not be joined to the area around the art Vissa öar kunde inte förbindas med området runt teckningen @msg `width` must be from {lo} to {hi} pt `width` måste vara från {lo} till {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` måste vara från -180 till 180 grader +@msg `roundness` must be from 1 to 100% `roundness` måste vara från 1 till 100 % @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` måste vara ett heltal från 1 till {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Rensningsram och rensningslinjer… Weed Box and Lines Rensningsram och rensningslinjer diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ef5211d4e6..33a6584e3b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2851,6 +2851,36 @@ fn three_d_refusals_are_translated_in_every_complete_catalog() { assert!(missing.is_empty(), "{} 3D messages have no @msg row:\n{}", missing.len(), missing.join("\n")); } +/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`) and the Scissors' (`path.split` +/// `t`) show in every complete-message language with the key and the range numbers as given; the +/// error the command returns stays English. +#[test] +fn eraser_and_scissors_range_refusals_translate_with_their_values() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + let refusals = [ + ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "angle": 200}), "`angle`", ["-180", "180"]), + ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "roundness": 0}), "`roundness`", ["1", "100"]), + ("path.split", json!({"id": id, "segment": 0, "t": 1.5}), "`t`", ["0", "1"]), + ]; + for (cmd, p, key, numbers) in &refusals { + let e = s.execute(cmd, p).unwrap_err().to_string(); + assert!(e.starts_with(&format!("invalid parameters for `{cmd}`: ")) && e.contains(key) && e.contains(" must be from "), "{e}"); + assert_eq!(message(Lang::EN, &e), e); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &e); + assert!(!shown.contains(" must be from ") && shown.contains(&format!("`{cmd}`")) && shown.contains(key), "{code}: {e} -> {shown}"); + assert!(numbers.iter().all(|n| shown.contains(n)), "{code}: {e} -> {shown}"); + } + } + assert_eq!( + message(de(), &s.execute("path.eraseRegion", &json!({"points": [[10, 10], [60, 10]], "roundness": 101})).unwrap_err().to_string()), + "ungültige Parameter für `path.eraseRegion`: `roundness` muss zwischen 1 und 100 % liegen" + ); +} + /// A 3D effect's refusal shows in the interface language whole, with the effect's translated /// name, and with its numbers, the parameter keys it names and a symbol's name as given; the /// error the command returns stays English. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d507720b85..afd8cdce9a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1391,6 +1391,7 @@ font-technology Variable Değişken Connect Data Points Veri Noktalarını Bağla Edge-to-Edge Lines Kenardan Kenara Çizgiler Draw Filled Lines Dolgulu Çizgiler Çiz + Line Width Çizgi Genişliği Tick Values Onay İşareti Değerleri Override Calculated Values Hesaplanan Değerleri Geçersiz Kıl Divisions Bölümler @@ -9330,6 +9331,22 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Ortak Teğetler… + Common Tangents Ortak Teğetler + Tangents Teğetler + Centerline Merkez Çizgisi + External Dış + Internal İç +@msg select two closed paths iki kapalı yol seçin +@msg a selected path is open seçili bir yol açık +@msg a selected path is not convex seçili bir yol dışbükey değil +@msg a selected path has no area seçili bir yolun alanı yok +@msg a selected path has more than 10000 segments seçili bir yolun 10000'den fazla bölümü var +@msg the two paths have the same outline iki yolun ana hattı aynı +@msg One path lies inside the other, so they have no common tangents Bir yol diğerinin içinde, bu yüzden ortak teğetleri yok +@msg The paths overlap, so they have no internal tangents Yollar örtüşüyor, bu yüzden iç teğetleri yok +@msg One path lies inside the other, so they have no internal tangents Bir yol diğerinin içinde, bu yüzden iç teğetleri yok # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Tireleri Yollara Genişlet @msg select paths with dashed strokes to expand genişletilecek kesikli konturlu yolları seçin @@ -9631,6 +9648,8 @@ breakText Glyphs Glifler @msg No bridge of this width fits across the selected art Bu genişlikte bir köprü seçili çizime sığmıyor @msg Some islands could not be joined to the area around the art Bazı adalar çizimin çevresindeki alana bağlanamadı @msg `width` must be from {lo} to {hi} pt `width` {lo} ile {hi} pt arasında olmalıdır +@msg `angle` must be from -180 to 180 degrees `angle` -180 ile 180 derece arasında olmalıdır +@msg `roundness` must be from 1 to 100% `roundness` %1 ile %100 arasında olmalıdır @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 ile {MAX_BRIDGES_PER_ISLAND} arasında bir tam sayı olmalıdır Weed Box and Lines… Ayıklama Kutusu ve Çizgileri… Weed Box and Lines Ayıklama Kutusu ve Çizgileri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a45a5b51c1..682edcbd4b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1483,6 +1483,7 @@ file-filter Templates Шаблони Connect Data Points З'єднувати точки даних Edge-to-Edge Lines Лінії від краю до краю Draw Filled Lines Малювати заповнені лінії + Line Width Ширина лінії Tick Values Значення поділок Override Calculated Values Замінити обчислені значення Divisions Поділки @@ -7059,6 +7060,22 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Спільні дотичні… + Common Tangents Спільні дотичні + Tangents Дотичні + Centerline Осьова лінія + External Зовнішні + Internal Внутрішні +@msg select two closed paths виділіть два замкнені контури +@msg a selected path is open виділений контур відкритий +@msg a selected path is not convex виділений контур не опуклий +@msg a selected path has no area виділений контур не має площі +@msg a selected path has more than 10000 segments виділений контур містить понад 10000 сегментів +@msg the two paths have the same outline обидва контури мають однакову форму +@msg One path lies inside the other, so they have no common tangents Один контур лежить усередині іншого, тому вони не мають спільних дотичних +@msg The paths overlap, so they have no internal tangents Контури перекриваються, тому вони не мають внутрішніх дотичних +@msg One path lies inside the other, so they have no internal tangents Один контур лежить усередині іншого, тому вони не мають внутрішніх дотичних # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Розібрати штрихи на контури @msg select paths with dashed strokes to expand виділіть контури зі штриховим обведенням для розбору @@ -7476,6 +7493,8 @@ breakText Glyphs Гліфи @msg No bridge of this width fits across the selected art Місток такої ширини не вміщується впоперек виділеної графіки @msg Some islands could not be joined to the area around the art Деякі острівці не вдалося з’єднати з областю навколо графіки @msg `width` must be from {lo} to {hi} pt `width` має бути від {lo} до {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` має бути від -180 до 180 градусів +@msg `roundness` must be from 1 to 100% `roundness` має бути від 1 до 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` має бути цілим числом від 1 до {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Рамка й лінії вибірки… Weed Box and Lines Рамка й лінії вибірки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7fd6ab5d04..7cbc02163d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1739,6 +1739,7 @@ file-filter Templates Mẫu Connect Data Points Nối các điểm dữ liệu Edge-to-Edge Lines Đường từ mép đến mép Draw Filled Lines Vẽ đường tô đầy + Line Width Độ rộng đường Tick Values Giá trị vạch chia Override Calculated Values Ghi đè giá trị đã tính Divisions Số khoảng chia @@ -7089,6 +7090,22 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tiếp tuyến chung… + Common Tangents Tiếp tuyến chung + Tangents Tiếp tuyến + Centerline Đường tâm + External Ngoài + Internal Trong +@msg select two closed paths chọn hai đường dẫn khép kín +@msg a selected path is open một đường dẫn đã chọn đang mở +@msg a selected path is not convex một đường dẫn đã chọn không lồi +@msg a selected path has no area một đường dẫn đã chọn không có diện tích +@msg a selected path has more than 10000 segments một đường dẫn đã chọn có hơn 10000 đoạn +@msg the two paths have the same outline hai đường dẫn có cùng đường viền +@msg One path lies inside the other, so they have no common tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến chung +@msg The paths overlap, so they have no internal tangents Các đường dẫn chồng lên nhau, nên chúng không có tiếp tuyến trong +@msg One path lies inside the other, so they have no internal tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến trong # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Mở rộng nét đứt thành đường dẫn @msg select paths with dashed strokes to expand chọn các đường dẫn có nét đứt để mở rộng @@ -7403,6 +7420,8 @@ breakText Glyphs Glyph @msg No bridge of this width fits across the selected art Không có cầu nối nào rộng như vậy vừa với hình vẽ đã chọn @msg Some islands could not be joined to the area around the art Không thể nối một số đảo với vùng xung quanh hình vẽ @msg `width` must be from {lo} to {hi} pt `width` phải từ {lo} đến {hi} pt +@msg `angle` must be from -180 to 180 degrees `angle` phải từ -180 đến 180 độ +@msg `roundness` must be from 1 to 100% `roundness` phải từ 1 đến 100% @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` phải là số nguyên từ 1 đến {MAX_BRIDGES_PER_ISLAND} Weed Box and Lines… Khung và đường bóc phần thừa… Weed Box and Lines Khung và đường bóc phần thừa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 84c371c4c7..b445c6b44f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1418,6 +1418,7 @@ file-filter Templates 模板 Connect Data Points 连接数据点 Edge-to-Edge Lines 边到边线条 Draw Filled Lines 绘制填充线 + Line Width 线宽 Tick Values 刻度值 Override Calculated Values 覆盖计算值 Divisions 刻度数 @@ -7291,6 +7292,22 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 公切线… + Common Tangents 公切线 + Tangents 切线 + Centerline 中心线 + External 外部 + Internal 内部 +@msg select two closed paths 请选择两条闭合路径 +@msg a selected path is open 所选路径是开放的 +@msg a selected path is not convex 所选路径不是凸形 +@msg a selected path has no area 所选路径没有面积 +@msg a selected path has more than 10000 segments 所选路径的线段超过 10000 条 +@msg the two paths have the same outline 两条路径的轮廓相同 +@msg One path lies inside the other, so they have no common tangents 一条路径位于另一条之内,因此它们没有公切线 +@msg The paths overlap, so they have no internal tangents 路径相互重叠,因此它们没有内公切线 +@msg One path lies inside the other, so they have no internal tangents 一条路径位于另一条之内,因此它们没有内公切线 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 将短划线扩展为路径 @msg select paths with dashed strokes to expand 请选择要扩展的虚线描边路径 @@ -7589,6 +7606,8 @@ breakText Glyphs 字形 @msg No bridge of this width fits across the selected art 此宽度的连接桥无法放入所选图稿 @msg Some islands could not be joined to the area around the art 部分孤岛无法连接到图稿周围的区域 @msg `width` must be from {lo} to {hi} pt `width` 必须介于 {lo} 到 {hi} pt 之间 +@msg `angle` must be from -180 to 180 degrees `angle` 必须介于 -180 到 180 度之间 +@msg `roundness` must be from 1 to 100% `roundness` 必须介于 1 到 100% 之间 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必须是 1 到 {MAX_BRIDGES_PER_ISLAND} 之间的整数 Weed Box and Lines… 除废框和除废线… Weed Box and Lines 除废框和除废线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6b49436975..6f8e18baf0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1453,6 +1453,7 @@ file-filter Templates 範本 Connect Data Points 連接資料點 Edge-to-Edge Lines 邊到邊線條 Draw Filled Lines 繪製填色線條 + Line Width 線寬 Tick Values 刻度值 Override Calculated Values 覆寫計算值 Divisions 刻度數 @@ -7100,6 +7101,22 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 公切線… + Common Tangents 公切線 + Tangents 切線 + Centerline 中心線 + External 外部 + Internal 內部 +@msg select two closed paths 請選取兩條封閉路徑 +@msg a selected path is open 所選路徑是開放的 +@msg a selected path is not convex 所選路徑不是凸形 +@msg a selected path has no area 所選路徑沒有面積 +@msg a selected path has more than 10000 segments 所選路徑的線段超過 10000 條 +@msg the two paths have the same outline 兩條路徑的輪廓相同 +@msg One path lies inside the other, so they have no common tangents 一條路徑位於另一條之內,因此它們沒有公切線 +@msg The paths overlap, so they have no internal tangents 路徑互相重疊,因此它們沒有內公切線 +@msg One path lies inside the other, so they have no internal tangents 一條路徑位於另一條之內,因此它們沒有內公切線 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 將短破折號展開為路徑 @msg select paths with dashed strokes to expand 請選取要展開的虛線筆畫路徑 @@ -7398,6 +7415,8 @@ breakText Glyphs 字符 @msg No bridge of this width fits across the selected art 此寬度的連接橋無法放入所選圖稿 @msg Some islands could not be joined to the area around the art 部分孤島無法連接到圖稿周圍的區域 @msg `width` must be from {lo} to {hi} pt `width` 必須介於 {lo} 到 {hi} pt 之間 +@msg `angle` must be from -180 to 180 degrees `angle` 必須介於 -180 到 180 度之間 +@msg `roundness` must be from 1 to 100% `roundness` 必須介於 1 到 100% 之間 @msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必須是介於 1 到 {MAX_BRIDGES_PER_ISLAND} 的整數 Weed Box and Lines… 除廢框與除廢線… Weed Box and Lines 除廢框與除廢線 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index de2f3ab7a1..c30c1bfcbb 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -980,7 +980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index 3e3d51f8d6..727498c61c 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -684,8 +684,8 @@ fn a_key_anchor_is_chosen_named_and_aligned_to() { let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(); node.path_data().unwrap().anchors().map(|(_, _, a)| a.p.x).collect() }; - app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap(); - app.run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "toggle"})).unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + app.run("select.key", json!({"id": id, "anchor": [0, 2]})).unwrap(); let ctx = egui::Context::default(); let ([selection, key, _], left) = panel_buttons(&mut app, &ctx); assert_eq!((align_to(&app), chosen_align_to(&mut app, &ctx)), (AlignTo::Key, vec![key]), "chosen automatically"); diff --git a/docs/gaps.md b/docs/gaps.md index 425709e1ee..00b2a96f53 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -36,6 +36,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | | 2026-11-14 | minor | G12: Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu (Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol, Select All Instances), selecting the symbol first if unselected; scores and estimates unchanged. | @@ -125,7 +126,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. -- **Done (part of #4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. A Lab new color is kept, but can't be typed yet: the picker's Lab fields work in RGB, as for fill and stroke. **Missing:** Lab entry in the picker, swatch libraries in the picker and the row's right-click menu (Pick from Swatches, Limit to Library). +- **Done (#4028):** Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker, as the [public page](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html) describes. OK sets the row's new color in the model it was picked in, so a CMYK mix is no longer a hex value converted back; Cancel leaves the row. Lab color values can be typed directly in the Color Picker's Lab fields without converting to RGB. Swatch libraries are accessible in the picker via a library dropdown. Rows in the Recolor Artwork Assign tab feature a right-click context menu with "Pick from Swatches" (opening Color Picker in swatches view) and "Limit to Library" (with library submenu). - **Done (#3416):** Recolor Artwork Edit chips scroll to the last color while the heading, color wheel and actions stay visible. Screen resize and UI scaling, Preview, Confirm, Cancel, Undo and #1733 wheel drags are covered in `tests/recolor.rs`. No gap entry closed; estimates unchanged. diff --git a/docs/mcp.md b/docs/mcp.md index b31754a1d5..74ea95519a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2062,6 +2062,12 @@ were. `graph.setType` refuses `` `columnWidth` must be a number, not "50" `` for `` `type` must be a string `` for `type`, `valueAxis`, the three tick lengths, `prefix`, `suffix`, `rightPrefix`, `rightSuffix`, `pieLegend`, `piePosition` and `pieSort`; and `` `ticks` must be a number, not "5" `` (or `` `ticks` must be 0 or more `` for a negative number) for `ticks`, `rightTicks` and the three tick mark counts. +`lineWidth`, the Line Width of Draw Filled Lines in points (3 when the graph sets none), takes a number from 0.01 to +1000 (VectorCraft's own range); `"4"` is refused with `` `lineWidth` must be a number, not "4" ``, and a width below +0.01 or past 1000 with `` `lineWidth` must be from 0.01 to 1000 pt, not 0 ``. The graph stores a width only when it is +not 3, so a graph without one is saved and drawn as before. A graph with a width of its own is written to `.ai` as its +art, without the editable graph records. `graph.setType` with options that leave the graph as it is +records no undo step. `axisMin`, `axisMax`, `rightAxisMin` and `rightAxisMax` take a number, or null to go back to the value calculated from the data; any other value is refused with `` `axisMin` must be a number or null, not "10" ``. `graph.setData` and `graph.create` refuse a `csv` that is not a string, `series` or `categories` that are not lists, and `rows` that are not @@ -5947,6 +5953,12 @@ rotation that is neither a number nor null with `` `pressure` must be a number, (`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `at`, `in` or `out` that is not `[x, y]` with `` `in` must be [x, y] ``, naming the key. +`path.eraseRegion` refuses an `angle` outside -180° to 180° with `` `angle` must be from -180 to 180 degrees `` and a +`roundness` outside 1% to 100% with `` `roundness` must be from 1 to 100% ``. `path.split` refuses a `t` outside 0 to 1 +with `` `t` must be from 0 to 1 ``, with `segment` or with `anchor`. The document does not change and no undo step is +recorded. Left out or null, `angle` is 0° and `roundness` is 100%; left out, `t` is 0.5. The Eraser's ranges are +VectorCraft's own values. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and @@ -8929,6 +8941,18 @@ has the option as Preserve Text Editability {"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"preserveText":true}}} ``` +With or without layers, the file keeps the document's slices in image resource 1050, in version 6 of the slices +resource format of the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/). +`importSlices` reads that form, so the slices of an opened PSD file come back when the export is opened. The rest are +VectorCraft's own rules: + +- The user and object slices that reach into the exported artboard are written, each clipped to it, in its pixels, + at least one pixel each way. Auto slices aren't written; the document that opens the file lays them out again. +- An object slice is written as a user slice over its object's bounds. Each slice keeps its name, its type (Image + or No Image), its link, target, message, alternative text, cell text and background color. An HTML Text slice is + written as No Image with its type's text as HTML. Text alignment is written as the default. +- More than 10000 slices, a slice text longer than 65536 characters, or a slice without finite bounds is an error. + PSD files (`.psd`, and `.psb`, the large document format) place as their merged image, the flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution. @@ -11278,8 +11302,9 @@ A canvas-click dialog also has `preview` (initially on): tentative settings draw Object › Graph › Type… (`graph.setType` without params) and a double-click on a graph tool open Graph Type (dialog `graphType`) for the selected graph, or for the series picked in it with Group Selection. Its fields are the options `graph.setType {}` returns, under the command's names for them. `legend`, `pieLegend`, `piePosition`, `pieSort`, -`firstRowInFront`, `firstColumnInFront` and `filledLines` are held for every type, so a type picked in the dialog shows -the options it uses. `overrideValues` and `rightOverrideValues` are Override Calculated Values of the left (or only) +`firstRowInFront`, `firstColumnInFront`, `filledLines` and `lineWidth` are held for every type, so a type picked in the +dialog shows the options it uses. The Line Width field next to Draw Filled Lines is available only while Draw Filled +Lines and Connect Data Points are on. `overrideValues` and `rightOverrideValues` are Override Calculated Values of the left (or only) value axis and of the right one. While one is on, OK sends `axisMin`, `axisMax` and `ticks` (or `rightAxisMin`, `rightAxisMax` and `rightTicks`), and the dialog fills the ones the graph lacks with the values the axis would be calculated with for the type, value axis and Separate Scales the dialog shows. @@ -12369,6 +12394,26 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). +- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed + paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into + either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) + or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or + a path's center of area. Each tangent of paths that do not touch runs from where it touches the lower path to + where it touches the upper one; where a straight side of a path lies along the line, the line covers the whole + side. An ellipse drawn with the Ellipse tool, then moved, turned or scaled, is measured as an exact ellipse. Any + other path must be closed, have one outline, bend the same way all around and have at most 10,000 segments; an open + path, a path that bends inward, a path without area, a group, a compound path or type is refused, and so are two + paths whose outlines are the same to within the touching tolerance given below. Two separate paths have two + external and two internal tangents. Overlapping paths have external tangents only. A path inside the other has + none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point + where they touch and as long as the narrower path is wide along it. Paths that meet at a corner or along a shared + stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when + the gap between them is less than the tolerance, a billionth of the larger of their sizes and the distance between + their centers. The lines are stroked with the current stroke color and weight (black when the stroke is None), have + no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of + the kind asked for, nothing changes, and the result's `warning` says why. Common Tangents… + opens a dialog (Tangents, Centerline) with Preview. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; @@ -12382,6 +12427,7 @@ plain path from then on. {"name":"run_command","arguments":{"command":"addon.pathtools.crossings","params":{"cut":true}}} {"name":"run_command","arguments":{"command":"addon.pathtools.shape.create","params":{"kind":"star","center":[200,150],"width":120,"height":120,"count":7,"a":0.4}}} {"name":"run_command","arguments":{"command":"addon.pathtools.shape.set","params":{"id":14,"kind":"gear","count":16,"radius":2}}} +{"name":"run_command","arguments":{"command":"addon.pathtools.commonTangents","params":{"ids":[3,4],"tangents":"external","centerline":true}}} ``` ### Path Effects (live) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fbc1513c0f..909940215f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -620,6 +620,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -1205,6 +1206,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). + `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. @@ -1238,7 +1240,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. As VectorCraft's own rule, the axis lines and tick marks, and separately a radar graph's rings, keep the paint, weight, opacity and blend mode of their topmost fill and stroke rows and their object opacity and blend mode through the graph being drawn again after a paint, stroke weight, gradient, recolor, Appearance, Transparency or Graphic Styles edit, the Eyedropper, Swap Fill and Stroke or Default Fill and Stroke, the frontmost line of a kind setting what the kind keeps; the lines' dashes, caps, joins and arrowheads are not kept. An Appearance, Transparency (with a fill or stroke row) or Graphic Styles edit given the Axes group or the Legend group reaches the lines and labels in it and is kept the same way. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines at its Line Width (3 pt when none is set, 0.01 to 1000 pt), adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. As VectorCraft's own rule, the axis lines and tick marks, and separately a radar graph's rings, keep the paint, weight, opacity and blend mode of their topmost fill and stroke rows and their object opacity and blend mode through the graph being drawn again after a paint, stroke weight, gradient, recolor, Appearance, Transparency or Graphic Styles edit, the Eyedropper, Swap Fill and Stroke or Default Fill and Stroke, the frontmost line of a kind setting what the kind keeps; the lines' dashes, caps, joins and arrowheads are not kept. An Appearance, Transparency (with a fill or stroke row) or Graphic Styles edit given the Axes group or the Legend group reaches the lines and labels in it and is kept the same way. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are. What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. @@ -1932,6 +1934,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. + - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). @@ -2504,6 +2507,10 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Nest Shapes… (`addon.cutting.nest`) moves the selected objects close together onto a sheet or a roll of material ([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The rest is VectorCraft's own: the sheet is an artboard, or a set width and height from its top-left corner, and a roll is a set width with no end; a margin is kept inside the edges and a spacing between objects. Objects are packed by their bounding boxes, with or without strokes and effects (shadows, glows and blurs included), the tallest first, each where its bottom edge is highest and then furthest left; with Rotate an object may turn 90° where that places it higher or where only the turned object fits. Objects that do not fit go in a column to the right of the sheet, in stacking order. The command is one undo step, and its result gives the length of material used. The dialog has Preview. Tests: `cmd::addons::cutting::nest::tests` in `vectorcraft-engine`, `nest_shapes_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Nest Shapes. +## Path Precision Tools add-on: Common Tangents (2026-11-15) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4b107e9d3b..c4d7ed0cd4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -208,7 +208,7 @@ tools, never checked side by side) isn't captured row by row. | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | -| Align selected anchors to a key anchor | done | #1636; a Shift-click with Direct Selection makes the point it adds the key anchor, drawn as a larger filled square in a frame, and Align To shows Align to Key Anchor; Align moves the other points to it and Distribute with a spacing places them from it; `select.key {id, anchor}` | +| Align selected anchors to a key anchor | done | #1636; with multiple anchors selected via Direct Selection, clicking an already-selected anchor without modifiers designates it as the key anchor (or clears it if clicked again); drawn as a filled square with a distinct double outline; pressing Escape, clicking the canvas, or deselecting clears the key anchor; Align moves the other points to it and Distribute with a spacing places them from it; `select.key {id, anchor}` | | A ruler guide as the key object: a click on a guide selected with objects (or Align to Key Object with one object and a guide) makes it the key, drawn thicker; Align lines the objects (or selected anchors) up on it and the guide stays put | done | #2143; `select.key {guide}`; a vertical guide sets x only, a horizontal one y | | Distribute Objects and Distribute Spacing with a spacing from a key guide: the guide stays put and the other items are spaced the Distribute Spacing value from it, as from a key object with no size | done | Key guide from #3165; a vertical guide spaces the horizontal options, a horizontal one the vertical ones, and a guide along the axis leaves everything | | Distribute ruler guides: the Distribute Objects and Distribute Spacing buttons space the selected guides across the axis with the selected objects, as items with no size; two or more guides selected alone are enough | done | #1597 in part; guides alone: select them, choose Align to Artboard and click Horizontal (Vertical) Distribute Center for equal columns (rows) ([public forum answer, 2017](https://community.adobe.com/questions-652/illustrator-equal-guides-822924)); with objects: a guide on each artboard edge, included in the selection, keeps the outermost lines there ([public forum answer, 2025](https://www.signs101.com/threads/is-there-a-way-to-distribute-shapes-like-this-in-illustrator.179556/)); a guide has no width, so the three options of an axis are the same for it; guides along the axis stay | @@ -508,7 +508,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po - [x] Home screen (part of #4684, shared UI with PhotoCraft): the welcome, New / Open buttons and Community block are centred, and the large Discord button takes the theme's accent instead of Discord's colour; the layout and wording of the preset cards and Recent Files are unchanged. Still open from #4684: shortcut hints on the buttons, PhotoCraft's PRO and STUDIO themes, the Preferences layout (search box, theme swatches, Apply) and the title bar. -- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in (part of #4028); a Lab new color is kept but can't be typed yet (the picker's Lab fields work in RGB); Lab entry, swatch libraries and the row menu remain. +- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in, with native Lab entry, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). - [x] Recolor Artwork › Color Theme Picker: with the button beside the tabs on, a click on the canvas takes the color palette of an object or image, a drag takes the palette of the art inside its marquee, and Shift adds more picks; the rows that aren't excluded take the palette as their new colors and the art previews them ([Recolor artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-artwork.html)). The number and order of the picked colors are VectorCraft's own rule (`recolor.pickTheme`). Tests: `theme_picks_give_the_rows_the_palette_of_the_art_picked` and `the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas` in `crates/ui-egui/src/dialogs/recolor.rs`, `theme_picker_*` in `crates/engine/src/tests/recolor.rs`. @@ -670,6 +670,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-10-25 | minor | Selection tool: a double-click on a threaded port breaks the thread there (`text.thread.break`); scores and estimates unchanged | | 2026-10-25 | minor | A selected Grid Repeat shows handles: the one below the grid adds or removes rows, the one right of it columns, the one past its bottom-right corner both, and the sliders between the first two columns and rows set the horizontal and vertical spacing; each drag is one undo step and Escape cancels it (#2691); headless canvas and tool regressions; scores and estimates unchanged. | | 2026-10-25 | minor | Floating panels open in OS windows of their own on the desktop (inside the window on the web and on Wayland); saved layouts from earlier versions convert to the shared docking layout (#4135); scores and estimates unchanged (estimated) | +| 2026-10-25 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. | | 2026-10-25 | minor | Object › Expand… is dimmed for a selection with appearance attributes, with a tooltip to use Object › Expand Appearance first, so a stroked line with an effect expands to a stroked line before its stroke is outlined (#3089). Scores and estimates unchanged. | | 2026-10-25 | minor | Transform Each opens on the values it was last confirmed with (Copy aside) and has a Copy button left of Cancel instead of a Copy checkbox (#1732). Scores and estimates unchanged. | | 2026-10-25 | minor | Pathfinder panel › Pathfinder Options… opens a dialog with Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, which the panel's operations use (#3426); scores unchanged |