mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 13:22:18 +00:00
Merge remote-tracking branch 'origin/main' into feat/width-smooth-profile
# Conflicts: # docs/target-app-parity.md
This commit is contained in:
@@ -8,7 +8,6 @@ mod layers;
|
||||
mod profile;
|
||||
mod stroke_style;
|
||||
|
||||
pub(crate) use layers::HEAD_REACH;
|
||||
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
|
||||
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
|
||||
@@ -139,10 +139,6 @@ impl StrokeGradientMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
|
||||
/// cut square a little behind its 4 × 4 box).
|
||||
pub(crate) const HEAD_REACH: f64 = 4.6;
|
||||
|
||||
fn ten() -> f64 {
|
||||
10.0
|
||||
}
|
||||
@@ -188,7 +184,8 @@ impl StrokeLayer {
|
||||
}
|
||||
}
|
||||
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
|
||||
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
|
||||
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
|
||||
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
|
||||
pub fn arrow_weight(&self, end: bool) -> f64 {
|
||||
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
|
||||
(self.width * pct / 100.0).max(0.25)
|
||||
@@ -197,7 +194,7 @@ impl StrokeLayer {
|
||||
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
|
||||
pub fn head_reach(&self, end: bool) -> f64 {
|
||||
let head = if end { self.end_arrow } else { self.start_arrow };
|
||||
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
|
||||
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
|
||||
}
|
||||
/// How far the arrowheads can reach from the path's end points (0 without heads).
|
||||
pub fn arrow_reach(&self) -> f64 {
|
||||
|
||||
@@ -49,6 +49,10 @@ impl Dash {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight
|
||||
/// (the open arrow's arms are cut square a little behind the box).
|
||||
const HEAD_REACH: f64 = 4.6;
|
||||
|
||||
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Arrowhead {
|
||||
@@ -94,13 +98,18 @@ pub enum Arrowhead {
|
||||
Kite,
|
||||
TriangleBar,
|
||||
Oval,
|
||||
/// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or
|
||||
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
|
||||
/// the other heads.
|
||||
LineArrow,
|
||||
}
|
||||
|
||||
impl Arrowhead {
|
||||
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
|
||||
pub const ALL: [Arrowhead; 40] = [
|
||||
pub const ALL: [Arrowhead; 41] = [
|
||||
Arrowhead::Arrow,
|
||||
Arrowhead::ArrowOpen,
|
||||
Arrowhead::LineArrow,
|
||||
Arrowhead::Barbed,
|
||||
Arrowhead::Concave,
|
||||
Arrowhead::DoubleArrow,
|
||||
@@ -141,6 +150,22 @@ impl Arrowhead {
|
||||
Arrowhead::Fork,
|
||||
];
|
||||
|
||||
/// How far any part of the head can be from its tip, in units of its weight.
|
||||
pub fn reach(self) -> f64 {
|
||||
match self {
|
||||
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
|
||||
Arrowhead::LineArrow => 5.75,
|
||||
_ => HEAD_REACH,
|
||||
}
|
||||
}
|
||||
/// How far the head spreads either side of its line, in units of its weight.
|
||||
pub fn half_width(self) -> f64 {
|
||||
match self {
|
||||
Arrowhead::LineArrow => 4.0,
|
||||
_ => 2.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name the arrowhead menus show.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
@@ -184,6 +209,7 @@ impl Arrowhead {
|
||||
Arrowhead::Kite => "Kite",
|
||||
Arrowhead::TriangleBar => "Triangle to Bar",
|
||||
Arrowhead::Oval => "Oval",
|
||||
Arrowhead::LineArrow => "Line Arrow",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,7 +292,7 @@ fn profile_presets_round_trip_their_ids() {
|
||||
#[test]
|
||||
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
// Saved files store these names: they may only ever be appended to.
|
||||
const SAVED: [&str; 40] = [
|
||||
const SAVED: [&str; 41] = [
|
||||
"Triangle",
|
||||
"TriangleOpen",
|
||||
"Circle",
|
||||
@@ -333,6 +333,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
"Kite",
|
||||
"TriangleBar",
|
||||
"Oval",
|
||||
"LineArrow",
|
||||
];
|
||||
for name in SAVED {
|
||||
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
|
||||
@@ -366,9 +367,15 @@ fn outset_covers_arrowheads() {
|
||||
st.arrow_scale = (100.0, 200.0);
|
||||
assert_eq!(st.arrow_weight(false), 4.0);
|
||||
assert_eq!(st.arrow_weight(true), 8.0);
|
||||
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
|
||||
let reach = Arrowhead::Triangle.reach();
|
||||
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0));
|
||||
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
|
||||
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
|
||||
assert_eq!(a.outset(), reach * 8.0 + 2.0);
|
||||
// The line arrow's arms spread twice as wide, so it reaches further from its tip.
|
||||
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow);
|
||||
assert!(Arrowhead::LineArrow.reach() > reach);
|
||||
assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0);
|
||||
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle);
|
||||
a.stroke_mut().unwrap().width = 0.01;
|
||||
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{Arc, Deserialize, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip};
|
||||
use super::{Arc, Deserialize, LayerColor, Node, NodeId, Rect, Serialize, SymbolBoxes, skip};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Artboard {
|
||||
@@ -39,6 +39,18 @@ pub struct Artboard {
|
||||
/// it behind the art ([`super::Document::with_artboard_fills`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<vectorcraft_color::Color>,
|
||||
/// Guide label (Artboard Options): the color the canvas draws the artboard's own ruler guides
|
||||
/// in (a guide whose [`super::Guide::artboard`] is this artboard's id), a [`LayerColor`] preset
|
||||
/// or a custom RGB. None (No label) draws them in the guide color preference, as canvas guides
|
||||
/// are. Only the canvas uses it: the paper, exports and print don't. Written only when set; a
|
||||
/// file's preset outside [`super::LAYER_COLORS`] reads as no label.
|
||||
#[serde(default, deserialize_with = "label_within_palette", skip_serializing_if = "Option::is_none")]
|
||||
pub guide_label: Option<LayerColor>,
|
||||
}
|
||||
|
||||
/// A file's guide label: a preset index outside [`super::LAYER_COLORS`] reads as no label.
|
||||
fn label_within_palette<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<LayerColor>, D::Error> {
|
||||
Ok(Option::<LayerColor>::deserialize(d)?.filter(|c| !matches!(c, LayerColor::Preset(i) if usize::from(*i) >= super::LAYER_COLORS.len())))
|
||||
}
|
||||
|
||||
/// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times
|
||||
@@ -192,12 +204,7 @@ impl LockedArtboards<'_> {
|
||||
/// [`LockedArtboards::holds`] for new art too: is `n` on a locked artboard, whether or not it
|
||||
/// is new art?
|
||||
pub fn overlaps(&self, n: &Node) -> bool {
|
||||
if self.rects.is_empty()
|
||||
|| !n.visible
|
||||
|| n.is_layer()
|
||||
|| matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| self.pattern_art.contains(&n.id)
|
||||
{
|
||||
if self.rects.is_empty() || !n.visible || n.is_layer() || n.is_guide() || self.pattern_art.contains(&n.id) {
|
||||
return false;
|
||||
}
|
||||
if let Some(held) = self.held.borrow().get(&n.id) {
|
||||
|
||||
@@ -123,6 +123,24 @@ fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
|
||||
/// to `dropped`. Only layers holding one are copied.
|
||||
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
|
||||
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
|
||||
}
|
||||
if !holds(layer, out) {
|
||||
return;
|
||||
}
|
||||
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
|
||||
let before = children.len();
|
||||
children.retain(|c| !out(c));
|
||||
*dropped += before - children.len();
|
||||
for c in children.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop_guides(c, out, dropped);
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Remove what a read file has beyond the canvas ([`MAX_COORD`], or not finite): objects
|
||||
/// (see [`BeyondCanvas::objects`]; a top-level layer clipping by a path beyond it is emptied
|
||||
@@ -141,8 +159,9 @@ impl Document {
|
||||
for c in children.iter() {
|
||||
layers_in(c, &mut layers);
|
||||
}
|
||||
gone.objects += children.len();
|
||||
children.clear();
|
||||
// The layer's own ruler guides stay; only its art goes.
|
||||
gone.objects += children.iter().filter(|c| !c.is_ruler_guide()).count();
|
||||
children.retain(|c| c.is_ruler_guide());
|
||||
*clip = false;
|
||||
}
|
||||
} else {
|
||||
@@ -161,9 +180,18 @@ impl Document {
|
||||
self.retire_artboard_id(*id);
|
||||
}
|
||||
gone.artboards = removed.len();
|
||||
let guides = self.guides.len();
|
||||
self.guides.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
|
||||
gone.guides = guides - self.guides.len();
|
||||
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
|
||||
let guides = self.saved_guides.len();
|
||||
self.saved_guides
|
||||
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
|
||||
gone.guides = guides - self.saved_guides.len();
|
||||
let out = |n: &Node| match n.kind {
|
||||
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
|
||||
_ => false,
|
||||
};
|
||||
for layer in &mut self.layers {
|
||||
drop_guides(layer, &out, &mut gone.guides);
|
||||
}
|
||||
if !(in_range(self.ruler_origin.x) && in_range(self.ruler_origin.y)) {
|
||||
self.ruler_origin = Point::ZERO;
|
||||
gone.ruler_origin = true;
|
||||
@@ -232,12 +260,18 @@ mod tests {
|
||||
let far = Artboard { id: 9, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() };
|
||||
d.artboards.push(far);
|
||||
let guide = |pos: f64, artboard| Guide { artboard, ..Guide::new(false, pos) };
|
||||
d.guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))];
|
||||
d.saved_guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))];
|
||||
d.ruler_origin = Point::new(1e17, 0.0);
|
||||
// The same guides as nodes, as a document has them once read.
|
||||
let mut nodes = d.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 4);
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!(gone, BeyondCanvas { objects: 0, artboards: 1, guides: 3, ruler_origin: true });
|
||||
assert_eq!(d.artboards.len(), 1);
|
||||
assert_eq!(d.guides, [guide(50.0, None)], "the far artboard's own guide goes with it");
|
||||
assert_eq!(d.saved_guides, [guide(50.0, None)], "the far artboard's own guide goes with it");
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone);
|
||||
let left: Vec<(bool, f64, Option<u32>)> = nodes.ruler_guides().iter().map(|g| (g.vertical, g.pos, g.artboard)).collect();
|
||||
assert_eq!(left, [(false, 50.0, None)]);
|
||||
assert_eq!(d.ruler_origin, Point::ZERO);
|
||||
assert_eq!(
|
||||
gone.note().unwrap(),
|
||||
@@ -310,7 +344,8 @@ mod tests {
|
||||
let probe = Document::new(1.0, 1.0);
|
||||
let sub = sublayer(&probe, 40, vec![rect(41, 1e17), rect(42, 0.0)], true);
|
||||
let mut d = doc(vec![rect(10, 0.0), rect(11, 1e17), sub]);
|
||||
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_guides =
|
||||
vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
|
||||
d.assets = vec![
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
|
||||
@@ -320,7 +355,7 @@ mod tests {
|
||||
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!((gone.objects, gone.guides), (2, 1), "the far rectangle, the clipping sublayer and its layer guide");
|
||||
assert_eq!(d.guides.len(), 1, "the guide of a layer that stays, stays");
|
||||
assert_eq!(d.saved_guides.len(), 1, "the guide of a layer that stays, stays");
|
||||
assert_eq!(d.saved_selections[0].objects, [NodeId(10)]);
|
||||
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
|
||||
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
|
||||
|
||||
@@ -132,7 +132,7 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
out.push(a);
|
||||
continue;
|
||||
}
|
||||
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
let clip = n.clips();
|
||||
let (visible, locked) = (n.visible, n.locked);
|
||||
let mut held = n.children_mut().map(std::mem::take).unwrap_or_default();
|
||||
if clip && !held.is_empty() {
|
||||
@@ -148,6 +148,13 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
// What it held takes its place, and is looked at in its turn.
|
||||
left.extend(held.into_iter().rev());
|
||||
}
|
||||
// The ruler guides of a sublayer merged into its parent layer go above the parent's art, with
|
||||
// the parent's own.
|
||||
if out.iter().any(|c| c.is_ruler_guide()) {
|
||||
let (guides, art): (Vec<_>, Vec<_>) = out.into_iter().partition(|c| c.is_ruler_guide());
|
||||
out = art;
|
||||
out.extend(guides);
|
||||
}
|
||||
*nodes = out;
|
||||
true
|
||||
}
|
||||
|
||||
+436
-15
@@ -1,7 +1,7 @@
|
||||
//! Persistent dimension recipes. Children are ordinary paths and type for all renderers/exporters.
|
||||
use crate::{Document, NodeId, Unit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Vec2};
|
||||
|
||||
/// What a dimension measures.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -25,6 +25,17 @@ impl DimensionMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction a linear dimension measures in: along the line through its two points, or only
|
||||
/// their horizontal or vertical distance.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Orientation {
|
||||
#[default]
|
||||
Aligned,
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
/// The unit a length is labelled in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -295,6 +306,12 @@ pub enum DimensionSource {
|
||||
a: Option<PointRef>,
|
||||
b: Option<PointRef>,
|
||||
vertex: Option<PointRef>,
|
||||
/// The first point when it is not an anchor, held against a path's anchors.
|
||||
#[serde(default, rename = "freeA", skip_serializing_if = "Option::is_none")]
|
||||
free_a: Option<FreePoint>,
|
||||
/// The second point when it is not an anchor.
|
||||
#[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")]
|
||||
free_b: Option<FreePoint>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -304,7 +321,11 @@ impl DimensionSource {
|
||||
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
|
||||
Self::Angle { first, second } => vec![first.node, second.node],
|
||||
Self::Circle { node } => vec![*node],
|
||||
Self::Points { a, b, vertex } => [a, b, vertex].into_iter().filter_map(|p| p.as_ref().map(|r| r.node)).collect(),
|
||||
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
|
||||
.into_iter()
|
||||
.filter_map(|p| p.as_ref().map(|r| r.node))
|
||||
.chain([free_a, free_b].into_iter().filter_map(|p| p.as_ref().map(FreePoint::node)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
/// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle
|
||||
@@ -321,6 +342,34 @@ impl DimensionSource {
|
||||
old.is_some() && old != counts(after)
|
||||
})
|
||||
}
|
||||
/// The map that took the measured art from `before` to `after`, when every path it measures
|
||||
/// went through one [`art_transform`] that reflects it (a negative determinant). None when a
|
||||
/// measured path is unchanged, or when two of them went through different maps.
|
||||
pub fn reflection(&self, before: &Document, after: &Document) -> Option<Affine> {
|
||||
let mut first: Option<Affine> = None;
|
||||
for id in self.nodes() {
|
||||
let (old, new) = (before.node(id)?, after.node(id)?);
|
||||
if std::ptr::eq(old, new) || old.path_data() == new.path_data() {
|
||||
return None;
|
||||
}
|
||||
let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?;
|
||||
match first {
|
||||
None => first = Some(xf),
|
||||
Some(f) => {
|
||||
// The linear parts and the translations, each against its own size.
|
||||
let (a, b) = (f.as_coeffs(), xf.as_coeffs());
|
||||
let differ = |range: std::ops::Range<usize>, tolerance: f64| {
|
||||
let size = a[range.clone()].iter().map(|c| c.abs()).fold(1.0, f64::max);
|
||||
a[range.clone()].iter().zip(&b[range]).any(|(p, q)| (p - q).abs() > tolerance * size)
|
||||
};
|
||||
if differ(0..4, 1e-9) || differ(4..6, 1e-9) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
first
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -337,6 +386,235 @@ impl PointRef {
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of an anchor that an [`AnchorWeight`] names: the anchor, or one of its handles.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AnchorPart {
|
||||
#[default]
|
||||
Point,
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
|
||||
impl AnchorPart {
|
||||
fn of(self, a: &Anchor) -> Point {
|
||||
match self {
|
||||
Self::Point => a.p,
|
||||
Self::In => a.h_in,
|
||||
Self::Out => a.h_out,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One anchor's share of a [`FreePoint`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AnchorWeight {
|
||||
pub subpath: usize,
|
||||
pub anchor: usize,
|
||||
/// The anchor itself, or its in or out handle.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub part: AnchorPart,
|
||||
pub weight: f64,
|
||||
}
|
||||
|
||||
/// A measured point that is not an anchor (a point on a segment, or a point a Smart Guide gave),
|
||||
/// linked to one path so that it moves with it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum FreePoint {
|
||||
/// A point on a segment at curve parameter `t`, 0 at the segment's first anchor and 1 at its
|
||||
/// last. It stays on the segment when the segment's anchors or handles are edited.
|
||||
OnSegment { edge: SegmentRef, t: f64 },
|
||||
/// A weighted sum of two or three anchors or handles of one path, the weights adding up to 1,
|
||||
/// plus `across` times the vector from the first anchor to the second turned a quarter turn,
|
||||
/// from (x, y) to (-y, x), so that a vector pointing right in the y-down document space
|
||||
/// turns to point down (two anchors only). When the
|
||||
/// path is moved, scaled, rotated, reflected or sheared, a point held by three moves with
|
||||
/// it. A point held by two and `across`, beside a straight path, moves, turns and scales
|
||||
/// uniformly with it, and a reflection or a non-uniform scale moves it as a half turn or a
|
||||
/// uniform scale would.
|
||||
Anchors {
|
||||
node: NodeId,
|
||||
anchors: Vec<AnchorWeight>,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
across: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// A point of a path: (subpath, anchor, part, place).
|
||||
type PathPoint = (usize, usize, AnchorPart, Point);
|
||||
|
||||
/// Every anchor of `path` in order, each followed by its in and out handles when `handles` is set.
|
||||
fn path_points(path: &PathData, handles: bool) -> impl Iterator<Item = PathPoint> + Clone + '_ {
|
||||
let parts: &'static [AnchorPart] = if handles { &[AnchorPart::Point, AnchorPart::In, AnchorPart::Out] } else { &[AnchorPart::Point] };
|
||||
path.subpaths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(move |(si, sp)| sp.anchors.iter().enumerate().flat_map(move |(ai, a)| parts.iter().map(move |&part| (si, ai, part, part.of(a)))))
|
||||
}
|
||||
|
||||
/// Three points that span `points`: the first, the one farthest from it, and the one farthest
|
||||
/// from the line through those two. None when every point is in one place.
|
||||
fn spanning(points: impl Iterator<Item = PathPoint> + Clone) -> Option<[PathPoint; 3]> {
|
||||
let first = points.clone().next()?;
|
||||
let o = first.3;
|
||||
let second = points.clone().max_by(|x, y| x.3.distance(o).total_cmp(&y.3.distance(o)))?;
|
||||
let u = second.3 - o;
|
||||
let span = u.hypot();
|
||||
if !span.is_finite() || span <= 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let third = points.max_by(|x, y| u.cross(x.3 - o).abs().total_cmp(&u.cross(y.3 - o).abs()))?;
|
||||
Some([first, second, third])
|
||||
}
|
||||
|
||||
/// The map that takes the anchors and handles of path `node` in `before` to where they are in
|
||||
/// `after`, when one affine map does that for every one of them: the path was moved, scaled,
|
||||
/// rotated, reflected or sheared as a whole. None when its anchors changed in number, moved in
|
||||
/// another way, or lie on one line with all their handles, as on a straight line: a reflection
|
||||
/// across a line through such a path puts its points where a turn can put them too.
|
||||
pub fn art_transform(before: &Document, after: &Document, node: NodeId) -> Option<Affine> {
|
||||
fitted(before, after, node, |_| true)
|
||||
}
|
||||
|
||||
/// [`art_transform`] when the map passes `wanted`. The map is found from three points, and
|
||||
/// `wanted` is asked before every other point is checked against it.
|
||||
fn fitted(before: &Document, after: &Document, node: NodeId, wanted: impl Fn(&Affine) -> bool) -> Option<Affine> {
|
||||
let (old, new) = (before.node(node)?.path_data()?, after.node(node)?.path_data()?);
|
||||
if old.subpaths.len() != new.subpaths.len() || old.subpaths.iter().zip(&new.subpaths).any(|(o, n)| o.anchors.len() != n.anchors.len()) {
|
||||
return None;
|
||||
}
|
||||
let [o, f, g] = spanning(path_points(old, true))?;
|
||||
let place = |q: PathPoint| new.subpaths.get(q.0).and_then(|sp| sp.anchors.get(q.1)).map(|a| q.2.of(a));
|
||||
let (o2, f2, g2) = (place(o)?, place(f)?, place(g)?);
|
||||
let (u, v) = (f.3 - o.3, g.3 - o.3);
|
||||
let span = u.hypot();
|
||||
if u.cross(v).abs() <= 1e-9 * span * span {
|
||||
return None;
|
||||
}
|
||||
let basis = |u: Vec2, v: Vec2| Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]);
|
||||
let linear = basis(f2 - o2, g2 - o2) * basis(u, v).inverse();
|
||||
let xf = Affine::translate(o2.to_vec2()) * linear * Affine::translate(-o.3.to_vec2());
|
||||
if !xf.as_coeffs().iter().all(|c| c.is_finite()) || !wanted(&xf) {
|
||||
return None;
|
||||
}
|
||||
let tolerance = 1e-6 * span.max(1.0);
|
||||
path_points(old, true).zip(path_points(new, true)).all(|(o, n)| (xf * o.3).distance(n.3) <= tolerance).then_some(xf)
|
||||
}
|
||||
|
||||
impl FreePoint {
|
||||
/// Largest weight: a point far outside the anchors that hold it is not held.
|
||||
const MAX_WEIGHT: f64 = 1e4;
|
||||
|
||||
/// The path it is linked to.
|
||||
pub fn node(&self) -> NodeId {
|
||||
match self {
|
||||
Self::OnSegment { edge, .. } => edge.node,
|
||||
Self::Anchors { node, .. } => *node,
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` held against path `node`: three anchors that span the path; when all its anchors lie
|
||||
/// on one line or in one place, as on an arch, three of its anchors and handles; when its
|
||||
/// handles lie on that line too, or so nearly that the weights would be too large, two anchors
|
||||
/// and `p`'s distance across that line. None when none of these holds `p`.
|
||||
pub fn on(doc: &Document, node: NodeId, p: Point) -> Option<Self> {
|
||||
let path = doc.node(node)?.path_data()?;
|
||||
let weight = |(subpath, anchor, part, _): PathPoint, weight| AnchorWeight { subpath, anchor, part, weight };
|
||||
for handles in [false, true] {
|
||||
let Some([o, f, g]) = spanning(path_points(path, handles)) else { continue };
|
||||
let (u, v) = (f.3 - o.3, g.3 - o.3);
|
||||
let span = u.hypot();
|
||||
let det = u.cross(v);
|
||||
if det.abs() > 1e-9 * span * span {
|
||||
let s = (p - o.3).cross(v) / det;
|
||||
let t = u.cross(p - o.3) / det;
|
||||
let anchors = vec![weight(o, 1.0 - s - t), weight(f, s), weight(g, t)];
|
||||
// A nearly flat set of points gives weights too large to keep: the next fit is tried.
|
||||
if let Some(held) = (Self::Anchors { node, anchors, across: 0.0 }).holding(doc, p, span) {
|
||||
return Some(held);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every anchor and handle on one line, or nearly: along it from the first anchor, and across it.
|
||||
let [o, f, _] = spanning(path_points(path, false))?;
|
||||
let u = f.3 - o.3;
|
||||
let span = u.hypot();
|
||||
let (t, across) = ((p - o.3).dot(u) / (span * span), u.cross(p - o.3) / (span * span));
|
||||
Self::Anchors { node, anchors: vec![weight(o, 1.0 - t), weight(f, t)], across }.holding(doc, p, span)
|
||||
}
|
||||
|
||||
/// `p` on the segment `edge`, at the curve parameter of the segment's point nearest to it.
|
||||
/// None when the segment is gone or `p` is not on it.
|
||||
pub fn on_segment(doc: &Document, edge: &SegmentRef, p: Point) -> Option<Self> {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?;
|
||||
if edge.segment >= sp.segment_count() {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = edge.endpoints(doc)?;
|
||||
let t = sp.segment(edge.segment).nearest(p, 1e-12).t;
|
||||
Self::OnSegment { edge: edge.clone(), t }.holding(doc, p, a.distance(b))
|
||||
}
|
||||
|
||||
/// Itself when it is [`Self::valid`] and puts the point at `p`, within a tolerance that grows
|
||||
/// with `span`, the size of the art that holds it.
|
||||
fn holding(self, doc: &Document, p: Point, span: f64) -> Option<Self> {
|
||||
let at = self.position(doc)?;
|
||||
(at.distance(p) <= 1e-6 * span.max(1.0)).then_some(self)
|
||||
}
|
||||
|
||||
/// Whether its numbers can be used: a finite `t` from 0 to 1 on a segment; or two or three
|
||||
/// weights that add up to 1, with `across` set only for two, each finite and at most
|
||||
/// [`Self::MAX_WEIGHT`] across.
|
||||
pub fn valid(&self) -> bool {
|
||||
match self {
|
||||
Self::OnSegment { t, .. } => (0.0..=1.0).contains(t),
|
||||
Self::Anchors { anchors, across, .. } => {
|
||||
(2..=3).contains(&anchors.len())
|
||||
&& anchors.iter().all(|w| w.weight.is_finite() && w.weight.abs() <= Self::MAX_WEIGHT)
|
||||
&& (anchors.iter().map(|w| w.weight).sum::<f64>() - 1.0).abs() <= 1e-9
|
||||
&& across.is_finite()
|
||||
&& across.abs() <= Self::MAX_WEIGHT
|
||||
&& (*across == 0.0 || anchors.len() == 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the point is now. None when its segment or an anchor is gone or the point is not
|
||||
/// [`Self::valid`].
|
||||
pub fn position(&self, doc: &Document) -> Option<Point> {
|
||||
use vectorcraft_geom::kurbo::ParamCurve;
|
||||
if !self.valid() {
|
||||
return None;
|
||||
}
|
||||
let at = match self {
|
||||
Self::OnSegment { edge, t } => {
|
||||
let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?;
|
||||
if edge.segment >= sp.segment_count() {
|
||||
return None;
|
||||
}
|
||||
sp.segment(edge.segment).eval(*t)
|
||||
}
|
||||
Self::Anchors { node, anchors, across } => {
|
||||
let path = doc.node(*node)?.path_data()?;
|
||||
let place = |w: &AnchorWeight| path.subpaths.get(w.subpath).and_then(|sp| sp.anchors.get(w.anchor)).map(|a| w.part.of(a).to_vec2());
|
||||
let mut at = Vec2::ZERO;
|
||||
for w in anchors {
|
||||
at += place(w)? * w.weight;
|
||||
}
|
||||
if *across != 0.0 {
|
||||
let u = place(anchors.get(1)?)? - place(anchors.first()?)?;
|
||||
at += Vec2::new(-u.y, u.x) * *across;
|
||||
}
|
||||
at.to_point()
|
||||
}
|
||||
};
|
||||
(at.x.is_finite() && at.y.is_finite()).then_some(at)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Dimension {
|
||||
@@ -349,6 +627,10 @@ pub struct Dimension {
|
||||
pub length: f64,
|
||||
pub options: DimensionOptions,
|
||||
pub source: Option<DimensionSource>,
|
||||
/// What a linear dimension measures: the distance between its points (aligned), or only its
|
||||
/// horizontal or vertical part. Other modes ignore it.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub orientation: Orientation,
|
||||
/// How far a linked dimension was moved on its own since the last refresh: the refresh turns
|
||||
/// it into a new placement unless the measured art moved too.
|
||||
#[serde(skip)]
|
||||
@@ -359,16 +641,137 @@ impl Dimension {
|
||||
/// A point on the drawn dimension line (linear), arc (angular) or radius line.
|
||||
pub fn handle(&self) -> Point {
|
||||
match self.mode {
|
||||
DimensionMode::Linear => self.a.midpoint(self.b) + self.normal() * self.offset,
|
||||
DimensionMode::Linear => {
|
||||
let (a, b) = self.line_ends();
|
||||
a.midpoint(b)
|
||||
}
|
||||
DimensionMode::Angular => self.vertex + self.bisector() * self.offset.abs().max(12.0),
|
||||
DimensionMode::Radius | DimensionMode::Diameter => self.b,
|
||||
}
|
||||
}
|
||||
/// The left normal of a → b.
|
||||
/// The unit direction a linear dimension measures along: a → b when aligned, else the x axis
|
||||
/// (horizontal) or the y axis (vertical), whichever way the points lie.
|
||||
pub fn direction(&self) -> Vec2 {
|
||||
match self.orientation {
|
||||
Orientation::Horizontal if self.mode == DimensionMode::Linear => Vec2::new(1.0, 0.0),
|
||||
Orientation::Vertical if self.mode == DimensionMode::Linear => Vec2::new(0.0, 1.0),
|
||||
_ => {
|
||||
let u = self.b - self.a;
|
||||
let len = u.hypot();
|
||||
if len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The left normal of [`Self::direction`].
|
||||
pub fn normal(&self) -> Vec2 {
|
||||
let u = self.b - self.a;
|
||||
let len = u.hypot();
|
||||
if len > 1e-9 { Vec2::new(-u.y, u.x) / len } else { Vec2::new(0.0, 1.0) }
|
||||
let u = self.direction();
|
||||
Vec2::new(-u.y, u.x)
|
||||
}
|
||||
/// The length a linear dimension shows: the distance between its points along
|
||||
/// [`Self::direction`].
|
||||
pub fn measured(&self) -> f64 {
|
||||
(self.b - self.a).dot(self.direction()).abs()
|
||||
}
|
||||
/// The two ends of a linear dimension's line: the measured points moved onto one line along
|
||||
/// [`Self::direction`], `offset` from a along the normal.
|
||||
pub fn line_ends(&self) -> (Point, Point) {
|
||||
let (u, n) = (self.direction(), self.normal());
|
||||
let a = self.a + n * self.offset;
|
||||
(a, a + u * (self.b - self.a).dot(u))
|
||||
}
|
||||
/// A horizontal or vertical dimension whose points moved from `old`'s keeps its line as far
|
||||
/// outside them as it was, on the same side: the gap is measured from the outermost point
|
||||
/// on the line's side, so the line stays clear of art that turns. A line that lay between
|
||||
/// the two points keeps its distance from the first point.
|
||||
pub fn keep_gap(&mut self, old: &Dimension) {
|
||||
if self.mode != DimensionMode::Linear
|
||||
|| self.orientation == Orientation::Aligned
|
||||
|| old.orientation != self.orientation
|
||||
|| (self.a, self.b) == (old.a, old.b)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let line = across(old.a) + old.offset;
|
||||
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
|
||||
let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let at = if line >= high {
|
||||
new_high + (line - high)
|
||||
} else if line <= low {
|
||||
new_low + (line - low)
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
let offset = at - across(self.a);
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
}
|
||||
/// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes
|
||||
/// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far
|
||||
/// past the outermost point on that side as `old`'s line was. A line that lay between the two
|
||||
/// points is left as it is.
|
||||
pub fn mirror_line(&mut self, old: &Dimension, image: Point) {
|
||||
if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear {
|
||||
return;
|
||||
}
|
||||
let gap = {
|
||||
let n = old.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let line = across(old.a) + old.offset;
|
||||
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
|
||||
if line >= high {
|
||||
line - high
|
||||
} else if line <= low {
|
||||
low - line
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap };
|
||||
let offset = at - across(self.a);
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
}
|
||||
/// Whether a linear dimension's line lies strictly between its two points along the normal.
|
||||
fn line_between_points(&self) -> bool {
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let line = across(self.a) + self.offset;
|
||||
across(self.a).min(across(self.b)) < line && line < across(self.a).max(across(self.b))
|
||||
}
|
||||
/// Makes a linear dimension measure in `orientation`, with its line on the side of the points
|
||||
/// it was on. The line goes through the middle of the old line when that point lies outside
|
||||
/// the two points along the new normal; otherwise it lies as far past the outermost point on
|
||||
/// that side as the old line lay from its points.
|
||||
pub fn set_orientation(&mut self, orientation: Orientation) {
|
||||
if self.mode != DimensionMode::Linear || self.orientation == orientation {
|
||||
self.orientation = orientation;
|
||||
return;
|
||||
}
|
||||
let (handle, gap) = (self.handle(), self.offset.abs());
|
||||
self.orientation = orientation;
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let h = across(handle);
|
||||
let at = if h >= high || h <= low {
|
||||
h
|
||||
} else if 2.0 * h >= low + high {
|
||||
high + gap
|
||||
} else {
|
||||
low - gap
|
||||
};
|
||||
let offset = at - across(self.a);
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
self.length = self.measured();
|
||||
}
|
||||
fn bisector(&self) -> Vec2 {
|
||||
let start = (self.a - self.vertex).atan2();
|
||||
@@ -397,28 +800,46 @@ impl Dimension {
|
||||
self.moved = Some((xf * at) - at + self.moved.unwrap_or_default());
|
||||
return;
|
||||
}
|
||||
// A horizontal or vertical dimension keeps measuring along its axis, between the points
|
||||
// where they now are, and its line goes through where the transform puts it. When that
|
||||
// puts the line between the points (a quarter turn), the line keeps its gap from them.
|
||||
let before = (self.mode == DimensionMode::Linear && self.orientation != Orientation::Aligned).then(|| (self.clone(), xf * self.handle()));
|
||||
self.a = xf * self.a;
|
||||
self.b = xf * self.b;
|
||||
self.vertex = xf * self.vertex;
|
||||
if let Some((old, p)) = before {
|
||||
let offset = (p - self.a).dot(self.normal());
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
if self.line_between_points() && !old.line_between_points() {
|
||||
self.keep_gap(&old);
|
||||
}
|
||||
}
|
||||
if self.mode == DimensionMode::Linear {
|
||||
self.length = self.a.distance(self.b);
|
||||
self.length = self.measured();
|
||||
}
|
||||
}
|
||||
pub fn resolve(&mut self, doc: &Document) -> Result<(), String> {
|
||||
match &self.source {
|
||||
Some(DimensionSource::Points { a, b, vertex }) => {
|
||||
for (reference, point) in [(a, &mut self.a), (b, &mut self.b), (vertex, &mut self.vertex)] {
|
||||
if let Some(r) = reference {
|
||||
*point = r.position(doc).ok_or("Measured anchor no longer exists")?;
|
||||
Some(DimensionSource::Points { a, b, vertex, free_a, free_b }) => {
|
||||
for (reference, free, point) in [(a, free_a, &mut self.a), (b, free_b, &mut self.b), (vertex, &None, &mut self.vertex)] {
|
||||
match (reference, free) {
|
||||
// An end is an anchor or a free point, never both.
|
||||
(Some(_), Some(_)) => return Err("Invalid measured point".into()),
|
||||
(Some(r), None) => *point = r.position(doc).ok_or("Measured anchor no longer exists")?,
|
||||
(None, Some(f)) if !f.valid() => return Err("Invalid measured point".into()),
|
||||
(None, Some(f)) => *point = f.position(doc).ok_or("Measured anchor no longer exists")?,
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
self.length = self.a.distance(self.b);
|
||||
self.length = if self.mode == DimensionMode::Linear { self.measured() } else { self.a.distance(self.b) };
|
||||
}
|
||||
Some(DimensionSource::Segment { edge }) => {
|
||||
let (a, b) = edge.endpoints(doc).ok_or("Measured segment no longer exists")?;
|
||||
self.a = a;
|
||||
self.b = b;
|
||||
self.length = a.distance(b);
|
||||
self.length = self.measured();
|
||||
}
|
||||
Some(DimensionSource::Angle { first, second }) => {
|
||||
for edge in [first, second] {
|
||||
@@ -486,7 +907,7 @@ impl Dimension {
|
||||
DimensionMode::Angular => self.angle().abs().to_degrees(),
|
||||
DimensionMode::Radius => self.a.distance(self.b),
|
||||
DimensionMode::Diameter => self.a.distance(self.b) * 2.0,
|
||||
DimensionMode::Linear => self.a.distance(self.b),
|
||||
DimensionMode::Linear => self.measured(),
|
||||
};
|
||||
self.options.label(value, self.mode == DimensionMode::Angular)
|
||||
}
|
||||
|
||||
+34
-10
@@ -10,7 +10,7 @@ use super::{
|
||||
|
||||
impl Document {
|
||||
/// Is everything but the layers the same in `other`, as the next version of the document after
|
||||
/// an edit of its art? The id counter and the id index are left out, and art outside the layers
|
||||
/// an edit of its art? The id counter and the caches are left out, and art outside the layers
|
||||
/// (symbols, patterns, graph designs) compares by identity, which an edit keeps for what it
|
||||
/// doesn't change: quick for every frame of an animation.
|
||||
pub fn same_outside_layers(&self, other: &Self) -> bool {
|
||||
@@ -38,7 +38,7 @@ impl Document {
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
guides,
|
||||
saved_guides,
|
||||
views,
|
||||
saved_selections,
|
||||
variables,
|
||||
@@ -75,7 +75,9 @@ impl Document {
|
||||
dimensions,
|
||||
retired_artboard_id: _,
|
||||
opened_artboard: _,
|
||||
units_from_file: _,
|
||||
index: _,
|
||||
guide_cache: _,
|
||||
} = self;
|
||||
*version == other.version
|
||||
&& *title == other.title
|
||||
@@ -97,7 +99,7 @@ impl Document {
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& graph_designs.len() == other.graph_designs.len()
|
||||
&& graph_designs.iter().zip(&other.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& *guides == other.guides
|
||||
&& *saved_guides == other.saved_guides
|
||||
&& *views == other.views
|
||||
&& *saved_selections == other.saved_selections
|
||||
&& *variables == other.variables
|
||||
@@ -208,6 +210,7 @@ impl Document {
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
}],
|
||||
layers: vec![],
|
||||
swatches: swatches.into(),
|
||||
@@ -219,7 +222,7 @@ impl Document {
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
guides: vec![],
|
||||
saved_guides: vec![],
|
||||
views: vec![],
|
||||
saved_selections: Default::default(),
|
||||
variables: Default::default(),
|
||||
@@ -256,7 +259,9 @@ impl Document {
|
||||
dimensions: false,
|
||||
retired_artboard_id: Default::default(),
|
||||
opened_artboard: None,
|
||||
units_from_file: false,
|
||||
index: Default::default(),
|
||||
guide_cache: Default::default(),
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
|
||||
@@ -498,11 +503,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top).
|
||||
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes
|
||||
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]).
|
||||
pub fn insert(&mut self, parent: Option<NodeId>, index: usize, node: Node) -> Result<NodeId, DocError> {
|
||||
let id = node.id;
|
||||
self.check_ruler_guide_place(&node, parent)?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = index.min(ch.len());
|
||||
let i = Node::insert_index(ch, index, &node);
|
||||
ch.insert(i, Arc::new(node));
|
||||
Ok(id)
|
||||
}
|
||||
@@ -519,20 +526,33 @@ impl Document {
|
||||
Ok(ch.remove(idx))
|
||||
}
|
||||
|
||||
/// Move a node to `parent` at `index` (index measured after removal).
|
||||
/// Move a node to `parent` at `index` (index measured after removal), clamped as
|
||||
/// [`Document::insert`] clamps it.
|
||||
pub fn move_node(&mut self, id: NodeId, parent: Option<NodeId>, index: usize) -> Result<(), DocError> {
|
||||
if let Some(p) = parent
|
||||
&& self.ancestry(p).is_some_and(|a| a.contains(&id))
|
||||
{
|
||||
return Err(DocError::Invalid("cannot move an object into itself".into()));
|
||||
}
|
||||
if let Some(n) = self.node(id) {
|
||||
self.check_ruler_guide_place(n, parent)?;
|
||||
}
|
||||
let n = self.remove(id)?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = index.min(ch.len());
|
||||
let i = Node::insert_index(ch, index, &n);
|
||||
ch.insert(i, n);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An error when `n` is a ruler guide and `parent` is not a layer or sublayer: a ruler guide is
|
||||
/// always a direct child of one ([`NodeKind::RulerGuide`]).
|
||||
fn check_ruler_guide_place(&self, n: &Node, parent: Option<NodeId>) -> Result<(), DocError> {
|
||||
if n.is_ruler_guide() && !parent.and_then(|p| self.node(p)).is_some_and(Node::is_layer) {
|
||||
return Err(DocError::Invalid("a ruler guide goes only directly in a layer or sublayer".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Position of `id` within its parent: (parent, index, sibling count).
|
||||
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
|
||||
let parent = self.parent_of(id);
|
||||
@@ -736,7 +756,7 @@ impl Document {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_layer() {
|
||||
objects(c, out);
|
||||
} else {
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.insert(c.id);
|
||||
}
|
||||
}
|
||||
@@ -754,7 +774,8 @@ impl Document {
|
||||
}
|
||||
|
||||
/// The object of a layer or sublayer that holds node `id`: `id` itself when it is one, else
|
||||
/// the group or other object around it right inside a layer. None for a layer or sublayer.
|
||||
/// the group or other object around it right inside a layer. None for a layer, a sublayer or a
|
||||
/// ruler guide.
|
||||
pub fn layer_object(&self, id: NodeId) -> Option<&Node> {
|
||||
self.layer_object_at(&self.index_path(id)?)
|
||||
}
|
||||
@@ -765,6 +786,9 @@ impl Document {
|
||||
let mut nodes = &self.layers;
|
||||
for &i in path {
|
||||
let n = nodes.get(i)?;
|
||||
if n.is_ruler_guide() {
|
||||
return None;
|
||||
}
|
||||
if !n.is_layer() {
|
||||
return Some(n.as_ref());
|
||||
}
|
||||
|
||||
@@ -56,9 +56,12 @@ impl Document {
|
||||
if self.saved_selections.is_empty() {
|
||||
return;
|
||||
}
|
||||
// A saved selection names objects; ruler guides are not among them.
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
self.walk(|n| {
|
||||
ids.insert(n.id);
|
||||
if !n.is_ruler_guide() {
|
||||
ids.insert(n.id);
|
||||
}
|
||||
});
|
||||
let mut kept: Vec<SavedSelection> = vec![];
|
||||
for s in std::mem::take(&mut self.saved_selections) {
|
||||
@@ -101,12 +104,13 @@ impl Document {
|
||||
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The
|
||||
/// layer is removed wherever it is, also as a sublayer of another layer; an id that names
|
||||
/// anything other than a layer is left alone.
|
||||
/// anything other than a layer is left alone. Ruler guides on the layer stay in the document
|
||||
/// ([`Self::remove_edit_layer`]).
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)];
|
||||
for id in layers.into_iter().flatten() {
|
||||
if self.node(id).is_some_and(Node::is_layer) {
|
||||
let _ = self.remove(id);
|
||||
let _ = self.remove_edit_layer(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::document_ext::free_id;
|
||||
use super::guides::Guide;
|
||||
use super::limits::MAX_NEXT_ID;
|
||||
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
impl Document {
|
||||
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
|
||||
@@ -151,7 +153,7 @@ impl Document {
|
||||
rest.iter().any(|m| has(m, s, inside, true))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect, exact)),
|
||||
NodeKind::Path { guide: true, .. } => false,
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => false,
|
||||
_ => art_box_meets(c, s, rect, exact),
|
||||
}
|
||||
}
|
||||
@@ -171,6 +173,195 @@ impl Document {
|
||||
art
|
||||
}
|
||||
|
||||
/// Put the ruler guide nodes a file holds where ruler guides go: directly in a layer or
|
||||
/// sublayer, above its art. A ruler guide below art in a layer moves up to the layer's other
|
||||
/// guides, keeping their order. A ruler guide anywhere else (at the top level, in a group or
|
||||
/// another object, in opacity-mask art, in a symbol, a graph design or a pattern) is removed.
|
||||
/// Returns how many were removed.
|
||||
pub fn tidy_ruler_guides(&mut self) -> usize {
|
||||
let mut gone = self.layers.len();
|
||||
self.layers.retain(|l| !l.is_ruler_guide());
|
||||
gone -= self.layers.len();
|
||||
for l in &mut self.layers {
|
||||
if layer_untidy(l) {
|
||||
gone += tidy_layer(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
let others = self
|
||||
.symbols
|
||||
.iter_mut()
|
||||
.map(|s| &mut s.art)
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in others {
|
||||
if root.is_ruler_guide() {
|
||||
*root = Arc::new(Node::group(root.id, vec![]));
|
||||
gone += 1;
|
||||
} else if any_guide(root) {
|
||||
gone += drop_guides_below(Arc::make_mut(root));
|
||||
}
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Make the saved ruler guides (read from a file: [`Document::guides_to_saved`]'s list) into
|
||||
/// [`NodeKind::RulerGuide`] nodes, each at the top of its layer, in list order. A guide on a
|
||||
/// layer or sublayer the document has goes on it; one on no layer, or on a layer that is gone,
|
||||
/// goes on the top visible, unlocked layer ([`Self::default_layer`]), or on a new "Layer 1"
|
||||
/// when there is none. A guide keeps its saved id when no other node, slice or guide has it,
|
||||
/// and its name, lock and visibility. The saved list is emptied, so running this again does
|
||||
/// nothing. Returns how many guides became nodes.
|
||||
pub fn guides_into_nodes(&mut self) -> usize {
|
||||
let saved = std::mem::take(&mut self.saved_guides);
|
||||
if saved.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut used = HashSet::new();
|
||||
self.walk(|n| {
|
||||
used.insert(n.id);
|
||||
});
|
||||
used.extend(self.slices.iter().map(|s| s.id));
|
||||
used.extend(self.assets.iter().map(|a| NodeId(a.id)));
|
||||
let kept: Vec<Option<NodeId>> = saved.iter().map(|g| g.id.filter(|id| id.0 > 0 && id.0 < MAX_NEXT_ID && used.insert(*id))).collect();
|
||||
if let Some(max) = kept.iter().flatten().map(|id| id.0).max() {
|
||||
self.raise_next_id(max.saturating_add(1));
|
||||
}
|
||||
let mut home = None;
|
||||
// The guides of each layer, in list order.
|
||||
let mut by_layer: BTreeMap<NodeId, Vec<Arc<Node>>> = BTreeMap::new();
|
||||
let mut order = vec![];
|
||||
for (g, id) in saved.iter().zip(kept) {
|
||||
let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) {
|
||||
Some(l) => l,
|
||||
None => match home {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let h = self.default_layer().unwrap_or_else(|| self.add_layer(None));
|
||||
home = Some(h);
|
||||
h
|
||||
}
|
||||
},
|
||||
};
|
||||
let id = id.unwrap_or_else(|| self.alloc_id());
|
||||
let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard });
|
||||
n.name = g.name.clone();
|
||||
n.locked = g.locked;
|
||||
n.visible = !g.hidden;
|
||||
if !by_layer.contains_key(&layer) {
|
||||
order.push(layer);
|
||||
}
|
||||
by_layer.entry(layer).or_default().push(Arc::new(n));
|
||||
}
|
||||
for layer in order {
|
||||
let guides = by_layer.remove(&layer).unwrap_or_default();
|
||||
if let Ok(ch) = self.children_mut(Some(layer)) {
|
||||
ch.extend(guides);
|
||||
}
|
||||
}
|
||||
saved.len()
|
||||
}
|
||||
|
||||
/// Take the ruler guide nodes out of the layers and put them in the saved list, by ascending
|
||||
/// id, each naming its layer, after any entries not yet made into nodes: the form a file keeps
|
||||
/// them in, readable by versions from before ruler guides were nodes. For saving a copy of
|
||||
/// the document; [`Self::guides_into_nodes`] reverses it.
|
||||
pub fn guides_to_saved(&mut self) {
|
||||
let guides = self.ruler_guides();
|
||||
if guides.is_empty() {
|
||||
return;
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
if l.holds_ruler_guides() {
|
||||
Arc::make_mut(l).strip_ruler_guides();
|
||||
}
|
||||
}
|
||||
self.saved_guides.extend(guides);
|
||||
}
|
||||
|
||||
/// Every ruler guide, by ascending id, with the layer or sublayer it is on, its id, name and
|
||||
/// its own lock and visibility. A guide's place in this list is its index in the guide
|
||||
/// commands.
|
||||
pub fn ruler_guides(&self) -> Vec<Guide> {
|
||||
if let Some(listed) = self.guide_cache.get(&self.layers) {
|
||||
return listed.as_ref().clone();
|
||||
}
|
||||
fn visit(layer: &Node, out: &mut Vec<Guide>) {
|
||||
for c in layer.children().into_iter().flatten() {
|
||||
if let Some(g) = guide_of(c, layer.id) {
|
||||
out.push(g);
|
||||
} else if c.is_layer() {
|
||||
visit(c, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &self.layers {
|
||||
visit(l, &mut out);
|
||||
}
|
||||
out.sort_by_key(|g| g.id);
|
||||
self.guide_cache.set(&self.layers, &out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Ruler guide `id`, as [`Self::ruler_guides`] lists it. None when `id` is not a ruler guide
|
||||
/// on a layer.
|
||||
pub fn ruler_guide(&self, id: NodeId) -> Option<Guide> {
|
||||
let layer = self.parent_of(id)?;
|
||||
guide_of(self.node(id)?, layer)
|
||||
}
|
||||
|
||||
/// Change ruler guide `id` with `f` (its line, its artboard; the layer, id, name, lock and
|
||||
/// visibility fields are not read back). Returns false when `id` is not a ruler guide.
|
||||
pub fn edit_ruler_guide(&mut self, id: NodeId, f: impl FnOnce(&mut Guide)) -> bool {
|
||||
let Some(mut g) = self.ruler_guide(id) else { return false };
|
||||
f(&mut g);
|
||||
let Some(n) = self.node_mut(id) else { return false };
|
||||
n.kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard };
|
||||
true
|
||||
}
|
||||
|
||||
/// Add ruler guide `g` as a node with a new id at the top of its layer: `g.layer` when the
|
||||
/// document has that layer or sublayer, else the top visible, unlocked layer
|
||||
/// ([`Self::default_layer`]), or a new "Layer 1" when there is none. Its name, lock and
|
||||
/// visibility come from `g`. Returns the new id.
|
||||
pub fn add_ruler_guide(&mut self, g: &Guide) -> NodeId {
|
||||
let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) {
|
||||
Some(l) => l,
|
||||
None => self.default_layer().unwrap_or_else(|| self.add_layer(None)),
|
||||
};
|
||||
let id = self.alloc_id();
|
||||
let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard });
|
||||
n.name = g.name.clone();
|
||||
n.locked = g.locked;
|
||||
n.visible = !g.hidden;
|
||||
if let Ok(ch) = self.children_mut(Some(layer)) {
|
||||
ch.push(Arc::new(n));
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove node `id`, the temporary layer of opacity-mask, symbol or pattern editing, keeping the
|
||||
/// ruler guides on it and on its sublayers: they go to the top of the top visible, unlocked
|
||||
/// layer left ([`Self::default_layer`]), or of a new "Layer 1" when no layer is left, where a
|
||||
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
|
||||
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
|
||||
let mut layer = self.remove(id)?;
|
||||
if !layer.holds_ruler_guides() {
|
||||
return Ok(layer);
|
||||
}
|
||||
let mut guides = vec![];
|
||||
layer.walk(&mut |c| {
|
||||
if c.is_ruler_guide() {
|
||||
guides.push(Arc::new(c.clone()));
|
||||
}
|
||||
});
|
||||
Arc::make_mut(&mut layer).strip_ruler_guides();
|
||||
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
|
||||
self.children_mut(Some(home))?.extend(guides);
|
||||
Ok(layer)
|
||||
}
|
||||
|
||||
/// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its
|
||||
/// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose
|
||||
/// artboard is gone.
|
||||
@@ -179,79 +370,39 @@ impl Document {
|
||||
Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })
|
||||
}
|
||||
|
||||
/// The ruler guide node `g` names, if this document has it.
|
||||
fn guide_node(&self, g: &Guide) -> Option<NodeId> {
|
||||
g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide))
|
||||
}
|
||||
|
||||
/// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has.
|
||||
fn guide_layer(&self, g: &Guide) -> Option<NodeId> {
|
||||
g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer))
|
||||
}
|
||||
|
||||
/// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is
|
||||
/// visible? A guide whose layer is gone shows as one on no layer.
|
||||
/// Is ruler guide `g` shown: its node, and the layers it is on, visible? A guide that is not a
|
||||
/// node of this document shows unless hidden itself or on a hidden layer.
|
||||
pub fn guide_shown(&self, g: &Guide) -> bool {
|
||||
self.guide_layer(g).is_none_or(|l| self.is_visible(l))
|
||||
}
|
||||
|
||||
/// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked?
|
||||
pub fn guide_editable(&self, g: &Guide) -> bool {
|
||||
self.guide_layer(g).is_none_or(|l| self.is_editable(l))
|
||||
}
|
||||
|
||||
/// Put the ruler guides on no layer this document has (from files saved before guides had
|
||||
/// layers, or of layers merged into `layer`) on layer `layer`. Returns how many.
|
||||
pub fn rehome_guides(&mut self, layer: NodeId) -> usize {
|
||||
let lost: Vec<bool> = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect();
|
||||
let mut n = 0;
|
||||
for (g, lost) in self.guides.iter_mut().zip(lost) {
|
||||
if lost {
|
||||
g.layer = Some(layer);
|
||||
n += 1;
|
||||
}
|
||||
match self.guide_node(g) {
|
||||
Some(id) => self.is_visible(id),
|
||||
None => !g.hidden && self.guide_layer(g).is_none_or(|l| self.is_visible(l)),
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Put the ruler guides on no layer (from files saved before guides had layers), or on one that
|
||||
/// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many.
|
||||
pub fn adopt_guides(&mut self) -> usize {
|
||||
self.default_layer().map_or(0, |home| self.rehome_guides(home))
|
||||
/// Can ruler guide `g` be picked, moved and deleted: shown, and neither it nor its layers
|
||||
/// locked?
|
||||
pub fn guide_editable(&self, g: &Guide) -> bool {
|
||||
match self.guide_node(g) {
|
||||
Some(id) => self.is_editable(id),
|
||||
None => !g.hidden && !g.locked && self.guide_layer(g).is_none_or(|l| self.is_editable(l)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in
|
||||
/// step. Guides on no layer stay. Returns how many went.
|
||||
pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize {
|
||||
let gone: Vec<bool> = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect();
|
||||
self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made
|
||||
/// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies
|
||||
/// the objects on it. Returns how many.
|
||||
pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize {
|
||||
let layers = |n: &Node| {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |c| {
|
||||
if c.is_layer() {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect();
|
||||
let copies: Vec<Guide> = self
|
||||
.guides
|
||||
.iter()
|
||||
.filter_map(|g| {
|
||||
let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1;
|
||||
Some(Guide { layer: Some(to), ..g.clone() })
|
||||
})
|
||||
.collect();
|
||||
let n = copies.len();
|
||||
self.guides.extend(copies);
|
||||
n
|
||||
}
|
||||
|
||||
/// The ruler guides on layer `layer` (not its sublayers'), by index.
|
||||
pub fn guides_on(&self, layer: NodeId) -> impl Iterator<Item = (usize, &Guide)> + '_ {
|
||||
self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer))
|
||||
/// The ruler guides directly on layer `layer` (not its sublayers'), by ascending id.
|
||||
pub fn guides_on(&self, layer: NodeId) -> Vec<Guide> {
|
||||
let mut out: Vec<Guide> = self.children(Some(layer)).into_iter().flatten().filter_map(|c| guide_of(c, layer)).collect();
|
||||
out.sort_by_key(|g| g.id);
|
||||
out
|
||||
}
|
||||
|
||||
/// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)?
|
||||
@@ -260,45 +411,86 @@ impl Document {
|
||||
self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol)
|
||||
}
|
||||
|
||||
/// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their
|
||||
/// place among the rest (the selected art stays selected). Returns how many went.
|
||||
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize {
|
||||
let kept: Vec<bool> = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect();
|
||||
// Where each kept guide ends up.
|
||||
let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0);
|
||||
for k in &kept {
|
||||
to.push(k.then_some(n));
|
||||
n += usize::from(*k);
|
||||
/// Keep the ruler guides `keep` accepts, deleting the others; `sel` forgets the deleted ones
|
||||
/// (the selected art stays selected). Returns how many went.
|
||||
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(&Guide) -> bool) -> usize {
|
||||
let gone: HashSet<NodeId> = self.ruler_guides().into_iter().filter(|g| !keep(g)).filter_map(|g| g.id).collect();
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
|
||||
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
|
||||
}
|
||||
if !holds(layer, gone) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
|
||||
for c in ch.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop(c, gone);
|
||||
}
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
drop(l, &gone);
|
||||
}
|
||||
sel.guides.retain(|id| !gone.contains(id));
|
||||
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
|
||||
sel.key_guide = None;
|
||||
}
|
||||
gone.len()
|
||||
}
|
||||
|
||||
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
|
||||
/// position).
|
||||
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn holds(n: &Node, id: u32) -> bool {
|
||||
n.is_layer()
|
||||
&& n.children().is_some_and(|ch| {
|
||||
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
|
||||
})
|
||||
}
|
||||
if !holds(layer, id) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
for c in ch.iter_mut() {
|
||||
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
|
||||
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
|
||||
f(*vertical, pos);
|
||||
}
|
||||
} else if c.is_layer() {
|
||||
visit(c, id, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
visit(l, id, f);
|
||||
}
|
||||
sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect();
|
||||
sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten());
|
||||
let before = self.guides.len();
|
||||
let mut flags = kept.into_iter();
|
||||
self.guides.retain(|_| flags.next().unwrap_or(true));
|
||||
before - self.guides.len()
|
||||
}
|
||||
|
||||
/// Move the guides of artboard `id` by `d` (along with their artboard).
|
||||
pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) {
|
||||
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
|
||||
*g = g.moved(d);
|
||||
}
|
||||
self.edit_artboard_guides(id, &mut |vertical, pos| *pos += if vertical { d.x } else { d.y });
|
||||
}
|
||||
|
||||
/// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork
|
||||
/// with Artboard).
|
||||
pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) {
|
||||
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
|
||||
g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y };
|
||||
}
|
||||
self.edit_artboard_guides(id, &mut |vertical, pos| {
|
||||
*pos = if vertical { (xf * Point::new(*pos, 0.0)).x } else { (xf * Point::new(0.0, *pos)).y };
|
||||
});
|
||||
}
|
||||
|
||||
/// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their
|
||||
/// artboard).
|
||||
/// artboard), each on its guide's layer with a new id.
|
||||
pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) {
|
||||
let copies: Vec<Guide> =
|
||||
self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
|
||||
self.guides.extend(copies);
|
||||
self.ruler_guides().into_iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
|
||||
for g in &copies {
|
||||
self.add_ruler_guide(g);
|
||||
}
|
||||
}
|
||||
|
||||
/// An id for a new artboard: one no artboard has, above the ids given out before and the ids of
|
||||
@@ -367,3 +559,122 @@ impl Document {
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
|
||||
fn any_guide(n: &Node) -> bool {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
|
||||
any
|
||||
}
|
||||
|
||||
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
|
||||
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
|
||||
fn drop_guides_below(n: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(n);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let before = ch.len();
|
||||
ch.retain(|c| !c.is_ruler_guide());
|
||||
gone += before - ch.len();
|
||||
for c in ch.iter_mut().filter(|c| any_guide(c)) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
|
||||
/// becomes an empty group. Returns how many went.
|
||||
fn drop_mask_guides(n: &mut Node) -> usize {
|
||||
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
|
||||
if mask.art.is_ruler_guide() {
|
||||
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
|
||||
1
|
||||
} else if any_guide(&mask.art) {
|
||||
drop_guides_below(Arc::make_mut(&mut mask.art))
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
|
||||
/// in one of its sublayers?
|
||||
fn layer_untidy(l: &Node) -> bool {
|
||||
let Some(ch) = l.children() else { return false };
|
||||
let start = Node::guide_run_start(ch);
|
||||
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|
||||
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
|
||||
}
|
||||
|
||||
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
|
||||
fn tidy_layer(l: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(l);
|
||||
let Some(ch) = l.children_mut() else { return gone };
|
||||
for c in ch.iter_mut() {
|
||||
if c.is_layer() {
|
||||
if layer_untidy(c) {
|
||||
gone += tidy_layer(Arc::make_mut(c));
|
||||
}
|
||||
} else if !c.is_ruler_guide() && any_guide(c) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
|
||||
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
|
||||
*ch = art;
|
||||
ch.extend(guides);
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Node `n`, on layer `layer`, as a [`Guide`] value, if it is a ruler guide.
|
||||
fn guide_of(n: &Node, layer: NodeId) -> Option<Guide> {
|
||||
let NodeKind::RulerGuide { vertical, pos, artboard } = n.kind else { return None };
|
||||
Some(Guide { vertical, pos, artboard, layer: Some(layer), id: Some(n.id), name: n.name.clone(), locked: n.locked, hidden: !n.visible })
|
||||
}
|
||||
|
||||
/// The list [`Document::ruler_guides`] last made, with weak pointers to the top-level layers it was
|
||||
/// made from. While a weak pointer to a layer's allocation is held, nothing else can be at that
|
||||
/// address, and the layer can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut`
|
||||
/// moves it), so any edit inside a layer, and any layer added, removed or replaced, gives a list of
|
||||
/// layers the cache does not match. Clones of a document share the cached list.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct GuideCache(std::sync::RwLock<Option<Listed>>);
|
||||
|
||||
/// The top-level layers a guide list was made from, and the list.
|
||||
type Listed = (Vec<std::sync::Weak<Node>>, Arc<Vec<Guide>>);
|
||||
|
||||
impl GuideCache {
|
||||
/// The cached list, when it was made from `layers`.
|
||||
fn get(&self, layers: &[Arc<Node>]) -> Option<Arc<Vec<Guide>>> {
|
||||
let g = self.0.read().ok()?;
|
||||
let (from, listed) = g.as_ref()?;
|
||||
let same = from.len() == layers.len() && from.iter().zip(layers).all(|(w, l)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(l)));
|
||||
same.then(|| listed.clone())
|
||||
}
|
||||
|
||||
/// Keep `listed`, made from `layers`.
|
||||
fn set(&self, layers: &[Arc<Node>], listed: &[Guide]) {
|
||||
if let Ok(mut g) = self.0.write() {
|
||||
*g = Some((layers.iter().map(Arc::downgrade).collect(), Arc::new(listed.to_vec())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for GuideCache {
|
||||
fn clone(&self) -> Self {
|
||||
GuideCache(std::sync::RwLock::new(self.0.read().ok().and_then(|g| g.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
/// A cache, not document content: two documents are equal whatever their caches hold.
|
||||
impl PartialEq for GuideCache {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for GuideCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("GuideCache")
|
||||
}
|
||||
}
|
||||
|
||||
+24
-4
@@ -136,9 +136,11 @@ impl crate::Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// The character style a graph's labels keep through regeneration once formatted (Format the text in graphs): the
|
||||
/// value axis numbers, the category labels (category axis, radar spokes, pie names) and the legend labels (beside or
|
||||
/// across the top, or in pie wedges). `None` draws the default 9 pt black.
|
||||
/// The character style and anti-aliasing method a graph's labels keep through regeneration once formatted (Format
|
||||
/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the
|
||||
/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para`
|
||||
/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each
|
||||
/// label's alignment.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LabelStyles {
|
||||
@@ -148,6 +150,22 @@ pub struct LabelStyles {
|
||||
pub categories: Option<crate::CharStyle>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legend: Option<crate::CharStyle>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub values_para: Option<crate::ParaStyle>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub categories_para: Option<crate::ParaStyle>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legend_para: Option<crate::ParaStyle>,
|
||||
/// The anti-aliasing method the value axis numbers keep once set (Character panel › Anti-aliasing Method).
|
||||
/// `None` draws them Sharp.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub values_anti_alias: Option<crate::text::TypeAntiAlias>,
|
||||
/// The anti-aliasing method the category labels keep once set. `None` draws them Sharp.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub categories_anti_alias: Option<crate::text::TypeAntiAlias>,
|
||||
/// The anti-aliasing method the legend labels keep once set. `None` draws them Sharp.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legend_anti_alias: Option<crate::text::TypeAntiAlias>,
|
||||
}
|
||||
|
||||
impl LabelStyles {
|
||||
@@ -525,7 +543,9 @@ impl GraphSpec {
|
||||
out.push_str(&field(self.categories.get(i).map(String::as_str).unwrap_or_default(), true));
|
||||
out.push(',');
|
||||
}
|
||||
out.push_str(&r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(","));
|
||||
let line = r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(",");
|
||||
// A lone blank value would be an empty line, which readers skip; a quoted empty field keeps the row.
|
||||
out.push_str(if line.is_empty() && !labelled { "\"\"" } else { &line });
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use super::{Deserialize, NodeId, Serialize, Vec2};
|
||||
|
||||
/// A ruler guide as a value: an entry of the saved `guides` list, or a ruler guide node of a
|
||||
/// document as [`crate::Document::ruler_guides`] lists it. In a document, ruler guides are
|
||||
/// [`crate::NodeKind::RulerGuide`] nodes on their layers.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Guide {
|
||||
/// true = vertical guide at `pos` (x), false = horizontal at `pos` (y).
|
||||
@@ -14,12 +17,25 @@ pub struct Guide {
|
||||
/// from before guides had layers, and from files that don't say), always there.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layer: Option<NodeId>,
|
||||
/// The id of its node. None in an entry written before ruler guides were nodes: it gets a new
|
||||
/// id when the document is read.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<NodeId>,
|
||||
/// The name it shows in the Layers panel, if it was given one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Locked on its own (its layer's lock is separate).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub locked: bool,
|
||||
/// Hidden on its own (its layer's visibility is separate).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub hidden: bool,
|
||||
}
|
||||
|
||||
impl Guide {
|
||||
/// A canvas guide.
|
||||
pub fn new(vertical: bool, pos: f64) -> Self {
|
||||
Self { vertical, pos, artboard: None, layer: None }
|
||||
Self { vertical, pos, artboard: None, layer: None, id: None, name: None, locked: false, hidden: false }
|
||||
}
|
||||
|
||||
/// Moved by `d` (a vertical guide across, a horizontal one down).
|
||||
|
||||
+11
-6
@@ -588,7 +588,8 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
|
||||
if !c.visible || editable_only && (c.locked || c.is_template()) {
|
||||
return false;
|
||||
}
|
||||
if opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
// A ruler guide is picked by the guide commands, never by an object hit test.
|
||||
if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
return false;
|
||||
}
|
||||
// (An envelope's content sits where it was, not where the envelope draws it.)
|
||||
@@ -870,10 +871,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline)
|
||||
}
|
||||
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
|
||||
// #3291), and where its own fills and strokes paint ([`image_paint`]) except in outline
|
||||
// mode.
|
||||
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
|
||||
// own fills and strokes paint ([`image_paint`]) except in outline mode.
|
||||
NodeKind::Image(im) => {
|
||||
if opt.path_only {
|
||||
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
|
||||
frame.apply_affine(im.xf);
|
||||
@@ -909,6 +910,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if stroke_contains(&bp, 0.0, opt.tol, p) {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
// Outline mode draws the mesh lines, not the colours between them (#6437).
|
||||
if opt.outline {
|
||||
return stroke_contains(&m.lines().to_bezpath(), 0.0, opt.tol, p).then_some(HitKind::Outline);
|
||||
}
|
||||
(!opt.path_only && fill_contains(&bp, vectorcraft_geom::FillRule::NonZero, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
_ => None,
|
||||
@@ -1252,7 +1257,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
@@ -1281,7 +1286,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if c.visible && !c.locked && !c.is_template() {
|
||||
out.extend(layer_objects(c, r));
|
||||
}
|
||||
} else {
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.push((c, r));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -880,6 +880,45 @@ fn path_only_picks_paths_through_images() {
|
||||
assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame");
|
||||
}
|
||||
|
||||
/// #6437: in outline mode an image is drawn as its frame and a gradient mesh as its mesh lines,
|
||||
/// so a click inside them, on the outline of a path behind, picks that path, and a click on the
|
||||
/// frame or a mesh line picks the image or the mesh. In Preview they cover the path as before,
|
||||
/// and an image whose pixels show in outline mode (Show Images in Outline Mode) still does.
|
||||
#[test]
|
||||
fn outline_mode_picks_paths_through_images_and_meshes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (path, image, under, mesh) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let xf = vectorcraft_geom::Affine::translate((10.0, 10.0));
|
||||
let im = crate::ImageObject { key: "k".into(), width: 80, height: 80, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
d.insert(Some(l), 2, Node::path(under, shapes::rectangle(Rect::new(120.0, 120.0, 160.0, 160.0)), Appearance::default_art())).unwrap();
|
||||
let area = shapes::rectangle(Rect::new(110.0, 110.0, 190.0, 190.0));
|
||||
let m = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
|
||||
d.insert(Some(l), 3, Node::new(mesh, NodeKind::Mesh(m))).unwrap();
|
||||
let outline = HitOptions { outline: true, ..Default::default() };
|
||||
let hit = |d: &Document, p: Point, opt| hit_test(d, p, opt).map(|h| h.leaf);
|
||||
// The image: the path's edge and the inside, then the frame.
|
||||
let (path_edge, inside, frame) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(89.5, 50.0));
|
||||
assert_eq!(hit(&d, path_edge, HitOptions::default()), Some(image), "Preview: the image covers the path");
|
||||
assert_eq!(hit(&d, inside, HitOptions::default()), Some(image));
|
||||
assert_eq!(hit(&d, path_edge, outline), Some(path), "outline: the path through the image");
|
||||
assert_eq!(hit(&d, inside, outline), None, "outline: not inside the image");
|
||||
assert_eq!(hit(&d, frame, outline), Some(image), "outline: the image's frame");
|
||||
// The mesh: the path's edge and the inside, then its edge and a mesh line inside it.
|
||||
let (under_edge, inside, edge, line) = (Point::new(120.5, 130.0), Point::new(130.0, 170.0), Point::new(189.5, 130.0), Point::new(150.0, 170.0));
|
||||
assert_eq!(hit(&d, under_edge, HitOptions::default()), Some(mesh), "Preview: the mesh covers the path");
|
||||
assert_eq!(hit(&d, inside, HitOptions::default()), Some(mesh));
|
||||
assert_eq!(hit(&d, under_edge, outline), Some(under), "outline: the path through the mesh");
|
||||
assert_eq!(hit(&d, inside, outline), None, "outline: not between the mesh lines");
|
||||
assert_eq!(hit(&d, edge, outline), Some(mesh), "outline: the mesh's edge");
|
||||
assert_eq!(hit(&d, line, outline), Some(mesh), "outline: a mesh line");
|
||||
// Show Images in Outline Mode: the image's pixels are drawn, and it covers the path again.
|
||||
d.setup.outline_images = true;
|
||||
assert_eq!(hit(&d, path_edge, outline), Some(image));
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its
|
||||
/// frame and type on a path on its path, no longer anywhere in its bounds.
|
||||
#[test]
|
||||
|
||||
+41
-5
@@ -110,8 +110,9 @@ fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) {
|
||||
}
|
||||
|
||||
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an
|
||||
/// image's colorize color, not opacity masks) with its swatch link and tint. Mesh points have no
|
||||
/// link: changes to it are dropped.
|
||||
/// image's colorize color, the fills and strokes a dynamic symbol instance keeps for objects of its
|
||||
/// art, not opacity masks) with its swatch link and tint. Mesh points have no link: changes to it
|
||||
/// are dropped.
|
||||
pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
@@ -119,8 +120,13 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
AppearanceItem::Stroke(l) => visit_paint(&mut l.paint, f),
|
||||
}
|
||||
}
|
||||
if let Some(p) = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()) {
|
||||
visit_paint(p, f);
|
||||
if let Some(e) = n.extras.0.as_deref_mut() {
|
||||
if let Some(p) = e.colorize.as_deref_mut() {
|
||||
visit_paint(p, f);
|
||||
}
|
||||
for p in e.symbol_overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
|
||||
visit_paint(p, f);
|
||||
}
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
@@ -144,7 +150,8 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
}
|
||||
|
||||
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, text runs, mesh
|
||||
/// points) given its swatch link and tint, keeping the links.
|
||||
/// points, a dynamic symbol instance's own fills and strokes) given its swatch link and tint,
|
||||
/// keeping the links.
|
||||
pub fn map_node_colors(n: &mut Node, f: &mut dyn FnMut(&Color, Link) -> Color) {
|
||||
visit_node_colors(n, &mut |c, swatch, tint| *c = f(c, swatch.as_deref().map(|s| (s, *tint))));
|
||||
}
|
||||
@@ -158,3 +165,32 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
|
||||
map_node_colors(Arc::make_mut(&mut s.art), f);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NodeId, SymbolOverride};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
#[test]
|
||||
fn a_dynamic_instances_own_fills_and_strokes_are_visited() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
let spot = Paint::Solid { color: red, swatch: Some("Spot".into()), tint: 0.5 };
|
||||
let mut inst = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::IDENTITY });
|
||||
inst.extras_mut().symbol_overrides = vec![
|
||||
SymbolOverride { path: vec![0], fill: Some(spot), stroke: Some(Paint::solid(red)), ..Default::default() },
|
||||
SymbolOverride { path: vec![1], opacity: Some(0.5), ..Default::default() },
|
||||
];
|
||||
let mut links = vec![];
|
||||
map_node_colors(&mut inst, &mut |_, link| {
|
||||
links.push(link.map(|(s, t)| (s.to_string(), t)));
|
||||
blue
|
||||
});
|
||||
assert_eq!(links, vec![Some(("Spot".to_string(), 0.5)), None], "each override paint is visited once, with its link");
|
||||
let o = &inst.extras().symbol_overrides;
|
||||
assert_eq!(o[0].fill, Some(Paint::Solid { color: blue, swatch: Some("Spot".into()), tint: 0.5 }), "the link is kept");
|
||||
assert_eq!(o[0].stroke, Some(Paint::solid(blue)));
|
||||
assert_eq!((o[1].fill.as_ref(), o[1].stroke.as_ref()), (None, None), "an override without paint gets none");
|
||||
}
|
||||
}
|
||||
|
||||
+14
-2
@@ -207,8 +207,12 @@ pub struct Document {
|
||||
/// Object › Graph › Design…: art graphs can draw as markers.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub graph_designs: Vec<GraphDesign>,
|
||||
#[serde(default)]
|
||||
pub guides: Vec<Guide>,
|
||||
/// The saved form of the ruler guides: read from a file, then made into
|
||||
/// [`NodeKind::RulerGuide`] nodes on their layers ([`Document::guides_into_nodes`]), and
|
||||
/// written from those nodes when saving ([`Document::guides_to_saved`]). Empty in between.
|
||||
/// Each entry read counts as an object against the read's node budget.
|
||||
#[serde(default, rename = "guides", deserialize_with = "crate::node::counted_list")]
|
||||
saved_guides: Vec<Guide>,
|
||||
/// View → New View… (at most [`SavedView::MAX`]); saved with the document.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub views: Vec<SavedView>,
|
||||
@@ -339,6 +343,11 @@ pub struct Document {
|
||||
/// names it as the file's active artboard. `None`: the first. Native files do not keep it.
|
||||
#[serde(skip)]
|
||||
pub opened_artboard: Option<u32>,
|
||||
/// The file this document was read from recorded its units (a `.ai` file's
|
||||
/// `%AI5_RulerUnits`): it opens in them. A file that records none opens in Preferences ›
|
||||
/// Units › General (#5820). Native files do not keep it: they always keep their units.
|
||||
#[serde(skip)]
|
||||
pub units_from_file: bool,
|
||||
/// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this
|
||||
/// is set, so documents without any pay nothing for them.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -346,6 +355,9 @@ pub struct Document {
|
||||
/// Where each node is in the tree, for lookups by id ([`id_index`]): a cache, never saved.
|
||||
#[serde(skip)]
|
||||
index: id_index::IdIndex,
|
||||
/// The ruler guides as [`Document::ruler_guides`] lists them: a cache, never saved.
|
||||
#[serde(skip)]
|
||||
guide_cache: document_guides::GuideCache,
|
||||
}
|
||||
|
||||
fn ppi72() -> f64 {
|
||||
|
||||
@@ -643,6 +643,168 @@ mod tests {
|
||||
assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}");
|
||||
}
|
||||
|
||||
/// The polylines of `bp` flattened to 0.01 pt.
|
||||
fn flattened(bp: &BezPath) -> Vec<Vec<Point>> {
|
||||
let mut out: Vec<Vec<Point>> = vec![];
|
||||
vectorcraft_geom::kurbo::flatten(bp.iter(), 0.01, |el| match el {
|
||||
vectorcraft_geom::PathEl::MoveTo(p) => out.push(vec![p]),
|
||||
vectorcraft_geom::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|v| v.push(p)),
|
||||
vectorcraft_geom::PathEl::ClosePath => out.last_mut().into_iter().for_each(|v| v.push(v[0])),
|
||||
_ => {}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The distance from `p` to the nearest of `lines`.
|
||||
fn off_lines(lines: &[Vec<Point>], p: Point) -> f64 {
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|v| v.windows(2))
|
||||
.map(|w| {
|
||||
let d = w[1] - w[0];
|
||||
let t = if d.hypot2() > 0.0 { ((p - w[0]).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
p.distance(w[0] + d * t)
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// How far apart the border of `m` and the outline of `path` are, in points: the larger of the
|
||||
/// farthest a point of either lies from the other.
|
||||
fn mesh_border_off_path(m: &GradientMesh, path: &PathData) -> f64 {
|
||||
let (border, outline) = (flattened(&m.outline().to_bezpath()), flattened(&path.to_bezpath()));
|
||||
let one = border.iter().flatten().map(|p| off_lines(&outline, *p)).fold(0.0, f64::max);
|
||||
let other = outline.iter().flatten().map(|p| off_lines(&border, *p)).fold(0.0, f64::max);
|
||||
one.max(other)
|
||||
}
|
||||
|
||||
/// #2752: a gradient mesh keeps the exact outline of the path it is made from, sharp corners
|
||||
/// included, whether made by Create Gradient Mesh (1×1 and 4×4) or by a Mesh tool click at a
|
||||
/// point inside. Before, the border of each mesh was one cubic per edge between four corners
|
||||
/// near the bounding box's: up to 49 pt off a five-point star, 54 pt off a notched rectangle.
|
||||
#[test]
|
||||
fn a_mesh_keeps_the_outline_of_every_shape() {
|
||||
const OFF: f64 = 0.1;
|
||||
let poly = |pts: &[(f64, f64)]| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), true));
|
||||
let curves = |start: (f64, f64), cubics: &[[(f64, f64); 3]]| {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(start);
|
||||
for [a, b, c] in cubics {
|
||||
bp.curve_to(*a, *b, *c);
|
||||
}
|
||||
bp.close_path();
|
||||
PathData::from_bezpath(&bp)
|
||||
};
|
||||
let box_ = Rect::new(100.0, 100.0, 500.0, 400.0);
|
||||
let heart = curves(
|
||||
(300.0, 400.0),
|
||||
&[
|
||||
[(200.0, 320.0), (100.0, 250.0), (100.0, 170.0)],
|
||||
[(100.0, 100.0), (180.0, 70.0), (230.0, 90.0)],
|
||||
[(270.0, 105.0), (290.0, 130.0), (300.0, 150.0)],
|
||||
[(310.0, 130.0), (330.0, 105.0), (370.0, 90.0)],
|
||||
[(420.0, 70.0), (500.0, 100.0), (500.0, 170.0)],
|
||||
[(500.0, 250.0), (400.0, 320.0), (300.0, 400.0)],
|
||||
],
|
||||
);
|
||||
let teardrop = curves(
|
||||
(300.0, 100.0),
|
||||
&[
|
||||
[(350.0, 200.0), (420.0, 250.0), (420.0, 320.0)],
|
||||
[(420.0, 386.0), (366.0, 440.0), (300.0, 440.0)],
|
||||
[(234.0, 440.0), (180.0, 386.0), (180.0, 320.0)],
|
||||
[(180.0, 250.0), (250.0, 200.0), (300.0, 100.0)],
|
||||
],
|
||||
);
|
||||
let shapes: [(&str, PathData, Point); 14] = [
|
||||
("rectangle", shapes::rectangle(box_), Point::new(260.0, 230.0)),
|
||||
("rotated rectangle", shapes::rectangle(box_).transformed(Affine::rotate_about(0.5, box_.center())), Point::new(280.0, 240.0)),
|
||||
("triangle", poly(&[(300.0, 100.0), (500.0, 400.0), (100.0, 400.0)]), Point::new(300.0, 320.0)),
|
||||
("five-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0), Point::new(300.0, 300.0)),
|
||||
("twelve-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 140.0, 12, 0.0), Point::new(300.0, 300.0)),
|
||||
(
|
||||
"L-shape",
|
||||
poly(&[(100.0, 100.0), (200.0, 100.0), (200.0, 300.0), (400.0, 300.0), (400.0, 400.0), (100.0, 400.0)]),
|
||||
Point::new(150.0, 350.0),
|
||||
),
|
||||
("rounded rectangle", shapes::rounded_rectangle(box_, 40.0), Point::new(260.0, 230.0)),
|
||||
("heart", heart, Point::new(300.0, 250.0)),
|
||||
("teardrop", teardrop, Point::new(300.0, 330.0)),
|
||||
("ellipse", shapes::ellipse(box_), Point::new(200.0, 330.0)),
|
||||
("thin rectangle", shapes::rectangle(Rect::new(100.0, 100.0, 500.0, 110.0)), Point::new(260.0, 104.0)),
|
||||
(
|
||||
"notched rectangle",
|
||||
poly(&[(100.0, 100.0), (250.0, 100.0), (300.0, 200.0), (350.0, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]),
|
||||
Point::new(260.0, 300.0),
|
||||
),
|
||||
// A notch shorter than the steps along the outline an edge is checked at, and deeper
|
||||
// than the tolerance.
|
||||
(
|
||||
"rectangle with a tiny notch",
|
||||
poly(&[(100.0, 100.0), (301.1, 100.0), (301.2, 100.3), (301.3, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]),
|
||||
Point::new(260.0, 300.0),
|
||||
),
|
||||
// An outline that crosses itself, whose two lobes' areas cancel.
|
||||
("bow tie", poly(&[(100.0, 100.0), (500.0, 400.0), (500.0, 100.0), (100.0, 400.0)]), Point::new(150.0, 250.0)),
|
||||
];
|
||||
// Every shape and way of making the mesh is checked, and all that stray are named.
|
||||
let mut strays = vec![];
|
||||
for (name, path, click) in shapes {
|
||||
for (rows, cols) in [(1, 1), (4, 4)] {
|
||||
let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
let off = mesh_border_off_path(&m, &path);
|
||||
if off >= OFF {
|
||||
strays.push(format!("{name}, {rows}×{cols}: border {off:.2} pt off the outline"));
|
||||
}
|
||||
}
|
||||
let mut m = GradientMesh::for_path(&path, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
assert!(m.add_lines_at(click, 0.0).is_some(), "{name}: the click at {click:?} is outside the mesh");
|
||||
let off = mesh_border_off_path(&m, &path);
|
||||
if off >= OFF {
|
||||
strays.push(format!("{name}, Mesh tool click: border {off:.2} pt off the outline"));
|
||||
}
|
||||
}
|
||||
assert!(strays.is_empty(), "{strays:#?}");
|
||||
}
|
||||
|
||||
/// The lines a mesh takes to keep a path's outline are as few as do it: a rectangle's and an
|
||||
/// ellipse's meshes keep the rows and columns asked for, and a star's 1×1 mesh takes lines
|
||||
/// through its points, at most one each way per anchor. Paths without an outline to follow
|
||||
/// still give a mesh (an open path closes straight; a line there and back maps onto its box),
|
||||
/// and a point that isn't finite gives none.
|
||||
#[test]
|
||||
fn a_mesh_takes_lines_only_where_the_outline_needs_them() {
|
||||
let box_ = Rect::new(100.0, 100.0, 500.0, 400.0);
|
||||
for path in [shapes::rectangle(box_), shapes::ellipse(box_)] {
|
||||
for (rows, cols) in [(1, 1), (4, 4), (2, 5)] {
|
||||
let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
assert_eq!((m.rows, m.cols), (rows, cols));
|
||||
}
|
||||
}
|
||||
let star = shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0);
|
||||
let m = GradientMesh::for_path(&star, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
assert!(m.rows > 1 && m.cols > 1 && m.rows <= 10 && m.cols <= 10 && m.is_valid(), "{}×{}", m.rows, m.cols);
|
||||
// Every anchor of the star is a point of the mesh.
|
||||
for a in &star.subpaths[0].anchors {
|
||||
assert!(m.points.iter().any(|q| q.p.distance(a.p) < 1e-6), "{:?} is not a mesh point", a.p);
|
||||
}
|
||||
// An open path closes with a straight segment.
|
||||
let open = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
|
||||
let m = GradientMesh::for_path(&open, 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
let closed = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], true));
|
||||
assert!(mesh_border_off_path(&m, &closed) < 0.1);
|
||||
// A line there and back.
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 50.0)], true));
|
||||
let m = GradientMesh::for_path(&line, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
assert!(m.is_valid() && m.points.iter().all(|q| q.p.is_finite()));
|
||||
let mut nan = shapes::rectangle(box_);
|
||||
nan.subpaths[0].anchors[1].p.x = f64::NAN;
|
||||
assert!(GradientMesh::for_path(&nan, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).is_none());
|
||||
// A path of many anchors stays within the line limit and keeps its outline.
|
||||
let many = shapes::star(Point::new(300.0, 300.0), 200.0, 190.0, 400, 0.0);
|
||||
let m = GradientMesh::for_path(&many, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
|
||||
assert!(m.is_valid() && m.rows as usize <= mesh::MAX_BORDER_LINES && m.cols as usize <= mesh::MAX_BORDER_LINES, "{}×{}", m.rows, m.cols);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_insert_and_remove_lines() {
|
||||
let mut m =
|
||||
|
||||
@@ -140,6 +140,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
}
|
||||
// Its art is plain, so it warps at this depth.
|
||||
NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w),
|
||||
// A ruler guide has no shape to warp.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
+481
-8
@@ -470,6 +470,384 @@ fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(V
|
||||
fit
|
||||
}
|
||||
|
||||
/// The cubic from `p0` to `p3` leaving `p0` along `d0` and reaching `p3` against `d1` (unit
|
||||
/// vectors; `d1` points from `p3` back into the curve) that comes closest (least squares) to the
|
||||
/// points `qs`, which lie along the way in order; `None` when no such cubic has handles of positive
|
||||
/// length. Each point is matched to the curve's nearest point, refined over a few rounds, as in
|
||||
/// [`fit_edge`].
|
||||
fn fit_tangents(qs: &[Point], (p0, d0): (Point, Vec2), (p3, d1): (Point, Vec2)) -> Option<CubicBez> {
|
||||
const ROUNDS: usize = 6;
|
||||
let n = qs.len() + 1;
|
||||
let mut ts: Vec<f64> = (1..n).map(|i| i as f64 / n as f64).collect();
|
||||
let mut fit = None;
|
||||
for _ in 0..ROUNDS {
|
||||
let (mut c11, mut c12, mut c22, mut x1, mut x2) = (0.0, 0.0, 0.0, 0.0, 0.0);
|
||||
for (q, &t) in qs.iter().zip(&ts) {
|
||||
let s = 1.0 - t;
|
||||
let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
|
||||
let (a1, a2) = (d0 * b1, d1 * b2);
|
||||
let r = q.to_vec2() - (b0 + b1) * p0.to_vec2() - (b2 + b3) * p3.to_vec2();
|
||||
c11 += a1.dot(a1);
|
||||
c12 += a1.dot(a2);
|
||||
c22 += a2.dot(a2);
|
||||
x1 += r.dot(a1);
|
||||
x2 += r.dot(a2);
|
||||
}
|
||||
let det = c11 * c22 - c12 * c12;
|
||||
if det.abs() < 1e-12 {
|
||||
break;
|
||||
}
|
||||
let (l1, l2) = ((c22 * x1 - c12 * x2) / det, (c11 * x2 - c12 * x1) / det);
|
||||
if !(l1.is_finite() && l2.is_finite() && l1 > 0.0 && l2 > 0.0) {
|
||||
break;
|
||||
}
|
||||
let c = CubicBez::new(p0, p0 + d0 * l1, p3 + d1 * l2, p3);
|
||||
fit = Some(c);
|
||||
let (a, b, k) = (c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2);
|
||||
for (q, t) in qs.iter().zip(ts.iter_mut()) {
|
||||
let s = 1.0 - *t;
|
||||
let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k);
|
||||
let acc = 6.0 * (s * (b - a) + *t * (k - b));
|
||||
let e = c.eval(*t) - *q;
|
||||
let den = v.hypot2() + e.dot(acc);
|
||||
if den.abs() > 1e-12 {
|
||||
*t = (*t - e.dot(v) / den).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
fit
|
||||
}
|
||||
|
||||
/// How far (in points) a border edge of a mesh made from a path may stray from the path's outline
|
||||
/// before the mesh takes a line through an anchor of the outline there; a thousandth of the outline's
|
||||
/// size when that is less.
|
||||
const BORDER_TOLERANCE: f64 = 0.1;
|
||||
|
||||
/// The most lines each way a mesh made from a path takes to keep its border on the outline
|
||||
/// ([`BORDER_TOLERANCE`]); past that, each border edge keeps its closest fit.
|
||||
pub(super) const MAX_BORDER_LINES: usize = 256;
|
||||
|
||||
/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline.
|
||||
const MAX_BORDER_ROUNDS: usize = 64;
|
||||
|
||||
/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border
|
||||
/// edge that can't follow the outline takes a mesh line through its sharpest corner first.
|
||||
const SHARP_TURN: f64 = 0.01;
|
||||
|
||||
/// Steps of each segment's parameter at which [`Outline`] measures the segment's length.
|
||||
const LENGTH_STEPS: usize = 32;
|
||||
|
||||
/// Points of the outline each border edge of a mesh made from a path is fitted to
|
||||
/// ([`Outline::fit`]).
|
||||
const FIT_POINTS: usize = 32;
|
||||
|
||||
/// Points of the outline, and of the fitted edge, at which [`Outline::fit`] measures how far the
|
||||
/// two stray from each other.
|
||||
const CHECK_POINTS: usize = 128;
|
||||
|
||||
/// The outline a gradient mesh is made from: the largest subpath of a path, running clockwise on
|
||||
/// screen, an open one closed by a straight segment, without segments of no length. A place on it
|
||||
/// is a length from its first anchor, measured along a polyline through even steps of each
|
||||
/// segment's parameter; the same length always gives the same point.
|
||||
struct Outline {
|
||||
segs: Vec<CubicBez>,
|
||||
/// Where each segment starts, and the whole length last.
|
||||
starts: Vec<f64>,
|
||||
/// For each segment, the length from its start at each of [`LENGTH_STEPS`] + 1 even steps of
|
||||
/// its parameter.
|
||||
table: Vec<[f64; LENGTH_STEPS + 1]>,
|
||||
/// Lengths closer than this are the same place.
|
||||
eps: f64,
|
||||
}
|
||||
|
||||
/// One side of the patch a mesh made from a path spans: the stretch of the outline from `start`,
|
||||
/// `len` long, run backwards when `reversed` (the bottom and left sides run against the outline).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Side {
|
||||
start: f64,
|
||||
len: f64,
|
||||
reversed: bool,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
/// The place on the outline at `f` (0 to 1) along the side.
|
||||
fn at(&self, f: f64) -> f64 {
|
||||
self.start + if self.reversed { (1.0 - f) * self.len } else { f * self.len }
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction a cubic leaves its start in (`false`) or reaches its end in (`true`), from the
|
||||
/// first handle or point that is not at the end; zero when all its points are together.
|
||||
fn cubic_tangent(c: &CubicBez, end: bool) -> Vec2 {
|
||||
let near = 1e-12 * (c.p0.to_vec2().hypot() + c.p3.to_vec2().hypot() + 1.0);
|
||||
let options = if end { [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0] } else { [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0] };
|
||||
options.into_iter().find(|v| v.hypot() > near).unwrap_or(Vec2::ZERO)
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
/// The outline of `path`; `None` when it has no subpath of two anchors or more, a point that
|
||||
/// isn't finite, or all its points on one line (a line there and back).
|
||||
fn new(path: &PathData) -> Option<Self> {
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
if !sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let mut sp = sp.clone();
|
||||
if sp.signed_area() < 0.0 {
|
||||
sp.reverse();
|
||||
}
|
||||
// A straight segment's parameter runs evenly along it.
|
||||
let line = |a: Point, b: Point| CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b);
|
||||
let mut segs: Vec<CubicBez> =
|
||||
(0..sp.segment_count()).map(|i| if sp.segment_is_line(i) { line(sp.segment(i).p0, sp.segment(i).p3) } else { sp.segment(i) }).collect();
|
||||
if !sp.closed
|
||||
&& let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first())
|
||||
{
|
||||
segs.push(line(a.p, b.p));
|
||||
}
|
||||
segs.retain(|c| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9));
|
||||
if segs.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut starts = Vec::with_capacity(segs.len() + 1);
|
||||
let mut table = Vec::with_capacity(segs.len());
|
||||
let mut total = 0.0;
|
||||
for c in &segs {
|
||||
let mut lens = [0.0; LENGTH_STEPS + 1];
|
||||
let mut prev = c.p0;
|
||||
for (k, len) in lens.iter_mut().enumerate().skip(1) {
|
||||
let p = c.eval(k as f64 / LENGTH_STEPS as f64);
|
||||
*len = prev.distance(p);
|
||||
prev = p;
|
||||
}
|
||||
for k in 1..=LENGTH_STEPS {
|
||||
lens[k] += lens[k - 1];
|
||||
}
|
||||
starts.push(total);
|
||||
total += lens[LENGTH_STEPS];
|
||||
table.push(lens);
|
||||
}
|
||||
starts.push(total);
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
return None;
|
||||
}
|
||||
// An outline whose points all lie on one line encloses nothing; one that crosses itself
|
||||
// (a bow tie) may have areas that cancel, and is still followed.
|
||||
let pts: Vec<Point> = segs.iter().flat_map(|c| [c.p0, c.p1, c.p2, c.p3]).collect();
|
||||
let first = pts.first().copied()?;
|
||||
let far = pts.iter().copied().max_by(|a, b| a.distance_squared(first).total_cmp(&b.distance_squared(first)))?;
|
||||
let dir = far - first;
|
||||
let width = pts.iter().map(|p| ((*p - first).cross(dir) / dir.hypot()).abs()).fold(0.0, f64::max);
|
||||
if !(dir.hypot() > 0.0 && width > 1e-9 * total) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { segs, starts, table, eps: total * 1e-9 })
|
||||
}
|
||||
|
||||
fn total(&self) -> f64 {
|
||||
self.starts.last().copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The bounding box of the outline.
|
||||
fn bounds(&self) -> Option<Rect> {
|
||||
self.segs.iter().map(|c| c.bounding_box()).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The parameter of segment `i` `local` along it (clamped to the segment).
|
||||
fn seg_t(&self, i: usize, local: f64) -> f64 {
|
||||
let Some(lens) = self.table.get(i) else { return 0.0 };
|
||||
let k = lens.partition_point(|x| *x <= local).clamp(1, LENGTH_STEPS) - 1;
|
||||
let (l0, l1) = (lens[k], lens[k + 1]);
|
||||
let f = if l1 > l0 { ((local - l0) / (l1 - l0)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(k as f64 + f) / LENGTH_STEPS as f64
|
||||
}
|
||||
|
||||
/// The segment and its parameter at place `s` (wrapping around); a place at the very end of a
|
||||
/// segment is the start of the next.
|
||||
fn locate(&self, s: f64) -> (usize, f64) {
|
||||
let n = self.segs.len();
|
||||
let s = s.rem_euclid(self.total());
|
||||
let mut i = self.starts.partition_point(|x| *x <= s).clamp(1, n) - 1;
|
||||
if self.starts.get(i + 1).is_some_and(|end| end - s <= self.eps) {
|
||||
i = (i + 1) % n;
|
||||
return (i, 0.0);
|
||||
}
|
||||
(i, self.seg_t(i, s - self.starts[i]))
|
||||
}
|
||||
|
||||
fn point(&self, s: f64) -> Point {
|
||||
let (i, t) = self.locate(s);
|
||||
self.segs.get(i).map_or(Point::ZERO, |c| c.eval(t))
|
||||
}
|
||||
|
||||
/// The anchors strictly inside the stretch from `a`, `len` long: each one's distance from `a`
|
||||
/// and the segment it starts.
|
||||
fn anchors_in(&self, a: f64, len: f64) -> Vec<(f64, usize)> {
|
||||
let (total, n) = (self.total(), self.segs.len());
|
||||
let a = a.rem_euclid(total);
|
||||
let (lo, hi) = (a + self.eps, a + len - self.eps);
|
||||
let mut out = vec![];
|
||||
for lap in [0.0, total] {
|
||||
let from = self.starts[..n].partition_point(|x| x + lap <= lo);
|
||||
for (i, start) in self.starts[..n].iter().enumerate().skip(from) {
|
||||
let p = start + lap;
|
||||
if p >= hi {
|
||||
break;
|
||||
}
|
||||
out.push((p - a, i));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The piece of the outline from `a`, `len` long, which no anchor lies inside.
|
||||
fn piece(&self, a: f64, len: f64) -> CubicBez {
|
||||
let (i, t0) = self.locate(a);
|
||||
let Some(c) = self.segs.get(i) else { return CubicBez::new(Point::ZERO, Point::ZERO, Point::ZERO, Point::ZERO) };
|
||||
// At a segment's start (a place at the end of the one before counts as that), none of it is behind.
|
||||
let behind = if t0 == 0.0 { 0.0 } else { a.rem_euclid(self.total()) - self.starts[i] };
|
||||
let t1 = self.seg_t(i, behind + len);
|
||||
c.subsegment(t0..t1.max(t0))
|
||||
}
|
||||
|
||||
/// The direction the outline leaves place `s` in (`into` false) or reaches it in (`into` true).
|
||||
fn tangent(&self, s: f64, into: bool) -> Vec2 {
|
||||
let n = self.segs.len();
|
||||
let (i, t) = self.locate(s);
|
||||
let c = match (into, t <= 0.0) {
|
||||
(true, true) => self.segs[(i + n - 1) % n],
|
||||
(true, false) => self.segs[i].subsegment(0.0..t),
|
||||
(false, _) => self.segs[i].subsegment(t..1.0),
|
||||
};
|
||||
cubic_tangent(&c, into)
|
||||
}
|
||||
|
||||
/// How sharply the outline turns at the anchor starting segment `i` (radians, 0 to π).
|
||||
fn turn(&self, i: usize) -> f64 {
|
||||
let s = self.starts[i];
|
||||
let (din, dout) = (self.tangent(s, true), self.tangent(s, false));
|
||||
din.cross(dout).atan2(din.dot(dout)).abs()
|
||||
}
|
||||
|
||||
/// The place on the outline nearest `q`.
|
||||
fn nearest(&self, q: Point) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let mut best = (f64::INFINITY, 0.0);
|
||||
for (i, c) in self.segs.iter().enumerate() {
|
||||
let near = c.nearest(q, 1e-9);
|
||||
if near.distance_sq < best.0 {
|
||||
// The length at that parameter, from the table.
|
||||
let lens = &self.table[i];
|
||||
let x = near.t * LENGTH_STEPS as f64;
|
||||
let k = (x.floor() as usize).min(LENGTH_STEPS - 1);
|
||||
let local = lens[k] + (lens[k + 1] - lens[k]) * (x - k as f64);
|
||||
best = (near.distance_sq, self.starts[i] + local);
|
||||
}
|
||||
}
|
||||
best.1
|
||||
}
|
||||
|
||||
/// The cubic standing for the stretch from `a`, `len` long, and how far it strays from it: the
|
||||
/// piece of the segment when no anchor lies inside, otherwise a cubic fitted to the outline with
|
||||
/// its ends along the outline's own directions there.
|
||||
fn fit(&self, a: f64, len: f64) -> (CubicBez, f64) {
|
||||
let (p0, p3) = (self.point(a), self.point(a + len));
|
||||
if len <= self.eps {
|
||||
return (CubicBez::new(p0, p0, p0, p0), 0.0);
|
||||
}
|
||||
let anchors = self.anchors_in(a, len);
|
||||
if anchors.is_empty() {
|
||||
return (self.piece(a, len), 0.0);
|
||||
}
|
||||
let qs: Vec<Point> = (1..FIT_POINTS).map(|i| self.point(a + len * i as f64 / FIT_POINTS as f64)).collect();
|
||||
let (d0, d1) = (self.tangent(a, false), -self.tangent(a + len, true));
|
||||
let unit = |v: Vec2| if v.hypot() > 0.0 { Some(v / v.hypot()) } else { None };
|
||||
let straight = CubicBez::new(p0, p0.lerp(p3, 1.0 / 3.0), p0.lerp(p3, 2.0 / 3.0), p3);
|
||||
let c = match (unit(d0), unit(d1)) {
|
||||
(Some(d0), Some(d1)) => fit_tangents(&qs, (p0, d0), (p3, d1)),
|
||||
_ => None,
|
||||
}
|
||||
.unwrap_or(straight);
|
||||
// Both ways: the outline's points from the cubic, and the cubic's points from the outline.
|
||||
// The outline is checked at even steps and at every anchor inside, so a spike or a notch
|
||||
// narrower than a step is not missed.
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let mut at: Vec<f64> = (0..=CHECK_POINTS).map(|i| len * i as f64 / CHECK_POINTS as f64).chain(anchors.iter().map(|(o, _)| *o)).collect();
|
||||
at.sort_by(f64::total_cmp);
|
||||
let line: Vec<Point> = at.iter().map(|o| self.point(a + o)).collect();
|
||||
let off_outline = line.iter().map(|q| c.nearest(*q, 1e-9).distance_sq.sqrt()).fold(0.0, f64::max);
|
||||
let off_cubic = (0..=CHECK_POINTS)
|
||||
.map(|i| {
|
||||
let p = c.eval(i as f64 / CHECK_POINTS as f64);
|
||||
line.windows(2)
|
||||
.map(|w| {
|
||||
let (u, v) = (w[0], w[1]);
|
||||
let d = v - u;
|
||||
let t = if d.hypot2() > 0.0 { ((p - u).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
p.distance(u + d * t)
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
})
|
||||
.fold(0.0, f64::max);
|
||||
(c, off_outline.max(off_cubic))
|
||||
}
|
||||
|
||||
/// The border edge of `side` from `f0` to `f1` (0 to 1 along it, rising), run the way the side
|
||||
/// runs, and when it strays from the outline by more than `tol`, where along the side (0 to 1)
|
||||
/// a mesh line through an anchor would help: the sharpest corner inside it, or the anchor
|
||||
/// nearest its middle when none is sharp.
|
||||
fn edge(&self, side: &Side, f0: f64, f1: f64, tol: f64) -> (CubicBez, Option<f64>) {
|
||||
let len = (f1 - f0) * side.len;
|
||||
let a = side.at(if side.reversed { f1 } else { f0 });
|
||||
let (c, off) = self.fit(a, len);
|
||||
let c = if side.reversed { CubicBez::new(c.p3, c.p2, c.p1, c.p0) } else { c };
|
||||
if off <= tol || side.len <= 0.0 {
|
||||
return (c, None);
|
||||
}
|
||||
let anchors = self.anchors_in(a, len);
|
||||
let sharpest = anchors.iter().map(|&(o, i)| (self.turn(i), o)).max_by(|x, y| x.0.total_cmp(&y.0));
|
||||
let at = match sharpest {
|
||||
Some((turn, o)) if turn > SHARP_TURN => Some(o),
|
||||
_ => anchors.iter().map(|&(o, _)| o).min_by(|x, y| (x - len / 2.0).abs().total_cmp(&(y - len / 2.0).abs())),
|
||||
};
|
||||
let split = at.map(|o| if side.reversed { f1 - o / side.len } else { f0 + o / side.len });
|
||||
(c, split.filter(|f| *f > f0 && *f < f1))
|
||||
}
|
||||
|
||||
/// The cuts (0 to 1) of the lines across sides `one` and `other`: `even`, and as many more as
|
||||
/// keep every border edge along them within `tol` of the outline (see [`Self::edge`]), at most
|
||||
/// [`MAX_BORDER_LINES`] in all.
|
||||
fn cuts(&self, one: &Side, other: &Side, even: Vec<f64>, tol: f64) -> Vec<f64> {
|
||||
let mut cuts = even;
|
||||
for _ in 0..MAX_BORDER_ROUNDS {
|
||||
let mut add: Vec<f64> =
|
||||
[one, other].iter().flat_map(|s| cuts.windows(2).filter_map(|w| self.edge(s, w[0], w[1], tol).1).collect::<Vec<_>>()).collect();
|
||||
add.retain(|f| cuts.iter().all(|c| (c - f).abs() > 1e-9));
|
||||
add.truncate((MAX_BORDER_LINES + 1).saturating_sub(cuts.len()));
|
||||
if add.is_empty() {
|
||||
break;
|
||||
}
|
||||
cuts.extend(add);
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
cuts.dedup_by(|x, y| (*x - *y).abs() <= 1e-9);
|
||||
}
|
||||
cuts
|
||||
}
|
||||
|
||||
/// The points along `side` at `knots` (rising, 0 to 1).
|
||||
fn side_points(&self, side: &Side, knots: &[f64]) -> Vec<Point> {
|
||||
knots.iter().map(|f| self.point(side.at(*f))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sorted union of `cuts` and `SIDE` even steps.
|
||||
fn side_knots(cuts: &[f64]) -> Vec<f64> {
|
||||
let mut k: Vec<f64> = (0..SIDE).map(|i| i as f64 / (SIDE - 1) as f64).chain(cuts.iter().copied()).collect();
|
||||
k.sort_by(f64::total_cmp);
|
||||
k.dedup_by(|x, y| (*x - *y).abs() <= 1e-9);
|
||||
k
|
||||
}
|
||||
|
||||
/// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles
|
||||
/// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer
|
||||
/// ends: each outer handle grown back by the share of the curve its edge had, which undoes the
|
||||
@@ -599,19 +977,104 @@ impl GradientMesh {
|
||||
|
||||
/// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`.
|
||||
pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option<Self> {
|
||||
let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?;
|
||||
m.highlight(appearance, highlight);
|
||||
Self::for_path_shaded(path, rows, cols, &|_| (base, 1.0), appearance, highlight)
|
||||
}
|
||||
|
||||
/// As [`Self::for_path_with`], then lightened per `appearance` ([`Self::highlight`]), measured
|
||||
/// by where each line crosses the patch.
|
||||
pub fn for_path_shaded(
|
||||
path: &PathData,
|
||||
rows: u32,
|
||||
cols: u32,
|
||||
color_at: &dyn Fn(Point) -> (Color, f32),
|
||||
appearance: MeshAppearance,
|
||||
highlight: f64,
|
||||
) -> Option<Self> {
|
||||
let (mut m, us, vs) = Self::build_for_path(path, rows, cols, color_at)?;
|
||||
m.highlight_at(appearance, highlight, &us, &vs);
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh for a path: the outline split at its corners, each point taking the
|
||||
/// colour and opacity `color_at` gives at its position (a gradient fill's, say).
|
||||
pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> {
|
||||
let coons = Coons::from_path(path)?;
|
||||
Self::build_for_path(path, rows, cols, color_at).map(|(m, ..)| m)
|
||||
}
|
||||
|
||||
/// The mesh of [`Self::for_path_with`] and where its column and row lines cross the patch (0
|
||||
/// to 1). Its border lies on the outline of the path's largest subpath (#2752): the patch's
|
||||
/// corners are the outline's places nearest the corners of its bounding box (when those don't
|
||||
/// come in order round the outline, the top left one and the places a quarter, a half and three
|
||||
/// quarters of the way round from it), its points on the
|
||||
/// border sit on the outline, and each border edge is the piece of the outline between its
|
||||
/// points, a single cubic. Where the outline bends through an anchor between two of the `rows`
|
||||
/// × `cols` lines and no single cubic follows it within [`BORDER_TOLERANCE`], the mesh takes a
|
||||
/// line through that anchor (its sharpest corner first), as many as that needs up to
|
||||
/// [`MAX_BORDER_LINES`] each way. `None` when the path has no outline or a point that isn't
|
||||
/// finite; an outline whose points all lie on one line gives the mesh of its bounding box.
|
||||
fn build_for_path(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<(Self, Vec<f64>, Vec<f64>)> {
|
||||
if !path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (us, vs) = (even_steps(cols), even_steps(rows));
|
||||
let Some((o, sides)) = Outline::new(path).and_then(|o| {
|
||||
let r = o.bounds()?;
|
||||
let [tl, mut tr, mut br, mut bl] = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| o.nearest(Point::new(x, y)));
|
||||
let span = |a: f64, b: f64| (b - a).rem_euclid(o.total());
|
||||
// Corners met out of order around the outline would make sides that overlap: the
|
||||
// other three then go a quarter of the way round from the top left each.
|
||||
let around = span(tl, tr) + span(tr, br) + span(br, bl) + span(bl, tl);
|
||||
if (around - o.total()).abs() > 1e-6 * o.total() {
|
||||
let quarter = o.total() / 4.0;
|
||||
(tr, br, bl) = (tl + quarter, tl + 2.0 * quarter, tl + 3.0 * quarter);
|
||||
}
|
||||
let sides = [
|
||||
Side { start: tl, len: span(tl, tr), reversed: false },
|
||||
Side { start: tr, len: span(tr, br), reversed: false },
|
||||
Side { start: br, len: span(br, bl), reversed: true },
|
||||
Side { start: bl, len: span(bl, tl), reversed: true },
|
||||
];
|
||||
Some((o, sides))
|
||||
}) else {
|
||||
// No outline to follow: the patch of the flattened outline (its bounding box when it
|
||||
// encloses nothing), with each border edge fitted.
|
||||
let coons = Coons::from_path(path)?;
|
||||
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
|
||||
m.fit_border(&coons, &us, &vs);
|
||||
return Some((m, us, vs));
|
||||
};
|
||||
let [top, right, bottom, left] = sides;
|
||||
let size = o.bounds().map_or(0.0, |r| r.width() + r.height());
|
||||
let tol = BORDER_TOLERANCE.min(size * 1e-3).max(o.eps);
|
||||
let us = o.cuts(&top, &bottom, us, tol);
|
||||
let vs = o.cuts(&left, &right, vs, tol);
|
||||
let (ku, kv) = (side_knots(&us), side_knots(&vs));
|
||||
let coons = Coons {
|
||||
top: o.side_points(&top, &ku),
|
||||
right: o.side_points(&right, &kv),
|
||||
bottom: o.side_points(&bottom, &ku),
|
||||
left: o.side_points(&left, &kv),
|
||||
knots: Some(Box::new([ku.clone(), kv.clone(), ku, kv])),
|
||||
};
|
||||
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
|
||||
m.fit_border(&coons, &us, &vs);
|
||||
Some(m)
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let edges = [(0, &top), (rows, &bottom)]
|
||||
.map(|(r, side)| (r, side, true))
|
||||
.into_iter()
|
||||
.chain([(0, &left), (cols, &right)].map(|(c, side)| (c, side, false)));
|
||||
for (line, side, along_u) in edges {
|
||||
let steps = if along_u { &us } else { &vs };
|
||||
for (k, w) in steps.windows(2).enumerate() {
|
||||
let (a, b, out, back) =
|
||||
if along_u { (m.idx(line, k), m.idx(line, k + 1), H_RIGHT, H_LEFT) } else { (m.idx(k, line), m.idx(k + 1, line), H_DOWN, H_UP) };
|
||||
let (c, _) = o.edge(side, w[0], w[1], tol);
|
||||
m.points[a].p = c.p0;
|
||||
m.points[b].p = c.p3;
|
||||
m.points[a].handles[out] = c.p1 - c.p0;
|
||||
m.points[b].handles[back] = c.p2 - c.p3;
|
||||
}
|
||||
}
|
||||
Some((m, us, vs))
|
||||
}
|
||||
|
||||
/// Give each edge on the mesh's border the handles that make it follow the outline it stands
|
||||
@@ -657,11 +1120,21 @@ impl GradientMesh {
|
||||
/// the edges, by at most `highlight` %. Each point lightens towards white in its own colour
|
||||
/// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232).
|
||||
pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) {
|
||||
let even = |n: u32| (0..=n).map(|i| f64::from(i) / f64::from(n)).collect::<Vec<_>>();
|
||||
let (us, vs) = (even(self.cols), even(self.rows));
|
||||
self.highlight_at(appearance, highlight, &us, &vs);
|
||||
}
|
||||
|
||||
/// As [`Self::highlight`], with the column lines at `us` and the row lines at `vs` (0 to 1
|
||||
/// across the patch); a mesh whose lines don't match them is left as it is.
|
||||
fn highlight_at(&mut self, appearance: MeshAppearance, highlight: f64, us: &[f64], vs: &[f64]) {
|
||||
let h = (highlight / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let (rows, cols) = (self.rows as usize, self.cols as usize);
|
||||
for r in 0..=rows {
|
||||
for c in 0..=cols {
|
||||
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
|
||||
if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 {
|
||||
return;
|
||||
}
|
||||
for (r, &v) in vs.iter().enumerate() {
|
||||
for (c, &u) in us.iter().enumerate() {
|
||||
let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge
|
||||
let w = match appearance {
|
||||
MeshAppearance::Flat => 0.0,
|
||||
|
||||
@@ -88,7 +88,7 @@ impl Document {
|
||||
}
|
||||
let mut n = 0;
|
||||
n += vec_bytes(&self.artboards) + self.artboards.iter().map(|a| a.name.capacity()).sum::<usize>();
|
||||
n += vec_bytes(&self.guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets);
|
||||
n += vec_bytes(&self.saved_guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets);
|
||||
n += vec_bytes(&self.text_threads) + self.text_threads.iter().map(vec_bytes).sum::<usize>();
|
||||
n += self.images.iter().map(|(k, b)| 4 * size_of::<usize>() + k.capacity() + b.mime.capacity() + size_of_val(b)).sum::<usize>();
|
||||
n += map_bytes(&self.export_settings) + map_bytes(&self.extra) + self.print_setup.as_ref().map_or(0, json_bytes);
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use live_shape::{LiveShape, Scaling};
|
||||
pub use opacity::{Knockout, OpacityMask, whiten};
|
||||
pub use ops::{flattens, keeps_gradient_fit};
|
||||
use wire::NodeWire;
|
||||
pub(crate) use wire::counted_list;
|
||||
pub use wire::{MAX_READ_NODES, with_node_budget};
|
||||
|
||||
fn yes() -> bool {
|
||||
|
||||
@@ -19,7 +19,7 @@ impl Node {
|
||||
|
||||
fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) {
|
||||
match &self.kind {
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {}
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } | NodeKind::SymbolInstance { .. } => {}
|
||||
NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let mut bp = BezPath::new();
|
||||
|
||||
@@ -56,4 +56,30 @@ impl LayerColor {
|
||||
LayerColor::Custom(c) => c,
|
||||
}
|
||||
}
|
||||
|
||||
/// The color as text: a preset's name from [`LAYER_COLORS`], else `#rrggbb` (lowercase).
|
||||
pub fn label_text(self) -> String {
|
||||
let preset = match self {
|
||||
LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(i)),
|
||||
LayerColor::Custom(_) => None,
|
||||
};
|
||||
preset.map_or_else(
|
||||
|| {
|
||||
let [r, g, b] = self.rgb();
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
},
|
||||
|(name, _)| (*name).to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The color [`LayerColor::label_text`] names: a preset's name exactly as [`LAYER_COLORS`]
|
||||
/// spells it, or `#rrggbb` with six hex digits. None for anything else.
|
||||
pub fn from_label_text(s: &str) -> Option<Self> {
|
||||
if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| *name == s) {
|
||||
return u8::try_from(i).ok().map(LayerColor::Preset);
|
||||
}
|
||||
let hex = s.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))?;
|
||||
let byte = |k: usize| u8::from_str_radix(&hex[k..k + 2], 16).ok();
|
||||
Some(LayerColor::Custom([byte(0)?, byte(2)?, byte(4)?]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +122,17 @@ pub enum NodeKind {
|
||||
Intertwine {
|
||||
children: Vec<Arc<Node>>,
|
||||
},
|
||||
/// A ruler guide: a straight line across the canvas, or across one artboard, that draws on
|
||||
/// screen only. It is always a direct child of a layer or sublayer, above the layer's other
|
||||
/// children, and has no bounds.
|
||||
RulerGuide {
|
||||
/// true: a vertical guide at x = `pos`; false: a horizontal one at y = `pos`.
|
||||
vertical: bool,
|
||||
pos: f64,
|
||||
/// The [`crate::Artboard::id`] of the artboard it runs across; None: across the canvas.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
artboard: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every
|
||||
@@ -215,6 +226,12 @@ mod kind_de {
|
||||
Intertwine {
|
||||
children: Vec<Arc<Node>>,
|
||||
},
|
||||
RulerGuide {
|
||||
vertical: bool,
|
||||
pos: f64,
|
||||
#[serde(default)]
|
||||
artboard: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for NodeKind {
|
||||
|
||||
@@ -80,6 +80,16 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// A ruler guide ([`NodeKind::RulerGuide`]).
|
||||
pub fn is_ruler_guide(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. })
|
||||
}
|
||||
|
||||
/// A guide of either kind: a ruler guide, or a path made into a guide.
|
||||
pub fn is_guide(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
@@ -91,7 +101,7 @@ impl Node {
|
||||
pub fn layer_art(&self, editable: bool) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, editable: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if editable && (!c.visible || c.locked || c.is_template()) {
|
||||
if c.is_ruler_guide() || (editable && (!c.visible || c.locked || c.is_template())) {
|
||||
continue;
|
||||
}
|
||||
if c.is_layer() {
|
||||
@@ -142,6 +152,7 @@ impl Node {
|
||||
NodeKind::Repeat(r) => r.kind.label(),
|
||||
NodeKind::PlacedDocument(_) => "Placed Document",
|
||||
NodeKind::Intertwine { .. } => "Intertwine",
|
||||
NodeKind::RulerGuide { .. } => "Guide",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +321,8 @@ impl Node {
|
||||
NodeKind::PlacedDocument(p) => Some(p.bounds()),
|
||||
// The members drawn over the others are drawn where they are.
|
||||
NodeKind::Intertwine { children } => union(children),
|
||||
// A ruler guide runs across the canvas (or an artboard): it adds nothing to a box.
|
||||
NodeKind::RulerGuide { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,7 +386,10 @@ impl Node {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) {
|
||||
Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric),
|
||||
Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual),
|
||||
// A symbol drawn at other than its natural size goes through its 9-slice guides.
|
||||
Some((s, art)) if moves_only(*xf) && s.document().symbol_slice_map_of(symbol, art.geometric, *xf).is_none() => {
|
||||
xf.transform_rect_bbox(art.visual)
|
||||
}
|
||||
Some((s, art)) => {
|
||||
let placed = xf.transform_rect_bbox(art.geometric);
|
||||
match s.placed_visual(symbol, *xf).or_else(|| s.sliced_visual(symbol, *xf)) {
|
||||
@@ -519,6 +535,9 @@ impl Node {
|
||||
}
|
||||
NodeKind::Mesh(m) => m.transform(a),
|
||||
NodeKind::Repeat(r) => r.transform(a, *sc),
|
||||
// A ruler guide stays where it is when the art around it (its layer) is transformed:
|
||||
// the guide commands move it.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
// The frames of the objects attached to a path move with them, and the distances along the
|
||||
// path follow the path as it is now (a live shape's path is regenerated).
|
||||
@@ -554,10 +573,10 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// Count of nodes in this subtree.
|
||||
/// Count of nodes in this subtree, ruler guides left out.
|
||||
pub fn count(&self) -> usize {
|
||||
let mut n = 0;
|
||||
self.walk(&mut |_| n += 1);
|
||||
self.walk(&mut |c| n += usize::from(!c.is_ruler_guide()));
|
||||
n
|
||||
}
|
||||
|
||||
@@ -566,7 +585,7 @@ impl Node {
|
||||
pub fn count_with_masks(&self) -> usize {
|
||||
let mut n = 0;
|
||||
self.walk(&mut |c| {
|
||||
n += 1;
|
||||
n += usize::from(!c.is_ruler_guide());
|
||||
if let Some(m) = &c.extras().mask {
|
||||
n += m.art.count_with_masks();
|
||||
}
|
||||
@@ -685,7 +704,7 @@ impl Node {
|
||||
/// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves.
|
||||
pub fn knockout_elements(children: &[Arc<Node>]) -> Vec<&Arc<Node>> {
|
||||
fn push<'a>(children: &'a [Arc<Node>], out: &mut Vec<&'a Arc<Node>>) {
|
||||
for c in children.iter().filter(|c| c.visible) {
|
||||
for c in children.iter().filter(|c| c.visible && !c.is_ruler_guide()) {
|
||||
match c.children() {
|
||||
Some(ch) if c.passes_knockout_through() => push(ch, out),
|
||||
_ => out.push(c),
|
||||
@@ -698,8 +717,62 @@ impl Node {
|
||||
}
|
||||
|
||||
/// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest.
|
||||
/// A layer whose first child is a ruler guide holds no art, so a guide never clips it.
|
||||
pub fn clips(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. })
|
||||
match &self.kind {
|
||||
NodeKind::Group { clip, .. } => *clip,
|
||||
NodeKind::Layer { clip, children, .. } => *clip && children.first().is_none_or(|c| !c.is_ruler_guide()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the ruler guides at the end of `children` (a layer's) begin: the index past the last
|
||||
/// child that is not one. Art goes below this index and ruler guides at or above it.
|
||||
pub fn guide_run_start(children: &[Arc<Node>]) -> usize {
|
||||
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
|
||||
pub fn strip_ruler_guides(&mut self) {
|
||||
if !self.holds_ruler_guides() {
|
||||
return;
|
||||
}
|
||||
if let Some(ch) = self.children_mut() {
|
||||
ch.retain(|c| !c.is_ruler_guide());
|
||||
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
|
||||
Arc::make_mut(c).strip_ruler_guides();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
|
||||
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
|
||||
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
if !self.holds_ruler_guides() {
|
||||
return;
|
||||
}
|
||||
if let Some(ch) = self.children_mut() {
|
||||
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
|
||||
let c = Arc::make_mut(c);
|
||||
match &mut c.kind {
|
||||
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
|
||||
_ => c.map_ruler_guide_positions(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this layer or one of its sublayers holds a ruler guide.
|
||||
pub fn holds_ruler_guides(&self) -> bool {
|
||||
self.is_layer() && self.children().is_some_and(|ch| ch.iter().any(|c| c.is_ruler_guide() || c.holds_ruler_guides()))
|
||||
}
|
||||
|
||||
/// The index that an insert into `children` at `index` uses for `node`: art stays below the
|
||||
/// layer's ruler guides and a ruler guide goes among them.
|
||||
pub fn insert_index(children: &[Arc<Node>], index: usize, node: &Node) -> usize {
|
||||
let start = Self::guide_run_start(children);
|
||||
let i = index.min(children.len());
|
||||
if node.is_ruler_guide() { i.max(start) } else { i.min(start) }
|
||||
}
|
||||
|
||||
/// Make this group or layer clip its children by its first child, or stop it.
|
||||
|
||||
@@ -145,9 +145,10 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> {
|
||||
}
|
||||
|
||||
/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol
|
||||
/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed
|
||||
/// file of repeated empty items stays small while they take memory once read.
|
||||
fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
|
||||
/// overrides, a document's saved ruler guides), each item counting against [`with_node_budget`]
|
||||
/// as an object does: a compressed file of repeated empty items stays small while they take
|
||||
/// memory once read.
|
||||
pub(crate) fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
|
||||
struct Items<T>(std::marker::PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> {
|
||||
type Value = Vec<T>;
|
||||
|
||||
@@ -584,6 +584,8 @@ impl<'a> NestedCount<'a> {
|
||||
(NodeKind::Repeat(r), _) => r.in_all(self),
|
||||
(NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 },
|
||||
(NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) },
|
||||
// A ruler guide draws nothing, so a repeat makes no copies of it.
|
||||
(NodeKind::RulerGuide { .. }, _) => Cost::default(),
|
||||
(_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }),
|
||||
_ => Cost { instances: 0, copies: 1 },
|
||||
};
|
||||
|
||||
@@ -7,7 +7,6 @@ use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest};
|
||||
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
|
||||
|
||||
use crate::appearance::HEAD_REACH;
|
||||
use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
|
||||
|
||||
/// Arc-length accuracy for placing a point along a profile (document points).
|
||||
@@ -395,18 +394,19 @@ impl StrokeLayer {
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
|
||||
/// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With
|
||||
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
|
||||
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
|
||||
/// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap)
|
||||
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
|
||||
/// chord the path bends through under it, so anywhere within its length of the end.
|
||||
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
|
||||
let hw = self.arrow_weight(end);
|
||||
let v = p - at;
|
||||
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
|
||||
let (hw, v) = (self.arrow_weight(end), p - at);
|
||||
match self.arrow_align {
|
||||
ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol,
|
||||
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
|
||||
ArrowAlign::Extend => {
|
||||
let along = v.dot(out);
|
||||
v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol
|
||||
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-13
@@ -39,16 +39,16 @@ pub struct Selection {
|
||||
/// clears them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub slices: Vec<NodeId>,
|
||||
/// Ruler guides selected with a selection tool, as indexes into [`Document::guides`]. A new
|
||||
/// Ruler guides selected with a selection tool, by node id ([`Document::ruler_guides`]). A new
|
||||
/// selection ([`Self::set`]) clears them; Shift-adding or -removing objects keeps them, so
|
||||
/// guides and objects can be selected together, in either order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub guides: Vec<usize>,
|
||||
/// A selected ruler guide that is the key object for Align instead of [`Self::key`] (an index
|
||||
/// into [`Document::guides`], one of [`Self::guides`]): the objects line up on it. Never set
|
||||
/// with `key`; [`Self::prune`] clears it when no object is selected to align to it.
|
||||
pub guides: Vec<NodeId>,
|
||||
/// A selected ruler guide that is the key object for Align instead of [`Self::key`] (one of
|
||||
/// [`Self::guides`]): the objects line up on it. Never set with `key`; [`Self::prune`] clears
|
||||
/// it when no object is selected to align to it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<usize>,
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
@@ -139,10 +139,10 @@ impl Selection {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Select ruler guides `indexes` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, indexes: impl IntoIterator<Item = usize>) {
|
||||
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for i in indexes {
|
||||
for i in ids {
|
||||
if !self.guides.contains(&i) {
|
||||
self.guides.push(i);
|
||||
}
|
||||
@@ -150,7 +150,7 @@ impl Selection {
|
||||
}
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
pub fn toggle_guide(&mut self, i: usize) {
|
||||
pub fn toggle_guide(&mut self, i: NodeId) {
|
||||
self.symbol_part = None;
|
||||
if let Some(k) = self.guides.iter().position(|g| *g == i) {
|
||||
self.guides.remove(k);
|
||||
@@ -201,7 +201,9 @@ impl Selection {
|
||||
pub fn prune(&mut self, doc: &Document) {
|
||||
// Every id this looks up, found in one walk of the tree.
|
||||
let ids = self.objects.iter().chain(self.anchors.keys()).chain(self.segments.keys()).copied().chain(self.key).chain(self.target);
|
||||
let found = doc.index_paths(ids);
|
||||
let mut found = doc.index_paths(ids);
|
||||
// A ruler guide is selected in `guides` only, never as an object, an anchor or the key.
|
||||
found.retain(|_, p| !doc.node_at(p).is_some_and(|n| n.is_ruler_guide()));
|
||||
self.objects.retain(|id| found.contains_key(id));
|
||||
self.anchors.retain(|id, _| found.contains_key(id));
|
||||
self.segments.retain(|id, refs| {
|
||||
@@ -209,8 +211,12 @@ impl Selection {
|
||||
refs.retain(|&(si, seg)| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count()));
|
||||
!refs.is_empty() && self.objects.contains(id) && self.anchors.contains_key(id)
|
||||
});
|
||||
// Guides on a hidden or locked layer can't stay selected.
|
||||
self.guides.retain(|i| doc.guides.get(*i).is_some_and(|g| doc.guide_editable(g)));
|
||||
// Guides that are gone, or hidden or locked (themselves or by their layer), can't stay
|
||||
// selected.
|
||||
if !self.guides.is_empty() {
|
||||
let editable = doc.editable();
|
||||
self.guides.retain(|id| doc.node(*id).is_some_and(|n| n.is_ruler_guide()) && editable(*id));
|
||||
}
|
||||
// The key object stays while another selected object lies outside it, or while ruler
|
||||
// guides are selected for it to line up (#2143).
|
||||
let keep = self.key.and_then(|k| found.get(&k)).and_then(|p| doc.node_at(p)).is_some_and(|n| {
|
||||
|
||||
@@ -20,25 +20,30 @@ fn basic_ops() {
|
||||
fn guides_are_selected_on_their_own() {
|
||||
let mut s = Selection::default();
|
||||
s.add(NodeId(1));
|
||||
s.set_guides([2, 0, 2]);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![2, 0]));
|
||||
let (g0, g2) = (NodeId(10), NodeId(12));
|
||||
s.set_guides([g2, g0, g2]);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![g2, g0]));
|
||||
assert!(s.has_objects_or_guides() && s.is_empty());
|
||||
// Shift-adding an object keeps them; a new selection doesn't.
|
||||
s.add(NodeId(1));
|
||||
assert_eq!(s.guides, vec![2, 0]);
|
||||
assert_eq!(s.guides, vec![g2, g0]);
|
||||
s.set([NodeId(1)]);
|
||||
assert!(s.guides.is_empty());
|
||||
// Toggled, a guide joins (or leaves) the selected objects.
|
||||
s.toggle_guide(0);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![0]));
|
||||
s.toggle_guide(0);
|
||||
s.toggle_guide(g0);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![g0]));
|
||||
s.toggle_guide(g0);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![]));
|
||||
// Pruning drops guides the document no longer has.
|
||||
// Pruning drops guides the document no longer has, ids of other objects, and guides that are
|
||||
// locked or hidden themselves.
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.guides.push(crate::Guide::new(true, 10.0));
|
||||
s.set_guides([0, 1]);
|
||||
let layer = d.layers[0].id;
|
||||
let kept = d.add_ruler_guide(&crate::Guide::new(true, 10.0));
|
||||
let locked = d.add_ruler_guide(&crate::Guide { locked: true, ..crate::Guide::new(true, 20.0) });
|
||||
let hidden = d.add_ruler_guide(&crate::Guide { hidden: true, ..crate::Guide::new(true, 30.0) });
|
||||
s.set_guides([kept, NodeId(9999), layer, locked, hidden]);
|
||||
s.prune(&d);
|
||||
assert_eq!(s.guides, vec![0]);
|
||||
assert_eq!(s.guides, vec![kept]);
|
||||
}
|
||||
|
||||
/// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers
|
||||
@@ -131,16 +136,26 @@ fn guides_show_and_lock_with_their_layer() {
|
||||
assert!(d.guide_shown(&crate::Guide::new(false, 5.0)));
|
||||
let gone = crate::Guide { layer: Some(NodeId(9999)), ..crate::Guide::new(true, 1.0) };
|
||||
assert!(d.guide_shown(&gone) && d.guide_editable(&gone));
|
||||
d.guides.push(g);
|
||||
assert_eq!(d.guides_on(layer).count(), 1);
|
||||
// Guides on no layer, or a gone one, are adopted by the top visible, unlocked layer.
|
||||
// As a node, a guide shows and locks with its layer and on its own.
|
||||
let id = d.add_ruler_guide(&g);
|
||||
let node = d.ruler_guide(id).unwrap();
|
||||
assert_eq!(d.guides_on(layer), std::slice::from_ref(&node));
|
||||
assert!(!d.guide_shown(&node) && !d.guide_editable(&node), "its layer is hidden");
|
||||
d.node_mut(layer).unwrap().visible = true;
|
||||
d.node_mut(layer).unwrap().locked = false;
|
||||
d.guides.push(crate::Guide::new(false, 5.0));
|
||||
d.guides.push(gone);
|
||||
assert_eq!(d.adopt_guides(), 2);
|
||||
assert!(d.guides.iter().all(|g| g.layer == Some(layer)));
|
||||
assert_eq!(d.adopt_guides(), 0, "once");
|
||||
assert!(d.guide_shown(&node) && d.guide_editable(&node));
|
||||
d.node_mut(id).unwrap().locked = true;
|
||||
let node = d.ruler_guide(id).unwrap();
|
||||
assert!(d.guide_shown(&node) && !d.guide_editable(&node), "locked itself");
|
||||
d.node_mut(id).unwrap().visible = false;
|
||||
assert!(!d.guide_shown(&node), "hidden itself");
|
||||
// Saved guides on no layer, or a gone one, go on the top visible, unlocked layer.
|
||||
d.saved_guides.push(crate::Guide::new(false, 5.0));
|
||||
d.saved_guides.push(gone);
|
||||
assert_eq!(d.guides_into_nodes(), 2);
|
||||
assert!(d.ruler_guides().iter().all(|g| g.layer == Some(layer)));
|
||||
assert_eq!(d.ruler_guides().len(), 3);
|
||||
assert_eq!(d.guides_into_nodes(), 0, "once");
|
||||
// A guide saved before guides had layers reads as one on no layer.
|
||||
let old: crate::Guide = serde_json::from_str(r#"{"vertical": true, "pos": 5.0}"#).unwrap();
|
||||
assert_eq!(old.layer, None);
|
||||
@@ -267,7 +282,7 @@ fn random_selection(r: &mut u64, ids: &[NodeId]) -> Selection {
|
||||
s.key = s.objects.get(below(r, s.objects.len() as u64) as usize).copied();
|
||||
s.target = ids.get(below(r, ids.len() as u64) as usize).copied().filter(|_| below(r, 2) == 0);
|
||||
s.slices = ids.iter().copied().take(below(r, 3) as usize).collect();
|
||||
s.guides = vec![1, 0];
|
||||
s.guides = vec![NodeId(1), NodeId(0)];
|
||||
s
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,8 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
|
||||
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
|
||||
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -453,6 +455,71 @@ fn blends_transparency() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look).
|
||||
fn game_hud() -> Vec<GraphicStyle> {
|
||||
vec![
|
||||
style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]),
|
||||
style(
|
||||
"Mana Glow",
|
||||
vec![F(fill("#3498db"))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))],
|
||||
),
|
||||
style(
|
||||
"Damage Flash",
|
||||
vec![F(fill("#ff6b35"))],
|
||||
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))],
|
||||
),
|
||||
style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]),
|
||||
style(
|
||||
"Coin Shine",
|
||||
vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))],
|
||||
vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))],
|
||||
),
|
||||
style(
|
||||
"Boss Alert",
|
||||
vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Status Effects: buffs and debuffs for RPG/gamedev art (original, catalogue stylize effects only).
|
||||
fn status_effects() -> Vec<GraphicStyle> {
|
||||
let stealth = GraphicStyle {
|
||||
opacity: 0.45,
|
||||
blend: BlendMode::Normal,
|
||||
..style("Stealth Fade", vec![F(fill("#7f8c8d")), S(stroke("#2c3e50", 1.0))], vec![])
|
||||
};
|
||||
vec![
|
||||
style(
|
||||
"Poison Tint",
|
||||
vec![F(fill("#2ecc71"))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 80.0, "blur": 6.0, "color": "#58d68d"}))],
|
||||
),
|
||||
style(
|
||||
"Freeze Edge",
|
||||
vec![F(fill("#aed6f1")), S(stroke("#5dade2", 2.0))],
|
||||
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 70.0, "blur": 5.0, "color": "#d6eaf8", "source": "edge"}))],
|
||||
),
|
||||
style(
|
||||
"Burn Aura",
|
||||
vec![F(fill("#e67e22"))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 8.0, "color": "#f39c12"}))],
|
||||
),
|
||||
style(
|
||||
"Stun Pulse",
|
||||
vec![F(fill("#f4d03f"))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 7.0, "color": "#f7dc6f"}))],
|
||||
),
|
||||
stealth,
|
||||
style(
|
||||
"Shield Buff",
|
||||
vec![F(fill("#85c1e9")), S(round("#2874a6", 2.0))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 70.0, "blur": 5.0, "color": "#5dade2"}))],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -475,6 +542,14 @@ mod tests {
|
||||
}
|
||||
assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once");
|
||||
assert!(builtin_style_library("nope").is_none());
|
||||
let game = builtin_style_library("game-hud").unwrap();
|
||||
assert_eq!(game.name, "Game HUD");
|
||||
let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
|
||||
let status = builtin_style_library("status-effects").unwrap();
|
||||
assert_eq!(status.name, "Status Effects");
|
||||
let status_names: Vec<&str> = status.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -195,9 +195,10 @@ impl Document {
|
||||
/// The default name of a solid swatch: its values in its own colour model ("C=10 M=20 Y=30 K=0",
|
||||
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
|
||||
pub fn color_name(c: Color) -> String {
|
||||
// Clamped first, so a conversion's tiny negative never reads "-0".
|
||||
let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round();
|
||||
let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round();
|
||||
// Clamped first, so a conversion's tiny negative never reads "-0". `clamp` keeps a -0.0, so
|
||||
// `+ 0.0` turns it into 0.
|
||||
let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round() + 0.0;
|
||||
let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() + 0.0;
|
||||
match c {
|
||||
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
|
||||
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
|
||||
@@ -493,6 +494,13 @@ mod tests {
|
||||
assert_eq!(d.new_swatch_name(&Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "R=255 G=0 B=0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_names_read_negative_zero_as_zero() {
|
||||
assert_eq!(color_name(Color::Rgb { r: -0.0, g: 0.5, b: -0.0 }), "R=0 G=128 B=0");
|
||||
assert_eq!(color_name(Color::Cmyk { c: -0.0, m: 0.2, y: 0.3, k: -0.0 }), "C=0 M=20 Y=30 K=0");
|
||||
assert_eq!(color_name(Color::Gray { k: -0.0 }), "Gray K=0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_swatch_names_match_naming_each_swatch_as_it_is_added() {
|
||||
let (mut d, _, _) = doc();
|
||||
|
||||
@@ -492,7 +492,8 @@ impl NineSliceMap {
|
||||
/// [`Self::most_placed`] for a container placed by [`Self::container`].
|
||||
fn most_container(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
|
||||
let own = self.most_mask(n, boxes, depth).saturating_add(1);
|
||||
n.children().into_iter().flatten().fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1)))
|
||||
// As [`Self::container`] places it: a layer's ruler guides left out.
|
||||
n.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1)))
|
||||
}
|
||||
|
||||
/// [`Self::most_placed`] for the opacity mask of `n` as [`Self::place_mask`] places it: a
|
||||
@@ -560,7 +561,8 @@ impl NineSliceMap {
|
||||
let kids = out.children_mut().map(std::mem::take).unwrap_or_default();
|
||||
out.transform(center, false);
|
||||
if let Some(children) = out.children_mut() {
|
||||
*children = kids.iter().map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect();
|
||||
// A ruler guide of a layer is not art: it is not placed.
|
||||
*children = kids.iter().filter(|c| !c.is_ruler_guide()).map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect();
|
||||
}
|
||||
self.place_mask(n, &mut out, boxes, depth);
|
||||
out
|
||||
|
||||
@@ -5,6 +5,52 @@ mod lookups;
|
||||
mod slices;
|
||||
mod units;
|
||||
|
||||
/// A guide label's text is a layer color's name or `#rrggbb`, and reads back as the same color;
|
||||
/// other spellings, an alpha part and a short form are not labels.
|
||||
#[test]
|
||||
fn guide_label_text_names_a_layer_color_or_rgb() {
|
||||
for (i, (name, _)) in LAYER_COLORS.iter().enumerate() {
|
||||
let c = LayerColor::Preset(u8::try_from(i).unwrap());
|
||||
assert_eq!(c.label_text(), *name);
|
||||
assert_eq!(LayerColor::from_label_text(name), Some(c));
|
||||
}
|
||||
let custom = LayerColor::Custom([0x0a, 0xbc, 0xff]);
|
||||
assert_eq!(custom.label_text(), "#0abcff");
|
||||
assert_eq!(LayerColor::from_label_text("#0ABCff"), Some(custom));
|
||||
// A preset past the layer colors has no name: its text is the color it draws in.
|
||||
let [r, g, b] = LayerColor::Preset(200).rgb();
|
||||
assert_eq!(LayerColor::Preset(200).label_text(), format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
for bad in ["red", "Red ", "", "#", "#fff", "#0abcff00", "0abcff", "#0abcfg", "#0abcff"] {
|
||||
assert_eq!(LayerColor::from_label_text(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard's guide label: none unless set, left out of the JSON when none, and a preset past
|
||||
/// the layer colors reading as none.
|
||||
#[test]
|
||||
fn artboard_guide_label_defaults_and_skips_in_json() {
|
||||
let mut a = Document::new(100.0, 100.0).artboards[0].clone();
|
||||
assert_eq!(a.guide_label, None);
|
||||
let plain = serde_json::to_value(&a).unwrap();
|
||||
assert!(plain.get("guide_label").is_none(), "{plain}");
|
||||
a.guide_label = Some(LayerColor::Custom([1, 2, 3]));
|
||||
let v = serde_json::to_value(&a).unwrap();
|
||||
assert_eq!(v["guide_label"], serde_json::json!({"Custom": [1, 2, 3]}));
|
||||
assert_eq!(serde_json::from_value::<Artboard>(v).unwrap(), a);
|
||||
let read = |label: serde_json::Value| {
|
||||
let mut v = plain.clone();
|
||||
v["guide_label"] = label;
|
||||
serde_json::from_value::<Artboard>(v).map(|a| a.guide_label)
|
||||
};
|
||||
assert_eq!(read(serde_json::json!({"Preset": 26})).unwrap(), Some(LayerColor::Preset(26)));
|
||||
assert_eq!(read(serde_json::json!({"Preset": 27})).unwrap(), None);
|
||||
assert_eq!(read(serde_json::json!({"Preset": 255})).unwrap(), None);
|
||||
assert_eq!(read(serde_json::Value::Null).unwrap(), None);
|
||||
assert!(read(serde_json::json!({"Preset": -1})).is_err());
|
||||
assert!(read(serde_json::json!({"Tint": 1})).is_err());
|
||||
assert_eq!(serde_json::from_value::<Artboard>(plain).unwrap().guide_label, None, "older files have none");
|
||||
}
|
||||
|
||||
/// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch
|
||||
/// are binary fractions now, and the minor ticks between them stay binary too; every other
|
||||
/// unit is still read in tenths.
|
||||
@@ -45,6 +91,268 @@ fn an_inch_ruler_steps_in_binary_fractions() {
|
||||
assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0));
|
||||
}
|
||||
|
||||
/// Ruler guide nodes on a layer and a sublayer are not art: Select All, a layer's target circle,
|
||||
/// the object count, the art's bounds, clicks, the marquee and a knockout layer's elements are
|
||||
/// the same as without them, and transforming the layer leaves them where they are.
|
||||
#[test]
|
||||
fn ruler_guide_nodes_are_not_art() {
|
||||
use crate::hit::{HitOptions, hit_test, marquee, objects_at};
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(2))).unwrap();
|
||||
let s1 = d.alloc_id();
|
||||
d.insert(Some(sub), usize::MAX, Node::path(s1, shapes::rectangle(Rect::new(40.0, 0.0, 50.0, 10.0)), Appearance::default_art())).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
let all = Rect::new(-100.0, -100.0, 700.0, 900.0);
|
||||
let before = (
|
||||
d.selectable_art(),
|
||||
d.layers[0].layer_art(false),
|
||||
d.node_count(),
|
||||
d.art_bounds(),
|
||||
marquee(&d, all, None, false),
|
||||
hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)),
|
||||
);
|
||||
let guide = |id, vertical, pos| Node::new(id, NodeKind::RulerGuide { vertical, pos, artboard: None });
|
||||
let (g1, g2, g3) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, guide(g1, true, 5.0)).unwrap();
|
||||
d.insert(Some(layer), usize::MAX, guide(g2, false, 5.0)).unwrap();
|
||||
d.insert(Some(sub), usize::MAX, guide(g3, true, 45.0)).unwrap();
|
||||
let after = (
|
||||
d.selectable_art(),
|
||||
d.layers[0].layer_art(false),
|
||||
d.node_count(),
|
||||
d.art_bounds(),
|
||||
marquee(&d, all, None, false),
|
||||
hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)),
|
||||
);
|
||||
assert_eq!(after, before);
|
||||
assert_eq!(after.0, [a, b, s1]);
|
||||
for p in [Point::new(5.0, 300.0), Point::new(300.0, 5.0), Point::new(45.0, 300.0)] {
|
||||
assert!(hit_test(&d, p, opt).is_none(), "nothing to click on the guide at {p:?}");
|
||||
assert!(objects_at(&d, p, opt, None).is_empty());
|
||||
}
|
||||
let mut sel = Selection::default();
|
||||
sel.set_target(&d, layer);
|
||||
assert_eq!(sel.objects, [a, b, s1]);
|
||||
let children = d.layers[0].children().unwrap().clone();
|
||||
assert_eq!(Node::knockout_elements(&children).iter().map(|c| c.id).collect::<Vec<_>>(), [a, b, s1]);
|
||||
assert!(d.node(g1).is_some_and(Node::is_ruler_guide) && d.node(g1).is_some_and(Node::is_guide));
|
||||
assert_eq!(d.node(g1).map(Node::geometric_bounds), Some(None));
|
||||
let mut moved = (*d.layers[0]).clone();
|
||||
moved.transform(Affine::translate((10.0, 10.0)), true);
|
||||
let g = moved.children().unwrap().iter().find(|c| c.id == g1).unwrap();
|
||||
assert!(matches!(g.kind, NodeKind::RulerGuide { pos, .. } if pos == 5.0));
|
||||
}
|
||||
|
||||
/// Art inserted or moved onto a layer goes below the layer's ruler guides, a ruler guide goes
|
||||
/// among them, and a clipped layer whose art is gone does not clip by a guide.
|
||||
#[test]
|
||||
fn layer_art_stays_below_its_ruler_guides() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let guide = |id, pos| Node::new(id, NodeKind::RulerGuide { vertical: true, pos, artboard: None });
|
||||
let (g1, g2) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, guide(g1, 5.0)).unwrap();
|
||||
// Asked for the bottom, a guide still goes above the art.
|
||||
d.insert(Some(layer), 0, guide(g2, 7.0)).unwrap();
|
||||
let ids = |d: &Document| d.layers[0].children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&d), [a, b, g2, g1]);
|
||||
let c = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(c, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
|
||||
assert_eq!(ids(&d), [a, b, c, g2, g1]);
|
||||
d.move_node(a, Some(layer), usize::MAX).unwrap();
|
||||
assert_eq!(ids(&d), [b, c, a, g2, g1]);
|
||||
d.move_node(g1, Some(layer), 0).unwrap();
|
||||
assert_eq!(ids(&d), [b, c, a, g1, g2]);
|
||||
assert!(d.layer_object(g1).is_none());
|
||||
assert_eq!(d.layer_object(a).map(|n| n.id), Some(a));
|
||||
|
||||
// A clipped layer clips by its first art object; with only guides left it clips nothing.
|
||||
if let Some(NodeKind::Layer { clip, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
|
||||
*clip = true;
|
||||
}
|
||||
assert!(d.node(layer).is_some_and(Node::clips));
|
||||
for id in [a, b, c] {
|
||||
d.remove(id).unwrap();
|
||||
}
|
||||
assert!(!d.node(layer).is_some_and(Node::clips));
|
||||
|
||||
// Reading a file that clips a layer by a path beyond the canvas empties the layer of its art
|
||||
// only: its guides stay.
|
||||
let far = d.alloc_id();
|
||||
d.insert(Some(layer), 0, Node::path(far, shapes::rectangle(Rect::new(0.0, 0.0, 1e9, 10.0)), Appearance::default_art())).unwrap();
|
||||
assert!(d.node(layer).is_some_and(Node::clips));
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!(gone.objects, 1);
|
||||
assert_eq!(ids(&d), [g1, g2]);
|
||||
}
|
||||
|
||||
/// `ruler_guides` keeps its list while the layers are unchanged, and lists again after any change
|
||||
/// inside a layer, made in place or on a shared copy, and after layers are added, removed or
|
||||
/// reordered.
|
||||
#[test]
|
||||
fn ruler_guides_follow_every_edit() {
|
||||
let (mut d, _, _) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
|
||||
let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 5.0) });
|
||||
let g2 = d.add_ruler_guide(&Guide { layer: Some(sub), ..Guide::new(false, 6.0) });
|
||||
let line = |d: &Document| d.ruler_guides().iter().map(|g| (g.id, g.pos, g.hidden, g.layer)).collect::<Vec<_>>();
|
||||
assert_eq!(line(&d), [(Some(g1), 5.0, false, Some(layer)), (Some(g2), 6.0, false, Some(sub))]);
|
||||
// Changed in place: the document is the only holder of its layers.
|
||||
assert!(d.edit_ruler_guide(g2, |g| g.pos = 9.0));
|
||||
assert_eq!(line(&d)[1], (Some(g2), 9.0, false, Some(sub)));
|
||||
d.node_mut(g1).unwrap().visible = false;
|
||||
assert_eq!(line(&d)[0], (Some(g1), 5.0, true, Some(layer)));
|
||||
// A copy shares the list until one of them changes.
|
||||
let copy = d.clone();
|
||||
assert_eq!(line(©), line(&d));
|
||||
d.remove(g1).unwrap();
|
||||
assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub))]);
|
||||
assert_eq!(line(©).len(), 2);
|
||||
// A new layer with a guide, then the layers reordered and one removed.
|
||||
let top = d.add_layer(None);
|
||||
let g3 = d.add_ruler_guide(&Guide { layer: Some(top), ..Guide::new(true, 1.0) });
|
||||
assert_eq!(line(&d).len(), 2);
|
||||
d.layers.reverse();
|
||||
assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub)), (Some(g3), 1.0, false, Some(top))]);
|
||||
d.layers.retain(|l| l.id != layer);
|
||||
assert_eq!(line(&d), [(Some(g3), 1.0, false, Some(top))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_ruler_guides_leaves_a_layers_art() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let guide = |id| Node::new(id, NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None });
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
|
||||
let (g1, g2) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, guide(g1)).unwrap();
|
||||
d.insert(Some(sub), usize::MAX, guide(g2)).unwrap();
|
||||
let mut n = (*d.layers[0]).clone();
|
||||
assert!(n.holds_ruler_guides());
|
||||
n.strip_ruler_guides();
|
||||
assert!(!n.holds_ruler_guides());
|
||||
let mut left = vec![];
|
||||
n.walk(&mut |c| left.push(c.id));
|
||||
assert_eq!(left, [layer, a, b, sub]);
|
||||
// Other nodes hold none and are left as they are.
|
||||
let mut p = d.node(a).unwrap().clone();
|
||||
p.strip_ruler_guides();
|
||||
assert_eq!(&p, d.node(a).unwrap());
|
||||
}
|
||||
|
||||
/// The saved `guides` list becomes ruler guide nodes and is written back from them unchanged:
|
||||
/// guides on a layer, a sublayer, no layer and a deleted layer, with an artboard guide, keep their
|
||||
/// order, ids, names and their own lock and visibility; a saved id that another node has is
|
||||
/// replaced; and the saved form of an older entry still reads.
|
||||
#[test]
|
||||
fn saved_guides_become_nodes_and_are_saved_back_the_same() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let top = d.add_layer(Some("Top"));
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
|
||||
let json = serde_json::json!([
|
||||
{"vertical": true, "pos": 10.0, "layer": layer},
|
||||
{"vertical": false, "pos": 20.0, "layer": sub, "artboard": 1},
|
||||
{"vertical": true, "pos": 30.0},
|
||||
{"vertical": false, "pos": 40.0, "layer": 9999},
|
||||
{"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true},
|
||||
{"vertical": true, "pos": 60.0, "layer": layer, "id": a},
|
||||
]);
|
||||
d.saved_guides = serde_json::from_value(json).unwrap();
|
||||
let before = d.peek_next_id();
|
||||
assert_eq!(d.guides_into_nodes(), 6);
|
||||
assert!(d.saved_guides.is_empty());
|
||||
let guides = d.ruler_guides();
|
||||
let lines: Vec<(f64, Option<NodeId>)> = guides.iter().map(|g| (g.pos, g.layer)).collect();
|
||||
// A guide on no layer, or on a deleted one, goes on the top visible, unlocked layer.
|
||||
assert_eq!(lines[..4], [(50.0, Some(layer)), (10.0, Some(layer)), (20.0, Some(sub)), (30.0, Some(top))], "by id: the kept id first");
|
||||
assert_eq!(lines[4..], [(40.0, Some(top)), (60.0, Some(layer))]);
|
||||
assert_eq!(guides[0].id, Some(NodeId(500)));
|
||||
assert!(guides[1..].iter().all(|g| g.id.unwrap().0 > 500), "new ids start above a kept one");
|
||||
assert_ne!(guides[5].id, Some(a), "an id another object has is not reused");
|
||||
assert!(d.peek_next_id() > 500 && before <= 500);
|
||||
let edge = d.node(NodeId(500)).unwrap();
|
||||
assert!(edge.locked && !edge.visible && edge.name.as_deref() == Some("Edge"));
|
||||
assert_eq!(guides[2].artboard, Some(1));
|
||||
// Each layer's guides sit at its top, above its art and its sublayer.
|
||||
let kids: Vec<bool> = d.node(layer).unwrap().children().unwrap().iter().map(|c| c.is_ruler_guide()).collect();
|
||||
assert_eq!(kids, [false, false, false, true, true, true]);
|
||||
assert_eq!(d.guides_into_nodes(), 0, "a second run does nothing");
|
||||
|
||||
// Saved back: the guides leave the layers and the list names each one's layer and id.
|
||||
let mut saved = d.clone();
|
||||
saved.guides_to_saved();
|
||||
assert!(saved.ruler_guides().is_empty());
|
||||
assert_eq!(saved.node_count(), d.node_count());
|
||||
assert_eq!(saved.saved_guides, guides);
|
||||
let json = serde_json::to_value(&saved).unwrap();
|
||||
assert_eq!(json["guides"].as_array().map(Vec::len), Some(6));
|
||||
assert_eq!(
|
||||
json["guides"][0],
|
||||
serde_json::json!({"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true})
|
||||
);
|
||||
// Read again, the same guides come back with the same ids.
|
||||
let mut back: Document = serde_json::from_value(json).unwrap();
|
||||
back.fix_next_id();
|
||||
back.guides_into_nodes();
|
||||
assert_eq!(back.ruler_guides(), guides);
|
||||
// An older reader of the list ignores the new fields.
|
||||
#[derive(serde::Deserialize, PartialEq, Debug)]
|
||||
struct Old {
|
||||
vertical: bool,
|
||||
pos: f64,
|
||||
#[serde(default)]
|
||||
artboard: Option<u32>,
|
||||
#[serde(default)]
|
||||
layer: Option<NodeId>,
|
||||
}
|
||||
let old: Vec<Old> = serde_json::from_value(serde_json::to_value(&saved.saved_guides).unwrap()).unwrap();
|
||||
assert_eq!(old[0], Old { vertical: true, pos: 50.0, artboard: None, layer: Some(layer) });
|
||||
|
||||
// A document with no layer gets a "Layer 1" for its guides.
|
||||
let mut empty = Document::new(10.0, 10.0);
|
||||
empty.layers.clear();
|
||||
empty.saved_guides = vec![Guide::new(true, 1.0)];
|
||||
assert_eq!(empty.guides_into_nodes(), 1);
|
||||
assert_eq!(empty.layers.len(), 1);
|
||||
assert_eq!(empty.layers[0].name.as_deref(), Some("Layer 1"));
|
||||
assert_eq!(empty.ruler_guides().len(), 1);
|
||||
}
|
||||
|
||||
/// Editing, deleting and the artboard moves of ruler guide nodes, and the selection keeping step.
|
||||
#[test]
|
||||
fn ruler_guide_nodes_are_edited_by_id() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 10.0) });
|
||||
let g2 = d.add_ruler_guide(&Guide { artboard: Some(1), ..Guide::new(false, 20.0) });
|
||||
assert!(d.edit_ruler_guide(g1, |g| g.pos = 15.0));
|
||||
assert!(!d.edit_ruler_guide(a, |g| g.pos = 15.0), "not a guide");
|
||||
assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0));
|
||||
d.move_artboard_guides(1, Vec2::new(5.0, 7.0));
|
||||
assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(27.0));
|
||||
d.map_artboard_guides(1, Affine::scale(2.0));
|
||||
assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(54.0));
|
||||
assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0), "a canvas guide stays");
|
||||
d.copy_artboard_guides(1, 2, Vec2::new(0.0, 100.0));
|
||||
let copies: Vec<(f64, Option<u32>)> = d.ruler_guides().iter().filter(|g| g.artboard == Some(2)).map(|g| (g.pos, g.artboard)).collect();
|
||||
assert_eq!(copies, [(154.0, Some(2))]);
|
||||
let mut sel = Selection::default();
|
||||
sel.set_guides([g1, g2]);
|
||||
sel.key_guide = Some(g2);
|
||||
assert_eq!(d.retain_guides(&mut sel, |g| g.artboard.is_none()), 2);
|
||||
assert_eq!(sel.guides, [g1]);
|
||||
assert_eq!(sel.key_guide, None);
|
||||
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(g1)]);
|
||||
assert_eq!(d.retain_guides(&mut sel, |_| true), 0);
|
||||
}
|
||||
|
||||
fn doc_with_rects() -> (Document, NodeId, NodeId) {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
@@ -146,6 +454,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() {
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
let rect = |d: &mut Document, r: Rect, appearance: Appearance| {
|
||||
let id = d.alloc_id();
|
||||
|
||||
@@ -77,6 +77,12 @@ pub struct TextObject {
|
||||
/// them up round the inside.
|
||||
#[serde(default, rename = "pathSpacing", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub path_spacing: f64,
|
||||
/// Type › Dynamic Text (type on a path only): the layout scales the text by one factor so it
|
||||
/// fills the span between its start and end brackets, and fits it again after each edit. The
|
||||
/// stored sizes keep their proportions; the layout's `fit_scale` is the factor drawn. Off for new
|
||||
/// type and for documents from before it, and saved only when on.
|
||||
#[serde(default, rename = "dynamicText", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub dynamic_text: bool,
|
||||
/// Wrap objects above this area type, resolved by the engine after each edit (text space).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub wrap: Vec<WrapShape>,
|
||||
|
||||
@@ -22,10 +22,10 @@ pub struct CharStyle {
|
||||
/// Leading in points; None = Auto (120% of size).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub leading: Option<f64>,
|
||||
/// Tracking in 1/1000 em.
|
||||
/// Tracking in 1/1000 em; in horizontal type, of the em as [`Self::h_scale`] draws it.
|
||||
#[serde(default)]
|
||||
pub tracking: f64,
|
||||
/// Manual pair spacing in 1/1000 em; None uses the automatic mode.
|
||||
/// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub kerning: Option<f64>,
|
||||
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
|
||||
|
||||
@@ -89,6 +89,7 @@ impl TextObject {
|
||||
path_effect: PathEffect::default(),
|
||||
path_align: PathAlign::default(),
|
||||
path_spacing: 0.0,
|
||||
dynamic_text: false,
|
||||
wrap: Vec::new(),
|
||||
optical_margin: false,
|
||||
anti_alias: TypeAntiAlias::Sharp,
|
||||
@@ -367,6 +368,24 @@ impl TextObject {
|
||||
pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool {
|
||||
matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d))
|
||||
}
|
||||
/// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a
|
||||
/// path's path to `pos` in document space, as a path's anchor takes it
|
||||
/// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a
|
||||
/// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space,
|
||||
/// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their
|
||||
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
|
||||
/// exist, a degenerate `xf` or a path that would not be finite.
|
||||
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
|
||||
let xf = self.xf;
|
||||
matches!(self.kind, TextKind::OnPath { .. })
|
||||
&& self.reshape_local(|path, to_text| {
|
||||
let Some(a) = path.anchor_mut(si, ai) else { return false };
|
||||
let mut drawn = a.transform(xf);
|
||||
drawn.set_handle(out, pos, independent);
|
||||
*a = drawn.transform(to_text);
|
||||
true
|
||||
})
|
||||
}
|
||||
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
|
||||
/// when `f` succeeds and the result is finite.
|
||||
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
use super::*;
|
||||
|
||||
/// Dynamic Text is off for new type and for type saved before it, and saved only when on.
|
||||
#[test]
|
||||
fn dynamic_text_is_saved_only_when_on() {
|
||||
let t = TextObject::point(Point::ZERO, "Hi", CharStyle::default());
|
||||
assert!(!t.dynamic_text);
|
||||
let off = serde_json::to_value(&t).unwrap();
|
||||
assert!(off.get("dynamicText").is_none());
|
||||
assert!(!serde_json::from_value::<TextObject>(off).unwrap().dynamic_text);
|
||||
let on = TextObject { dynamic_text: true, ..t };
|
||||
let saved = serde_json::to_value(&on).unwrap();
|
||||
assert_eq!(saved["dynamicText"], true);
|
||||
assert!(serde_json::from_value::<TextObject>(saved).unwrap().dynamic_text);
|
||||
}
|
||||
|
||||
/// Character Direction is saved only when set, and styles written before it existed read as
|
||||
/// Default.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user