mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 18:34:42 +01:00
Merge main into fix/transform-copies-raster-effects-groups
This commit is contained in:
commit
eb48e1c0ed
138 files changed
+11078
-793
No files matched your search
@@ -142,6 +142,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -140,7 +140,7 @@ impl crate::Document {
|
||||
/// 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.
|
||||
/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LabelStyles {
|
||||
@@ -180,6 +180,14 @@ pub struct LabelStyles {
|
||||
/// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legend_rows: Option<LabelRows>,
|
||||
/// The object rows the axis lines and tick marks keep once set with the paint, stroke or Appearance controls
|
||||
/// ([`LabelRows`]). They replace the default 0.5 pt black stroke; kept rows without paint draw none. `None`: the
|
||||
/// default stroke.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub axis_rows: Option<LabelRows>,
|
||||
/// The object rows the rings of a radar graph keep, as [`Self::axis_rows`]. `None`: the default 0.25 pt gray stroke.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ring_rows: Option<LabelRows>,
|
||||
}
|
||||
|
||||
impl LabelStyles {
|
||||
|
||||
+525
-56
@@ -239,6 +239,190 @@ thread_local! {
|
||||
static LIVE_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The art an object draws in Preview with the geometry effects in it applied, at every depth, as
|
||||
/// plain art whose objects keep the ids of the objects they are drawn from: `None` when no geometry
|
||||
/// effect in it changes what it draws. Effects are evaluated above this crate, so the engine
|
||||
/// registers one with [`set_drawn_art`].
|
||||
pub type DrawnArt = fn(&SymbolBoxes<'_>, &Node) -> Option<Node>;
|
||||
|
||||
static DRAWN_ART: OnceLock<DrawnArt> = OnceLock::new();
|
||||
|
||||
/// Register how the art an object draws with its geometry effects is found, for clicks and
|
||||
/// marquees (the first registration stays).
|
||||
pub fn set_drawn_art(f: DrawnArt) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = DRAWN_ART.set(f);
|
||||
}
|
||||
|
||||
/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and
|
||||
/// the box round everything that art can paint.
|
||||
struct EvaluatedDrawn {
|
||||
of: EvaluatedLive,
|
||||
reach: Option<Rect>,
|
||||
}
|
||||
|
||||
/// How many objects' drawn art [`drawn`] keeps on each thread. Every pointer move measures every
|
||||
/// object with effects that it passes, so the art of all of a document's objects with effects is
|
||||
/// kept, within [`LIVE_KEPT_SIZE`], not only the latest few as with live objects.
|
||||
const DRAWN_KEPT: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The drawn art [`drawn`] keeps, by object, and the sum of their sizes.
|
||||
static DRAWN: RefCell<(HashMap<NodeId, EvaluatedDrawn>, usize)> = RefCell::new((HashMap::new(), 0));
|
||||
/// Whether [`drawn`] gives no art: set while art it gave is tested ([`DrawnOff`]).
|
||||
static DRAWN_OFF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many objects' drawn art [`drawn`] evaluated on this thread.
|
||||
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
|
||||
/// in it applied, and is tested as it is.
|
||||
struct DrawnOff {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl DrawnOff {
|
||||
fn set() -> Self {
|
||||
Self { was: DRAWN_OFF.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DrawnOff {
|
||||
fn drop(&mut self) {
|
||||
DRAWN_OFF.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
f()
|
||||
}
|
||||
|
||||
/// The art object `n` draws with the geometry effects in it applied ([`set_drawn_art`]), empty when
|
||||
/// none changes what it draws, and the box round everything that art can paint. `None` while
|
||||
/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated
|
||||
/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a
|
||||
/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the
|
||||
/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and
|
||||
/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new
|
||||
/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is
|
||||
/// kept alone.
|
||||
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
|
||||
let f = DRAWN_ART.get()?;
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
|
||||
return None;
|
||||
}
|
||||
let doc = symbols.document();
|
||||
let inputs = live_inputs();
|
||||
let kept = DRAWN.with_borrow(|(kept, _)| kept.get(&n.id).filter(|e| e.of.is_of(doc, n, inputs)).map(|e| (e.of.art.clone(), e.reach)));
|
||||
if kept.is_some() {
|
||||
return kept;
|
||||
}
|
||||
#[cfg(test)]
|
||||
DRAWN_EVALUATED.with(|c| c.set(c.get() + 1));
|
||||
let art = f(symbols, n);
|
||||
let reach = art.as_ref().and_then(|a| a.reach_bounds_with(symbols));
|
||||
let art = Rc::new(art.into_iter().collect::<Vec<_>>());
|
||||
let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n)));
|
||||
if !holds_placed(doc, n) {
|
||||
let of = EvaluatedLive {
|
||||
node: n.clone(),
|
||||
symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
|
||||
patterns: doc.patterns.clone(),
|
||||
swatches: doc.swatches.clone(),
|
||||
swatch_groups: doc.swatch_groups.clone(),
|
||||
inputs,
|
||||
art: art.clone(),
|
||||
size,
|
||||
};
|
||||
DRAWN.with_borrow_mut(|(kept, total)| {
|
||||
if let Some(old) = kept.remove(&n.id) {
|
||||
*total = total.saturating_sub(old.of.size);
|
||||
}
|
||||
while kept.len() >= DRAWN_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
|
||||
let Some(other) = kept.keys().next().copied() else { break };
|
||||
if let Some(old) = kept.remove(&other) {
|
||||
*total = total.saturating_sub(old.of.size);
|
||||
}
|
||||
}
|
||||
kept.insert(n.id, EvaluatedDrawn { of, reach });
|
||||
*total = total.saturating_add(size);
|
||||
});
|
||||
}
|
||||
Some((art, reach))
|
||||
}
|
||||
|
||||
/// Is `n` an object whose art [`drawn`] evaluates: a path or compound path, or a group or layer with
|
||||
/// geometry effects or fills and strokes of its own, which paint its members as their effects draw
|
||||
/// them?
|
||||
fn evaluates(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide, .. } => !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The art path or compound path `n` draws with its geometry effects ([`drawn`]) in Preview, or
|
||||
/// group or layer `n` with geometry effects or fills and strokes of its own: `None` in outline
|
||||
/// (`outline`, where the canvas draws no effects), for other objects, and when no geometry effect
|
||||
/// changes what it draws. Also `None` for a clip group or layer whose art holds only its clipping
|
||||
/// path and that path's strokes, not the art it clips: its members are then tested one by one.
|
||||
fn drawn_art(symbols: &SymbolBoxes, n: &Node, outline: bool) -> Option<Rc<Vec<Node>>> {
|
||||
if outline {
|
||||
return None;
|
||||
}
|
||||
drawn(symbols, n).map(|(art, _)| art).filter(|art| !art.is_empty() && (!n.clips() || holds_clipped_art(n, art)))
|
||||
}
|
||||
|
||||
/// Does `art`, the drawn art of clip group or layer `n`, hold any of the objects `n` clips (its
|
||||
/// members after the clipping path), or does `n` clip none?
|
||||
fn holds_clipped_art(n: &Node, art: &[Node]) -> bool {
|
||||
let clipped: HashSet<NodeId> = n.children().into_iter().flatten().skip(1).map(|c| c.id).collect();
|
||||
if clipped.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let mut found = false;
|
||||
for a in art {
|
||||
a.walk(&mut |c| found |= clipped.contains(&c.id));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `base`, a box round what `n` paints without its geometry effects, grown to hold the art they
|
||||
/// draw ([`effects_reach`]). `None` when `base` is.
|
||||
fn drawn_reach(symbols: &SymbolBoxes, n: &Node, base: Option<Rect>) -> Option<Rect> {
|
||||
let base = base?;
|
||||
Some(effects_reach(symbols, n).map_or(base, |r| base.union(r)))
|
||||
}
|
||||
|
||||
/// The box round the art that the geometry effects in `n` draw: that of its own art ([`drawn`])
|
||||
/// when it is evaluated ([`evaluates`]), else the union of its members' in a group, layer or
|
||||
/// Intertwine group. `None` when
|
||||
/// no geometry effect changes what it draws, and while a [`DrawnOff`] guard lives.
|
||||
fn effects_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
if DRAWN_OFF.get() {
|
||||
return None;
|
||||
}
|
||||
if evaluates(n) {
|
||||
return drawn(symbols, n).filter(|(art, _)| !art.is_empty()).and_then(|(_, reach)| reach);
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => {
|
||||
children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, effects_reach(symbols, c)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Topmost editable object under `p`.
|
||||
pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit> {
|
||||
hit_test_skipping(doc, p, opt, &|_| false, true)
|
||||
@@ -365,6 +549,11 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
|
||||
let Some(children) = layer.children() else { return true };
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
// A layer whose own geometry effects reshape its art is hit where that art is drawn, which the
|
||||
// general traversal finds ([`hit_children`]).
|
||||
if drawn_art(symbols, layer, opt.outline).is_some() {
|
||||
return false;
|
||||
}
|
||||
if layer.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
@@ -397,11 +586,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
}
|
||||
let skip = |id| seen.contains(&id);
|
||||
let mut chain = Vec::new();
|
||||
let hit = match &c.kind {
|
||||
let hit = plain(i == 0 && layer.clips(), || match &c.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Intertwine { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some(),
|
||||
NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some() || hit_leaf(c, p, opt, symbols).is_some(),
|
||||
_ => hit_leaf(c, p, opt, symbols).is_some(),
|
||||
};
|
||||
});
|
||||
if hit && seen.insert(c.id) {
|
||||
tops.push(c.id);
|
||||
}
|
||||
@@ -462,6 +651,23 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
|
||||
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
|
||||
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
|
||||
let Some(children) = parent.children() else { return };
|
||||
// A group or layer whose own geometry effects reshape what it holds: the locked objects drawn
|
||||
// under `p` ([`drawn_hit`]).
|
||||
if !(parent.clips() && edits_inside(parent, opt.scope))
|
||||
&& let Some(art) = drawn_art(symbols, parent, opt.outline)
|
||||
{
|
||||
let _off = DrawnOff::set();
|
||||
let mut list = |id: NodeId, _: HitKind| {
|
||||
if let Some(locked) = locked_member(parent, id, opt)
|
||||
&& !out.contains(&locked)
|
||||
{
|
||||
out.push(locked);
|
||||
}
|
||||
out.len() >= MAX_LOCKED_AT
|
||||
};
|
||||
art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut list));
|
||||
return;
|
||||
}
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
|
||||
return;
|
||||
}
|
||||
@@ -474,7 +680,7 @@ fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
continue;
|
||||
}
|
||||
if c.locked {
|
||||
if locked_hit(c, p, opt, symbols) {
|
||||
if plain(i == 0 && parent.clips(), || locked_hit(c, p, opt, symbols)) {
|
||||
out.push(c.id);
|
||||
}
|
||||
continue;
|
||||
@@ -599,13 +805,26 @@ pub fn set_clip_region(f: ClipRegion) {
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
|
||||
clip.walk(&mut |n| found |= has_own_effects(n));
|
||||
found
|
||||
}
|
||||
|
||||
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
|
||||
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
|
||||
fn has_own_effects(n: &Node) -> bool {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
|
||||
}
|
||||
|
||||
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
|
||||
/// path elements.
|
||||
@@ -748,15 +967,7 @@ pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_
|
||||
/// hidden, when it can't be edited (`editable_only`), when it is the part of a Shaper group that
|
||||
/// isn't shown, or when `p` is outside its reach.
|
||||
fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editable_only: bool) -> bool {
|
||||
if shaper_hides(parent, i, opt.scope) {
|
||||
return false;
|
||||
}
|
||||
// Read-only samples can read locked/template art; hidden art never participates.
|
||||
if !c.visible || editable_only && (c.locked || c.is_template()) {
|
||||
return false;
|
||||
}
|
||||
// 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, .. }) {
|
||||
if !may_reach(parent, i, c, opt, editable_only) {
|
||||
return false;
|
||||
}
|
||||
// (An envelope's content sits where it was, not where the envelope draws it.)
|
||||
@@ -765,11 +976,28 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
|
||||
|| cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
|
||||
}
|
||||
|
||||
/// Can a click hit `c`, the child `i` of `parent`, or something inside it, wherever it is? Not
|
||||
/// when it is hidden, when it can't be edited (`editable_only`), when it is a ruler guide or a
|
||||
/// guide while guides are locked or hidden, or when it is the part of a Shaper group that isn't
|
||||
/// shown.
|
||||
fn may_reach(parent: &Node, i: usize, c: &Node, opt: HitOptions, editable_only: bool) -> bool {
|
||||
if shaper_hides(parent, i, opt.scope) {
|
||||
return false;
|
||||
}
|
||||
// Read-only samples can read locked/template art; hidden art never participates.
|
||||
if !c.visible || editable_only && (c.locked || c.is_template()) {
|
||||
return false;
|
||||
}
|
||||
// A ruler guide is picked by the guide commands, never by an object hit test.
|
||||
!(c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }))
|
||||
}
|
||||
|
||||
/// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except
|
||||
/// that paths and compound paths are measured by their control points ([`PathData::control_bounds`],
|
||||
/// which hold the curves) instead of along their curves, which a compound path of thousands of
|
||||
/// members takes milliseconds to do on every click and hover. The box only rules points out, and it
|
||||
/// is at least as large, so the same objects are hit.
|
||||
/// is at least as large, so the same objects are hit. It also holds the art that the geometry
|
||||
/// effects in `c` draw ([`drawn_reach`]), wherever they move it.
|
||||
///
|
||||
/// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds
|
||||
fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
@@ -778,10 +1006,10 @@ fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => {
|
||||
children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b))
|
||||
}
|
||||
_ => return c.reach_bounds_with(symbols),
|
||||
_ => return drawn_reach(symbols, c, c.reach_bounds_with(symbols)),
|
||||
};
|
||||
let o = c.appearance.outset();
|
||||
control.map(|b| b.inflate(o, o))
|
||||
drawn_reach(symbols, c, control.map(|b| b.inflate(o, o)))
|
||||
}
|
||||
|
||||
/// The members of compound path `children` that a click at `p` within `tol` can touch, as one
|
||||
@@ -855,19 +1083,36 @@ fn hit_children(
|
||||
editable_only: bool,
|
||||
) -> Option<Hit> {
|
||||
let children = parent.children()?;
|
||||
if parent.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
if let Some(kind) = clip_outline_hit(parent, clip, p, opt, symbols, editable_only).filter(|_| !skip(clip.id)) {
|
||||
let clip = children.first().filter(|_| parent.clips());
|
||||
// The selection tools in isolation mode within a clip group (or a layer with a clipping mask)
|
||||
// hit what it holds outside its clipping mask too.
|
||||
let edited = clip.is_some() && opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
// A group or layer whose own geometry effects reshape what it holds hits where that art is drawn.
|
||||
let art = if edited { None } else { drawn_art(symbols, parent, opt.outline) };
|
||||
if let Some(clip) = clip {
|
||||
// The clipping mask's outline first, where it is drawn.
|
||||
let drawn_clip = art.as_deref().and_then(|a| a.first()).filter(|a| a.clips()).and_then(|a| a.children()?.first());
|
||||
let kind = match drawn_clip {
|
||||
Some(drawn) => {
|
||||
let takes = opt.clip_outlines && editable_only && may_reach(parent, 0, clip, opt, editable_only);
|
||||
takes.then(|| clip_outline(drawn, p, opt)).flatten()
|
||||
}
|
||||
None => clip_outline_hit(parent, clip, p, opt, symbols, editable_only),
|
||||
};
|
||||
if let Some(kind) = kind.filter(|_| !skip(clip.id)) {
|
||||
chain.push(clip.id);
|
||||
return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
|
||||
// the selection tools in isolation mode within it.
|
||||
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
if !edited && !clip_contains(clip, p, opt.outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Some(art) = art {
|
||||
return drawn_hit(parent, &art, p, opt, symbols, skip, chain, editable_only);
|
||||
}
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it.
|
||||
if let Some(clip) = clip
|
||||
&& !edited
|
||||
&& !clip_contains(clip, p, opt.outline)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
let Some(c) = children.get(i) else { continue };
|
||||
@@ -875,7 +1120,7 @@ fn hit_children(
|
||||
continue;
|
||||
}
|
||||
chain.push(c.id);
|
||||
let hit = match &c.kind {
|
||||
let hit = plain(i == 0 && clip.is_some(), || match &c.kind {
|
||||
// A sublayer whose Preview is off is clicked in outline, like an outline view.
|
||||
NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only),
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => {
|
||||
@@ -888,7 +1133,7 @@ fn hit_children(
|
||||
NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, skip, chain, editable_only)
|
||||
.or_else(|| hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 })),
|
||||
_ => hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }),
|
||||
};
|
||||
});
|
||||
if hit.is_some() {
|
||||
return hit;
|
||||
}
|
||||
@@ -897,6 +1142,123 @@ fn hit_children(
|
||||
None
|
||||
}
|
||||
|
||||
/// What a click at `p` hits in `art`, the art that group or layer `parent` draws with its own
|
||||
/// geometry effects ([`drawn_art`]): the member of `parent` that the topmost object of the art hit
|
||||
/// there is drawn from, found by its id, at the depth [`hit_children`] gives it, or `parent` itself,
|
||||
/// when it is not a layer, for art of its own (its own fills and strokes). Where that member can't be hit (hidden, locked,
|
||||
/// skipped, a guide, a Shaper group's part that isn't shown), the click goes on to the art below.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn drawn_hit(
|
||||
parent: &Node,
|
||||
art: &[Node],
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &SymbolBoxes,
|
||||
skip: &dyn Fn(NodeId) -> bool,
|
||||
chain: &mut Vec<NodeId>,
|
||||
editable_only: bool,
|
||||
) -> Option<Hit> {
|
||||
let _off = DrawnOff::set();
|
||||
let mut found = None;
|
||||
let mut accept = |id: NodeId, kind: HitKind| {
|
||||
found = member_chain(parent, id, opt, skip, editable_only).map(|path| (path, kind));
|
||||
found.is_some()
|
||||
};
|
||||
if !art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut accept)) {
|
||||
return None;
|
||||
}
|
||||
let (path, kind) = found?;
|
||||
let leaf = path.last().copied().unwrap_or(parent.id);
|
||||
chain.extend(path);
|
||||
Some(Hit { leaf, ancestry: chain.clone(), kind, contents_of: None, layers: 1 })
|
||||
}
|
||||
|
||||
/// The ids from a child of `parent` down to its member `id`, when a click may hit each of them
|
||||
/// ([`may_reach`], and not passed over by `skip`); empty when `id` is `parent` itself, `parent` is
|
||||
/// not a layer and `skip` does not pass over it. `None` otherwise, and when `id` is not in `parent`.
|
||||
fn member_chain(parent: &Node, id: NodeId, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Vec<NodeId>> {
|
||||
// A layer's own fills and strokes are not an object to select.
|
||||
if id == parent.id {
|
||||
return (!skip(id) && !parent.is_layer()).then(Vec::new);
|
||||
}
|
||||
let mut steps = vec![];
|
||||
if !path_to(parent, id, &mut steps) {
|
||||
return None;
|
||||
}
|
||||
let reachable = steps.iter().all(|(n, i, c)| may_reach(n, *i, c, opt, editable_only) && !skip(c.id));
|
||||
reachable.then(|| steps.iter().map(|(_, _, c)| c.id).collect())
|
||||
}
|
||||
|
||||
/// Each container from `n` down to its member `id`, with the index and the child it holds on the
|
||||
/// way, into `path`. `false` when `id` is not in `n`.
|
||||
fn path_to<'a>(n: &'a Node, id: NodeId, path: &mut Vec<(&'a Node, usize, &'a Node)>) -> bool {
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
path.push((n, i, c));
|
||||
if c.id == id || path_to(c, id, path) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The locked object [`locked_objects_at`] lists for member `id` of `parent`: the outermost object
|
||||
/// with its own lock on, from a child of `parent` down to `id`, when a click may reach each of them
|
||||
/// ([`may_reach`] with locked objects counted) and none is a locked or template layer, as
|
||||
/// [`locked_children`] goes down. `None` otherwise.
|
||||
fn locked_member(parent: &Node, id: NodeId, opt: HitOptions) -> Option<NodeId> {
|
||||
let mut steps = vec![];
|
||||
if !path_to(parent, id, &mut steps) {
|
||||
return None;
|
||||
}
|
||||
for (n, i, c) in steps {
|
||||
if !may_reach(n, i, c, opt, false) || c.is_layer() && (c.locked || c.is_template()) {
|
||||
return None;
|
||||
}
|
||||
if c.locked {
|
||||
return Some(c.id);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Does a click at `p` hit an object of `art` (the art [`drawn_art`] gives) that `accept` takes? The
|
||||
/// objects are tried front first, the members of an Intertwine group in the order they are drawn at
|
||||
/// `p` ([`hit_order`]), and `accept` is given the id and the hit kind of each object hit until it
|
||||
/// takes one.
|
||||
fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &mut dyn FnMut(NodeId, HitKind) -> bool) -> bool {
|
||||
if !n.visible {
|
||||
return false;
|
||||
}
|
||||
if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return false;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => {
|
||||
// A layer with Preview off is clicked in outline, as [`hit_children`] clicks it.
|
||||
let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt };
|
||||
if n.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
// The selection tools take a clipping path on its outline before the art it clips,
|
||||
// as [`hit_children`] does.
|
||||
if opt.clip_outlines
|
||||
&& clip.visible
|
||||
&& let Some(kind) = clip_outline(clip, p, opt)
|
||||
&& accept(clip.id, kind)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(clip, p, opt.outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The order a click at `p` tries the children of `parent` in, front first: their stacking order
|
||||
/// from the top, except that in an Intertwine group the members are tried in the order they are
|
||||
/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]).
|
||||
@@ -965,10 +1327,17 @@ thread_local! {
|
||||
/// What a click at `p` hits on leaf object `n`: its outline, strokes and fills, its frame or its
|
||||
/// bounds, by kind. Raster effects (drop shadows, glows, blurs) do not take clicks: the area they
|
||||
/// paint beyond the object is left out here and in [`cull_reach`], so a click there reaches the
|
||||
/// object under it.
|
||||
/// object under it. Except in outline, a path or compound path with geometry effects is hit by the
|
||||
/// art they draw ([`drawn_art`]), its own geometry only where that art lies.
|
||||
fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
#[cfg(test)]
|
||||
LEAVES_TESTED.with(|c| c.set(c.get() + 1));
|
||||
// A path or compound path whose geometry effects reshape it is hit where its art is drawn, and
|
||||
// not where its own geometry no longer paints.
|
||||
if let Some(art) = drawn_art(symbols, n, opt.outline) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
if opt.outline
|
||||
@@ -1132,16 +1501,26 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
|
||||
}
|
||||
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
|
||||
// passed by without being measured.
|
||||
if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
if !edits_contents(n)
|
||||
&& n.extras().shaper.is_none()
|
||||
&& drawn_reach(symbols, n, n.reach_bounds_with(symbols)).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// A group whose own geometry effects reshape its members hits where that art is drawn.
|
||||
if matches!(n.kind, NodeKind::Group { .. })
|
||||
&& let Some(art) = drawn_art(symbols, n, opt.outline)
|
||||
{
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols));
|
||||
}
|
||||
match &n.kind {
|
||||
// A clip group only hits inside its clipping path.
|
||||
NodeKind::Group { children, clip } => {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
|
||||
return None;
|
||||
}
|
||||
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
|
||||
children.iter().enumerate().rev().find_map(|(i, c)| plain(i == 0 && *clip, || hit_any(c, p, opt, symbols)))
|
||||
}
|
||||
// An intertwine group hits by its members, as on the canvas.
|
||||
NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)),
|
||||
@@ -1313,7 +1692,7 @@ impl FindPart<'_> {
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if let Some(kind) = self.find(c, path, whole, outline) {
|
||||
if let Some(kind) = plain(i == 0 && n.clips(), || self.find(c, path, whole, outline)) {
|
||||
return Some(kind);
|
||||
}
|
||||
path.pop();
|
||||
@@ -1635,7 +2014,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
/// the selection tools' clicks.
|
||||
/// the selection tools' clicks. Except in outline, a path or compound path with geometry effects, and
|
||||
/// the members of a group or layer with geometry effects of its own, are touched where the art those
|
||||
/// effects draw lies ([`set_drawn_art`]), as clicks hit them.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
}
|
||||
@@ -1661,25 +2042,30 @@ fn previews_off(n: &Node) -> bool {
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let mut out = Vec::new();
|
||||
let symbols = doc.symbol_boxes();
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// 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, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None))
|
||||
.collect(),
|
||||
Some(c) => {
|
||||
// In an isolated clip group, its members by their own geometry, as clicks take
|
||||
// them ([`edits_inside`]).
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None, drawn.clone()))
|
||||
.collect()
|
||||
}
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
.and_then(|p| doc.node(p))
|
||||
.and_then(|p| p.children())
|
||||
.into_iter()
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None, None)))
|
||||
.collect(),
|
||||
},
|
||||
// The objects of the layers, looking through sublayers (hidden, locked and template ones
|
||||
@@ -1688,36 +2074,80 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, r, outline))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
|
||||
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
|
||||
/// shapes ([`mask_marquee`]).
|
||||
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
|
||||
/// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object
|
||||
/// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around
|
||||
/// `l` has such effects.
|
||||
fn layer_objects<'a>(
|
||||
l: &'a Node,
|
||||
s: &SymbolBoxes,
|
||||
r: Rect,
|
||||
outline: bool,
|
||||
whole_compounds: bool,
|
||||
drawn: Option<Rc<HashSet<NodeId>>>,
|
||||
) -> Vec<Top<'a>> {
|
||||
let mut out = vec![];
|
||||
let outline = outline || previews_off(l);
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline));
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
if let Some(inner) = inner
|
||||
if let Some(inner) = if drawn.is_some() { Some(r) } else { inner }
|
||||
&& c.visible
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, inner, outline));
|
||||
out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone()));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r)));
|
||||
if drawn.is_some() {
|
||||
out.push((c, Some(r), outline, None, drawn.clone()));
|
||||
} else if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r), None));
|
||||
} else if inner.is_some() {
|
||||
out.push((c, inner, outline, None));
|
||||
out.push((c, inner, outline, None, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The ids of the objects of the art that group or layer `n` draws with its own geometry
|
||||
/// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them.
|
||||
/// `None` in outline and when it has no such effects.
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
let art = drawn_art(s, n, outline)?;
|
||||
let _off = DrawnOff::set();
|
||||
let mut ids = vec![];
|
||||
for a in art.iter().filter(|a| a.visible) {
|
||||
collect_leaves(a, s, r, None, whole_compounds, false, &mut ids);
|
||||
}
|
||||
Some(Rc::new(ids.into_iter().collect()))
|
||||
}
|
||||
/// The objects inside `n` that a marquee collects ([`collect_leaves`]) whose ids are in
|
||||
/// `drawn` ([`touched_in_art`]), into `out`: leaves, and groups whose own fills and strokes
|
||||
/// the art paints there.
|
||||
fn collect_drawn(n: &Node, drawn: &HashSet<NodeId>, scope: Option<NodeId>, out: &mut Vec<NodeId>) {
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
continue;
|
||||
}
|
||||
if is_leaf(c) {
|
||||
if drawn.contains(&c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else {
|
||||
if drawn.contains(&c.id) && !c.is_layer() {
|
||||
out.push(c.id);
|
||||
}
|
||||
collect_drawn(c, drawn, scope, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
|
||||
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
|
||||
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
|
||||
@@ -1750,6 +2180,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
|
||||
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
|
||||
if let Some(art) = drawn_art(s, n, outline || previews_off(n)) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
@@ -1759,7 +2195,8 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)))
|
||||
|| clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
}
|
||||
@@ -1813,6 +2250,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let outline = outline || previews_off(n);
|
||||
// The members that the art its own geometry effects draw touches, and a group whose
|
||||
// own fills and strokes that art paints, as clicks hit it ([`member_chain`]).
|
||||
if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) {
|
||||
if drawn.contains(&n.id) && !n.is_layer() {
|
||||
out.push(n.id);
|
||||
}
|
||||
collect_drawn(n, &drawn, scope, out);
|
||||
return;
|
||||
}
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
@@ -1821,7 +2267,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out));
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
@@ -1838,12 +2284,33 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
for (t, r, outline, edge) in tops {
|
||||
for (t, r, outline, edge, drawn) in tops {
|
||||
if !t.visible || t.locked || locks.holds_id(t.id) {
|
||||
continue;
|
||||
}
|
||||
// In a layer or isolated container whose own geometry effects reshape its art: by what
|
||||
// that art touches.
|
||||
if let Some(drawn) = drawn {
|
||||
if !leaves {
|
||||
let mut touched = false;
|
||||
t.walk(&mut |n| touched |= drawn.contains(&n.id));
|
||||
if touched {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else {
|
||||
// A leaf, or a group whose own fills and strokes the art paints, and its members.
|
||||
if drawn.contains(&t.id) && !t.is_layer() {
|
||||
out.push(t.id);
|
||||
}
|
||||
if !is_leaf(t) {
|
||||
collect_drawn(t, &drawn, scope, &mut out);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A layer's clipping mask counts by its own geometry ([`plain`]).
|
||||
let _mask = edge.is_some().then(DrawnOff::set);
|
||||
if leaves {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
@@ -1863,8 +2330,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
|
||||
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
|
||||
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`), and in a layer or an
|
||||
/// isolated container whose own geometry effects reshape its art, the ids of the objects of that art
|
||||
/// the marquee touches (`touched_in_art`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>, Option<Rc<HashSet<NodeId>>>);
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
|
||||
|
||||
@@ -307,6 +307,423 @@ fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
|
||||
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
|
||||
}
|
||||
|
||||
/// A stand-in for the engine's [`DrawnArt`]: an object with a visible effect named `test.shift`
|
||||
/// draws 100 pt to the right of its own place, and one with a visible effect named `test.copy`
|
||||
/// draws at its own place and 100 pt to the right. The effects are applied innermost first, and
|
||||
/// the art keeps the ids of the objects it is drawn from. An instance of a symbol whose art has a
|
||||
/// visible effect draws as a 50 pt square from (100, 0), white with a black 1 pt stroke. A clip
|
||||
/// group with a visible effect named `test.mask_only` draws as a group of its clipping path alone,
|
||||
/// as the engine's art for a clip group whose clipping path's strokes have geometry effects is.
|
||||
/// Without any of these, no geometry effect changes what an object draws.
|
||||
fn shifted_art(s: &SymbolBoxes<'_>, n: &Node) -> Option<Node> {
|
||||
if n.clips()
|
||||
&& n.appearance.effects.iter().any(|e| e.visible && e.id == "test.mask_only")
|
||||
&& let Some(mask) = n.children().and_then(|c| c.first())
|
||||
{
|
||||
return Some(Node::group(n.id, vec![mask.clone()]));
|
||||
}
|
||||
fn draw(s: &SymbolBoxes<'_>, n: &Node, found: &mut bool) -> Node {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& s.has_effects(symbol)
|
||||
{
|
||||
*found = true;
|
||||
return Node::path(n.id, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art());
|
||||
}
|
||||
let mut m = n.clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(draw(s, c, found));
|
||||
}
|
||||
}
|
||||
let has = |id: &str| n.appearance.effects.iter().any(|e| e.visible && e.id == id);
|
||||
let (shift, copy) = (has("test.shift"), has("test.copy"));
|
||||
m.appearance.effects.retain(|e| e.id != "test.shift" && e.id != "test.copy");
|
||||
*found |= shift || copy;
|
||||
let shifted = |m: &Node| moved(m, vectorcraft_geom::Affine::translate((100.0, 0.0)));
|
||||
if shift {
|
||||
shifted(&m)
|
||||
} else if copy {
|
||||
Node::group(n.id, vec![Arc::new(shifted(&m)), Arc::new(m)])
|
||||
} else {
|
||||
m
|
||||
}
|
||||
}
|
||||
let mut found = false;
|
||||
let art = draw(s, n, &mut found);
|
||||
found.then_some(art)
|
||||
}
|
||||
|
||||
/// A visible effect named `id`.
|
||||
fn effect(id: &str) -> crate::Effect {
|
||||
crate::Effect { id: id.into(), params: serde_json::json!({}), visible: true }
|
||||
}
|
||||
|
||||
/// A 50 pt square at `x`, `y`, white with a black 1 pt stroke.
|
||||
fn square(d: &mut Document, x: f64, y: f64) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 50.0, y + 50.0)), Appearance::default_art())
|
||||
}
|
||||
|
||||
/// The leaf and the kind a click at (`x`, `y`) hits.
|
||||
fn hit_at(d: &Document, x: f64, y: f64, opt: HitOptions) -> Option<(NodeId, HitKind)> {
|
||||
hit_test(d, Point::new(x, y), opt).map(|h| (h.leaf, h.kind))
|
||||
}
|
||||
|
||||
/// A path that a geometry effect moves is clicked where it is drawn, and not at its own place,
|
||||
/// which it no longer paints; with Object Selection by Path Only on its drawn outline, not its
|
||||
/// fill. Outline view draws no effects: there its own outline is clicked. Hidden, the effect no
|
||||
/// longer moves what clicks hit.
|
||||
#[test]
|
||||
fn a_click_hits_a_paths_shifted_art_not_its_source() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut p = square(&mut d, 0.0, 0.0);
|
||||
p.appearance.effects.push(effect("test.shift"));
|
||||
let a = p.id;
|
||||
d.insert(Some(l), 0, p).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)), "where it is drawn");
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place");
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a]);
|
||||
assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty());
|
||||
let path_only = HitOptions { path_only: true, ..opt };
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, path_only), None, "path only: the drawn fill");
|
||||
assert_eq!(hit_at(&d, 100.0, 25.0, path_only), Some((a, HitKind::Stroke)), "path only: the drawn outline");
|
||||
let outline = HitOptions { outline: true, ..opt };
|
||||
assert_eq!(hit_at(&d, 0.5, 25.0, outline), Some((a, HitKind::Outline)), "outline: its own outline");
|
||||
assert_eq!(hit_at(&d, 100.5, 25.0, outline), None, "outline: no drawn art");
|
||||
d.node_mut(a).unwrap().appearance.effects[0].visible = false;
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), Some((a, HitKind::Fill)), "hidden effect: its own place");
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "hidden effect: nothing drawn there");
|
||||
}
|
||||
|
||||
/// A geometry effect that copies a path is clicked on the copy and on the path, the topmost of the
|
||||
/// stack first. The pointer moving over it evaluates its art once until it changes, and a path
|
||||
/// without effects is not evaluated.
|
||||
#[test]
|
||||
fn a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let below = square(&mut d, 100.0, 0.0);
|
||||
let mut p = square(&mut d, 0.0, 0.0);
|
||||
p.appearance.effects.push(effect("test.copy"));
|
||||
let (a, b) = (p.id, below.id);
|
||||
d.insert(Some(l), 0, below).unwrap();
|
||||
d.insert(Some(l), 1, p).unwrap();
|
||||
let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let opt = HitOptions::default();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt).map(|h| h.0), Some(a), "the path");
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt).map(|h| h.0), Some(a), "its copy, over the square below");
|
||||
}
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a, b]);
|
||||
assert_eq!(evaluated(), before + 1, "evaluated once");
|
||||
if let Some(NodeKind::Path { path, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
|
||||
*path = shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 50.0));
|
||||
}
|
||||
assert_eq!(hit_at(&d, 140.0, 25.0, opt).map(|h| h.0), Some(b), "narrowed, the copy leaves the square below");
|
||||
assert_eq!(evaluated(), before + 2, "evaluated again after it changed");
|
||||
// The square below has no effects: it is never evaluated.
|
||||
assert_eq!(hit_at(&d, 145.0, 45.0, opt).map(|h| h.0), Some(b));
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// A group without effects or fills and strokes of its own is not evaluated as a whole: a click
|
||||
/// on the art of a moved member in it evaluates that member only, and finds the group by it.
|
||||
#[test]
|
||||
fn a_click_in_a_plain_group_evaluates_only_its_member_with_effects() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut moved = square(&mut d, 0.0, 0.0);
|
||||
moved.appearance.effects.push(effect("test.shift"));
|
||||
let still = square(&mut d, 0.0, 100.0);
|
||||
let (a, g) = (moved.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(moved), Arc::new(still)])).unwrap();
|
||||
let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let opt = HitOptions::default();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)));
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]);
|
||||
}
|
||||
assert_eq!(evaluated(), before + 1, "only the member with effects, once");
|
||||
}
|
||||
|
||||
/// A compound path that a geometry effect moves keeps its hole where it is drawn, for clicks and
|
||||
/// marquees.
|
||||
#[test]
|
||||
fn a_compound_paths_shifted_art_keeps_its_hole() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let outer = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 60.0)), Appearance::default());
|
||||
let hole = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default());
|
||||
let c = d.alloc_id();
|
||||
let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd });
|
||||
compound.appearance = Appearance::default_art().into();
|
||||
compound.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 105.0, 5.0, opt), Some((c, HitKind::Fill)), "its drawn fill");
|
||||
assert_eq!(hit_at(&d, 130.0, 30.0, opt), None, "its drawn hole");
|
||||
assert_eq!(hit_at(&d, 5.0, 5.0, opt), None, "its own place");
|
||||
assert_eq!(marquee(&d, Rect::new(155.0, 25.0, 165.0, 35.0), None, false), [c], "a marquee across the drawn edge");
|
||||
assert!(marquee(&d, Rect::new(-5.0, 25.0, 5.0, 35.0), None, false).is_empty(), "a marquee across its own edge");
|
||||
}
|
||||
|
||||
/// A marquee touches a path that a geometry effect moves where it is drawn, and not at its own
|
||||
/// place; in Outline view, at its own place.
|
||||
#[test]
|
||||
fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut p = square(&mut d, 0.0, 0.0);
|
||||
p.appearance.effects.push(effect("test.shift"));
|
||||
let a = p.id;
|
||||
d.insert(Some(l), 0, p).unwrap();
|
||||
let (drawn, own) = (Rect::new(140.0, 40.0, 160.0, 60.0), Rect::new(40.0, 40.0, 60.0, 60.0));
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose own geometry effect moves its members is clicked where each member is drawn: the
|
||||
/// member, inside the group, is hit, and a locked member lets the click through to what is below
|
||||
/// and is listed for unlocking there. A marquee there touches the group, or the member for Direct
|
||||
/// Selection.
|
||||
#[test]
|
||||
fn a_groups_own_effect_moves_where_its_members_are_hit() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let below = square(&mut d, 150.0, 0.0);
|
||||
let (a, b) = (square(&mut d, 0.0, 0.0), square(&mut d, 50.0, 0.0));
|
||||
let (below_id, a_id, b_id, g) = (below.id, a.id, b.id, d.alloc_id());
|
||||
let mut group = Node::group(g, vec![Arc::new(a), Arc::new(b)]);
|
||||
group.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, below).unwrap();
|
||||
d.insert(Some(l), 1, group).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
let h = hit_test(&d, Point::new(125.0, 25.0), opt).unwrap();
|
||||
assert_eq!((h.leaf, h.top_object(None)), (a_id, g), "the first member, drawn there");
|
||||
assert_eq!(h.ancestry, [l, g, a_id]);
|
||||
assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(b_id), "the second member, over the square below");
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "the first member's own place");
|
||||
assert_eq!(objects_at(&d, Point::new(175.0, 25.0), opt, None), [g, below_id]);
|
||||
let drawn = Rect::new(195.0, 20.0, 205.0, 30.0);
|
||||
assert_eq!(marquee(&d, drawn, None, false), [below_id, g]);
|
||||
assert_eq!(marquee(&d, drawn, None, true), [below_id, b_id]);
|
||||
assert!(marquee(&d, Rect::new(-5.0, 20.0, 5.0, 30.0), None, true).is_empty(), "the members' own place");
|
||||
d.node_mut(b_id).unwrap().locked = true;
|
||||
assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(below_id), "a locked member lets the click through");
|
||||
assert_eq!(marquee(&d, drawn, None, true), [below_id], "nor does a marquee collect it");
|
||||
assert_eq!(locked_objects_at(&d, Point::new(175.0, 25.0), opt), [b_id], "the Unlock submenu lists it where it is drawn");
|
||||
assert!(locked_objects_at(&d, Point::new(75.0, 25.0), opt).is_empty(), "and not at its own place");
|
||||
// Outline view draws no effects: the members are clicked at their own places.
|
||||
let outline = HitOptions { outline: true, ..opt };
|
||||
assert_eq!(hit_at(&d, 0.5, 25.0, outline).map(|h| h.0), Some(a_id));
|
||||
}
|
||||
|
||||
/// A layer whose own geometry effect moves its art is clicked and marqueed where the art is
|
||||
/// drawn. With the layer's Preview off, its art is clicked at its own place, in outline.
|
||||
#[test]
|
||||
fn a_layers_own_effect_moves_where_its_art_is_hit() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = square(&mut d, 0.0, 0.0);
|
||||
let a_id = a.id;
|
||||
d.insert(Some(l), 0, a).unwrap();
|
||||
d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift"));
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "where it is drawn");
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place");
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a_id]);
|
||||
assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty());
|
||||
let (drawn, own) = (Rect::new(145.0, 20.0, 155.0, 30.0), Rect::new(-5.0, 20.0, 5.0, 30.0));
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a_id], "a marquee where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "a marquee at its own place");
|
||||
}
|
||||
if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(l).map(|n| &mut n.kind) {
|
||||
*preview = false;
|
||||
}
|
||||
assert_eq!(hit_at(&d, 0.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: its own outline");
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: no drawn art");
|
||||
assert_eq!(marquee(&d, own, None, false), [a_id], "preview off: a marquee at its own place");
|
||||
}
|
||||
|
||||
/// In a layer whose own geometry effect moves its art, a sublayer with Preview off is clicked in
|
||||
/// outline: on the outline of its art where the art is drawn, not inside its fill.
|
||||
#[test]
|
||||
fn a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap();
|
||||
let a = square(&mut d, 0.0, 0.0);
|
||||
let a_id = a.id;
|
||||
d.insert(Some(sub), 0, a).unwrap();
|
||||
d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift"));
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "preview on: inside its fill");
|
||||
if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(sub).map(|n| &mut n.kind) {
|
||||
*preview = false;
|
||||
}
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: inside its fill");
|
||||
assert_eq!(hit_at(&d, 100.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: on its outline");
|
||||
}
|
||||
|
||||
/// A group with fills and strokes of its own around an instance of a symbol whose art has an
|
||||
/// effect is clicked where its art is drawn, though no object in the group has an effect.
|
||||
#[test]
|
||||
fn a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut art = square(&mut d, 0.0, 0.0);
|
||||
art.appearance.effects.push(effect("test.raster"));
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Effected".into(), art: Arc::new(art) });
|
||||
let (g, inst) = (d.alloc_id(), d.alloc_id());
|
||||
let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: "Effected".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut group = Node::group(g, vec![Arc::new(instance)]);
|
||||
group.appearance = Appearance::default_art().into();
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((inst, HitKind::Fill)), "where its art is drawn");
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]);
|
||||
}
|
||||
|
||||
/// In a layer with fills and strokes of its own whose art is evaluated for a member's geometry
|
||||
/// effect, an Intertwine group's members are still clicked in the order they are drawn at the
|
||||
/// click: where the lower member is woven over the upper one, the click takes the lower member.
|
||||
#[test]
|
||||
fn an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
d.node_mut(l).unwrap().appearance = Appearance::default_art().into();
|
||||
let mut a = square(&mut d, 0.0, 100.0);
|
||||
a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(25.0, 100.0, 50.0, 150.0))));
|
||||
let b = square(&mut d, 25.0, 100.0);
|
||||
let (a_id, b_id, g) = (a.id, b.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap();
|
||||
let mut moved = square(&mut d, 200.0, 0.0);
|
||||
moved.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 1, moved).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 40.0, 125.0, opt), Some((a_id, HitKind::Fill)), "where the lower member is woven over");
|
||||
assert_eq!(hit_at(&d, 60.0, 125.0, opt), Some((b_id, HitKind::Fill)), "where the upper member is drawn over");
|
||||
}
|
||||
|
||||
/// The clipping path of a clip group and of a clipping layer is still marqueed by its own geometry
|
||||
/// when a geometry effect moves what it draws.
|
||||
#[test]
|
||||
fn a_clipping_path_keeps_its_own_geometry_under_a_geometry_effect() {
|
||||
set_drawn_art(shifted_art);
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
// A clip group.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(effect("test.shift"));
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clip group");
|
||||
// A clipping layer.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(effect("test.shift"));
|
||||
let (mask_id, art_id) = (mask.id, art.id);
|
||||
let layer = d.node_mut(l).unwrap();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
|
||||
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
|
||||
}
|
||||
assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clipping layer");
|
||||
}
|
||||
|
||||
/// The selection tools take the clipping path of a clip group whose own geometry effect moves it
|
||||
/// on its outline where it is drawn, before the art it clips, and not at its own place.
|
||||
#[test]
|
||||
fn a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
clip.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let tools = HitOptions { clip_outlines: true, ..HitOptions::default() };
|
||||
assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "the drawn edge, over the art");
|
||||
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "the drawn art inside the mask");
|
||||
assert_eq!(hit_at(&d, 0.5, 50.0, tools), None, "the mask's own edge");
|
||||
// The same clip group in a group whose own effect moves it.
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
outer.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, outer).unwrap();
|
||||
assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "in a moved group: the drawn edge, over the art");
|
||||
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "in a moved group: the drawn art");
|
||||
}
|
||||
|
||||
/// In isolation mode in a clip group whose own geometry effect moves it, the selection tools take
|
||||
/// the art outside the clipping mask by its own geometry, for a marquee as for a click.
|
||||
#[test]
|
||||
fn an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
clip.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let tools = HitOptions { clip_outlines: true, scope: Some(g), ..HitOptions::default() };
|
||||
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "a click outside the mask");
|
||||
let edge = Rect::new(190.0, 40.0, 210.0, 60.0);
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, edge, Some(g), leaves), [art_id], "a marquee across its own edge outside the mask");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip group whose drawn art holds only its clipping path still has the art it clips clicked
|
||||
/// inside the mask.
|
||||
#[test]
|
||||
fn a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
clip.appearance.effects.push(effect("test.mask_only"));
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 50.0, 50.0, opt), Some((art_id, HitKind::Fill)), "inside the mask");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), opt, None), [g]);
|
||||
assert!(hit_at(&d, 150.0, 50.0, opt).is_none(), "outside the mask");
|
||||
}
|
||||
|
||||
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
|
||||
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
|
||||
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
|
||||
|
||||
@@ -384,14 +384,14 @@ pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
|
||||
}
|
||||
|
||||
/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its
|
||||
/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out.
|
||||
/// The paints a graph keeps for its series, its labels and its lines ([`crate::graph::GraphSpec`]), which
|
||||
/// its marks, labels and lines take each time it is drawn again and which [`node_paints`] leaves out.
|
||||
pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
let g = n.extras().graph.as_deref();
|
||||
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
|
||||
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
|
||||
let l = g.map(|g| &g.label_styles);
|
||||
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten();
|
||||
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows, &l.axis_rows, &l.ring_rows]).flatten();
|
||||
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten())
|
||||
}
|
||||
|
||||
@@ -400,7 +400,7 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mu
|
||||
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
|
||||
let l = &mut g.label_styles;
|
||||
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
|
||||
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten();
|
||||
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten();
|
||||
series
|
||||
.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
|
||||
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
|
||||
@@ -718,6 +718,14 @@ mod tests {
|
||||
paint: crate::SeriesPaint { fill: Some(red.clone()), ..Default::default() },
|
||||
..Default::default()
|
||||
}),
|
||||
axis_rows: Some(crate::LabelRows {
|
||||
paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() },
|
||||
..Default::default()
|
||||
}),
|
||||
ring_rows: Some(crate::LabelRows {
|
||||
paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() },
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
@@ -725,18 +733,20 @@ mod tests {
|
||||
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
|
||||
let mut seen = 0;
|
||||
d.visit_paints(&mut |p| seen += usize::from(*p == red));
|
||||
assert_eq!(seen, 5, "the fill and the graph's series fill, series stroke, legend fill and value label fill row");
|
||||
assert_eq!(seen, 7, "the fill and the graph's series fill, series stroke, legend fill, value label fill row and axis and ring stroke rows");
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
|
||||
assert_eq!(d.map_solid_paints(&mut to_blue), 5);
|
||||
assert_eq!(d.map_solid_paints(&mut to_blue), 7);
|
||||
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
|
||||
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
|
||||
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
|
||||
let legend = g.label_styles.legend.unwrap();
|
||||
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
|
||||
assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand")));
|
||||
assert_eq!(g.label_styles.axis_rows.unwrap().paint.stroke, Some(linked(blue, "Brand")));
|
||||
assert_eq!(g.label_styles.ring_rows.unwrap().paint.stroke, Some(linked(blue, "Brand")));
|
||||
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
|
||||
assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four");
|
||||
assert_eq!(d.map_paints(&mut cleared), 7, "the fill and the graph's six");
|
||||
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_sources, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
@@ -32,6 +32,16 @@ fn outline(n: &Node, out: &mut PathData) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline area type wraps around for wrap object `n`, in document coordinates, as
|
||||
/// [`resolve_wrap`] makes it: a path's subpaths that are closed or have more than two anchors, those
|
||||
/// of the shown members of a group or compound path, a clip group's clipping object's, and the
|
||||
/// bounds of other art. Empty when `n` has none.
|
||||
pub fn wrap_outline(n: &Node) -> PathData {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
pd
|
||||
}
|
||||
|
||||
enum Item<'a> {
|
||||
Wrap(&'a Node),
|
||||
Text(&'a Node),
|
||||
|
||||
@@ -683,9 +683,11 @@ fn apart(offsets: &[Vec2], b: Rect) -> bool {
|
||||
|
||||
/// Type `n` whose own geometry effects only move it ([`transform_moves`]) as a group of the moved
|
||||
/// type ([`moved_type`]). The group keeps `n`'s id, name, visibility, transparency, opacity mask and
|
||||
/// remaining (raster) effects, and the type in it has none of them. `None` otherwise.
|
||||
/// remaining (raster) effects, and the type in it has none of them. `None` otherwise, and for type
|
||||
/// whose copies each carry the raster effects listed before their Transform effect
|
||||
/// ([`crate::outer_effects`]), which is baked through its outlines as the canvas draws it.
|
||||
fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::Text(_)) {
|
||||
if !matches!(n.kind, NodeKind::Text(_)) || crate::reshape::copied_raster_at(n).is_some() {
|
||||
return None;
|
||||
}
|
||||
let moves = transform_moves(&geometry_effects(n))?;
|
||||
|
||||
@@ -168,6 +168,62 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
|
||||
if sign < 0.0 { footprint.reverse_subpaths() } else { footprint }
|
||||
}
|
||||
|
||||
/// The most edges a facet may have for [`seamed_fill`] to test it for crossing edges.
|
||||
const SEAMED_FILL_EDGES: usize = 256;
|
||||
|
||||
/// Facet `path` and its round seam `seam` wide as one path to fill ([`footprint`]), so that at an
|
||||
/// edge pixel the facet and its seam cover it once between them, not a fill's coverage and then a
|
||||
/// stroke's over it. `None` unless `path` is one closed polygon of up to [`SEAMED_FILL_EDGES`]
|
||||
/// finite edges, with an area, and with no two edges that are not neighbors touching: only there
|
||||
/// does the footprint's nonzero fill cover the facet and its seam and nothing more. `None` too for
|
||||
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
|
||||
/// than the facet.
|
||||
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
|
||||
use kurbo::{PathEl, Point, Shape};
|
||||
if !(seam.is_finite() && seam > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let bez = path.to_bezpath();
|
||||
let mut elements = bez.elements().iter();
|
||||
let Some(PathEl::MoveTo(first)) = elements.next() else { return None };
|
||||
let mut points = vec![*first];
|
||||
let mut closed = false;
|
||||
for el in elements {
|
||||
match el {
|
||||
PathEl::LineTo(p) if !closed => points.push(*p),
|
||||
PathEl::ClosePath if !closed => closed = true,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
if points.len() > 1 && points.first() == points.last() {
|
||||
points.pop();
|
||||
}
|
||||
let area = bez.area().abs();
|
||||
if !closed || !(3..=SEAMED_FILL_EDGES).contains(&points.len()) || points.iter().any(|p| !p.is_finite()) || !area.is_finite() || area <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let side = |a: Point, b: Point, c: Point| (b - a).cross(c - a);
|
||||
let touch = |a: Point, b: Point, c: Point, d: Point| {
|
||||
let boxes = a.x.min(b.x) <= c.x.max(d.x) && c.x.min(d.x) <= a.x.max(b.x) && a.y.min(b.y) <= c.y.max(d.y) && c.y.min(d.y) <= a.y.max(b.y);
|
||||
boxes && side(a, b, c) * side(a, b, d) <= 0.0 && side(c, d, a) * side(c, d, b) <= 0.0
|
||||
};
|
||||
let n = points.len();
|
||||
let edge = |i: usize| (points[i], points[(i + 1) % n]);
|
||||
for i in 0..n {
|
||||
for j in i + 2..n {
|
||||
if i == 0 && j == n - 1 {
|
||||
continue;
|
||||
}
|
||||
let ((a, b), (c, d)) = (edge(i), edge(j));
|
||||
if touch(a, b, c, d) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let fill = footprint(&bez, seam);
|
||||
(fill.bounding_box().is_finite() && fill.area().abs() >= area).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
|
||||
}
|
||||
|
||||
/// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same
|
||||
/// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets'
|
||||
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
|
||||
@@ -227,7 +283,9 @@ pub(crate) fn underlay(
|
||||
/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each
|
||||
/// channel, an underlay of the facets with wide seams lies under the facets themselves, so a
|
||||
/// shared edge is opaque in that channel's own light before the channels are screened together;
|
||||
/// the black backdrop shows only outside the surface, which the clip removes.
|
||||
/// the black backdrop shows only outside the surface, which the clip removes. Each facet over the
|
||||
/// underlay is one fill of the facet and its seam together ([`seamed_fill`]), or a fill and a seam
|
||||
/// stroke where that is `None`.
|
||||
pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node {
|
||||
use kurbo::Shape;
|
||||
use std::sync::Arc;
|
||||
@@ -251,6 +309,8 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
|
||||
let clip = Node::path(id, PathData::from_bezpath(&boundary), Appearance::default());
|
||||
let bounds = bounds.unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
|
||||
let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0));
|
||||
let seam = |face: &vectorcraft_three_d::Facet| (face.thickness() / 2.0).clamp(0.05, 0.75);
|
||||
let exact: Vec<Option<PathData>> = facets.iter().map(|face| seamed_fill(&face.path(), seam(face))).collect();
|
||||
let channels = (0..3)
|
||||
.map(|channel| {
|
||||
let mut color = [0.0; 3];
|
||||
@@ -286,7 +346,17 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
|
||||
};
|
||||
let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))];
|
||||
children.extend(draw(|_| UNDERLAY_SEAM));
|
||||
children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75)));
|
||||
children.extend(facets.iter().zip(&exact).zip(&paints).map(|((face, fill), paint)| {
|
||||
let mut items = vec![AppearanceItem::Fill(FillLayer::new(paint.clone()))];
|
||||
let path = match fill {
|
||||
Some(fill) => fill.clone(),
|
||||
None => {
|
||||
items.push(AppearanceItem::Stroke(seam_stroke(paint.clone(), seam(face))));
|
||||
face.path()
|
||||
}
|
||||
};
|
||||
Arc::new(Node::path(id, path, Appearance { items, ..Default::default() }))
|
||||
}));
|
||||
let mut group = Node::group(id, children);
|
||||
group.isolate = true;
|
||||
group.blend = BlendMode::Screen;
|
||||
@@ -529,4 +599,65 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
|
||||
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
|
||||
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
|
||||
/// nonzero fill (no area, crossing edges, a hole, curves) or a seam with no width has none.
|
||||
#[test]
|
||||
fn seamed_fill_covers_a_polygon_and_its_seam_once() {
|
||||
use kurbo::Shape;
|
||||
use vectorcraft_geom::BezPath;
|
||||
let polygon = |points: &[(f64, f64)]| {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(points[0]);
|
||||
for p in &points[1..] {
|
||||
bp.line_to(*p);
|
||||
}
|
||||
bp.close_path();
|
||||
bp
|
||||
};
|
||||
let covers = |fill: &vectorcraft_geom::PathData, x: f64, y: f64| fill.to_bezpath().winding(Point::new(x, y)) != 0;
|
||||
let notched = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (6.0, 10.0), (6.0, 4.0), (4.0, 4.0), (4.0, 10.0), (0.0, 10.0)];
|
||||
let mut reversed = notched;
|
||||
reversed.reverse();
|
||||
for points in [¬ched[..], &reversed[..], &[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)][..]] {
|
||||
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(points)), 0.75).expect("a simple polygon");
|
||||
let contours = fill.to_bezpath().elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count();
|
||||
assert!(contours >= 2, "{points:?}: the seam's outline and the facet, {contours} contours");
|
||||
for (x, y) in [(1.0, 1.0), (2.0, 0.5), (5.0, -0.3), (-0.3, 5.0), (-0.2, -0.2)] {
|
||||
assert!(covers(&fill, x, y), "{points:?} covers ({x},{y})");
|
||||
}
|
||||
for (x, y) in [(5.0, -0.5), (-0.5, 5.0), (-0.3, -0.3), (12.0, 12.0)] {
|
||||
assert!(!covers(&fill, x, y), "{points:?} leaves ({x},{y})");
|
||||
}
|
||||
}
|
||||
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(¬ched)), 0.75).unwrap();
|
||||
assert!(covers(&fill, 4.3, 8.0) && covers(&fill, 5.0, 4.3), "the notch's edges carry the seam");
|
||||
assert!(!covers(&fill, 5.0, 8.0), "the notch stays open");
|
||||
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
|
||||
let mut holed = square.clone();
|
||||
holed.extend(polygon(&[(3.0, 3.0), (3.0, 7.0), (7.0, 7.0), (7.0, 3.0)]).iter());
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((0.0, 0.0));
|
||||
curved.quad_to((5.0, -5.0), (10.0, 0.0));
|
||||
curved.line_to((5.0, 10.0));
|
||||
curved.close_path();
|
||||
let mut open = BezPath::new();
|
||||
open.move_to((0.0, 0.0));
|
||||
open.line_to((10.0, 0.0));
|
||||
open.line_to((10.0, 10.0));
|
||||
for (name, path, seam) in [
|
||||
("sliver", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)]), 0.75),
|
||||
("bow tie", polygon(&[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)]), 0.75),
|
||||
("a vertex visited twice", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 5.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0)]), 0.75),
|
||||
("hole", holed, 0.75),
|
||||
("curve", curved, 0.75),
|
||||
("open", open, 0.75),
|
||||
("no seam", square.clone(), 0.0),
|
||||
("endless seam", square, f64::INFINITY),
|
||||
] {
|
||||
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&path), seam).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,20 +111,29 @@ fn reaches_appearance(e: &Effect) -> bool {
|
||||
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
|
||||
/// baked and expanded through that art ([`reshape`]).
|
||||
pub fn has_transform_art(n: &Node) -> bool {
|
||||
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some()
|
||||
has_gradient_copies(n)
|
||||
|| has_layered_copies(n)
|
||||
|| has_transform_options(n)
|
||||
|| has_painted_effects(n)
|
||||
|| (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some())
|
||||
}
|
||||
|
||||
/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform
|
||||
/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index
|
||||
/// of the last visible Transform effect that makes copies, when a visible raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it and every other
|
||||
/// visible effect before it is a geometry effect or such a raster effect. `None` otherwise, and for
|
||||
/// a path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect
|
||||
/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of
|
||||
/// its own.
|
||||
/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so
|
||||
/// that each copy of a Transform effect carries the raster effects listed before that effect
|
||||
/// ([`copied_raster_art`]): the index of the last visible Transform effect that makes copies, when
|
||||
/// a visible raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed
|
||||
/// before it and every other visible effect before it is a geometry effect or such a raster effect.
|
||||
/// `None` otherwise, and for an object with a linked opacity mask, a 3D effect, Crop Marks, Vector
|
||||
/// Halftone, a live-effect plug-in that paints what it returns, a fill or stroke that paints with
|
||||
/// geometry effects of its own, or (type, images and symbol instances) a perspective.
|
||||
pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
|
||||
return None;
|
||||
match n.kind {
|
||||
NodeKind::Path { guide: false, clipping: false, .. }
|
||||
| NodeKind::Compound { .. }
|
||||
| NodeKind::Text(_)
|
||||
| NodeKind::Image(_)
|
||||
| NodeKind::SymbolInstance { .. } => {}
|
||||
_ => return None,
|
||||
}
|
||||
let effects = &n.appearance.effects;
|
||||
// Checked first: this runs for every object drawn.
|
||||
@@ -143,7 +152,8 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
|| crate::has_crop_marks(n)
|
||||
|| crate::addons::halftone::has_halftone(n)
|
||||
|| has_painted_effects(n)
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()));
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
|
||||
|| n.projection().is_some();
|
||||
(carried && !excluded).then_some(t)
|
||||
}
|
||||
|
||||
@@ -1025,7 +1035,8 @@ fn as_art_opts(
|
||||
apart: bool,
|
||||
) -> Option<Node> {
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n));
|
||||
let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart);
|
||||
return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
@@ -1120,20 +1131,35 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node {
|
||||
art
|
||||
}
|
||||
|
||||
/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the
|
||||
/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then
|
||||
/// copied by that Transform effect, each copy an object of its own carrying those raster effects
|
||||
/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry
|
||||
/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without
|
||||
/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do,
|
||||
/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an
|
||||
/// object of its own ([`copy_leaf`]).
|
||||
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node {
|
||||
/// The art of `n` whose own effects split at `t` ([`copied_raster_at`]): the art the effects before
|
||||
/// the Transform effect at `t` make of `n`, with their raster effects, then copied by that
|
||||
/// Transform effect, each copy an object of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry effects after
|
||||
/// it. The art keeps `n`'s id and carries the raster effects from `t` on, without `n`'s name,
|
||||
/// visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, each with
|
||||
/// its raster effects. With `apart`, the Transform effects before `t` make each copy of a path an
|
||||
/// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through
|
||||
/// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame
|
||||
/// and an instance as its symbol's art, whose members take their own geometry effects first
|
||||
/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art.
|
||||
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option<Node>) -> Option<Node> {
|
||||
let (before, rest) = n.appearance.effects.split_at(t);
|
||||
let mut source = n.clone();
|
||||
source.appearance.effects = before.to_vec();
|
||||
let piece = match copied_raster_at(&source) {
|
||||
Some(at) => copied_raster_art(doc, &source, at, apart),
|
||||
Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?,
|
||||
None if needs_outline(&source) => {
|
||||
let mut art = outlined(&source)?;
|
||||
if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() {
|
||||
// The copying Transform effect reshapes what the symbol's members draw.
|
||||
crate::group::members_as_drawn(doc, &mut art);
|
||||
}
|
||||
art.name = None;
|
||||
art.visible = true;
|
||||
(art.opacity, art.blend, art.isolate, art.knockout_shape) = (1.0, Default::default(), false, false);
|
||||
art.extras_mut().mask = None;
|
||||
art
|
||||
}
|
||||
None => {
|
||||
let mut art = one_piece(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
|
||||
@@ -1183,12 +1209,13 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) ->
|
||||
carry.hide_skipped(&mut ran);
|
||||
}
|
||||
art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
|
||||
art
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect
|
||||
/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`])
|
||||
/// and for a group or layer whose copies do ([`copied_container_raster_at`]).
|
||||
/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster
|
||||
/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do
|
||||
/// ([`copied_container_raster_at`]).
|
||||
pub fn outer_effects(n: &Node) -> &[Effect] {
|
||||
match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) {
|
||||
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
|
||||
@@ -1224,7 +1251,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n));
|
||||
return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
|
||||
// One element: its pieces never knock each other out.
|
||||
|
||||
@@ -1766,11 +1766,24 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() {
|
||||
assert_eq!(ramps, one.iter().skip(1).collect::<Vec<_>>(), "the same light ramps");
|
||||
// The single face's clip holds its seam: the clip reaches past the facet by half the seam.
|
||||
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
|
||||
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect();
|
||||
assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}");
|
||||
let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") };
|
||||
let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap());
|
||||
assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}");
|
||||
let reaches = |b: Rect| (b.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (b.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1;
|
||||
assert!(reaches(clip), "{clip:?} {facet:?}");
|
||||
// In the composite, the facet over the underlay is one fill of the facet and its seam in each
|
||||
// channel: no seam stroke of its own, and a path that reaches past the facet by half the seam.
|
||||
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect();
|
||||
assert!(widths.is_empty(), "{widths:?}");
|
||||
let mut seamed = vec![];
|
||||
batch.walk(&mut |n| {
|
||||
if let [AppearanceItem::Fill(f)] = n.appearance.items.as_slice()
|
||||
&& f.paint != Paint::solid(Color::BLACK)
|
||||
&& f.paint != paint
|
||||
{
|
||||
seamed.extend(n.path_data().and_then(PathData::bounds));
|
||||
}
|
||||
});
|
||||
assert!(seamed.len() == 3 && seamed.iter().all(|b| reaches(*b)), "{seamed:?} {facet:?}");
|
||||
}
|
||||
|
||||
/// `square_node` moved right by `dx`, with id `id` and fill `fill`.
|
||||
|
||||
@@ -1414,3 +1414,96 @@ fn copies_past_the_budget_each_keep_their_shadow() {
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
|
||||
/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`.
|
||||
fn type_node(id: u64, effects: Vec<Effect>) -> Node {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
|
||||
n.appearance.effects = effects;
|
||||
n
|
||||
}
|
||||
|
||||
/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square
|
||||
/// centered on its origin.
|
||||
fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
|
||||
let art = Node::path(
|
||||
NodeId(900),
|
||||
shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::translate((50.0, 50.0)) });
|
||||
n.appearance.effects = effects;
|
||||
(n, art)
|
||||
}
|
||||
|
||||
/// Type, an image and a symbol instance with a Transform effect that makes copies give each copy
|
||||
/// the shadow listed before it, turned and scaled with that copy, the last copy lowest: drawn and
|
||||
/// expanded. The object paints none around all of them, and a shadow listed after the Transform
|
||||
/// effect still paints once around them. Built without fonts, type lays out no glyphs and only the
|
||||
/// image and the instance are checked.
|
||||
#[test]
|
||||
fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() {
|
||||
let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0);
|
||||
if !fonts {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
}
|
||||
let objects = |effects: Vec<Effect>| {
|
||||
let (inst, art) = instance(96, effects.clone());
|
||||
let mut out = vec![("image", image(97, effects.clone()), None), ("instance", inst, Some(art))];
|
||||
if fonts {
|
||||
out.push(("type", type_node(95, effects), None));
|
||||
}
|
||||
out
|
||||
};
|
||||
let cases = [
|
||||
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
|
||||
];
|
||||
for (params, want, blurs) in cases {
|
||||
for (kind, n, symbol) in objects(vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]) {
|
||||
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{kind} {params}");
|
||||
let symbol = symbol.as_ref();
|
||||
for (how, drawn) in [("drawn", crate::reshape(None, &n, symbol)), ("expanded", expand_outlined(None, &n, symbol))] {
|
||||
let drawn = drawn.unwrap_or_else(|| panic!("{kind} {params}: {how}"));
|
||||
assert_eq!(drawn.children().map_or(0, Vec::len), want.len(), "{kind} {params}: {how} copies");
|
||||
assert!(drawn.appearance.effects.is_empty(), "{kind} {params}: {how} {:?}", drawn.appearance.effects);
|
||||
assert!(near(&shadows_in(&drawn), &want), "{kind} {params}: {how} {:?}", shadows_in(&drawn));
|
||||
let b = shadow_blurs_in(&drawn);
|
||||
assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{kind} {params}: {how} blurs {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
|
||||
for (kind, n, symbol) in objects(effects) {
|
||||
assert_eq!(crate::outer_effects(&n).len(), 2, "{kind}");
|
||||
let drawn = crate::reshape(None, &n, symbol.as_ref()).unwrap();
|
||||
assert!(near(&shadows_in(&drawn), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{kind}: {:?}", shadows_in(&drawn));
|
||||
}
|
||||
}
|
||||
|
||||
/// Type whose Transform effect only moves its copies, baked for export, gives each copy the shadow
|
||||
/// listed before that effect, as the canvas draws it, rather than staying type under one shadow.
|
||||
#[test]
|
||||
fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() {
|
||||
if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let n = type_node(99, vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
|
||||
let drawn = baked(n);
|
||||
assert!(near(&shadows_in(&drawn), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&drawn));
|
||||
}
|
||||
|
||||
/// Type with a fill whose own geometry effects reshape it keeps one set of raster effects around
|
||||
/// all the copies.
|
||||
#[test]
|
||||
fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() {
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
let mut filled = type_node(98, effects.clone());
|
||||
filled.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
|
||||
effects: vec![fx("path.offsetPath", json!({"offset": 2}))],
|
||||
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
|
||||
}));
|
||||
assert_eq!(crate::outer_effects(&filled).len(), 2);
|
||||
}
|
||||
@@ -235,11 +235,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> {
|
||||
/// editing and symbol editing mode isolate their own layer, which does not count here; an object
|
||||
/// isolated inside them counts.
|
||||
pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> {
|
||||
st.isolation.filter(|l| {
|
||||
!st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
})
|
||||
vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation)
|
||||
}
|
||||
/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at
|
||||
/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items.
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply as Filter",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed}",
|
||||
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed}",
|
||||
has_selection,
|
||||
filter
|
||||
),
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Ink Fixes",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
has_doc,
|
||||
print_fixes::run
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Nearest Swatch",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
|
||||
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
|
||||
has_selection,
|
||||
nearest::apply
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Fill to Stroke",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again, and its axis lines, tick marks and radar rings keep their new rows for every line of their kind. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, true)
|
||||
),
|
||||
@@ -259,7 +259,10 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
|
||||
// The graph keeps the paint its series marks and labels now have.
|
||||
let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written);
|
||||
let labels = super::super::graph::capture_label_styles(d, &ids, ©_run);
|
||||
Ok(objects + usize::from(series || labels))
|
||||
let painted: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
|
||||
// A line keeps the paint written to it, also when it already showed it, and the rest stays as its kind keeps it.
|
||||
let lines = super::super::graph::capture_line_changes(&before, d, &painted) | super::super::graph::capture_line_paint_writes(d, &written);
|
||||
Ok(objects + usize::from(series || labels || lines))
|
||||
})?;
|
||||
}
|
||||
// The defaults for new art change the same way, as Swap Fill and Stroke changes them.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths and Trim at Crossings ([`trim`]).
|
||||
//! into Paths, Trim at Crossings ([`trim`]) and Tangent Circle ([`tangent_circle`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
@@ -12,6 +12,7 @@ mod corners;
|
||||
mod effect_tests;
|
||||
mod shape;
|
||||
mod shared_edge;
|
||||
mod tangent_circle;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod trim;
|
||||
@@ -180,6 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(corners::specs());
|
||||
v.extend(shared_edge::specs());
|
||||
v.extend(trim::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Tangent Circle: draw the circles that touch two paths or compound paths at a given radius, or
|
||||
//! that touch three of them. The geometry is the pathops crate's
|
||||
//! ([`tangent_circles`](vectorcraft_pathops::addons::pathtools::tangent_circles)).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData};
|
||||
use vectorcraft_pathops::addons::pathtools::{self as pt, TangentCircleError};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, checked_ids_param, cmd, has_selection, index_opt, number_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The command.
|
||||
pub(crate) const COMMAND: &str = "addon.pathtools.tangentCircle";
|
||||
/// The undo step's name.
|
||||
const LABEL: &str = "Tangent Circle";
|
||||
/// The radius the command takes with two shapes (pt).
|
||||
const RADIUS: std::ops::RangeInclusive<f64> = 0.01..=1e6;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.tangentCircle",
|
||||
"Tangent Circle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{ids?: [id…] (two or three paths or compound paths; default: the selection), radius?: pt 0.01..1000000 (needed with two shapes; three shapes set the radius themselves and take none), circle?: 0..64 (0: every circle found; n: only the nth, the circles listed by radius, then top to bottom, then left to right)} draw the circles that touch two shapes and have the radius, or that touch three shapes. A circle touches a shape when it meets the shape's outline without crossing it, the whole outline lying outside the circle or inside it: it is tangent to the outline at a smooth point and passes through a corner or an open end; the members of a compound path count as one outline. With three shapes, circles up to 64 times the diagonal of the box around the shapes' anchors and handles are found. Each circle is a new ellipse with the current paint on top of the current layer, or of the isolated group (inside an isolated compound path they join it); the circles are selected; one undo step. Locked and hidden shapes given by `ids` are read and left as they are. No circle is an error, and so are more than 64 (shapes touched along a whole curve, such as two concentric circles), an object named twice, shapes at one point or too small for the radius, and more than 2000 segments in all; the document is then unchanged → {ids, found (how many circles touch the shapes)}",
|
||||
has_selection,
|
||||
tangent_circle
|
||||
)]
|
||||
}
|
||||
|
||||
/// The paths of path or compound path `id`: itself, or its members.
|
||||
fn paths_of(d: &Document, id: NodeId) -> Result<Vec<&PathData>> {
|
||||
let value = id.0;
|
||||
let n = d.node(id).ok_or_else(|| bad(COMMAND, format!("no such object id {value}")))?;
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => Ok(vec![path]),
|
||||
NodeKind::Compound { children, .. } => Ok(children.iter().filter_map(|c| c.path_data()).collect()),
|
||||
_ => Err(bad(COMMAND, format!("object {value} is not a path or compound path"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outlines of `ids`, each path's or compound path's subpaths together; counted before they
|
||||
/// are copied.
|
||||
fn outlines(d: &Document, ids: &[NodeId]) -> Result<Vec<PathData>> {
|
||||
let parts = ids.iter().map(|id| paths_of(d, *id)).collect::<Result<Vec<_>>>()?;
|
||||
let segments: usize = parts.iter().flatten().map(|p| pt::tangent_circle_segments(p)).sum();
|
||||
if segments > pt::MAX_TANGENT_CIRCLE_SEGMENTS {
|
||||
return Err(bad(COMMAND, TOO_COMPLEX));
|
||||
}
|
||||
Ok(parts.iter().map(|paths| PathData::new(paths.iter().flat_map(|p| p.subpaths.iter().cloned()).collect())).collect())
|
||||
}
|
||||
|
||||
const TOO_COMPLEX: &str = "the shapes are too complex: at most 2000 segments in all";
|
||||
|
||||
fn tangent_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A repeated id is refused before the ids inside another given one are dropped.
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
let mut seen = HashSet::new();
|
||||
if checked_ids_param(s, p, "ids", COMMAND)?.iter().any(|id| !seen.insert(*id)) {
|
||||
return Err(bad(COMMAND, "`ids` names an object twice"));
|
||||
}
|
||||
}
|
||||
let ids = checked_ids_or_selection(s, p, COMMAND)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if !(2..=3).contains(&ids.len()) {
|
||||
return Err(bad(COMMAND, "select two or three paths or compound paths"));
|
||||
}
|
||||
let outlines = outlines(d, &ids)?;
|
||||
if outlines.iter().any(|o| o.subpaths.iter().all(|sp| sp.anchors.is_empty())) {
|
||||
return Err(bad(COMMAND, "a shape has no outline"));
|
||||
}
|
||||
let given_radius = p.get("radius").is_some_and(|v| !v.is_null());
|
||||
let radius = number_or(p, "radius", 0.0, COMMAND)?;
|
||||
let radius = match (ids.len(), given_radius) {
|
||||
(2, true) if RADIUS.contains(&radius) => Some(radius),
|
||||
(2, true) => return Err(bad(COMMAND, "`radius` must be from 0.01 to 1000000 pt")),
|
||||
(2, false) => return Err(bad(COMMAND, "two shapes need a `radius`")),
|
||||
(_, true) => return Err(bad(COMMAND, "three shapes set the radius themselves: leave `radius` out")),
|
||||
(_, false) => None,
|
||||
};
|
||||
let pick = index_opt(p, "circle", COMMAND)?.unwrap_or(0);
|
||||
if pick > pt::MAX_TANGENT_CIRCLES {
|
||||
return Err(bad(COMMAND, "`circle` must be from 0 to 64"));
|
||||
}
|
||||
let refs: Vec<&PathData> = outlines.iter().collect();
|
||||
let found = pt::tangent_circles(&refs, radius).map_err(|e| match e {
|
||||
// Every outline has points (checked above): all at one place, or too small for the radius.
|
||||
TangentCircleError::BadInput => bad(COMMAND, "these shapes are too small to measure"),
|
||||
// The segments were counted above: the search itself went past its limits.
|
||||
TangentCircleError::TooComplex => bad(COMMAND, "these shapes take too long to search"),
|
||||
TangentCircleError::TooMany => bad(COMMAND, "more than 64 circles touch these shapes: they may touch along a whole curve"),
|
||||
})?;
|
||||
if found.is_empty() {
|
||||
return Err(bad(COMMAND, "no circle touches these shapes"));
|
||||
}
|
||||
let chosen: Vec<pt::Circle> = match pick {
|
||||
0 => found.clone(),
|
||||
n => match found.get(n - 1) {
|
||||
Some(c) => vec![*c],
|
||||
None => {
|
||||
let found = found.len();
|
||||
return Err(bad(COMMAND, format!("`circle` is past the last circle found ({found})")));
|
||||
}
|
||||
},
|
||||
};
|
||||
// Path art: inside an isolated compound path, the circles join it and take its appearance.
|
||||
let parent = s.doc()?.target_parent_for_path()?;
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ids = s.edit(LABEL, |d, sel| {
|
||||
let mut ids = vec![];
|
||||
for c in &chosen {
|
||||
let (r, at) = (c.radius, c.center);
|
||||
let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) };
|
||||
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
|
||||
let mut n = Node::new(d.alloc_id(), kind);
|
||||
look.apply(d, &mut n);
|
||||
ids.push(n.id);
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "found": found.len() }))
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! Tangent Circle: circles drawn for two shapes and a radius or three shapes, one undo step, the
|
||||
//! current paint, compound paths, one circle picked, and the errors that leave the document as it was.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::COMMAND;
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn ellipse(s: &mut Session, x: f64, y: f64, w: f64, h: f64, rotation: f64) -> u64 {
|
||||
let id = s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "rotation": rotation})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> u64 {
|
||||
ellipse(s, cx - r, cy - r, 2.0 * r, 2.0 * r, 0.0)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().len()
|
||||
}
|
||||
|
||||
/// The circle path `id` is: (center, radius) from its live ellipse.
|
||||
fn drawn(s: &Session, id: &Value) -> (Point, f64) {
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap();
|
||||
let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not a live shape") };
|
||||
let LiveShape::Ellipse { w, h, xf, .. } = live.as_ref() else { panic!("not an ellipse") };
|
||||
assert!((w - h).abs() < 1e-9);
|
||||
(*xf * Point::new(w / 2.0, h / 2.0), w / 2.0)
|
||||
}
|
||||
|
||||
fn refused(s: &mut Session, p: Value) -> String {
|
||||
let (steps, objects) = (undo_steps(s), count(s));
|
||||
let e = s.execute(COMMAND, &p).unwrap_err().to_string();
|
||||
assert_eq!((undo_steps(s), count(s)), (steps, objects), "{p} changed the document");
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_and_a_radius_draw_every_circle_as_one_step() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 130.0, 100.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 20})).unwrap();
|
||||
assert_eq!(r["found"], 6);
|
||||
let ids = r["ids"].as_array().unwrap().clone();
|
||||
assert_eq!(ids.len(), 6);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(count(&s), 8);
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), 6);
|
||||
let fill = st.doc.node(NodeId(ids[0].as_u64().unwrap())).unwrap().appearance.fill_paint();
|
||||
assert_eq!(fill, s.paint.fill);
|
||||
// Outside both: 30 from each center, at x = 115.
|
||||
let h = (900.0f64 - 225.0).sqrt();
|
||||
let centers: Vec<(Point, f64)> = ids.iter().map(|id| drawn(&s, id)).collect();
|
||||
for want in [Point::new(115.0, 100.0 - h), Point::new(115.0, 100.0 + h)] {
|
||||
// Within the Bézier circles' own error (0.0273% of the radius) of the ideal answer.
|
||||
assert!(centers.iter().any(|(c, r)| (*c - want).hypot() < 0.02 && (r - 20.0).abs() < 1e-9), "{centers:?}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_circles_and_one_picked() {
|
||||
let mut s = session();
|
||||
let ids = [circle(&mut s, 100.0, 100.0, 10.0), circle(&mut s, 180.0, 100.0, 10.0), circle(&mut s, 100.0, 160.0, 10.0)];
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
// The selection: all eight, smallest first; the first is the one outside all three, about the
|
||||
// circumcenter (140, 130), 50 from each center.
|
||||
let r = s.execute(COMMAND, &json!({"circle": 1})).unwrap();
|
||||
assert_eq!(r["found"], 8);
|
||||
let one = r["ids"].as_array().unwrap();
|
||||
assert_eq!(one.len(), 1);
|
||||
let (c, radius) = drawn(&s, &one[0]);
|
||||
assert!((c - Point::new(140.0, 130.0)).hypot() < 0.05 && (radius - 40.0).abs() < 0.05, "{c:?} {radius}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
assert_eq!(s.execute(COMMAND, &json!({})).unwrap()["ids"].as_array().unwrap().len(), 8);
|
||||
assert!(refused(&mut s, json!({"ids": ids, "circle": 9})).contains("past the last circle found (8)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_rotated_and_locked_shapes() {
|
||||
let mut s = session();
|
||||
// A ring as a compound path, and an ellipse turned 30° inside its hole.
|
||||
let outer = circle(&mut s, 200.0, 150.0, 80.0);
|
||||
let inner = circle(&mut s, 200.0, 150.0, 60.0);
|
||||
s.execute("select.set", &json!({"ids": [outer, inner]})).unwrap();
|
||||
let ring = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let oval = ellipse(&mut s, 180.0, 140.0, 40.0, 20.0, 30.0);
|
||||
s.execute("select.set", &json!({"ids": [oval]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [ring]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"ids": [ring, oval], "radius": 22})).unwrap();
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
// In the hole, 38 from the center, and 22 from the oval (reaching 42 along its long axis and
|
||||
// 32 along its short one): two by each end of the oval.
|
||||
assert_eq!(ids.len(), 4, "{r}");
|
||||
for id in ids {
|
||||
let (c, radius) = drawn(&s, id);
|
||||
assert!(((c - Point::new(200.0, 150.0)).hypot() - (60.0 - radius)).abs() < 0.05, "{c:?}");
|
||||
}
|
||||
// The locked oval and the hidden ring were read and left as they were.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(oval)).unwrap().locked);
|
||||
assert!(!d.node(NodeId(ring)).unwrap().visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_go_into_an_isolated_group() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 130.0, 100.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": group})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 5})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(id), Some(NodeId(group)));
|
||||
// On top of the group's art.
|
||||
assert_eq!(d.node(NodeId(group)).unwrap().children().unwrap().last().map(|n| n.id), Some(id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_join_an_isolated_compound_path() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 130.0, 100.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": compound})).unwrap();
|
||||
let members: Vec<u64> = s.doc().unwrap().doc.node(NodeId(compound)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
let r = s.execute(COMMAND, &json!({"ids": members, "radius": 5})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(NodeId(compound)));
|
||||
// A compound path and one of its own members are taken as the compound path alone: one shape.
|
||||
let e = refused(&mut s, json!({"ids": [compound, members[0]], "radius": 5}));
|
||||
assert!(e.contains("two or three"), "{e}");
|
||||
// A repeated member is refused even though the compound path holds it.
|
||||
let other = circle(&mut s, 300.0, 100.0, 10.0);
|
||||
let e = refused(&mut s, json!({"ids": [compound, members[0], members[0], other], "radius": 5}));
|
||||
assert!(e.contains("twice"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_leave_the_document_unchanged() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 50.0, 10.0);
|
||||
let b = circle(&mut s, 250.0, 50.0, 10.0);
|
||||
let c = circle(&mut s, 150.0, 200.0, 10.0);
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 5})).contains("no circle touches"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b]})).contains("need a `radius`"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b, c], "radius": 5})).contains("leave `radius` out"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 0})).contains("0.01"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": "5 mm"})).contains("must be a number"));
|
||||
assert!(refused(&mut s, json!({"ids": [a], "radius": 5})).contains("two or three"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, a], "radius": 5})).contains("twice"));
|
||||
let e = refused(&mut s, json!({"ids": [a, a as f64], "radius": 5}));
|
||||
assert!(e.contains("not a non-negative integer"), "{e}");
|
||||
// Two lone anchors at one place.
|
||||
let dot = |s: &mut Session| s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap();
|
||||
let (p, q) = (dot(&mut s), dot(&mut s));
|
||||
assert!(refused(&mut s, json!({"ids": [p, q], "radius": 5})).contains("too small to measure"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": 65})).contains("from 0 to 64"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": -1})).contains("whole number"));
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 280, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(refused(&mut s, json!({"ids": [a, t], "radius": 5})).contains("not a path"));
|
||||
let anchors: Vec<Value> = (0..2002).map(|i| json!({"x": i as f64 * 0.1, "y": 250.0 + (i % 2) as f64})).collect();
|
||||
let zigzag = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(refused(&mut s, json!({"ids": [a, zigzag], "radius": 5})).contains("at most 2000 segments"));
|
||||
// Concentric circles touched all the way round.
|
||||
let inner = circle(&mut s, 50.0, 50.0, 40.0);
|
||||
assert!(refused(&mut s, json!({"ids": [a, inner], "radius": 15})).contains("whole curve"));
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
//! Trim at Crossings: remove the stretch of a path between the places where other paths, or the
|
||||
//! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle
|
||||
//! touches, or every stretch a line through some points crosses. It works on every path that can
|
||||
//! be edited, selected or not.
|
||||
|
||||
use std::collections::HashSet;
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::{Line, PathSeg};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Pick, Stretches};
|
||||
|
||||
use super::super::super::draw2::replace_with_pieces;
|
||||
use super::super::super::pathops::Beside;
|
||||
@@ -41,16 +39,6 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// What picks the stretches to remove.
|
||||
enum Pick {
|
||||
/// The stretch of the nearest path within the tolerance of the point.
|
||||
At(Point, f64),
|
||||
/// Every stretch the rectangle touches.
|
||||
Rect(Rect),
|
||||
/// Every stretch the line through the points crosses.
|
||||
Line(Vec<Point>, Rect),
|
||||
}
|
||||
|
||||
fn pick(p: &Value) -> Result<Pick> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let given = |key: &str| p.get(key).filter(|v| !v.is_null());
|
||||
@@ -89,194 +77,15 @@ fn pick(p: &Value) -> Result<Pick> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that takes part: its id, geometry and control-point box.
|
||||
type Part<'a> = (NodeId, &'a PathData, Rect);
|
||||
|
||||
/// The paths that take part, bottom to top: the ones that can be edited, without guides and
|
||||
/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the
|
||||
/// members of a compound clipping path included.
|
||||
fn parts(d: &Document) -> Vec<Part<'_>> {
|
||||
let editable = d.editable();
|
||||
let mut masks = HashSet::new();
|
||||
d.walk(|n| {
|
||||
if n.clips()
|
||||
&& let Some(first) = n.children().and_then(|c| c.first())
|
||||
{
|
||||
first.walk(&mut |m| {
|
||||
masks.insert(m.id);
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind
|
||||
&& !masks.contains(&n.id)
|
||||
&& let Some(b) = path.control_bounds()
|
||||
&& editable(n.id)
|
||||
{
|
||||
out.push((n.id, path, b));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Most box tests one command makes between a line's pieces and the paths' segments.
|
||||
const MAX_LINE_TESTS: usize = 60_000_000;
|
||||
/// Most tests one command makes between the boxes of the paths to trim and of the other paths.
|
||||
const MAX_BOX_TESTS: usize = 50_000_000;
|
||||
|
||||
/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`;
|
||||
/// `None` once it is spent.
|
||||
fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option<bool> {
|
||||
let segs: Vec<_> = (0..sp.segment_count())
|
||||
.map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9))
|
||||
})
|
||||
.collect();
|
||||
let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) };
|
||||
for w in pts.windows(2) {
|
||||
let [a, b] = w else { continue };
|
||||
let piece = Rect::from_points(*a, *b);
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if !reach.overlaps(piece) {
|
||||
continue;
|
||||
}
|
||||
for (c, r) in &segs {
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() {
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`.
|
||||
fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result<bool> {
|
||||
match pick {
|
||||
Pick::At(..) => Ok(false),
|
||||
Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)),
|
||||
Pick::Line(pts, _) => crossed_by_line(piece, pts, budget)
|
||||
.ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths
|
||||
/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no
|
||||
/// part of `path` leaves it out before its crossings are looked for.
|
||||
fn trimmed(
|
||||
path: &PathData,
|
||||
others: &[&PathData],
|
||||
pick: &Pick,
|
||||
on: Option<pt::Place>,
|
||||
budget: &mut usize,
|
||||
work: &mut pt::Work,
|
||||
) -> Result<Option<(Vec<SubPath>, usize)>> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let reached = match pick {
|
||||
Pick::At(..) => true,
|
||||
Pick::Rect(r) => hit::intersects_rect(path, *r),
|
||||
Pick::Line(..) => {
|
||||
let mut any = false;
|
||||
for sp in &path.subpaths {
|
||||
if touches(sp, pick, budget)? {
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
};
|
||||
if !reached {
|
||||
return Ok(None);
|
||||
}
|
||||
let places =
|
||||
pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?;
|
||||
let mut subs = vec![];
|
||||
let mut removed = 0;
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
// The places come in subpath order: this subpath's are one run of them.
|
||||
let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si);
|
||||
let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect();
|
||||
let spans = pt::spans(sp, &here);
|
||||
let marks: Vec<bool> = match pick {
|
||||
Pick::At(..) => {
|
||||
let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t));
|
||||
(0..spans.len()).map(|i| Some(i) == at).collect()
|
||||
}
|
||||
_ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::<Result<_>>()?,
|
||||
};
|
||||
match pt::without_spans(sp, &spans, &marks) {
|
||||
Some(pieces) => {
|
||||
removed += marks.iter().filter(|m| **m).count();
|
||||
subs.extend(pieces);
|
||||
}
|
||||
None => subs.push(sp.clone()),
|
||||
}
|
||||
}
|
||||
Ok((removed > 0).then_some((subs, removed)))
|
||||
}
|
||||
|
||||
fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let pick = pick(p)?;
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let parts = parts(d);
|
||||
// In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them.
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id));
|
||||
// The paths to trim, each with the place `at` falls on.
|
||||
let targets: Vec<(usize, Option<pt::Place>)> = match &pick {
|
||||
Pick::At(at, tolerance) => {
|
||||
let mut best: Option<(usize, pt::Place, f64)> = None;
|
||||
for (i, (id, path, b)) in parts.iter().enumerate() {
|
||||
if !in_scope(*id) {
|
||||
continue;
|
||||
}
|
||||
let b = b.inflate(*tolerance, *tolerance);
|
||||
if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) {
|
||||
continue;
|
||||
}
|
||||
// Of paths equally near, the one on top.
|
||||
if let Some((si, seg, t, _, dist)) = path.nearest(*at)
|
||||
&& dist <= *tolerance
|
||||
&& best.is_none_or(|b| dist <= b.2)
|
||||
{
|
||||
best = Some((i, (si, seg, t), dist));
|
||||
}
|
||||
}
|
||||
best.map(|(i, on, _)| (i, Some(on))).into_iter().collect()
|
||||
}
|
||||
Pick::Rect(r) | Pick::Line(_, r) => {
|
||||
parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect()
|
||||
}
|
||||
};
|
||||
// Each path to trim has its box tested against every other path's.
|
||||
if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS {
|
||||
return Err(bad(C, "the rectangle or line reaches too many paths to check"));
|
||||
}
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
let mut removed = 0;
|
||||
let mut budget = MAX_LINE_TESTS;
|
||||
// One budget of crossing work for every path the command trims.
|
||||
let mut work = pt::Work::default();
|
||||
for (i, on) in targets {
|
||||
let Some((id, path, b)) = parts.get(i) else { continue };
|
||||
let reach = b.inflate(1e-3, 1e-3);
|
||||
let others: Vec<&PathData> =
|
||||
parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect();
|
||||
let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue };
|
||||
removed += n;
|
||||
// A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths.
|
||||
let pieces = match (path.subpaths.len(), subs.is_empty()) {
|
||||
(_, true) => vec![],
|
||||
(1, false) => subs.into_iter().map(PathData::single).collect(),
|
||||
_ => vec![PathData::new(subs)],
|
||||
};
|
||||
plan.push((*id, pieces));
|
||||
}
|
||||
let trimmed = plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).map_err(|e| bad(C, e.message()))?;
|
||||
let removed: usize = trimmed.iter().map(|t| t.count).sum();
|
||||
let plan: Vec<(NodeId, Vec<_>)> = trimmed.into_iter().map(|t| (t.id, t.pieces)).collect();
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [], "removed": 0 }));
|
||||
}
|
||||
|
||||
@@ -480,6 +480,129 @@ fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() {
|
||||
assert_eq!(steps(&s), n + 2);
|
||||
}
|
||||
|
||||
/// The ends of each red path the tool shows.
|
||||
fn highlighted(s: &mut Session, view: crate::ViewInfo) -> Vec<(Point, Point)> {
|
||||
use vectorcraft_geom::kurbo::ParamCurve;
|
||||
s.overlays(view)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => {
|
||||
let segs: Vec<_> = path.segments().collect();
|
||||
Some((segs.first()?.start(), segs.last()?.end()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_with_the_tool_shows_the_stretch_its_click_removes() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let (h, _, _) = across_and_uprights(&mut s);
|
||||
let hidden = line(&mut s, &[(0.0, 200.0), (300.0, 200.0)], false);
|
||||
set_flags(&mut s, hidden, false, false);
|
||||
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
|
||||
s.select_tool("trimAtCrossings", view).unwrap();
|
||||
let n = steps(&s);
|
||||
// Over the middle of the line across: the stretch between the uprights, and nothing changes.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap();
|
||||
let shown = highlighted(&mut s, view);
|
||||
assert!(matches!(shown.as_slice(), [(a, b)] if near(*a, 100.0, 100.0) && near(*b, 200.0, 100.0)), "{shown:?}");
|
||||
assert_eq!(steps(&s), n);
|
||||
// Over the hidden path and over empty canvas: nothing.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 200.0), view).unwrap();
|
||||
assert!(highlighted(&mut s, view).is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 250.0), view).unwrap();
|
||||
assert!(highlighted(&mut s, view).is_empty());
|
||||
// A click where the stretch was shown removes exactly it: the line keeps 0 to 100 and 200 to 300.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 101.0), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 101.0), view).unwrap();
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 100.0, 100.0));
|
||||
let rest = stack(&s).into_iter().find(|id| *id != h && path(&s, *id).subpaths.len() == 1 && near(ends(&s, *id).0, 200.0, 100.0));
|
||||
assert!(rest.is_some_and(|id| near(ends(&s, id).1, 300.0, 100.0)));
|
||||
assert!(highlighted(&mut s, view).is_empty(), "the edit drops the highlight");
|
||||
}
|
||||
|
||||
/// The red paths the tool shows.
|
||||
fn red(s: &mut Session, view: crate::ViewInfo) -> Vec<vectorcraft_geom::BezPath> {
|
||||
s.overlays(view)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The length of every path in the first layer.
|
||||
fn total_length(s: &Session) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
stack(s).into_iter().flat_map(|id| path(s, id).to_bezpath().segments().collect::<Vec<_>>()).map(|seg| seg.arclen(1e-9)).sum()
|
||||
}
|
||||
|
||||
/// `act` removes exactly the red paths shown before it: the paths lose their length, and nothing
|
||||
/// is left on the middle of any of them.
|
||||
fn removes_what_was_shown(s: &mut Session, view: crate::ViewInfo, act: &dyn Fn(&mut Session)) {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen};
|
||||
let shown = red(s, view);
|
||||
assert!(!shown.is_empty());
|
||||
let shown_length: f64 = shown.iter().flat_map(|p| p.segments().collect::<Vec<_>>()).map(|seg| seg.arclen(1e-9)).sum();
|
||||
let before = total_length(s);
|
||||
act(s);
|
||||
assert!((before - total_length(s) - shown_length).abs() < 1e-3, "{before} - {} != {shown_length}", total_length(s));
|
||||
for p in &shown {
|
||||
let segs: Vec<_> = p.segments().collect();
|
||||
let mid = segs[segs.len() / 2].eval(if segs.len() % 2 == 1 { 0.5 } else { 0.0 });
|
||||
let left = stack(s).into_iter().filter_map(|id| path(s, id).nearest(mid)).map(|n| n.4).fold(f64::INFINITY, f64::min);
|
||||
assert!(left > 0.5, "a path is left at {mid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_tool_shows_before_a_click_or_a_release_is_what_the_command_removes() {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
|
||||
let ev = |kind, x, y| PointerEvent::new(kind, x, y);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
line(&mut s, &[(50.0, 100.0), (350.0, 100.0)], false);
|
||||
// A Z whose first and last sides cross.
|
||||
line(&mut s, &[(0.0, 160.0), (100.0, 260.0), (100.0, 160.0), (0.0, 260.0)], false);
|
||||
s.select_tool("trimAtCrossings", view).unwrap();
|
||||
s
|
||||
};
|
||||
// A click on the ellipse's top, on the line inside it and on the Z's loop.
|
||||
for (x, y) in [(200.0, 51.0), (200.0, 101.0), (101.0, 210.0)] {
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Move, x, y), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Down, x, y), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, x, y), view).unwrap();
|
||||
});
|
||||
}
|
||||
// A rectangle over the ellipse's left side and the line.
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Down, 90.0, 90.0), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 120.0, 110.0), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Up, 120.0, 110.0), view).unwrap();
|
||||
});
|
||||
// An Alt line through the ellipse's bottom and the Z's tail.
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Down, 200.0, 140.0).with_mods(alt), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 200.0, 170.0).with_mods(alt), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 10.0, 250.0).with_mods(alt), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Up, 10.0, 250.0).with_mods(alt), view).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_too_long_to_check_against_the_paths_is_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the paint, weight, opacity and blend mode it writes to the line's topmost visible row)",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; moving rows of such a group whose members' rows differ is an error), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -538,7 +538,8 @@ pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// it, and each such Axes or Legend group of a graph by the lines and labels directly inside it
|
||||
/// ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty())
|
||||
@@ -559,8 +560,9 @@ fn holds_no_look(group: &Node) -> bool {
|
||||
}
|
||||
|
||||
/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own
|
||||
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or
|
||||
/// another attribute of its own is read itself, with that attribute.
|
||||
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first, and such an Axes or Legend group of a graph
|
||||
/// the lines and labels directly inside it. A series group with an effect, an opacity or another attribute of its own is
|
||||
/// read itself, with that attribute.
|
||||
fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, &[id], holds_no_look)
|
||||
}
|
||||
@@ -626,11 +628,48 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Refuse a row index given a graph's Axes or Legend group that stands for lines and labels whose stacks differ
|
||||
/// ([`rowless_series_marks`]), unless the index is `aligned`, a row of the backmost one's stack: the same index names a
|
||||
/// different row in each of them.
|
||||
pub(crate) fn check_part_rows(s: &Session, p: &Value, aligned: bool, cmd: &str) -> Result<()> {
|
||||
if aligned {
|
||||
return Ok(());
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
for id in appearance_targets(s, p)? {
|
||||
let Some(n) = d.node(id).filter(|n| n.appearance.items.is_empty()) else { continue };
|
||||
if let Some(members) = super::graph::graph_part_members(d, n)
|
||||
&& appearances_differ(d, &members)
|
||||
{
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("the lines and labels in graph group {} have different appearance rows: pass `aligned: true` or their ids", id.0),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether row `index` of `n` is the topmost visible row of its kind, the row a graph keeps for a label or line.
|
||||
fn is_top_shown(n: &Node, index: usize) -> bool {
|
||||
let items = &n.appearance.items;
|
||||
items.get(index).is_some_and(|it| items.iter().rposition(|o| o.is_fill() == it.is_fill() && o.visible()) == Some(index))
|
||||
}
|
||||
|
||||
/// `ids` without the objects whose topmost visible fill and stroke rows ([`super::graph::label_rows`]) an edit left as
|
||||
/// they were (`before`: the document before it), unless `wrote` says the edit wrote one of those rows. An edit of a
|
||||
/// hidden row of a graph label or line then leaves what the graph keeps for its kind as it is.
|
||||
fn shown_rows_edited(before: &Document, d: &Document, ids: Vec<NodeId>, wrote: impl Fn(NodeId) -> bool) -> Vec<NodeId> {
|
||||
let shown = |doc: &Document, id: NodeId| doc.node(id).map(super::graph::label_rows);
|
||||
ids.into_iter().filter(|id| wrote(*id) || shown(before, *id) != shown(d, *id)).collect()
|
||||
}
|
||||
|
||||
/// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke
|
||||
/// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters).
|
||||
/// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the
|
||||
/// rows and characters of graph labels, is stored on their graphs in the same step
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]), and so are the rows of
|
||||
/// the graph lines it reaches ([`super::graph::capture_line_changes`]). Nothing targeted is not
|
||||
/// an edit, and when `f` leaves every target as it was, the document and its undo history stay as
|
||||
/// they are.
|
||||
///
|
||||
@@ -652,7 +691,7 @@ pub(crate) fn edit_items(
|
||||
edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
// The rows `f` edited are kept by `edit_items_then`.
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false);
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false, None);
|
||||
Ok(series || labels)
|
||||
})
|
||||
}
|
||||
@@ -670,6 +709,45 @@ pub(crate) fn edit_items_then(
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_writing_then(s, ids, item, of, cmd, label, fill, super::graph::RowWrites::NONE, f, after)
|
||||
}
|
||||
|
||||
/// [`edit_items`] for an edit that writes the attributes `writes` says to the row of each target it edits: a graph line
|
||||
/// keeps them for its kind when that row is its topmost visible one, also when the line already showed them
|
||||
/// ([`super::graph::capture_line_row_writes`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn edit_items_writing(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
writes: super::graph::RowWrites,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_writing_then(s, ids, item, of, cmd, label, fill, writes, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false, None);
|
||||
Ok(series || labels)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`edit_items_then`] with the attributes `writes` says, as [`edit_items_writing`] keeps them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_items_writing_then(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
writes: super::graph::RowWrites,
|
||||
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
@@ -693,6 +771,10 @@ pub(crate) fn edit_items_then(
|
||||
let mut edited = Vec::new();
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
let mut rows = Vec::new();
|
||||
// The objects where `f` wrote the topmost visible row of its kind.
|
||||
let mut wrote = Vec::new();
|
||||
// The row of each object `f` wrote: its index, else the topmost row of the kind.
|
||||
let mut written = Vec::new();
|
||||
for (id, item) in ids.iter().zip(&per) {
|
||||
let Some(item) = item else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
@@ -702,10 +784,22 @@ pub(crate) fn edit_items_then(
|
||||
if index.is_some() {
|
||||
rows.push(*id);
|
||||
}
|
||||
if index.is_none_or(|i| is_top_shown(n, i)) {
|
||||
wrote.push(*id);
|
||||
}
|
||||
written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at)));
|
||||
}
|
||||
let more = after(&before, d, &edited)?;
|
||||
let labels = super::graph::capture_label_rows(d, &rows);
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
|
||||
// A graph line keeps only the attributes of its rows that the edit changed, and those it wrote (`writes`): the
|
||||
// others stay as its kind keeps them, which the line may not show yet.
|
||||
rows.retain(|id| !super::graph::is_graph_line(d, *id));
|
||||
let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, rows, |id| wrote.contains(&id)));
|
||||
let mut lines = super::graph::capture_line_changes(&before, d, &edited);
|
||||
if writes != super::graph::RowWrites::NONE {
|
||||
let (on_fill, on_stroke) = if fill { (writes, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, writes) };
|
||||
lines |= super::graph::capture_line_row_writes(d, &written, on_fill, on_stroke);
|
||||
}
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines))
|
||||
})?;
|
||||
Ok(aimed)
|
||||
}
|
||||
@@ -716,6 +810,17 @@ pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, id
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// Keep the object rows of the graph labels among `ids` for every label of their kind
|
||||
/// ([`super::graph::capture_label_rows`]), and of the graph lines among them only the attributes the edit changed
|
||||
/// ([`super::graph::capture_line_changes`]): a line's other attributes stay as its kind keeps them, which the line may
|
||||
/// not show yet. Returns whether what a graph keeps changed.
|
||||
fn capture_row_edits(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
|
||||
let labels: Vec<NodeId> = ids.iter().copied().filter(|id| !super::graph::is_graph_line(d, *id)).collect();
|
||||
let labels = super::graph::capture_label_rows(d, &labels);
|
||||
let lines = super::graph::capture_line_changes(before, d, ids);
|
||||
labels || lines
|
||||
}
|
||||
|
||||
/// How many of `ids` differ in `d` from `before`.
|
||||
pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_doc::Document, ids: &[NodeId]) -> usize {
|
||||
ids.iter().filter(|id| d.node(**id) != before.node(**id)).count()
|
||||
@@ -854,10 +959,13 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let lines: Vec<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
capture_row_edits(&before, d, &ids);
|
||||
// A graph line keeps the row it got for its kind, also when it showed that row's paint, weight and transparency.
|
||||
super::graph::capture_line_kind_rows(d, &lines, (fill, !fill), false);
|
||||
Ok(())
|
||||
})?;
|
||||
// A fill added above the active row becomes the active row; otherwise the rows above the new
|
||||
@@ -1046,7 +1154,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect();
|
||||
if targets.is_empty() {
|
||||
if stands {
|
||||
return Err(bad(C, "`source` is the only path in series group `target`"));
|
||||
return Err(bad(C, "`source` is the only path, line or label that graph group `target` stands for"));
|
||||
}
|
||||
targets.push(target);
|
||||
}
|
||||
@@ -1091,8 +1199,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
rows.extend(painted_rows(d, both_kinds(&targets)));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let object = super::graph::capture_series_object_opacity(d, &changed);
|
||||
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps.
|
||||
let labels = super::graph::capture_label_rows(d, &changed);
|
||||
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. Graph lines are
|
||||
// taken in paint order, so the targets are captured again on their own, after a cleared source in front of them.
|
||||
let labels = super::graph::capture_label_rows(d, &changed) | super::graph::capture_label_rows(d, &targets);
|
||||
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
|
||||
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot))
|
||||
})?;
|
||||
@@ -1150,7 +1259,7 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
let labels = capture_row_edits(&before, d, &ids);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
@@ -1167,6 +1276,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.setItem", "select objects or give ids"));
|
||||
}
|
||||
check_part_rows(s, p, aligned(p, "appearance.setItem")?, "appearance.setItem")?;
|
||||
let blend = str_param(p, "blend").and_then(BlendMode::parse);
|
||||
// When every object comes out as it was (for example, when none has item `index`), the document
|
||||
// and its undo history stay as they are.
|
||||
@@ -1175,6 +1285,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let per = rows_per_target(&before, of, &ids, &[idx], aligned(p, "appearance.setItem")?);
|
||||
super::overprint::edit_counted(s, "Appearance", |d| {
|
||||
let mut edited = Vec::new();
|
||||
// The targets that have the row: an aligned row leaves out the members of a graph's Axes or Legend group that
|
||||
// lack it, and the graph keeps the rows of the labels and lines it reached only.
|
||||
let mut reached = Vec::new();
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
let Some(&idx) = at.first() else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
@@ -1185,6 +1298,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let bounds = n.geometric_bounds();
|
||||
let Some(item) = n.appearance.items.get_mut(idx) else { continue };
|
||||
reached.push(*id);
|
||||
let (pp, op, bl, vis, bounds) = match item {
|
||||
AppearanceItem::Fill(f) => (&mut f.paint, &mut f.opacity, &mut f.blend, &mut f.visible, bounds),
|
||||
AppearanceItem::Stroke(st) => {
|
||||
@@ -1227,8 +1341,19 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, written));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id));
|
||||
let labels = capture_row_edits(&before, d, &reached);
|
||||
// A graph line keeps what was written to its topmost visible row, also when it already showed it.
|
||||
let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect();
|
||||
// Only the values the edit applied: a null weight or opacity leaves the row as it is.
|
||||
let writes = super::graph::RowWrites {
|
||||
paint: paint.is_some(),
|
||||
weight: p.get("weight").and_then(Value::as_f64).is_some(),
|
||||
opacity: p.get("opacity").and_then(Value::as_f64).is_some(),
|
||||
blend: blend.is_some(),
|
||||
};
|
||||
let lines = super::graph::capture_line_row_writes(d, &tops, super::graph::RowWrites { weight: false, ..writes }, writes);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels || lines))
|
||||
})?;
|
||||
if let Some(pa) = &paint {
|
||||
s.remember_paint(pa);
|
||||
@@ -1256,14 +1381,20 @@ pub(super) fn item_indices(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let idx = item_indices(p, "appearance.removeItem")?;
|
||||
let ids = require_targets(s, p, "appearance.removeItem")?;
|
||||
check_part_rows(s, p, aligned(p, "appearance.removeItem")?, "appearance.removeItem")?;
|
||||
// When no object has an item at any of the indices, the document and its undo history stay as
|
||||
// they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let of = design_reference(s, p, "appearance.removeItem")?;
|
||||
let per = rows_per_target(&before, of, &ids, &idx, aligned(p, "appearance.removeItem")?);
|
||||
super::overprint::edit_counted(s, "Remove Item", |d| {
|
||||
// The targets that had a row to remove, as in `set_item`.
|
||||
let mut reached = Vec::new();
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
if idx.iter().any(|i| *i < n.appearance.items.len()) {
|
||||
reached.push(*id);
|
||||
}
|
||||
let mut idx = idx.clone();
|
||||
idx.sort_unstable();
|
||||
// From the top down, so the lower indices stay valid.
|
||||
@@ -1275,7 +1406,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |_| false));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
// The rows removed from the active row's object, which need not come first in `ids`.
|
||||
@@ -1295,6 +1426,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`contents` goes with `to`"));
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
check_part_rows(s, p, aligned(p, C)?, C)?;
|
||||
// Where the first target's copy landed, and where it landed on the active row's object (the
|
||||
// first selected one, not always the first target): copies placed at `to` land at a different
|
||||
// index on stacks of other lengths.
|
||||
@@ -1319,6 +1451,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
// showed it.
|
||||
let mut added = Vec::new();
|
||||
// The targets that took a copy, as in `set_item`.
|
||||
let mut reached = Vec::new();
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let has_contents = n.contents_label().is_some();
|
||||
@@ -1343,6 +1477,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ap.set_contents_at(c);
|
||||
}
|
||||
any = true;
|
||||
reached.push(*id);
|
||||
continue;
|
||||
}
|
||||
let mut idx = idx.clone();
|
||||
@@ -1357,6 +1492,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
added.push((*id, kind));
|
||||
}
|
||||
any = true;
|
||||
if reached.last() != Some(id) {
|
||||
reached.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1365,9 +1503,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
let top_copies: Vec<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id)));
|
||||
Ok(())
|
||||
})?;
|
||||
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
|
||||
@@ -1407,7 +1546,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown));
|
||||
super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown));
|
||||
super::graph::capture_label_rows(d, &shown);
|
||||
capture_row_edits(&before, d, &shown);
|
||||
Ok(shown)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
@@ -1431,6 +1570,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
check_part_rows(s, p, aligned, C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
@@ -1457,7 +1597,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, true, None);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
// The moved row stays the active one; the rows it passed shift by one.
|
||||
@@ -1503,7 +1643,7 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, ids));
|
||||
let labels = super::graph::capture_label_rows(d, ids);
|
||||
let labels = super::graph::capture_label_changes(&before, d, ids, true, None);
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
let m = idx.len();
|
||||
@@ -1536,8 +1676,8 @@ fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result<Value> {
|
||||
slot.get_or_insert(n.appearance.contents_at());
|
||||
}
|
||||
slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?;
|
||||
// A graph label's kind keeps where its rows paint relative to the characters.
|
||||
let labels = super::graph::capture_label_rows(d, ids);
|
||||
// A graph label's kind keeps where its rows paint relative to the characters, from the labels the move changed.
|
||||
let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, ids.to_vec(), |_| false));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(labels))
|
||||
})?;
|
||||
Ok(json!({ "contents": slot }))
|
||||
@@ -1804,15 +1944,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let object = super::graph::capture_series_object_opacity(d, &objects);
|
||||
// Graph labels keep their new rows, characters and paragraphs per kind of label.
|
||||
// On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other
|
||||
// attributes go to the characters.
|
||||
// attributes go to the characters. Without a transparency pick, the object opacity and blend mode a kind keeps stay,
|
||||
// also when the label or line picked onto still shows other ones until the graph is drawn again. `append` keeps
|
||||
// only the kinds of row it added; a row of the other kind stays as the kind keeps it.
|
||||
let transparency = attrs.appearance.transparency;
|
||||
let rows = if append {
|
||||
super::graph::capture_label_rows(d, &targets)
|
||||
super::graph::capture_label_kind_rows(d, &targets, paints, transparency)
|
||||
} else {
|
||||
attrs.appearance.transparency && super::graph::capture_label_object_opacity(d, &targets)
|
||||
transparency && super::graph::capture_label_object_opacity(d, &targets)
|
||||
};
|
||||
// `append` adds rows and leaves the characters as they were.
|
||||
let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?;
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text))
|
||||
// A graph line is a path: a whole pick and `append` write its rows. A pick of some attributes keeps those it
|
||||
// changed, and the rest stay as its kind keeps them, which the line may not show yet. Row attributes the graph
|
||||
// does not keep (overprint, caps, joins, miter limit, dashes) leave what its kind keeps as it is.
|
||||
let lines = match (rows_written, transparency) {
|
||||
_ if append => super::graph::capture_line_kind_rows(d, &targets, paints, transparency),
|
||||
(true, true) => super::graph::capture_line_rows(d, &targets),
|
||||
(true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets),
|
||||
(false, _) => {
|
||||
// The topmost row of each kind, which the pick wrote: what it wrote is kept also when the line showed it.
|
||||
let tops: Vec<(NodeId, usize)> = targets
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id).map(|n| (*id, &n.appearance.items)))
|
||||
.flat_map(|(id, items)| {
|
||||
[true, false].into_iter().filter_map(move |kind| items.iter().rposition(|it| it.is_fill() == kind).map(|at| (id, at)))
|
||||
})
|
||||
.collect();
|
||||
// A transparency pick applies the row's opacity and blend mode together.
|
||||
let on_fill = super::graph::RowWrites { paint: fill.color, weight: false, opacity: opacities.0, blend: opacities.0 };
|
||||
let on_stroke = super::graph::RowWrites {
|
||||
paint: stroke.color,
|
||||
weight: stroke.weight && source_has(false),
|
||||
opacity: opacities.1,
|
||||
blend: opacities.1,
|
||||
};
|
||||
super::graph::capture_line_changes(&before, d, &targets) | super::graph::capture_line_row_writes(d, &tops, on_fill, on_stroke)
|
||||
}
|
||||
};
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines))
|
||||
})?;
|
||||
Ok(finish(s, &targets))
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -23,20 +23,30 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]).
|
||||
/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths
|
||||
/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto
|
||||
/// Grouping groups hold filled paths.)
|
||||
/// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose
|
||||
/// members after the clipping path are all stroked paths without fills, or all filled paths
|
||||
/// without strokes (the strokes' outlines, on a stretched image), so that it is still found after
|
||||
/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made
|
||||
/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one
|
||||
/// of stroked paths without fills. (Auto Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
let stroke_only = |m: &Arc<Node>| {
|
||||
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& m.appearance.fill_paint() == Paint::None
|
||||
&& m.appearance.stroke_paint() != Paint::None
|
||||
};
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only)))
|
||||
let path = |m: &Arc<Node>| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
let stroke_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None;
|
||||
let fill_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None;
|
||||
let named = n.name.as_deref() == Some(SEAM_FILLS_NAME);
|
||||
match &n.kind {
|
||||
NodeKind::Group { clip: true, children } => {
|
||||
named
|
||||
|| children
|
||||
.split_first()
|
||||
.is_some_and(|(_, members)| !members.is_empty() && (members.iter().all(stroke_only) || members.iter().all(fill_only)))
|
||||
}
|
||||
NodeKind::Group { clip: false, children } => named || (!children.is_empty() && children.iter().all(stroke_only)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
@@ -411,7 +421,8 @@ fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is,
|
||||
/// under every other group. Any other group among `items` (Auto Grouping) is refused.
|
||||
/// under every other group; above another item it is refused. Any other group among `items` (Auto
|
||||
/// Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
@@ -465,6 +476,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
let mut large: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
let mut all_boxes: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
for (item, bounds) in items {
|
||||
if is_seam_fills(&item) {
|
||||
return Err(bad(cmd, "byColor needs the seam fills' group under every path: move it to the bottom or delete it"));
|
||||
}
|
||||
if matches!(item.kind, NodeKind::Group { .. }) {
|
||||
return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
@@ -637,12 +651,12 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam
|
||||
/// fills ([`seams_within`]).
|
||||
/// fills, if any ([`seams_within`]).
|
||||
pub struct Traced {
|
||||
inputs: TraceInputs,
|
||||
raster: (u32, u32),
|
||||
res: tr::TraceResult,
|
||||
seams: Vec<tr::TracedPath>,
|
||||
seams: Option<tr::SeamFills>,
|
||||
}
|
||||
|
||||
impl Traced {
|
||||
@@ -669,18 +683,127 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64
|
||||
tr::TraceError::Cancelled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
let seams = seams_within(&res, params, MAX_TRACE_ANCHORS);
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams })
|
||||
if !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let size = (raster.width, raster.height);
|
||||
let outlined = seam_unit(inputs.image.xf, raster_xf(&inputs.image, size)).is_none();
|
||||
let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined, steps)?;
|
||||
Ok(Traced { inputs: inputs.clone(), raster: size, res, seams })
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam
|
||||
/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the
|
||||
/// paths, so a trace whose paths have more than half of `max` gets none.
|
||||
fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec<tr::TracedPath> {
|
||||
if res.anchor_count() > max / 2 {
|
||||
return vec![];
|
||||
/// Pixel space of a `size` raster decoded from `img` → the image object's pixel space → document.
|
||||
fn raster_xf(img: &ImageObject, size: (u32, u32)) -> vectorcraft_geom::Affine {
|
||||
let sx = img.width.max(1) as f64 / size.0.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / size.1.max(1) as f64;
|
||||
img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy)
|
||||
}
|
||||
|
||||
/// Whether `xf` scales every direction alike (turning and mirroring allowed): its axes keep equal
|
||||
/// lengths and stay at right angles.
|
||||
fn scales_alike(xf: vectorcraft_geom::Affine) -> bool {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (across, down) = (a * a + b * b, c * c + d * d);
|
||||
let t = across + down;
|
||||
t.is_finite() && t > 0.0 && (across - down).abs() <= 1e-9 * t && (a * c + b * d).abs() <= 1e-9 * t
|
||||
}
|
||||
|
||||
/// The smallest length that `xf` scales a unit vector to (its smaller singular value): the
|
||||
/// difference of the lengths of its turning part and its stretching part.
|
||||
fn least_scale(xf: vectorcraft_geom::Affine) -> f64 {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let turning = ((a + d) / 2.0).hypot((b - c) / 2.0);
|
||||
let stretching = ((a - d) / 2.0).hypot((b + c) / 2.0);
|
||||
(turning - stretching).abs()
|
||||
}
|
||||
|
||||
/// Document units per raster pixel for the seam fills' strokes when the image object's transform
|
||||
/// `img_xf` scales every direction alike: the smaller scale of the raster-to-document transform
|
||||
/// `xf`, so that a stroke 1.5 pixels wide covers at most 0.75 pixels on each side of its edge at
|
||||
/// any angle. (A raster decoded scaled down to fit can be scaled a little differently across and
|
||||
/// down, as each side is rounded.) `None` when `img_xf` stretches one direction more than another
|
||||
/// or is degenerate, where a stroke of any one width would cover more pixels across some edges
|
||||
/// than across others.
|
||||
fn seam_unit(img_xf: vectorcraft_geom::Affine, xf: vectorcraft_geom::Affine) -> Option<f64> {
|
||||
let least = least_scale(xf);
|
||||
(scales_alike(img_xf) && least.is_finite() && least > 0.0).then_some(least)
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while
|
||||
/// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`,
|
||||
/// each stroke is replaced by a filled path, its outline in raster pixels ([`outline_seams`]),
|
||||
/// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as
|
||||
/// many anchors as the paths and the clip at most [`SEAM_CLIP_ANCHORS`], so a trace whose paths
|
||||
/// have more than half of `max` less four gets none. Outlines, which have more anchors, are
|
||||
/// counted as each is made, and none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes'
|
||||
/// anchors would not fit, or once those made so far no longer fit. [`EngineError::Cancelled`]
|
||||
/// once `steps` answers `false`.
|
||||
fn seams_within(
|
||||
res: &tr::TraceResult,
|
||||
params: &tr::TraceParams,
|
||||
size: (u32, u32),
|
||||
max: usize,
|
||||
outlined: bool,
|
||||
steps: &(dyn Fn(u64, u64) -> bool + Sync),
|
||||
) -> Result<Option<tr::SeamFills>> {
|
||||
if res.anchor_count().saturating_mul(2).saturating_add(SEAM_CLIP_ANCHORS) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(mut seams) = tr::seam_fills(&res.paths, params, size) else { return Ok(None) };
|
||||
if outlined {
|
||||
let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::<usize>();
|
||||
let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(SEAM_CLIP_ANCHORS);
|
||||
if res.anchor_count().saturating_add(estimate) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
let budget = max.saturating_sub(res.anchor_count()).saturating_sub(SEAM_CLIP_ANCHORS);
|
||||
if !outline_seams(&mut seams.strokes, budget, steps)? {
|
||||
return Ok(None);
|
||||
}
|
||||
seams.strokes.retain(|tp| !tp.path.is_empty());
|
||||
if seams.strokes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(Some(seams))
|
||||
}
|
||||
|
||||
/// The most anchors the seam fills' clip has: the image's box cut to the box of the traced paths
|
||||
/// ([`within_box`]), four corners and at most four more where the image is turned.
|
||||
const SEAM_CLIP_ANCHORS: usize = 8;
|
||||
|
||||
/// How many seam strokes [`outline_seams`] outlines between asking whether to go on.
|
||||
const SEAM_OUTLINE_STEP: usize = 64;
|
||||
|
||||
/// Outline each of `strokes` ([`outlined_seam`]) while the outlines' anchors stay within `budget`,
|
||||
/// asking `steps` every [`SEAM_OUTLINE_STEP`] strokes whether to go on → whether every outline
|
||||
/// fits (it stops at the first that does not), or [`EngineError::Cancelled`] once `steps`
|
||||
/// answers `false`.
|
||||
fn outline_seams(strokes: &mut [tr::TracedPath], budget: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<bool> {
|
||||
let mut total = 0usize;
|
||||
for (i, tp) in strokes.iter_mut().enumerate() {
|
||||
if i % SEAM_OUTLINE_STEP == 0 && !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
outlined_seam(tp);
|
||||
total = total.saturating_add(tp.path.anchor_count());
|
||||
if total > budget {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// About how many anchors a seam stroke's outline ([`outlined_seam`]) has for each anchor of the
|
||||
/// stroke: both sides of each segment and a round join at each anchor. Curves can take more.
|
||||
const SEAM_OUTLINE_ANCHORS: usize = 6;
|
||||
|
||||
/// Replace a seam stroke `tp` by the area it covers, as a filled path in the same raster pixels:
|
||||
/// butt caps and round joins, as the strokes have.
|
||||
fn outlined_seam(tp: &mut tr::TracedPath) {
|
||||
if let Some(width) = tp.stroke.take() {
|
||||
tp.path = vectorcraft_pathops::outline_stroke(&tp.path, width, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Round, 4.0);
|
||||
}
|
||||
tr::seam_fills(&res.paths, params)
|
||||
}
|
||||
|
||||
/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`]
|
||||
@@ -780,19 +903,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
warnings.extend(trace_warnings((img.width, img.height), raster, res.worked_at));
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.0.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / raster.1.max(1) as f64;
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
let xf = raster_xf(&img, raster);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
// Seam fills: document units per raster pixel along the direction the image is stretched most,
|
||||
// so that a stroke covers its pixels across an edge at any angle.
|
||||
let seam_unit = {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
|
||||
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
};
|
||||
// Seam fills: strokes when the image is scaled alike in every direction; on an image stretched
|
||||
// more one way, the trace outlined them in raster pixels ([`seams_within`]).
|
||||
let seam_unit = seam_unit(img.xf, xf);
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
// A library color fills with the swatch's displayed color (its model kept), unlinked.
|
||||
@@ -824,29 +940,41 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
|
||||
};
|
||||
// Abutting: the seam fills, in a group of their own under every path.
|
||||
let seams: Vec<Arc<Node>> = seam_fills
|
||||
// Abutting: the seam fills, in a clip group of their own under every path, clipped to the
|
||||
// image's box within the traced paths' box: strokes, or on an image stretched more one
|
||||
// way, their outlines filled.
|
||||
let strokes: Vec<Arc<Node>> = seam_fills
|
||||
.iter()
|
||||
.flat_map(|f| &f.strokes)
|
||||
.filter_map(|tp| {
|
||||
let width = tp.stroke?;
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * seam_unit)
|
||||
})],
|
||||
..Default::default()
|
||||
let outline = match (tp.stroke, seam_unit) {
|
||||
(Some(width), Some(u)) => {
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * u)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into();
|
||||
return Some(Arc::new(n));
|
||||
}
|
||||
// The trace leaves strokes only for an image scaled alike in every direction,
|
||||
// with these same inputs; a stroke is left out here rather than outlined
|
||||
// outside the anchor limit.
|
||||
(Some(_), None) => return None,
|
||||
(None, _) => tp.path.clone(),
|
||||
};
|
||||
if outline.is_empty() {
|
||||
return None;
|
||||
}
|
||||
.into();
|
||||
let mut n = shape_node(d, outline.transformed(xf), None);
|
||||
n.appearance = fill_only(paint_of(tp)).into();
|
||||
Some(Arc::new(n))
|
||||
})
|
||||
.collect();
|
||||
if !seams.is_empty() {
|
||||
let mut g = Node::group(d.alloc_id(), seams);
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let paint = paint_of(&tp);
|
||||
@@ -873,6 +1001,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
};
|
||||
traced.push(n);
|
||||
}
|
||||
// The seam fills' clip is the image's box cut to the box of the traced paths, so the group
|
||||
// stays within the box the paths measure.
|
||||
let art = traced.iter().filter_map(Node::geometric_bounds).reduce(|a, b| a.union(b));
|
||||
if let (Some(f), Some(art)) = (seam_fills.as_ref().filter(|_| !strokes.is_empty()), art) {
|
||||
let corners: Vec<Point> = f.clip.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| xf * a.p)).collect();
|
||||
let inside = within_box(&corners, art);
|
||||
if inside.len() >= 3 {
|
||||
let mut clip = shape_node(d, vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&inside, true)), None);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let members = std::iter::once(Arc::new(clip)).chain(strokes).collect();
|
||||
let mut g = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
}
|
||||
children.extend(grouped(d, traced, &res.parents));
|
||||
if group_by_color {
|
||||
children = color_groups(c, d, children)?;
|
||||
@@ -894,6 +1039,28 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
Ok(json!({ "id": id.0, "paths": npaths, "anchors": anchors, "colors": colors, "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// The part of the convex polygon `poly` inside `r`, as a polygon with at most four more corners
|
||||
/// than `poly` (each side of `r` cuts at most one corner off and adds two); empty when none of it
|
||||
/// is inside.
|
||||
fn within_box(poly: &[Point], r: Rect) -> Vec<Point> {
|
||||
let sides: [&dyn Fn(Point) -> f64; 4] = [&|p| p.x - r.x0, &|p| r.x1 - p.x, &|p| p.y - r.y0, &|p| r.y1 - p.y];
|
||||
let mut out = poly.to_vec();
|
||||
for side in sides {
|
||||
let corners = std::mem::take(&mut out);
|
||||
for (k, &p) in corners.iter().enumerate() {
|
||||
let Some(&q) = corners.get((k + 1) % corners.len()) else { continue };
|
||||
let (dp, dq) = (side(p), side(q));
|
||||
if dp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (dp > 0.0 && dq < 0.0) || (dp < 0.0 && dq > 0.0) {
|
||||
out.push(p + (q - p) * (dp / (dp - dq)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Images larger than this on a side are traced, but more slowly: the trace says so.
|
||||
pub const LARGE_TRACE_SIDE: u32 = 1500;
|
||||
|
||||
@@ -1193,7 +1360,7 @@ mod color_group_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings};
|
||||
use super::{MAX_TRACE_ANCHORS, SEAM_CLIP_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
#[test]
|
||||
@@ -1206,13 +1373,89 @@ mod trace_limit_tests {
|
||||
});
|
||||
let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let all = tr::seam_fills(&res.paths, ¶ms);
|
||||
assert!(!all.is_empty(), "{res:?}");
|
||||
let all = tr::seam_fills(&res.paths, ¶ms, (24, 16));
|
||||
assert!(all.is_some(), "{res:?}");
|
||||
let anchors = res.anchor_count();
|
||||
// Twice the paths' anchors leaves room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all);
|
||||
assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + SEAM_CLIP_ANCHORS);
|
||||
let go = |_: u64, _: u64| true;
|
||||
// Twice the paths' anchors and the clip's eight at most leave room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS, false, &go).unwrap(), all);
|
||||
// One anchor short of that: none.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []);
|
||||
assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS - 1, false, &go).unwrap(), None);
|
||||
// Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes'
|
||||
// anchors each.
|
||||
let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::<usize>();
|
||||
let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap();
|
||||
assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}");
|
||||
let n = strokes(all.as_ref().unwrap());
|
||||
assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined));
|
||||
// A staircase edge: the outline's round joins give it more anchors than the paths have. The
|
||||
// outlines are made only when SEAM_OUTLINE_ANCHORS times the strokes' anchors fit.
|
||||
let img = tr::Raster::from_fn(32, 32, |x, y| if x < y / 4 * 4 + 4 { [200, 40, 50, 255] } else { [30, 90, 200, 255] });
|
||||
let params = tr::TraceParams { corners: 100.0, ..params };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let anchors = res.anchor_count();
|
||||
let all = tr::seam_fills(&res.paths, ¶ms, (32, 32)).unwrap();
|
||||
let n = strokes(&all);
|
||||
let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap();
|
||||
assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined));
|
||||
assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined));
|
||||
let fits = anchors + SEAM_OUTLINE_ANCHORS * n + SEAM_CLIP_ANCHORS;
|
||||
assert!(fits > 2 * anchors + SEAM_CLIP_ANCHORS, "{fits}, {anchors} in the paths");
|
||||
assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true, &go).unwrap(), Some(outlined.clone()));
|
||||
assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true, &go).unwrap(), None);
|
||||
assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false, &go).unwrap(), Some(all.clone()));
|
||||
// The outlines are counted as each is made: they stop at the first one past the budget, so
|
||||
// outlines with more anchors than the estimate allows are refused too.
|
||||
let need = strokes(&outlined);
|
||||
assert!(outline_seams(&mut all.strokes.clone(), need, &go).unwrap());
|
||||
assert!(!outline_seams(&mut all.strokes.clone(), need - 1, &go).unwrap());
|
||||
// Canceled while outlining: the run stops.
|
||||
let stop = |_: u64, _: u64| false;
|
||||
assert!(matches!(seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &stop), Err(super::EngineError::Cancelled)));
|
||||
assert!(matches!(outline_seams(&mut all.strokes.clone(), need, &stop), Err(super::EngineError::Cancelled)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn within_box_cuts_a_turned_box_to_a_box() {
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
// A square turned by 45° in a smaller box: each side cuts a corner off, 8 corners.
|
||||
let diamond = [Point::new(0.0, -10.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0), Point::new(-10.0, 0.0)];
|
||||
let cut = super::within_box(&diamond, Rect::new(-6.0, -6.0, 6.0, 6.0));
|
||||
assert_eq!(cut.len(), 8, "{cut:?}");
|
||||
assert!(cut.iter().all(|p| p.x.abs() <= 6.0 + 1e-12 && p.y.abs() <= 6.0 + 1e-12 && p.x.abs() + p.y.abs() <= 10.0 + 1e-12), "{cut:?}");
|
||||
// A corner on a side is kept once.
|
||||
let square = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0), Point::new(0.0, 4.0)];
|
||||
assert_eq!(super::within_box(&square, Rect::new(0.0, 0.0, 4.0, 4.0)), square.to_vec());
|
||||
assert_eq!(super::within_box(&square, Rect::new(1.0, 0.0, 4.0, 4.0)).len(), 4);
|
||||
assert!(super::within_box(&square, Rect::new(5.0, 5.0, 6.0, 6.0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() {
|
||||
use super::seam_unit;
|
||||
use vectorcraft_geom::Affine;
|
||||
assert_eq!(seam_unit(Affine::scale(2.0), Affine::scale(2.0)), Some(2.0));
|
||||
assert_eq!(seam_unit(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0]), Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0])), Some(2.0));
|
||||
// Turned and scaled alike at any angle, rounding included.
|
||||
for k in [0.5, 1.0, 3.0, 17.0] {
|
||||
for i in 0..2000 {
|
||||
let xf = Affine::rotate(f64::from(i) * std::f64::consts::TAU / 2000.0) * Affine::scale(k);
|
||||
let unit = seam_unit(xf, xf);
|
||||
assert!(unit.is_some_and(|u| (u - k).abs() < 1e-9 * k), "{unit:?} at step {i}, scale {k}");
|
||||
}
|
||||
}
|
||||
let xf = Affine::rotate(0.0496) * Affine::scale(0.5);
|
||||
assert!(seam_unit(xf, xf).is_some());
|
||||
// A raster decoded scaled down to fit (10000 × 7000 pixels as 9791 × 6853) of an image placed
|
||||
// at 2×: strokes, at the smaller scale.
|
||||
let (sx, sy) = (10000.0 / 9791.0, 7000.0 / 6853.0);
|
||||
let unit = seam_unit(Affine::scale(2.0), Affine::scale(2.0) * Affine::scale_non_uniform(sx, sy)).unwrap();
|
||||
assert!((unit - 2.0 * f64::min(sx, sy)).abs() < 1e-12, "{unit}");
|
||||
assert_eq!(seam_unit(Affine::scale_non_uniform(20.0, 1.0), Affine::scale_non_uniform(20.0, 1.0)), None);
|
||||
assert_eq!(seam_unit(Affine::skew(0.5, 0.0), Affine::skew(0.5, 0.0)), None);
|
||||
assert_eq!(seam_unit(Affine::scale_non_uniform(1.0, 0.0), Affine::scale_non_uniform(1.0, 0.0)), None);
|
||||
assert_eq!(seam_unit(Affine::scale(0.0), Affine::scale(0.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Invert Colors",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
|
||||
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
|
||||
has_selection,
|
||||
|s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert)
|
||||
),
|
||||
@@ -533,7 +533,7 @@ pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor:
|
||||
let n = recolor(d)?;
|
||||
if let Some(before) = before.filter(|_| n > 0) {
|
||||
super::appearance::capture_series_changes(&before, d, &marks);
|
||||
super::graph::capture_label_changes(&before, d, &labels, true);
|
||||
super::graph::capture_label_changes(&before, d, &labels, true, Some(roots));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
@@ -803,8 +803,8 @@ fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Col
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and
|
||||
/// labels take each time it is drawn again.
|
||||
/// `f` applied to the series paints, the label styles and the line rows that graph `g` keeps, which
|
||||
/// its marks, labels and lines take each time it is drawn again.
|
||||
fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for p in g.series_paints.iter_mut() {
|
||||
for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() {
|
||||
@@ -823,7 +823,10 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color
|
||||
}
|
||||
map_paint_colors(&mut st.stroke, f);
|
||||
}
|
||||
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() {
|
||||
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows, &mut styles.axis_rows, &mut styles.ring_rows]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
for paint in [&mut r.paint.fill, &mut r.paint.stroke].into_iter().flatten() {
|
||||
map_paint_colors(paint, f);
|
||||
}
|
||||
|
||||
@@ -881,7 +881,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
|
||||
/// filled with the current fill unless that is None or white (black then), in the document's
|
||||
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
|
||||
/// #7975), in the document's
|
||||
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
|
||||
let mut style = CharStyle::default();
|
||||
@@ -899,8 +900,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
|
||||
}
|
||||
style.fill = match p.get("color").and_then(color_value) {
|
||||
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
|
||||
None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(),
|
||||
None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK),
|
||||
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
|
||||
};
|
||||
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
|
||||
// for the default. Type already in a document keeps its own.
|
||||
|
||||
@@ -857,14 +857,12 @@ mod tests {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute(
|
||||
"paint.setFill",
|
||||
&json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
|
||||
// New type starts black (#7975); filled with the gradient, its characters make it a gradient object too.
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient, "ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// The type's characters take the current gradient fill, so it is a gradient object too.
|
||||
assert_eq!(
|
||||
(i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()),
|
||||
(Some(1), Some(1), Some(2))
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Knife",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the cut)} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}",
|
||||
has_doc,
|
||||
knife
|
||||
),
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Path Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
has_selection,
|
||||
erase_segments
|
||||
),
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
|
||||
has_selection,
|
||||
smooth_region
|
||||
),
|
||||
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Join",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
|
||||
has_doc,
|
||||
join_scrub
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -28,6 +28,27 @@ pub(super) struct Sample {
|
||||
/// x and y.
|
||||
const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"];
|
||||
|
||||
/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation
|
||||
/// 0..360 degrees (360 is the same direction as 0).
|
||||
const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)];
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size, in points.
|
||||
pub(super) const SIZES: (f64, f64) = (0.1, 1000.0);
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size Variation, in points.
|
||||
pub(super) const SIZE_VARIATIONS: (f64, f64) = (0.0, 1000.0);
|
||||
|
||||
/// `v`, or an error naming `key` when it is outside `lo..=hi` (or not a number at all, NaN).
|
||||
fn within(v: f64, key: &str, (lo, hi): (f64, f64), cmd: &str) -> Result<f64> {
|
||||
if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
}
|
||||
|
||||
/// The number `p` gives for `key`, `default` when it leaves it out or gives null, as [`number_or`]
|
||||
/// reads it, or an error naming `key` when the number is outside `range`.
|
||||
pub(super) fn ranged(p: &Value, key: &str, default: f64, range: (f64, f64), cmd: &str) -> Result<f64> {
|
||||
within(number_or(p, key, default, cmd)?, key, range, cmd)
|
||||
}
|
||||
|
||||
/// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite
|
||||
/// number.
|
||||
pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
@@ -42,27 +63,36 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
/// [`points_param`] with what a pen read at each point, as far as it is given:
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure
|
||||
/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in
|
||||
/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is
|
||||
/// neither a number nor null, is an error.
|
||||
/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or
|
||||
/// rotation is neither a number nor null or is outside its range, or an array of more than six
|
||||
/// numbers, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sample>> {
|
||||
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
|
||||
let pts: Vec<Sample> = a
|
||||
.iter()
|
||||
.map(|v| {
|
||||
.enumerate()
|
||||
.map(|(at, v)| {
|
||||
const MAX_ITEMS: usize = 2 + PEN_KEYS.len();
|
||||
if let Value::Array(xy) = v
|
||||
&& xy.len() > MAX_ITEMS
|
||||
{
|
||||
let key = format!("{key}[{at}]");
|
||||
return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries")));
|
||||
}
|
||||
let mut pen = [None; 4];
|
||||
for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() {
|
||||
for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() {
|
||||
let given = match v {
|
||||
Value::Array(xy) => xy.get(i + 2),
|
||||
_ => v.get(*key),
|
||||
};
|
||||
*slot = match given {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(n @ Value::Number(_)) => n.as_f64(),
|
||||
Some(n @ Value::Number(_)) => n.as_f64().map(|x| within(x, key, range, cmd)).transpose()?,
|
||||
Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
};
|
||||
}
|
||||
let [pressure, tx, ty, rotation] = pen;
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0)));
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0)));
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation })
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
@@ -186,18 +216,14 @@ impl PenRecord {
|
||||
}
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with
|
||||
/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for
|
||||
/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size.
|
||||
/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None`
|
||||
/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the
|
||||
/// size. A `sizeVariation` outside its range is an error with Fixed too.
|
||||
pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?;
|
||||
match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) {
|
||||
None | Some(Ok("fixed")) => Ok(None),
|
||||
Some(Ok("pressure")) => {
|
||||
let variation = number_or(p, "sizeVariation", 0.0, cmd)?;
|
||||
if !(variation.is_finite() && variation >= 0.0) {
|
||||
return Err(bad(cmd, "sizeVariation must be 0 or more"));
|
||||
}
|
||||
Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation)))
|
||||
}
|
||||
Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))),
|
||||
Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))),
|
||||
Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))),
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::common::{
|
||||
PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces,
|
||||
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds,
|
||||
pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
|
||||
@@ -293,10 +293,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return erase_rect(s, marquee_param(rect, C)?);
|
||||
}
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let vary = eraser_variations(p, C)?;
|
||||
@@ -401,12 +398,13 @@ const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bea
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how
|
||||
/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null
|
||||
/// is 0; any other mode, or a variation that is negative or past its most, is refused.
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points, at most 1000), its
|
||||
/// mode and how far it varies either way. A mode left out or null is Fixed, and a variation left
|
||||
/// out or null is 0; any other mode, or a variation that is negative or past its most, is refused,
|
||||
/// in every mode.
|
||||
fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
const KEYS: [(&str, &str, f64); 3] =
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)];
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", SIZE_VARIATIONS.1)];
|
||||
let mut out = [(Variation::Fixed, 0.0); 3];
|
||||
for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) {
|
||||
let mode = match p.get(mode_key).filter(|v| !v.is_null()) {
|
||||
@@ -419,7 +417,11 @@ fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
return Err(bad(cmd, format!("{var_key} must be 0 or more")));
|
||||
}
|
||||
if variation > most {
|
||||
return Err(bad(cmd, format!("{var_key} must be at most {most}")));
|
||||
// Size Variation is refused as path.blob refuses it.
|
||||
return Err(match var_key {
|
||||
"sizeVariation" => bad(cmd, format!("`{var_key}` must be from {} to {most}", SIZE_VARIATIONS.0)),
|
||||
_ => bad(cmd, format!("{var_key} must be at most {most}")),
|
||||
});
|
||||
}
|
||||
*slot = (mode, variation);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::common::{
|
||||
PenRecord, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint,
|
||||
subpath_len, target_paths, within_input_bound,
|
||||
PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure,
|
||||
stroke_paint, subpath_len, target_paths, within_input_bound,
|
||||
};
|
||||
use super::{
|
||||
Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
@@ -486,10 +486,7 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec
|
||||
pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.blob";
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !angle.is_finite() || !roundness.is_finite() {
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
|
||||
@@ -268,6 +268,8 @@ struct RasterOptions {
|
||||
/// PSD: Write Layers.
|
||||
layers: Option<bool>,
|
||||
max_editability: Option<bool>,
|
||||
/// PSD: Preserve Text Editability (with layers).
|
||||
preserve_text: Option<bool>,
|
||||
hidden_layers: Option<bool>,
|
||||
/// Appearance of Black › Printing / Exporting (`prefs.blackOutput`); agents can set it here too.
|
||||
rich_black: Option<bool>,
|
||||
@@ -350,6 +352,7 @@ impl RasterOptions {
|
||||
color_model,
|
||||
layers: self.layers.unwrap_or(true),
|
||||
max_editability: self.max_editability.unwrap_or(false),
|
||||
preserve_text: self.preserve_text.unwrap_or(false),
|
||||
hidden_layers: self.hidden_layers.unwrap_or(false),
|
||||
embed_icc,
|
||||
},
|
||||
@@ -374,6 +377,7 @@ fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> {
|
||||
let r = match format {
|
||||
RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()),
|
||||
RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()),
|
||||
RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()),
|
||||
RasterFormat::Bmp => o.bmp.check(),
|
||||
RasterFormat::Tga => o.tga.check(),
|
||||
_ => Ok(()),
|
||||
|
||||
@@ -318,6 +318,13 @@ const MAX_EDITABILITY: FormatOption = FormatOption {
|
||||
description: "with layers: layers and sublayers become groups and every object a layer of its own, named as the Layers panel names it (text by its text); clipping, masked or knockout layers stay one layer",
|
||||
};
|
||||
|
||||
const PRESERVE_TEXT: FormatOption = FormatOption {
|
||||
name: "preserveText",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers (with their pixels); a layer holding such type becomes a group of its type layers and pixel layers of the art between them, unless other art in it blends in a mode other than normal; refused with layers: false",
|
||||
};
|
||||
|
||||
const PSD_HIDDEN_LAYERS: FormatOption = FormatOption {
|
||||
name: "hiddenLayers",
|
||||
ty: "boolean",
|
||||
@@ -339,6 +346,7 @@ const PSD_OPTIONS: &[FormatOption] = &[
|
||||
ANTI_ALIAS,
|
||||
COLOR_MODEL,
|
||||
PSD_LAYERS,
|
||||
PRESERVE_TEXT,
|
||||
MAX_EDITABILITY,
|
||||
PSD_HIDDEN_LAYERS,
|
||||
EMBED_ICC,
|
||||
|
||||
@@ -69,6 +69,23 @@ fn psd_writes_layers_groups_and_text_named_after_it() {
|
||||
assert!(s.execute("document.export", &json!({"format": "psd", "colorModel": "lab"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserve_text_writes_point_type_as_type_layers_and_needs_layers() {
|
||||
let mut s = session();
|
||||
let file = export(&mut s, json!({"preserveText": true}));
|
||||
let (_, count, names) = layers(&file);
|
||||
assert_eq!((count, names), (-4, vec!["Layer 1".into(), "</Layer group>".into(), "Hello".into(), "Words".into()]), "Words becomes a group");
|
||||
assert_eq!(file.windows(8).filter(|w| w == b"8BIMTySh").count(), 1, "one type layer");
|
||||
assert_eq!(export(&mut s, json!({"preserveText": false})), export(&mut s, json!({})));
|
||||
// Without layers there are no type layers to write.
|
||||
let err = s.execute("document.export", &json!({"format": "psd", "layers": false, "preserveText": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("preserveText") && err.contains("layers: true"), "{err}");
|
||||
assert!(s.execute("document.export", &json!({"format": "psd", "preserveText": "yes"})).is_err());
|
||||
// Other formats don't take it.
|
||||
let r = s.execute("document.export", &json!({"format": "png", "preserveText": true})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("preserveText"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() {
|
||||
let mut s = Session::new();
|
||||
@@ -79,7 +96,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() {
|
||||
(psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()),
|
||||
(Some("PSD"), Some(true), Some(true), Some(true))
|
||||
);
|
||||
for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] {
|
||||
for k in ["colorModel", "layers", "preserveText", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] {
|
||||
assert!(psd["options"].get(k).is_some(), "psd takes {k}");
|
||||
}
|
||||
let r = s.execute("document.export", &json!({"format": "psd", "useArtboards": true})).unwrap();
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Vector",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
|
||||
@@ -48,9 +48,11 @@ use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades,
|
||||
is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity,
|
||||
capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes,
|
||||
capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows,
|
||||
capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art,
|
||||
is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
};
|
||||
|
||||
|
||||
@@ -543,7 +543,7 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
for v in tick_values(lo, hi, step).into_iter().skip(1) {
|
||||
let ring: Vec<Point> = (0..ncat).map(|c| at(c, v)).collect();
|
||||
axes.push(self.b.path(polyline(&ring, true), Paint::None, Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25));
|
||||
axes.push(self.b.ring(polyline(&ring, true)));
|
||||
}
|
||||
let ax = self.b.group("Axes", axes);
|
||||
self.b.out.push(ax);
|
||||
|
||||
@@ -82,9 +82,49 @@ fn kept_rows(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vecto
|
||||
}
|
||||
}
|
||||
|
||||
/// Give label `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their kept order and
|
||||
/// place relative to the characters, and the object opacity and blend mode. An opacity read from a file is held to 0..1
|
||||
/// and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt).
|
||||
/// What a graph line is, for the rows it keeps: an axis line or tick mark, or a ring of a radar graph.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(crate) enum Line {
|
||||
Axis,
|
||||
Ring,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// The stroke and weight the graph draws lines of this kind with when they keep no rows. They have no fill.
|
||||
fn default_stroke(self) -> (Paint, f64) {
|
||||
match self {
|
||||
Line::Axis => (Paint::solid(Color::BLACK), 0.5),
|
||||
Line::Ring => (Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows ([`super::series::label_rows`]) a line of this kind shows as the graph draws it with no kept rows.
|
||||
pub(super) fn default_rows(self) -> vectorcraft_doc::LabelRows {
|
||||
let (stroke, width) = self.default_stroke();
|
||||
let paint = vectorcraft_doc::SeriesPaint { fill: Some(Paint::None), stroke: Some(stroke), stroke_width: Some(width), ..Default::default() };
|
||||
vectorcraft_doc::LabelRows { paint, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows lines of kind `line` keep, if any.
|
||||
pub(super) fn kept_line_rows(styles: &vectorcraft_doc::LabelStyles, line: Line) -> Option<&vectorcraft_doc::LabelRows> {
|
||||
match line {
|
||||
Line::Axis => styles.axis_rows.as_ref(),
|
||||
Line::Ring => styles.ring_rows.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot of `styles` that holds the rows lines of kind `line` keep.
|
||||
pub(super) fn line_slot(styles: &mut vectorcraft_doc::LabelStyles, line: Line) -> &mut Option<vectorcraft_doc::LabelRows> {
|
||||
match line {
|
||||
Line::Axis => &mut styles.axis_rows,
|
||||
Line::Ring => &mut styles.ring_rows,
|
||||
}
|
||||
}
|
||||
|
||||
/// Give label or graph line `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their
|
||||
/// kept order and place relative to the contents, and the object opacity and blend mode. An opacity read from a file is
|
||||
/// held to 0..1 and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt).
|
||||
fn apply_label_rows(n: &mut Node, kept: &vectorcraft_doc::LabelRows) {
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, StrokeLayer};
|
||||
let rows = &kept.paint;
|
||||
@@ -124,7 +164,20 @@ impl Gen<'_> {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(a);
|
||||
bp.line_to(b);
|
||||
self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5)
|
||||
self.kept_line(Line::Axis, PathData::from_bezpath(&bp))
|
||||
}
|
||||
/// A ring of a radar graph through `pd`.
|
||||
pub(super) fn ring(&mut self, pd: PathData) -> Arc<Node> {
|
||||
self.kept_line(Line::Ring, pd)
|
||||
}
|
||||
/// A graph line of kind `line` through `pd`, with the rows lines of its kind keep, else its default stroke.
|
||||
fn kept_line(&mut self, line: Line, pd: PathData) -> Arc<Node> {
|
||||
let (stroke, width) = line.default_stroke();
|
||||
let mut n = Node::path(self.d.alloc_id(), pd, Appearance::basic(Paint::None, stroke, width));
|
||||
if let Some(rows) = kept_line_rows(self.styles, line) {
|
||||
apply_label_rows(&mut n, rows);
|
||||
}
|
||||
Arc::new(n)
|
||||
}
|
||||
pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc<Node> {
|
||||
let t = self.text_object(role, at, s, justify);
|
||||
|
||||
@@ -4,7 +4,7 @@ use vectorcraft_geom::Shape;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
use super::generate::is_dark;
|
||||
use super::labels::{Role, filled_lines_on, label_para, label_size, label_style};
|
||||
use super::labels::{Line, Role, filled_lines_on, kept_line_rows, label_para, label_size, label_style, line_slot};
|
||||
use super::{
|
||||
Affine, Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad,
|
||||
refresh_bounds,
|
||||
@@ -155,13 +155,32 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series
|
||||
/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other
|
||||
/// ids and the art of a graph design pass through, and the order of `ids` is kept.
|
||||
/// group: the graph draws its series groups again with no rows of their own. A graph's Axes group is replaced by the
|
||||
/// lines and labels directly inside it, and its Legend group by the labels directly inside it, which the graph keeps
|
||||
/// rows for ([`capture_label_rows`]). A group with no such member, other ids and the art of a graph design pass
|
||||
/// through, and the order of `ids` is kept.
|
||||
pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
series_group_marks_where(doc, ids, |_| true)
|
||||
}
|
||||
|
||||
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
|
||||
/// The lines and labels directly in `n` when it is the Axes group of a graph, or the labels directly in it when it is
|
||||
/// the graph's Legend group, in paint order. `None` for any other object.
|
||||
pub(crate) fn graph_part_members(doc: &Document, n: &Node) -> Option<Vec<NodeId>> {
|
||||
if !matches!(n.kind, NodeKind::Group { .. }) || n.extras().series_index.is_some() {
|
||||
return None;
|
||||
}
|
||||
let axes = match n.name.as_deref() {
|
||||
Some("Axes") => true,
|
||||
Some("Legend") => false,
|
||||
_ => return None,
|
||||
};
|
||||
let spec = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref())?;
|
||||
let member = |c: &Node| matches!(c.kind, NodeKind::Text(_)) || (axes && line_in(spec, n, c).is_some());
|
||||
Some(n.children().into_iter().flatten().filter(|c| member(c)).map(|c| c.id).collect())
|
||||
}
|
||||
|
||||
/// [`series_group_marks`] for the series groups, Axes groups and Legend groups `stands` accepts; the others pass
|
||||
/// through.
|
||||
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
@@ -172,6 +191,10 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
|
||||
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
|
||||
}
|
||||
Some(part) if stands(part) => match graph_part_members(doc, part) {
|
||||
Some(members) if !members.is_empty() => out.extend(members),
|
||||
_ => out.push(*id),
|
||||
},
|
||||
_ => out.push(*id),
|
||||
}
|
||||
}
|
||||
@@ -1185,21 +1208,34 @@ pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], metho
|
||||
/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels
|
||||
/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or
|
||||
/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so
|
||||
/// they undo together. Returns whether a kept style changed.
|
||||
/// they undo together. A kind that keeps no style and that `change` leaves at the default style keeps none, unless
|
||||
/// `change` sets the legend fill. Returns whether a kept style changed.
|
||||
pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, role) in label_kinds(doc, ids) {
|
||||
changed |= store_label_style(doc, graph, role, change);
|
||||
changed |= store_label_style(doc, graph, role, change, true);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// [`capture_label_styles`], except that a kind that keeps no style keeps the default style when `change` leaves it
|
||||
/// unchanged, for a command that gives character attributes (a size equal to the labels' own, for example).
|
||||
pub(crate) fn capture_label_styles_given(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, role) in label_kinds(doc, ids) {
|
||||
changed |= store_label_style(doc, graph, role, change, false);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that
|
||||
/// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether
|
||||
/// the kept style or that mark changed.
|
||||
fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
/// the kept style or that mark changed. With `unless_default`, a kind that keeps no style and that `change` leaves at
|
||||
/// the default style keeps none, unless `change` sets the legend fill.
|
||||
fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle), unless_default: bool) -> bool {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false };
|
||||
let mut style = label_style(&spec.label_styles, role);
|
||||
let was = label_style(&spec.label_styles, role);
|
||||
let mut style = was.clone();
|
||||
// The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one
|
||||
// of two different fills something else.
|
||||
let sets_fill = role == Role::Legend
|
||||
@@ -1215,6 +1251,9 @@ fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn
|
||||
Role::Category => &mut styles.categories,
|
||||
Role::Legend => &mut styles.legend,
|
||||
};
|
||||
if unless_default && slot.is_none() && style == was && !(sets_fill && !styles.legend_fill_set) {
|
||||
return false;
|
||||
}
|
||||
let mut changed = slot.as_ref() != Some(&style);
|
||||
*slot = Some(style);
|
||||
if sets_fill && !styles.legend_fill_set {
|
||||
@@ -1277,37 +1316,356 @@ pub(crate) fn label_rows(n: &Node) -> Option<vectorcraft_doc::LabelRows> {
|
||||
(rows != vectorcraft_doc::LabelRows::default()).then_some(rows)
|
||||
}
|
||||
|
||||
/// The graph and kind of graph line `id`: a path directly in a graph's Axes group. Looked up through its parents, with no
|
||||
/// pass over the document.
|
||||
fn graph_line(doc: &Document, id: NodeId) -> Option<(NodeId, Line)> {
|
||||
let line = doc.node(id)?;
|
||||
if !matches!(line.kind, NodeKind::Path { .. }) {
|
||||
return None;
|
||||
}
|
||||
let path = doc.ancestry(id)?;
|
||||
let [.., graph, axes, _] = path.as_slice() else { return None };
|
||||
let spec = doc.node(*graph)?.extras().graph.as_deref()?;
|
||||
Some((*graph, line_in(spec, doc.node(*axes)?, line)?))
|
||||
}
|
||||
|
||||
/// The kind of graph line `line` is when `axes` is the Axes group of a graph drawn from `spec` and `line` a path directly
|
||||
/// in it. A radar graph's rings are its closed paths; its spokes, open, are axis lines.
|
||||
fn line_in(spec: &GraphSpec, axes: &Node, line: &Node) -> Option<Line> {
|
||||
if axes.name.as_deref() != Some("Axes") || axes.extras().series_index.is_some() || !matches!(axes.kind, NodeKind::Group { .. }) {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::Path { path, .. } = &line.kind else { return None };
|
||||
Some(if spec.kind == GraphKind::Radar && path.is_closed() { Line::Ring } else { Line::Axis })
|
||||
}
|
||||
|
||||
/// The graph lines among `ids`, each with its graph and kind, from the back to the front and each once: a later line's
|
||||
/// capture replaces an earlier one's, so the frontmost line of a kind sets what the kind keeps.
|
||||
fn lines_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, NodeId, Line)> {
|
||||
let mut out: Vec<(NodeId, NodeId, Line)> = ids.iter().filter_map(|id| graph_line(doc, *id).map(|(g, line)| (*id, g, line))).collect();
|
||||
out.sort_by_cached_key(|(id, ..)| doc.index_path(*id));
|
||||
out.dedup_by_key(|(id, ..)| *id);
|
||||
out
|
||||
}
|
||||
|
||||
/// Which of the object rows ([`label_rows`]) a graph label or line shows its kind keeps after an edit.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Keep {
|
||||
/// All of them.
|
||||
All,
|
||||
/// Only the object opacity and blend mode; the fill and stroke rows stay as the kind keeps them.
|
||||
Object,
|
||||
/// The fill and stroke rows; the object opacity and blend mode stay as the kind keeps them.
|
||||
Rows,
|
||||
/// The fill row with `fill`, the stroke row with `stroke`, and the object opacity and blend mode with `object`; the
|
||||
/// others stay as the kind keeps them. Each row keeps its place relative to the characters; a row taken from the
|
||||
/// label or line paints above a kept row on the same side of them, unless the label or line shows it below its own row
|
||||
/// of that kind.
|
||||
Kinds { fill: bool, stroke: bool, object: bool },
|
||||
}
|
||||
|
||||
/// The kinds (true: fill) of the rows in `rows` from the bottom up, each with whether it paints below the characters.
|
||||
fn row_places(rows: &vectorcraft_doc::LabelRows) -> Vec<(bool, bool)> {
|
||||
let order = if rows.stroke_under { [false, true] } else { [true, false] };
|
||||
let has = |fill: bool| if fill { rows.paint.fill.is_some() } else { rows.paint.stroke.is_some() };
|
||||
let below = usize::from(rows.below.unwrap_or(0));
|
||||
order.into_iter().filter(|k| has(*k)).enumerate().map(|(i, k)| (k, i < below)).collect()
|
||||
}
|
||||
|
||||
/// Where the rows paint when the row of kind `taken` (true: fill) comes from `shown` and the row of the other kind from
|
||||
/// `kept`, each keeping its place relative to the characters: `below` and `stroke_under` of [`vectorcraft_doc::LabelRows`].
|
||||
fn merged_places(kept: &vectorcraft_doc::LabelRows, shown: &vectorcraft_doc::LabelRows, taken: bool) -> (Option<u8>, bool) {
|
||||
let in_shown = row_places(shown);
|
||||
let t = in_shown.iter().copied().find(|p| p.0 == taken);
|
||||
let o = row_places(kept).into_iter().find(|p| p.0 != taken);
|
||||
let order = match (t, o) {
|
||||
(Some(t), Some(o)) => {
|
||||
// Rows on different sides of the characters: the one below them is lower. On the same side: as the label or
|
||||
// line shows them, else the taken row on top.
|
||||
let at = |kind: bool| in_shown.iter().position(|p| p.0 == kind);
|
||||
let o_first = if t.1 != o.1 {
|
||||
o.1
|
||||
} else {
|
||||
match (at(!taken), at(taken)) {
|
||||
(Some(o_at), Some(t_at)) => o_at < t_at,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
if o_first { vec![o, t] } else { vec![t, o] }
|
||||
}
|
||||
(t, o) => t.into_iter().chain(o).collect(),
|
||||
};
|
||||
let below = order.iter().filter(|p| p.1).fold(0u8, |k, _| k + 1);
|
||||
((below > 0).then_some(below), order.len() == 2 && !order[0].0)
|
||||
}
|
||||
|
||||
/// `shown` with the parts of the rows `kept` keeps that `keep` leaves as they are.
|
||||
fn keep_rows(kept: vectorcraft_doc::LabelRows, shown: vectorcraft_doc::LabelRows, keep: Keep) -> vectorcraft_doc::LabelRows {
|
||||
match keep {
|
||||
Keep::All => shown,
|
||||
Keep::Object => {
|
||||
let mut kept = kept;
|
||||
(kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend);
|
||||
kept
|
||||
}
|
||||
Keep::Rows => {
|
||||
let mut shown = shown;
|
||||
(shown.paint.opacity, shown.paint.blend) = (kept.paint.opacity, kept.paint.blend);
|
||||
shown
|
||||
}
|
||||
Keep::Kinds { fill, stroke, object } => {
|
||||
let places = match (fill, stroke) {
|
||||
(true, true) => (shown.below, shown.stroke_under),
|
||||
(false, false) => (kept.below, kept.stroke_under),
|
||||
(taken, _) => merged_places(&kept, &shown, taken),
|
||||
};
|
||||
let mut rows = shown;
|
||||
(rows.below, rows.stroke_under) = places;
|
||||
let (r, k) = (&mut rows.paint, kept.paint);
|
||||
if !object {
|
||||
(r.opacity, r.blend) = (k.opacity, k.blend);
|
||||
}
|
||||
if !fill {
|
||||
(r.fill, r.fill_opacity, r.fill_blend, r.fill_unit_box) = (k.fill, k.fill_opacity, k.fill_blend, k.fill_unit_box);
|
||||
}
|
||||
if !stroke {
|
||||
(r.stroke, r.stroke_width, r.stroke_opacity, r.stroke_blend, r.stroke_unit_box) =
|
||||
(k.stroke, k.stroke_width, k.stroke_opacity, k.stroke_blend, k.stroke_unit_box);
|
||||
}
|
||||
rows
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), of which `keep` says what is
|
||||
/// taken from the line: `None` when that is how the graph draws them with no kept rows.
|
||||
fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, keep: Keep) -> Option<vectorcraft_doc::LabelRows> {
|
||||
let shown = label_rows(n).unwrap_or_default();
|
||||
let rows = keep_rows(slot.cloned().unwrap_or_else(|| line.default_rows()), shown, keep);
|
||||
(rows != line.default_rows()).then_some(rows)
|
||||
}
|
||||
|
||||
/// Keep the object rows ([`label_rows`]) of the graph lines among `ids` for every line of their kind (axis lines and tick
|
||||
/// marks, or a radar graph's rings), the part of them `keep` says, even when a line already showed them. Returns whether
|
||||
/// kept rows changed.
|
||||
fn store_line_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool {
|
||||
let mut changed = false;
|
||||
for (id, graph, line) in lines_of(doc, ids) {
|
||||
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { continue };
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, keep);
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = line_slot(&mut spec.label_styles, line);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep the object rows of graph lines `ids` for every line of their kind, as [`capture_label_rows`] keeps a label's,
|
||||
/// for an edit that wrote their fill or stroke. Lines of a kind that the edit reached differently take the frontmost
|
||||
/// one's rows. Called inside the same edit, so they undo together. Returns whether kept rows changed.
|
||||
pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_line_rows(doc, ids, Keep::All)
|
||||
}
|
||||
|
||||
/// [`capture_line_rows`] for an edit that wrote the fill and stroke rows of graph lines `ids` and left their object
|
||||
/// opacity and blend mode alone: those stay as the kind keeps them, also when a line still shows other ones until the
|
||||
/// graph is drawn again.
|
||||
pub(crate) fn capture_line_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_line_rows(doc, ids, Keep::Rows)
|
||||
}
|
||||
|
||||
/// Keep, for every line of their kind, the attributes of the object rows ([`label_rows`]) that an edit changed on the
|
||||
/// graph lines among `ids` (`before`: the document before the edit). The attributes the edit left alone stay as the kind
|
||||
/// keeps them, also when a line still shows other ones until the graph is drawn again. Lines of a kind that the edit
|
||||
/// changed differently take the frontmost one's attributes. Called inside the same edit, so they undo together. Returns
|
||||
/// whether kept rows changed.
|
||||
pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
let mut changed = false;
|
||||
for (id, graph, line) in lines_of(doc, ids) {
|
||||
let old = before.node(id).and_then(label_rows).unwrap_or_default();
|
||||
let new = doc.node(id).and_then(label_rows).unwrap_or_default();
|
||||
if old == new {
|
||||
continue;
|
||||
}
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = line_slot(&mut spec.label_styles, line);
|
||||
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
|
||||
merge_row_edits(&mut rows, &old, &new);
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep, for every line of their kind, the paint an edit wrote to row `at` of graph line `id` for each `(id, at)` in
|
||||
/// `written` when that row is the line's topmost visible fill or stroke, also when the line already showed that paint:
|
||||
/// the paint replaces the one its kind keeps from another line. The other attributes stay as the kind keeps them. Lines
|
||||
/// of a kind take the frontmost one's paint. Called inside the same edit, so they undo together. Returns whether kept
|
||||
/// rows changed.
|
||||
pub(crate) fn capture_line_paint_writes(doc: &mut Document, written: &[(NodeId, usize)]) -> bool {
|
||||
let paint = RowWrites { paint: true, ..RowWrites::NONE };
|
||||
capture_line_row_writes(doc, written, paint, paint)
|
||||
}
|
||||
|
||||
/// Which attributes of a fill or stroke row an edit wrote, for [`capture_line_row_writes`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(crate) struct RowWrites {
|
||||
/// The paint.
|
||||
pub paint: bool,
|
||||
/// The weight (a stroke row only).
|
||||
pub weight: bool,
|
||||
/// The row's opacity.
|
||||
pub opacity: bool,
|
||||
/// The row's blend mode.
|
||||
pub blend: bool,
|
||||
}
|
||||
|
||||
impl RowWrites {
|
||||
/// No attribute.
|
||||
pub const NONE: RowWrites = RowWrites { paint: false, weight: false, opacity: false, blend: false };
|
||||
}
|
||||
|
||||
/// [`capture_line_paint_writes`] for the attributes `fill` says of a written fill row and `stroke` says of a written
|
||||
/// stroke row: each is kept for every line of the kind as the line shows it, also when the line already showed it, in
|
||||
/// place of what its kind keeps from another line.
|
||||
pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, usize)], fill: RowWrites, stroke: RowWrites) -> bool {
|
||||
let ids: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
|
||||
let mut changed = false;
|
||||
for (id, graph, line) in lines_of(doc, &ids) {
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
let items = &n.appearance.items;
|
||||
let wrote = |kind: bool| items.iter().rposition(|it| it.is_fill() == kind && it.visible()).is_some_and(|at| written.contains(&(id, at)));
|
||||
let on_fill = if wrote(true) { fill } else { RowWrites::NONE };
|
||||
let on_stroke = if wrote(false) { stroke } else { RowWrites::NONE };
|
||||
if on_fill == RowWrites::NONE && on_stroke == RowWrites::NONE {
|
||||
continue;
|
||||
}
|
||||
let shown = label_rows(n).unwrap_or_default().paint;
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = line_slot(&mut spec.label_styles, line);
|
||||
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
|
||||
let k = &mut rows.paint;
|
||||
if on_fill.paint {
|
||||
k.fill = shown.fill;
|
||||
}
|
||||
if on_fill.opacity {
|
||||
k.fill_opacity = shown.fill_opacity;
|
||||
}
|
||||
if on_fill.blend {
|
||||
k.fill_blend = shown.fill_blend;
|
||||
}
|
||||
if on_stroke.paint {
|
||||
k.stroke = shown.stroke;
|
||||
}
|
||||
if on_stroke.weight {
|
||||
k.stroke_width = shown.stroke_width;
|
||||
}
|
||||
if on_stroke.opacity {
|
||||
k.stroke_opacity = shown.stroke_opacity;
|
||||
}
|
||||
if on_stroke.blend {
|
||||
k.stroke_blend = shown.stroke_blend;
|
||||
}
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Is `id` a graph line: a path directly in a graph's Axes group?
|
||||
pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool {
|
||||
graph_line(doc, id).is_some()
|
||||
}
|
||||
|
||||
/// Set each attribute of `rows` that differs between `old` and `new` as `new` has it.
|
||||
fn merge_row_edits(rows: &mut vectorcraft_doc::LabelRows, old: &vectorcraft_doc::LabelRows, new: &vectorcraft_doc::LabelRows) {
|
||||
fn take<T: PartialEq + Clone>(kept: &mut T, old: &T, new: &T) {
|
||||
if old != new {
|
||||
*kept = new.clone();
|
||||
}
|
||||
}
|
||||
let (k, o, n) = (&mut rows.paint, &old.paint, &new.paint);
|
||||
take(&mut k.fill, &o.fill, &n.fill);
|
||||
take(&mut k.stroke, &o.stroke, &n.stroke);
|
||||
take(&mut k.stroke_width, &o.stroke_width, &n.stroke_width);
|
||||
take(&mut k.fill_opacity, &o.fill_opacity, &n.fill_opacity);
|
||||
take(&mut k.stroke_opacity, &o.stroke_opacity, &n.stroke_opacity);
|
||||
take(&mut k.fill_blend, &o.fill_blend, &n.fill_blend);
|
||||
take(&mut k.stroke_blend, &o.stroke_blend, &n.stroke_blend);
|
||||
take(&mut k.opacity, &o.opacity, &n.opacity);
|
||||
take(&mut k.blend, &o.blend, &n.blend);
|
||||
take(&mut rows.below, &old.below, &new.below);
|
||||
take(&mut rows.stroke_under, &old.stroke_under, &new.stroke_under);
|
||||
}
|
||||
|
||||
/// Would [`store_line_rows`] with [`Keep::Object`] change what a graph keeps for the lines among `ids`? Reads the
|
||||
/// document without copying it.
|
||||
fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
let mut kept: Vec<(NodeId, Line, Option<vectorcraft_doc::LabelRows>)> = vec![];
|
||||
for (id, graph, line) in lines_of(doc, ids) {
|
||||
let (Some(spec), Some(n)) = (doc.node(graph).and_then(|n| n.extras().graph.as_deref()), doc.node(id)) else { continue };
|
||||
let slot = match kept.iter().position(|(g, l, _)| *g == graph && *l == line) {
|
||||
Some(i) => kept.swap_remove(i).2,
|
||||
None => kept_line_rows(&spec.label_styles, line).cloned(),
|
||||
};
|
||||
kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, Keep::Object)));
|
||||
}
|
||||
kept.into_iter().any(|(graph, line, rows)| {
|
||||
doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|spec| kept_line_rows(&spec.label_styles, line) != rows.as_ref())
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep the object rows ([`label_rows`]) of graph labels `ids` for every label of their kind, as
|
||||
/// [`capture_label_styles`] keeps a character format, even when a label already showed them: the last label of a kind
|
||||
/// in the order of `ids` sets what that kind keeps. Objects other than type are left out before the graph's labels are
|
||||
/// looked up. Called inside the same edit, so they undo together. Returns whether kept rows changed.
|
||||
/// looked up. The graph lines among `ids` keep their rows for every line of their kind too ([`capture_line_rows`]).
|
||||
/// Called inside the same edit, so they undo together. Returns whether kept rows changed.
|
||||
pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_label_rows(doc, ids, false)
|
||||
store_label_rows(doc, ids, Keep::All)
|
||||
}
|
||||
|
||||
/// Keep the object opacity and blend mode of graph labels `ids` for every label of their kind, as [`capture_label_rows`]
|
||||
/// keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph keeps changed.
|
||||
/// Keep the object opacity and blend mode of graph labels and graph lines `ids` for every label or line of their kind, as
|
||||
/// [`capture_label_rows`] keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph
|
||||
/// keeps changed.
|
||||
pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_label_rows(doc, ids, true)
|
||||
store_label_rows(doc, ids, Keep::Object)
|
||||
}
|
||||
|
||||
/// Keep, for every label or line of their kind, the fill row (with `fill`) and the stroke row (with `stroke`) that graph
|
||||
/// labels and graph lines `ids` show, and with `object` their object opacity and blend mode, as [`capture_label_rows`]
|
||||
/// keeps them, for an edit that wrote only those: a row of the other kind stays as the kind keeps it, also when a label or
|
||||
/// line still shows its own one until the graph is drawn again. Returns whether what the graph keeps changed.
|
||||
pub(crate) fn capture_label_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool {
|
||||
store_label_rows(doc, ids, Keep::Kinds { fill, stroke, object })
|
||||
}
|
||||
|
||||
/// [`capture_label_kind_rows`] for the graph lines among `ids` alone.
|
||||
pub(crate) fn capture_line_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool {
|
||||
store_line_rows(doc, ids, Keep::Kinds { fill, stroke, object })
|
||||
}
|
||||
|
||||
/// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying
|
||||
/// it.
|
||||
pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| {
|
||||
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false };
|
||||
let slot = match role {
|
||||
Role::Value => &spec.label_styles.values_rows,
|
||||
Role::Category => &spec.label_styles.categories_rows,
|
||||
Role::Legend => &spec.label_styles.legend_rows,
|
||||
};
|
||||
*slot != kept_label_rows(slot, rows, true)
|
||||
})
|
||||
line_object_opacity_differs(doc, ids)
|
||||
|| label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| {
|
||||
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false };
|
||||
let slot = match role {
|
||||
Role::Value => &spec.label_styles.values_rows,
|
||||
Role::Category => &spec.label_styles.categories_rows,
|
||||
Role::Legend => &spec.label_styles.legend_rows,
|
||||
};
|
||||
*slot != kept_label_rows(slot, rows, Keep::Object)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`].
|
||||
fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool {
|
||||
let mut changed = false;
|
||||
/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_kind_rows`], as `keep` says.
|
||||
fn store_label_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool {
|
||||
let mut changed = store_line_rows(doc, ids, keep);
|
||||
for (graph, role, rows) in label_rows_of(doc, ids) {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = match role {
|
||||
@@ -1315,26 +1673,23 @@ fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bo
|
||||
Role::Category => &mut spec.label_styles.categories_rows,
|
||||
Role::Legend => &mut spec.label_styles.legend_rows,
|
||||
};
|
||||
let kept = kept_label_rows(slot, rows, object_only);
|
||||
let kept = kept_label_rows(slot, rows, keep);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// What a kind keeps after a label of it shows `rows`: those rows, or with `object_only` what `slot` keeps with the
|
||||
/// label's object opacity and blend mode.
|
||||
/// What a kind keeps (`slot`) after a label of it shows `rows`, of which `keep` says what is taken from the label.
|
||||
fn kept_label_rows(
|
||||
slot: &Option<vectorcraft_doc::LabelRows>,
|
||||
rows: Option<vectorcraft_doc::LabelRows>,
|
||||
object_only: bool,
|
||||
keep: Keep,
|
||||
) -> Option<vectorcraft_doc::LabelRows> {
|
||||
if !object_only {
|
||||
if keep == Keep::All {
|
||||
return rows;
|
||||
}
|
||||
let mut kept = slot.clone().unwrap_or_default();
|
||||
let shown = rows.unwrap_or_default();
|
||||
(kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend);
|
||||
let kept = keep_rows(slot.clone().unwrap_or_default(), rows.unwrap_or_default(), keep);
|
||||
(kept != vectorcraft_doc::LabelRows::default()).then_some(kept)
|
||||
}
|
||||
|
||||
@@ -1454,23 +1809,38 @@ pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool {
|
||||
g.picks_legend_fill()
|
||||
}
|
||||
|
||||
/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them.
|
||||
/// The graph labels and graph lines among `roots` and inside them, for an edit that reaches them without naming them.
|
||||
pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut texts = Vec::new();
|
||||
let mut lines = Vec::new();
|
||||
for id in roots {
|
||||
// A root that is a line, or the Axes group: found through its parents.
|
||||
if graph_line(doc, *id).is_some() {
|
||||
lines.push(*id);
|
||||
}
|
||||
let Some(root) = doc.node(*id) else { continue };
|
||||
if let Some(parent) = doc.parent_of(*id).and_then(|p| doc.node(p))
|
||||
&& let Some(spec) = parent.extras().graph.as_deref()
|
||||
{
|
||||
lines.extend(root.children().into_iter().flatten().filter(|c| line_in(spec, root, c).is_some()).map(|c| c.id));
|
||||
}
|
||||
root.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
texts.push(n.id);
|
||||
}
|
||||
if let Some(spec) = n.extras().graph.as_deref() {
|
||||
for axes in n.children().into_iter().flatten() {
|
||||
lines.extend(axes.children().into_iter().flatten().filter(|c| line_in(spec, axes, c).is_some()).map(|c| c.id));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// Graph labels are type: without type among `roots`, the graph's labels are not looked up.
|
||||
if texts.is_empty() {
|
||||
return texts;
|
||||
if !texts.is_empty() {
|
||||
let labels = graph_labels(doc);
|
||||
texts.retain(|id| labels.contains_key(id));
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
texts.retain(|id| labels.contains_key(id));
|
||||
texts.extend(lines.into_iter().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))));
|
||||
// Nested roots (a graph and one of its labels) reach a label twice.
|
||||
texts.sort_unstable();
|
||||
texts.dedup();
|
||||
@@ -1482,10 +1852,14 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
/// and stroke attributes ([`RUN_PAINT`]) that changed on all of a label's characters, on the kind's kept style. The
|
||||
/// frontmost label of a kind sets what that kind keeps, whatever order `ids` are in. On a graph that colors its legend
|
||||
/// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one
|
||||
/// fill. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed.
|
||||
pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool) -> bool {
|
||||
/// fill and the edit named them: with `named`, only a legend label among `named` (an edit that reached the others
|
||||
/// through the graph or a group leaves them the graph's black or white); without it, every label in `ids`. The graph
|
||||
/// lines among `ids` whose rows changed keep what changed for every line of their kind ([`capture_line_changes`]), with or without
|
||||
/// `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed.
|
||||
pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool, named: Option<&[NodeId]>) -> bool {
|
||||
let lines = capture_line_changes(before, doc, ids);
|
||||
if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
|
||||
return false;
|
||||
return lines;
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
let mut picked: Vec<NodeId> = ids.iter().copied().filter(|id| labels.contains_key(id)).collect();
|
||||
@@ -1510,18 +1884,25 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids:
|
||||
if rows && label_rows(was) != label_rows(now) {
|
||||
changed_rows.push(id);
|
||||
}
|
||||
let fill = kind.1 != Role::Legend || one_fill(kind.0);
|
||||
let aimed = !wedge_fills.contains_key(&kind.0) || named.is_none_or(|n| n.contains(&id));
|
||||
let fill = kind.1 != Role::Legend || (one_fill(kind.0) && aimed);
|
||||
characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change)));
|
||||
}
|
||||
let mut changed = capture_label_rows(doc, &changed_rows);
|
||||
let mut changed = capture_label_rows(doc, &changed_rows) | lines;
|
||||
for ((graph, role), (style, entries)) in &characters {
|
||||
changed |= store_label_style(doc, *graph, *role, &|st| {
|
||||
for i in entries {
|
||||
if let Some(copy) = RUN_PAINT.get(*i) {
|
||||
copy(style, st);
|
||||
changed |= store_label_style(
|
||||
doc,
|
||||
*graph,
|
||||
*role,
|
||||
&|st| {
|
||||
for i in entries {
|
||||
if let Some(copy) = RUN_PAINT.get(*i) {
|
||||
copy(style, st);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
@@ -7762,6 +7762,936 @@ fn a_recolor_leaves_wedge_legend_labels_their_contrast() {
|
||||
assert_eq!(kept.and_then(|f| f.color()).map(|c| c.to_hex()).as_deref(), Some("#ffffff"));
|
||||
}
|
||||
|
||||
/// A recolor of the whole graph that turns every wedge legend label the same color (one series) still leaves them to
|
||||
/// the graph's black or white, so a label stays readable when its wedge is painted light again.
|
||||
#[test]
|
||||
fn a_recolor_of_a_one_series_pie_leaves_its_wedge_label_its_contrast() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = make(&mut s, "pie", ",a\nP1,1");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap();
|
||||
// The white wedge turns black and its black label white.
|
||||
s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.legend, None);
|
||||
s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1]]})).unwrap();
|
||||
let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") };
|
||||
assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#000000"));
|
||||
}
|
||||
|
||||
/// The lines in graph `id`'s Axes group (axis lines, tick marks and a radar graph's rings), in paint order.
|
||||
fn line_nodes(s: &Session, id: NodeId) -> Vec<vectorcraft_doc::Node> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
group(&n, "Axes").children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Text(_))).map(|c| (**c).clone()).collect()
|
||||
}
|
||||
|
||||
/// How line `n` looks: its stroke color (empty without one), stroke weight and object opacity.
|
||||
fn line_look(n: &vectorcraft_doc::Node) -> (String, f64, f32) {
|
||||
let stroke = n.appearance.stroke_paint().color().map(|c| c.to_hex()).unwrap_or_default();
|
||||
(stroke, n.appearance.stroke_width(), n.opacity)
|
||||
}
|
||||
|
||||
/// The looks of graph `id`'s lines after it is drawn again.
|
||||
fn redrawn_line_looks(s: &mut Session, id: NodeId) -> Vec<(String, f64, f32)> {
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
line_nodes(s, id).iter().map(line_look).collect()
|
||||
}
|
||||
|
||||
/// A stroke, a weight, no stroke or an opacity given to one axis line is kept for every axis line and tick mark when the
|
||||
/// graph is drawn again, and undo takes it back with its edit.
|
||||
#[test]
|
||||
fn paint_set_on_one_axis_line_is_kept_for_every_line() {
|
||||
let cases = [
|
||||
("paint.setStroke", json!({"color": "#ff0000"}), ("#ff0000", 0.5, 1.0)),
|
||||
("stroke.set", json!({"weight": 2}), ("#000000", 2.0, 1.0)),
|
||||
("paint.setStroke", json!({"none": true}), ("", 0.0, 1.0)),
|
||||
("appearance.clear", json!({}), ("", 0.0, 1.0)),
|
||||
("transparency.set", json!({"opacity": 40}), ("#000000", 0.5, 0.4)),
|
||||
];
|
||||
every_case(cases, |(cmd, params, (hex, width, opacity))| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
assert!(lines.len() > 2, "{lines:?}");
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([lines[0].id.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
let want = (hex.to_string(), *width, *opacity);
|
||||
assert!(looks.iter().all(|l| (&l.0, (l.1 - want.1).abs() < 1e-9, (l.2 - want.2).abs() < 1e-6) == (&want.0, true, true)), "{cmd}: {looks:?}");
|
||||
// Undo takes back the redraw, then the edit and what the graph keeps.
|
||||
for _ in 0..2 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(spec(&s, id).label_styles.axis_rows, None, "{cmd}");
|
||||
});
|
||||
}
|
||||
|
||||
/// A recolor of the whole graph, or Swap Fill and Stroke on its axis lines, is kept for its axis lines, and the labels'
|
||||
/// paint stays its own.
|
||||
#[test]
|
||||
fn recoloring_a_graph_keeps_its_axis_lines_paint() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ffffff"), "inverted black lines are white");
|
||||
let ids: Vec<u64> = line_nodes(&s, id).iter().map(|n| n.id.0).collect();
|
||||
s.execute("paint.swap", &json!({"ids": ids})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.axis_rows.unwrap();
|
||||
assert_eq!((kept.paint.fill.and_then(|p| p.color()).map(|c| c.to_hex()), kept.paint.stroke), (Some("#ffffff".into()), Some(Paint::None)));
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the lines have no stroke after the swap");
|
||||
// The value labels keep their inverted fill, not the lines' swapped paint.
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label_paint: Vec<(String, bool)> = group(&n, "Axes")
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|c| match &c.kind {
|
||||
NodeKind::Text(t) => Some((t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default(), t.runs[0].style.stroke.is_none())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!label_paint.is_empty() && label_paint.iter().all(|l| *l == ("#ffffff".to_string(), true)), "{label_paint:?}");
|
||||
}
|
||||
|
||||
/// A stroke given the whole graph, or its Axes group, is kept for its axis lines.
|
||||
#[test]
|
||||
fn a_stroke_given_the_whole_graph_or_its_axes_group_is_kept_for_its_axis_lines() {
|
||||
for axes in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let target = if axes { group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id } else { id };
|
||||
s.execute("paint.setStroke", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000"), "axes: {axes}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A radar graph's rings keep what is set on one of them, apart from its spokes.
|
||||
#[test]
|
||||
fn a_radar_graphs_rings_keep_their_paint_apart_from_its_spokes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "radar");
|
||||
let lines = line_nodes(&s, id);
|
||||
// Three categories: three spokes, then the rings.
|
||||
assert_eq!(line_look(&lines[3]), ("#999999".into(), 0.25, 1.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[3].id.0], "color": "#00ff00"})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks[..3].iter().all(|l| l.0 == "#000000" && l.1 == 0.5), "{looks:?}");
|
||||
assert!(looks[3..].iter().all(|l| l.0 == "#00ff00" && l.1 == 0.25), "{looks:?}");
|
||||
s.execute("paint.setStroke", &json!({"ids": [line_nodes(&s, id)[0].id.0], "color": "#0000ff"})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#00ff00"), "{looks:?}");
|
||||
}
|
||||
|
||||
/// When an edit gives axis lines different paint, the frontmost one sets what they keep, whatever order `ids` are in.
|
||||
#[test]
|
||||
fn the_frontmost_axis_line_sets_what_its_recolor_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
let (back, front) = (lines[0].id, lines[lines.len() - 1].id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("edit.colors.invert", &json!({"ids": [front.0, back.0]})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex());
|
||||
assert_eq!(kept.as_deref(), Some("#00ffff"), "the inverted red of the frontmost line");
|
||||
}
|
||||
|
||||
/// An appearance moved from an axis line to one behind it is kept for every axis line, not the cleared source's.
|
||||
#[test]
|
||||
fn an_appearance_moved_to_an_axis_line_behind_is_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
let (back, front) = (lines[0].id, lines[lines.len() - 1].id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("appearance.transfer", &json!({"source": front.0, "target": back.0})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex());
|
||||
assert_eq!(kept.as_deref(), Some("#ff0000"), "the moved red, not the cleared source");
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000"));
|
||||
}
|
||||
|
||||
/// A radar graph's spoke brought in front of its rings is still a spoke: what is set on it is kept for the spokes.
|
||||
#[test]
|
||||
fn a_radar_spoke_moved_in_front_of_the_rings_keeps_its_kind() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "radar");
|
||||
let spoke = line_nodes(&s, id)[0].id;
|
||||
s.execute("object.arrange.bringToFront", &json!({"ids": [spoke.0]})).unwrap();
|
||||
assert_eq!(line_nodes(&s, id).last().map(|n| n.id), Some(spoke), "the spoke is in front of the rings");
|
||||
s.execute("paint.setStroke", &json!({"ids": [spoke.0], "color": "#0000ff"})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#999999"), "{looks:?}");
|
||||
}
|
||||
|
||||
/// A graphic style linked to an axis line passes a redefinition on to every axis line.
|
||||
#[test]
|
||||
fn a_redefined_graphic_style_on_an_axis_line_is_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Axis"})).unwrap();
|
||||
let line = line_nodes(&s, id)[0].id;
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Axis", "ids": [line.0]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Axis", "id": rect.0})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex());
|
||||
assert_eq!(kept.as_deref(), Some("#00ff00"));
|
||||
}
|
||||
|
||||
/// An Eyedropper pick and Apply Stroke to Fill on an axis line are kept for every axis line.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_and_stroke_to_fill_on_an_axis_line_are_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap();
|
||||
let line = line_nodes(&s, id)[0].id;
|
||||
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [line.0]})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000" && l.1 == 1.0), "the picked 1 pt red stroke");
|
||||
let line = line_nodes(&s, id)[1].id;
|
||||
s.execute("addon.color.strokeToFill", &json!({"ids": [line.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let fills: Vec<String> = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect();
|
||||
assert!(fills.iter().all(|f| f == "#ff0000"), "{fills:?}");
|
||||
}
|
||||
|
||||
/// Setting a line to the paint it is drawn with by default keeps nothing, and is no edit.
|
||||
#[test]
|
||||
fn axis_lines_given_their_default_paint_keep_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let line = line_nodes(&s, id)[0].id;
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#000000"})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.axis_rows, None);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed");
|
||||
}
|
||||
|
||||
/// `object.setProps` and `transparency.set` without an `item` keep only a line's object opacity: the stroke its kind
|
||||
/// keeps from another line stays, though the line they are given still shows the default stroke.
|
||||
#[test]
|
||||
fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
|
||||
for (cmd, params) in [("object.setProps", json!({"opacity": 50})), ("transparency.set", json!({"opacity": 50}))] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again");
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([lines[1].id.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{cmd}: {looks:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A reorder that leaves an axis line's rows as they were keeps what its kind keeps from another line and is no edit.
|
||||
#[test]
|
||||
fn a_reorder_that_changes_nothing_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again");
|
||||
let stroke = top_row(&s, lines[1].id, false);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "from": stroke, "to": stroke})).unwrap();
|
||||
s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "indices": [stroke], "to": stroke})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed");
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick that applies only the object's transparency to an axis line keeps the stroke its kind keeps, though
|
||||
/// the line it is applied to still shows the default stroke.
|
||||
#[test]
|
||||
fn a_transparency_only_pick_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("transparency.set", &json!({"ids": [rect.0], "opacity": 50})).unwrap();
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again");
|
||||
let fill = json!({"color": false, "transparency": false, "overprint": false});
|
||||
let stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false});
|
||||
let apply = json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false});
|
||||
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}");
|
||||
}
|
||||
|
||||
/// The Eyedropper Options that apply every fill and stroke attribute but not the object's transparency.
|
||||
fn every_row_attribute_without_transparency() -> serde_json::Value {
|
||||
let fill = json!({"color": true, "transparency": true, "overprint": true});
|
||||
let stroke =
|
||||
json!({"color": true, "transparency": true, "overprint": true, "weight": true, "cap": true, "join": true, "miter": true, "dash": true});
|
||||
json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false})
|
||||
}
|
||||
|
||||
/// An Eyedropper pick of every fill and stroke attribute without the object's transparency, with or without `append`,
|
||||
/// keeps the object opacity the axis lines keep from another line, though the line it is applied to still shows 100%.
|
||||
#[test]
|
||||
fn a_pick_without_transparency_on_an_axis_line_keeps_the_opacity_its_kind_keeps() {
|
||||
for append in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap();
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("transparency.set", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).2, 1.0, "append {append}: the other lines show 100% until the graph is drawn again");
|
||||
let pick = json!({"source": rect.0, "ids": [lines[1].id.0], "apply": every_row_attribute_without_transparency(), "append": append});
|
||||
s.execute("appearance.copyFrom", &pick).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "append {append}: {looks:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graphic style added on top of a graph label's or axis line's appearance keeps the object opacity its kind keeps
|
||||
/// from another label or line, though the one it is added to still shows 100%.
|
||||
#[test]
|
||||
fn a_graphic_style_added_to_a_label_or_axis_line_keeps_the_opacity_its_kind_keeps() {
|
||||
for label in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Red"})).unwrap();
|
||||
let (first, second) = if label {
|
||||
(text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2"))
|
||||
} else {
|
||||
let lines = line_nodes(&s, id);
|
||||
(lines[0].id, lines[1].id)
|
||||
};
|
||||
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(second).unwrap().opacity, 1.0, "label {label}: 100% until the graph is drawn again");
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Red", "ids": [second.0], "add": true})).unwrap();
|
||||
if label {
|
||||
let looks = redrawn_label_rows(&mut s, id);
|
||||
for q in ["Q1", "Q2", "Q3"] {
|
||||
let (rows, opacity) = rows_of(&looks, q);
|
||||
assert!((opacity - 0.4).abs() < 1e-6 && rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?} {opacity}");
|
||||
}
|
||||
} else {
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "{looks:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill-only graphic style added on top of a graph label or axis line, or a fill-only source appended to one with the
|
||||
/// Eyedropper, keeps the stroke its kind keeps from another label or line, though the one it is added to still shows its
|
||||
/// own.
|
||||
#[test]
|
||||
fn a_fill_added_to_a_label_or_axis_line_keeps_the_stroke_its_kind_keeps() {
|
||||
let cases = [(false, false), (false, true), (true, false), (true, true)];
|
||||
every_case(cases, |&(label, append)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let (first, second) = if label {
|
||||
(text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2"))
|
||||
} else {
|
||||
let lines = line_nodes(&s, id);
|
||||
(lines[0].id, lines[1].id)
|
||||
};
|
||||
if label {
|
||||
s.execute("appearance.addStroke", &json!({"ids": [first.0]})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [first.0], "index": top_row(&s, first, false), "color": "#ff0000"})).unwrap();
|
||||
} else {
|
||||
s.execute("paint.setStroke", &json!({"ids": [first.0], "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
if append {
|
||||
let pick = json!({"source": rect.0, "ids": [second.0], "apply": every_row_attribute_without_transparency(), "append": true});
|
||||
s.execute("appearance.copyFrom", &pick).unwrap();
|
||||
} else {
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [second.0], "add": true})).unwrap();
|
||||
}
|
||||
if label {
|
||||
let looks = redrawn_label_rows(&mut s, id);
|
||||
for q in ["Q1", "Q2", "Q3"] {
|
||||
let (rows, _) = rows_of(&looks, q);
|
||||
let shows = |fill: bool, hex: &str| rows.iter().any(|r| r.0 == fill && r.1 == hex);
|
||||
assert!(shows(false, "#ff0000") && shows(true, "#0000ff"), "{q}: {rows:?}");
|
||||
}
|
||||
} else {
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A stroke a label's kind keeps below the characters stays below them when a fill-only graphic style is added on top of
|
||||
/// another label of the kind, or a fill-only source appended to it, and the new fill paints above the characters.
|
||||
#[test]
|
||||
fn a_fill_added_to_a_label_keeps_the_kept_stroke_below_the_characters() {
|
||||
every_case([false, true], |&append| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2"));
|
||||
s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap();
|
||||
s.execute("appearance.moveItem", &json!({"ids": [q1.0], "from": "contents", "to": 1})).unwrap();
|
||||
if append {
|
||||
let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true});
|
||||
s.execute("appearance.copyFrom", &pick).unwrap();
|
||||
} else {
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [q2.0], "add": true})).unwrap();
|
||||
}
|
||||
redrawn_label_rows(&mut s, id);
|
||||
let look = |ap: &vectorcraft_doc::Appearance| (ap.contents_at(), ap.items.iter().map(|it| it.is_fill()).collect::<Vec<_>>());
|
||||
for q in ["Q1", "Q2", "Q3"] {
|
||||
assert_eq!(look(&label_node(&s, id, "Axes", q).appearance), (1, vec![false, true]), "append {append}: {q}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A Contents (Characters) row move that leaves a graph label as it was keeps the rows its kind keeps from another label
|
||||
/// and is no edit.
|
||||
#[test]
|
||||
fn a_contents_move_that_changes_nothing_on_a_label_keeps_the_rows_its_kind_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2"));
|
||||
s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [q1.0], "index": top_row(&s, q1, false), "color": "#ff0000"})).unwrap();
|
||||
let at = s.doc().unwrap().doc.node(q2).unwrap().appearance.contents_at();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("appearance.moveItem", &json!({"ids": [q2.0], "from": "contents", "to": at})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed");
|
||||
let looks = redrawn_label_rows(&mut s, id);
|
||||
for q in ["Q1", "Q2", "Q3"] {
|
||||
let (rows, _) = rows_of(&looks, q);
|
||||
assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An Eyedropper pick with `append` and without the object's transparency on a graph label keeps the object opacity its
|
||||
/// kind keeps from another label, though the label it is applied to still shows 100%.
|
||||
#[test]
|
||||
fn an_appended_pick_without_transparency_on_a_label_keeps_the_opacity_its_kind_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0], "opacity": 40})).unwrap();
|
||||
let q2 = text_id(&s, id, "Axes", "Q2");
|
||||
assert_eq!(s.doc().unwrap().doc.node(q2).unwrap().opacity, 1.0, "Q2 shows 100% until the graph is drawn again");
|
||||
let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true});
|
||||
s.execute("appearance.copyFrom", &pick).unwrap();
|
||||
let looks = redrawn_label_rows(&mut s, id);
|
||||
for q in ["Q1", "Q2", "Q3"] {
|
||||
let (rows, opacity) = rows_of(&looks, q);
|
||||
assert!((opacity - 0.4).abs() < 1e-6, "{q}: {opacity}");
|
||||
assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An edit of some attributes on an axis line that still shows the default stroke keeps what it changes, and the stroke
|
||||
/// its kind keeps from another line stays: a cap is not kept, so it changes nothing the kind keeps.
|
||||
#[test]
|
||||
fn an_edit_of_some_attributes_on_an_axis_line_keeps_the_rest_its_kind_keeps() {
|
||||
let cases = [
|
||||
("stroke.set", json!({"cap": "round"}), ""),
|
||||
("paint.setFill", json!({"color": "#0000ff"}), "#0000ff"),
|
||||
("appearance.setItem", json!({"index": 0, "color": "#00ff00"}), "#00ff00"),
|
||||
];
|
||||
for (cmd, params, fill) in cases {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again");
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([lines[1].id.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| *l == ("#ff0000".into(), 0.5, 1.0)), "{cmd}: {looks:?}");
|
||||
let fills: Vec<String> =
|
||||
line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect();
|
||||
assert!(fills.iter().all(|f| f == fill), "{cmd}: {fills:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An opacity and a stroke weight given to a radar graph's ring are kept for its rings, and its spokes keep their own.
|
||||
#[test]
|
||||
fn transparency_and_stroke_weight_on_a_radar_ring_are_kept_for_its_rings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "radar");
|
||||
let ring = line_nodes(&s, id)[3].id;
|
||||
s.execute("transparency.set", &json!({"ids": [ring.0], "opacity": 40})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [ring.0], "weight": 1})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks[..3].iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{looks:?}");
|
||||
assert!(looks[3..].iter().all(|l| l.0 == "#999999" && l.1 == 1.0 && (l.2 - 0.4).abs() < 1e-6), "{looks:?}");
|
||||
}
|
||||
|
||||
/// A placed gradient on an axis line's stroke is kept for every axis line without its placement.
|
||||
#[test]
|
||||
fn a_gradient_on_an_axis_line_is_kept_without_its_placement() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let line = line_nodes(&s, id)[0].id;
|
||||
s.execute("paint.editGradient", &json!({"ids": [line.0], "kind": "linear", "stroke": true})).unwrap();
|
||||
let placement = json!({"ids": [line.0], "stroke": true, "start": [100, 100], "end": [200, 100], "aspect": 50});
|
||||
s.execute("paint.setGradientGeom", &placement).unwrap();
|
||||
let shown = line_nodes(&s, id)[0].appearance.stroke_paint().clone();
|
||||
assert!(matches!(&shown, Paint::Gradient(g) if g.geom.is_some()), "the line's gradient is placed: {shown:?}");
|
||||
let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke;
|
||||
assert!(matches!(&kept, Some(Paint::Gradient(g)) if g.geom.is_none() && g.freeform.is_none()), "{kept:?}");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
assert!(line_nodes(&s, id).iter().all(|n| matches!(n.appearance.stroke_paint(), Paint::Gradient(_))));
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke and Apply Fill to Stroke on an axis line are kept for every axis line.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_and_fill_to_stroke_on_an_axis_line_are_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let line = line_nodes(&s, id)[0].id;
|
||||
s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.default", &json!({"ids": [line.0]})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke");
|
||||
let fills: Vec<String> = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect();
|
||||
assert!(fills.iter().all(|f| f == "#ffffff"), "{fills:?}");
|
||||
let line = line_nodes(&s, id)[1].id;
|
||||
s.execute("paint.setFill", &json!({"ids": [line.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("addon.color.fillToStroke", &json!({"ids": [line.0]})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#0000ff"), "the blue fill on the stroke");
|
||||
}
|
||||
|
||||
/// The Appearance commands and `graphicStyle.apply` given a graph's Axes group or Legend group edit the lines and labels
|
||||
/// directly in it, as given a series group they edit its paths: every line and label of each kind keeps what they set
|
||||
/// when the graph is drawn again, and the groups keep no rows of their own.
|
||||
#[test]
|
||||
fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let part = |s: &Session, name: &str| group(s.doc().unwrap().doc.node(id).unwrap(), name).clone();
|
||||
s.execute("appearance.clear", &json!({"ids": [part(&s, "Axes").id.0]})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the cleared lines have no stroke");
|
||||
let (_, blue) = blue_style(&mut s, "Blue", false);
|
||||
for name in ["Axes", "Legend"] {
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [part(&s, name).id.0]})).unwrap();
|
||||
}
|
||||
let kept = spec(&s, id).label_styles;
|
||||
let fill = |rows: Option<vectorcraft_doc::LabelRows>| rows.and_then(|r| r.paint.fill);
|
||||
assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "axis lines");
|
||||
assert_eq!(fill(kept.values_rows), Some(blue.clone()), "value labels");
|
||||
assert_eq!(fill(kept.legend_rows), Some(blue.clone()), "legend labels");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
for name in ["Axes", "Legend"] {
|
||||
let g = part(&s, name);
|
||||
assert!(g.appearance.items.is_empty(), "{name} keeps no rows of its own");
|
||||
let members: Vec<Paint> = g.children().unwrap().iter().map(|c| c.appearance.fill_paint()).collect();
|
||||
assert!(!members.is_empty() && members.iter().all(|p| *p == blue), "{name}: {members:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row
|
||||
/// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph
|
||||
/// keeps the change when it is drawn again.
|
||||
#[test]
|
||||
fn a_row_index_given_the_axes_group_is_a_row_of_its_backmost_member_with_aligned() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone();
|
||||
let back = axes.children().unwrap()[0].id;
|
||||
assert!(line_nodes(&s, id).iter().any(|l| l.id == back), "the backmost member is a line");
|
||||
let stroke = top_row(&s, back, false);
|
||||
for (cmd, p) in [
|
||||
("appearance.setItem", json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000"})),
|
||||
("appearance.removeItem", json!({"ids": [axes.id.0], "index": stroke})),
|
||||
("appearance.duplicateItem", json!({"ids": [axes.id.0], "index": stroke})),
|
||||
("appearance.moveItem", json!({"ids": [axes.id.0], "from": stroke, "to": 0})),
|
||||
("transparency.set", json!({"ids": [axes.id.0], "item": stroke, "opacity": 40})),
|
||||
] {
|
||||
let err = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(err.contains("aligned"), "{cmd}: {err}");
|
||||
}
|
||||
let labels = |s: &Session| -> Vec<vectorcraft_doc::Appearance> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
group(&n, "Axes").children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| (*c.appearance).clone()).collect()
|
||||
};
|
||||
let was = labels(&s);
|
||||
s.execute("appearance.setItem", &json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000", "aligned": true})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [axes.id.0], "item": stroke, "opacity": 40, "aligned": true})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}");
|
||||
let rows = spec(&s, id).label_styles.axis_rows.unwrap();
|
||||
assert_eq!(rows.paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
|
||||
let now = labels(&s);
|
||||
assert!(!now.is_empty() && now.iter().all(|a| *a == was[0]), "the labels keep their rows");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let l = &group(&n, "Axes").children().unwrap()[0];
|
||||
assert!((l.appearance.items[top_row(&s, l.id, false)].opacity() - 0.4).abs() < 1e-6, "the stroke row's opacity is kept");
|
||||
}
|
||||
|
||||
/// An aligned row edit given the Axes group leaves alone what a kind of label keeps from a label without that row: the
|
||||
/// category labels keep the orange fill row of one of them through an edit of the lines' stroke rows.
|
||||
#[test]
|
||||
fn an_aligned_row_edit_given_the_axes_group_keeps_the_rows_of_labels_it_did_not_reach() {
|
||||
let cases = [("appearance.setItem", json!({"color": "#0000ff"})), ("appearance.duplicateItem", json!({})), ("appearance.removeItem", json!({}))];
|
||||
every_case(cases, |(cmd, params)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let c = text_id(&s, id, "Axes", "Q2");
|
||||
s.execute("appearance.addFill", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [c.0], "index": 0, "color": "#ff8000"})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.categories_rows;
|
||||
assert!(kept.is_some(), "the category labels keep the orange row");
|
||||
let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone();
|
||||
let back = axes.children().unwrap()[0].id;
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([axes.id.0]);
|
||||
p["index"] = json!(top_row(&s, back, false));
|
||||
p["aligned"] = json!(true);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories_rows, kept, "{cmd}");
|
||||
});
|
||||
}
|
||||
|
||||
/// An edit of a hidden row of an axis line leaves what its kind keeps from another line: the line's visible rows did not
|
||||
/// change.
|
||||
#[test]
|
||||
fn an_edit_of_a_hidden_row_of_an_axis_line_keeps_what_its_kind_keeps() {
|
||||
let cases = [
|
||||
("appearance.setItem", json!({"color": "#0000ff"})),
|
||||
("appearance.duplicateItem", json!({})),
|
||||
("appearance.removeItem", json!({})),
|
||||
("transparency.set", json!({"opacity": 40})),
|
||||
("paint.setStroke", json!({"color": "#0000ff"})),
|
||||
];
|
||||
every_case(cases, |(cmd, params)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
let line = lines[1].id;
|
||||
s.execute("appearance.addStroke", &json!({"ids": [line.0]})).unwrap();
|
||||
let hidden = top_row(&s, line, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [line.0], "index": hidden, "visible": false})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.axis_rows;
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([line.0]);
|
||||
p[if cmd.starts_with("appearance.") { "index" } else { "item" }] = json!(hidden);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.axis_rows, kept, "{cmd}");
|
||||
});
|
||||
}
|
||||
|
||||
/// An Eyedropper pick of only the object's opacity, or of only stroke options the graph does not keep, on an axis line
|
||||
/// keeps the stroke its kind keeps from another line, though the line it is given still shows the default stroke.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_of_only_the_opacity_keeps_the_stroke_its_kind_keeps() {
|
||||
let fill = json!({"color": false, "transparency": false, "overprint": false});
|
||||
let stroke = |dash: bool| json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": dash});
|
||||
let cases = [
|
||||
(json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke(false)}}), 0.5),
|
||||
(json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke(true)}}), 1.0),
|
||||
];
|
||||
every_case(cases, |(pick, opacity)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"ids": [rect.0], "opacity": 50})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [rect.0], "dash": [4, 2]})).unwrap();
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "pickUp": pick})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - *opacity).abs() < 1e-6), "{pick}: {looks:?}");
|
||||
});
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke on a label or an axis line that already shows the default paint is kept for its kind, in
|
||||
/// place of the paint the kind keeps from another label or line.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_on_a_label_or_line_that_shows_it_is_kept_for_its_kind() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("paint.setFill", &json!({"ids": [text_id(&s, id, "Axes", "4").0], "color": "#ff0000"})).unwrap();
|
||||
let hex = |st: &CharStyle| st.fill.color().map(|c| c.to_hex());
|
||||
assert_eq!(hex(&label_run_style(&s, id, "Axes", "0")).as_deref(), Some("#000000"), "the other labels show black until the graph is drawn again");
|
||||
s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "0").0]})).unwrap();
|
||||
label_looks(&mut s, id);
|
||||
let st = label_run_style(&s, id, "Axes", "4");
|
||||
assert_eq!((hex(&st).as_deref(), st.stroke.is_none()), (Some("#000000"), true));
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap();
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke");
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke on a label of a kind that keeps no style, which already shows the default paint, is no edit.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_on_a_label_that_shows_it_is_no_edit() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "4").0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.values, None);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on an Axes group linked to the style with rows of its own (as a file can hold it) restyles and
|
||||
/// links the lines and labels in it, and clears and unlinks the group; Break Link given the group unlinks them. A style
|
||||
/// applied through the group links its lines and labels, and the graph keeps their look, not the link, when it is drawn
|
||||
/// again.
|
||||
#[test]
|
||||
fn graphic_style_links_given_the_axes_group() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id;
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(axes).unwrap();
|
||||
g.appearance = style.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(style.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
|
||||
let axes_now = |s: &Session| group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone();
|
||||
let members = |s: &Session| -> Vec<(Paint, Option<u32>)> {
|
||||
axes_now(s).children().unwrap().iter().map(|c| (c.appearance.fill_paint(), c.extras().graphic_style)).collect()
|
||||
};
|
||||
let g = axes_now(&s);
|
||||
assert!(g.appearance.items.is_empty() && g.extras().graphic_style.is_none(), "the group is cleared and unlinked");
|
||||
assert!(members(&s).iter().all(|m| *m == (green.clone(), Some(style.id))), "{:?}", members(&s));
|
||||
s.execute("graphicStyle.breakLink", &json!({"ids": [axes_now(&s).id.0]})).unwrap();
|
||||
assert!(members(&s).iter().all(|m| m.1.is_none()), "unlinked");
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes_now(&s).id.0]})).unwrap();
|
||||
assert!(members(&s).iter().all(|m| m.1 == Some(style.id)), "linked");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
assert!(members(&s).iter().all(|m| *m == (green.clone(), None)), "{:?}", members(&s));
|
||||
}
|
||||
|
||||
/// The Appearance commands given a radar graph's Axes group reach its spokes and rings, which keep the edit apart.
|
||||
#[test]
|
||||
fn a_style_given_a_radar_graphs_axes_group_is_kept_for_spokes_and_rings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "radar");
|
||||
let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id;
|
||||
let (_, blue) = blue_style(&mut s, "Blue", false);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes.0]})).unwrap();
|
||||
let kept = spec(&s, id).label_styles;
|
||||
let fill = |rows: Option<vectorcraft_doc::LabelRows>| rows.and_then(|r| r.paint.fill);
|
||||
assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "spokes");
|
||||
assert_eq!(fill(kept.ring_rows), Some(blue.clone()), "rings");
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0.is_empty()), "the style has no stroke: {looks:?}");
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke on an axis line that already shows the default paint is kept for every axis line, in place of
|
||||
/// the stroke the kind keeps from another line, and leaves the object opacity the kind keeps from another line.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_on_an_axis_line_that_shows_it_is_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [lines[1].id.0], "opacity": 50})).unwrap();
|
||||
s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the 1 pt black default stroke: {looks:?}");
|
||||
assert!(looks.iter().all(|l| (l.2 - 0.5).abs() < 1e-6), "the kind keeps its 50% opacity: {looks:?}");
|
||||
}
|
||||
|
||||
/// A stroke paint written to an axis line that already shows it is kept for every axis line, in place of the stroke the
|
||||
/// kind keeps from another line.
|
||||
#[test]
|
||||
fn a_stroke_written_to_an_axis_line_that_shows_it_is_kept() {
|
||||
let cases = [("paint.setStroke", json!({"color": "#000000"})), ("addon.color.fillToStroke", json!({}))];
|
||||
every_case(cases, |(cmd, params)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setFill", &json!({"ids": [lines[1].id.0], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again");
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([lines[1].id.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| l.0 == "#000000"), "{cmd}: {looks:?}");
|
||||
});
|
||||
}
|
||||
|
||||
/// A stroke added to an axis line whose stroke shows the paint the new one takes is kept for every axis line, in place of
|
||||
/// the stroke the kind keeps from another line.
|
||||
#[test]
|
||||
fn a_stroke_added_to_an_axis_line_is_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again");
|
||||
s.execute("appearance.addStroke", &json!({"ids": [lines[1].id.0]})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the added 1 pt black stroke: {looks:?}");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick of the stroke color, weight or transparency alone onto an axis line that already shows what it
|
||||
/// writes is kept for every axis line, in place of what the kind keeps from another line.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_an_axis_line_already_shows_is_kept() {
|
||||
let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap();
|
||||
let cases = [("color", json!({"color": "#ff0000"})), ("weight", json!({"weight": 2})), ("transparency", json!({"opacity": 40}))];
|
||||
every_case(cases, |(attr, edit)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [rect.0], "weight": 0.5})).unwrap();
|
||||
let lines = line_nodes(&s, id);
|
||||
let mut p = edit.clone();
|
||||
p["ids"] = json!([lines[0].id.0]);
|
||||
match *attr {
|
||||
"color" => s.execute("paint.setStroke", &p),
|
||||
"weight" => s.execute("stroke.set", &p),
|
||||
_ => {
|
||||
p["index"] = json!(stroke_row(&lines[0]));
|
||||
s.execute("appearance.setItem", &p)
|
||||
}
|
||||
}
|
||||
.unwrap();
|
||||
let shown = line_nodes(&s, id)[1].clone();
|
||||
assert_eq!(line_look(&shown), ("#000000".into(), 0.5, 1.0), "{attr}: the other lines show the default until the graph is drawn again");
|
||||
let fill = json!({"color": false, "transparency": false, "overprint": false});
|
||||
let mut stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false});
|
||||
stroke[*attr] = json!(true);
|
||||
let apply = json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false});
|
||||
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap();
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{attr}: {looks:?}");
|
||||
let opacities: Vec<f32> = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect();
|
||||
assert!(opacities.iter().all(|o| *o == 1.0), "{attr}: {opacities:?}");
|
||||
});
|
||||
}
|
||||
|
||||
/// A stroke color, weight or opacity set with `appearance.setItem`, or a weight set with `stroke.set`, on an axis line
|
||||
/// that already shows it is kept for every axis line, in place of what the kind keeps from another line.
|
||||
#[test]
|
||||
fn a_row_attribute_set_on_an_axis_line_that_shows_it_is_kept() {
|
||||
let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap();
|
||||
let cases = [
|
||||
("appearance.setItem", json!({"color": "#ff0000"}), json!({"color": "#000000"})),
|
||||
("appearance.setItem", json!({"weight": 2}), json!({"weight": 0.5})),
|
||||
("appearance.setItem", json!({"opacity": 40}), json!({"opacity": 100})),
|
||||
("stroke.set", json!({"weight": 2}), json!({"weight": 0.5})),
|
||||
];
|
||||
every_case(cases, |(cmd, kept, shown)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
for (line, values) in [(&lines[0], kept), (&lines[1], shown)] {
|
||||
let mut p = values.clone();
|
||||
p["ids"] = json!([line.id.0]);
|
||||
if *cmd == "appearance.setItem" {
|
||||
p["index"] = json!(stroke_row(line));
|
||||
}
|
||||
s.execute(cmd, &p).unwrap();
|
||||
}
|
||||
let looks = redrawn_line_looks(&mut s, id);
|
||||
assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{cmd} {shown}: {looks:?}");
|
||||
let opacities: Vec<f32> = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect();
|
||||
assert!(opacities.iter().all(|o| *o == 1.0), "{cmd} {shown}: {opacities:?}");
|
||||
});
|
||||
}
|
||||
|
||||
/// `appearance.setItem` of a row's opacity alone on an axis line keeps the blend mode the kind keeps from another line,
|
||||
/// and of its blend mode alone the opacity; a null weight or opacity writes nothing and adds no undo step.
|
||||
#[test]
|
||||
fn a_row_attribute_set_on_an_axis_line_keeps_the_others_its_kind_keeps() {
|
||||
let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap();
|
||||
let row = |n: &vectorcraft_doc::Node| {
|
||||
let it = &n.appearance.items[stroke_row(n)];
|
||||
(it.opacity(), it.blend())
|
||||
};
|
||||
let cases = [
|
||||
(json!({"blend": "multiply"}), json!({"opacity": 100}), (1.0, BlendMode::Multiply)),
|
||||
(json!({"opacity": 40}), json!({"blend": "normal"}), (0.4, BlendMode::Normal)),
|
||||
];
|
||||
every_case(cases, |(kept, shown, want)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
for (line, values) in [(&lines[0], kept), (&lines[1], shown)] {
|
||||
let mut p = values.clone();
|
||||
p["ids"] = json!([line.id.0]);
|
||||
p["index"] = json!(stroke_row(line));
|
||||
s.execute("appearance.setItem", &p).unwrap();
|
||||
}
|
||||
redrawn_line_looks(&mut s, id);
|
||||
let rows: Vec<(f32, BlendMode)> = line_nodes(&s, id).iter().map(row).collect();
|
||||
assert!(rows.iter().all(|r| *r == *want), "{shown}: {rows:?}");
|
||||
});
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for key in ["weight", "opacity"] {
|
||||
let mut p = json!({"ids": [lines[1].id.0], "index": stroke_row(&lines[1])});
|
||||
p[key] = serde_json::Value::Null;
|
||||
s.execute("appearance.setItem", &p).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a null value adds no undo step");
|
||||
assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pie_names_and_wedge_labels_keep_their_style() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swap Fill and Stroke",
|
||||
[],
|
||||
Some("Shift+X"),
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
swap
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (for a fill or stroke item, a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `item` needs `aligned` and is a row of the backmost one), the graph stores that object's opacity and blend mode for every label or line of its kind, and with `item` its topmost visible fill and stroke rows too",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -655,6 +655,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
},
|
||||
|before, d, changed| {
|
||||
let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow());
|
||||
// A graph line keeps the paint written to it, also when it already showed it.
|
||||
let lines = super::graph::capture_line_paint_writes(d, &written.borrow());
|
||||
let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| {
|
||||
if fill {
|
||||
st.fill = unplaced(&paint);
|
||||
@@ -665,7 +667,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
st.stroke = unplaced(&paint);
|
||||
}
|
||||
});
|
||||
Ok(series || labels)
|
||||
Ok(series || lines || labels)
|
||||
},
|
||||
)?;
|
||||
// Rejected edits leave the next shape's appearance and active proxy untouched.
|
||||
@@ -1011,7 +1013,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The swap writes the paint of the topmost fill and stroke, not their opacity.
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false, None);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
})?;
|
||||
}
|
||||
@@ -1047,8 +1049,15 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
// The graph keeps the default paint for every label of a kind it reached, and the default fill and stroke rows
|
||||
// for every line of a kind it reached, also when one already showed them; the object opacity a line kind keeps
|
||||
// stays.
|
||||
let labels = super::graph::capture_label_styles(d, &ids, &|st| {
|
||||
st.fill = Paint::solid(Color::BLACK);
|
||||
st.stroke = Paint::None;
|
||||
});
|
||||
let lines = super::graph::capture_line_fill_stroke_rows(d, &ids);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines))
|
||||
})?;
|
||||
}
|
||||
super::newart::reset(s);
|
||||
@@ -1269,6 +1278,9 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level.
|
||||
let item_ids = if editing_mask { ids } else { row_targets(s, p, C)? };
|
||||
if !editing_mask {
|
||||
super::appearance::check_part_rows(s, p, aligned || !explicit, C)?;
|
||||
}
|
||||
// The art of a graph design whose stack an explicit aligned item is a row of goes first: appearance.setItem leaves
|
||||
// it as it is and matches the other objects' rows against it.
|
||||
let of = if editing_mask || !explicit { None } else { super::appearance::design_reference(s, p, C)? };
|
||||
|
||||
@@ -63,6 +63,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.pathtools.shape.set",
|
||||
"addon.pathtools.slideAnchor",
|
||||
"addon.pathtools.smooth",
|
||||
"addon.pathtools.tangentCircle",
|
||||
"addon.pathtools.trim",
|
||||
"addon.pen.append",
|
||||
"addon.pen.close",
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
["Window", "Stroke"],
|
||||
None,
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}",
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}",
|
||||
has_doc,
|
||||
stroke_set
|
||||
),
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Weight Up",
|
||||
[],
|
||||
Some("Cmd+Alt+."),
|
||||
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind (docs/mcp.md) → {objects}",
|
||||
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
|
||||
has_doc,
|
||||
|s, p| stroke_step(s, p, true)
|
||||
),
|
||||
@@ -307,8 +307,10 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| {
|
||||
// The objects counted: with a design's art, those with a row equal to the art's. A graph line keeps the weight
|
||||
// given to it, also when it already showed it.
|
||||
let writes = super::graph::RowWrites { weight: change.weight.is_some(), ..super::graph::RowWrites::NONE };
|
||||
let ids = super::appearance::edit_items_writing(s, &ids, item, of, C, "Stroke", false, writes, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}",
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it, and a graph's Axes or Legend group with none of these for its topmost line or label; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}",
|
||||
has_doc,
|
||||
style_new
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {name}",
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it, a graph's Axes group for the group and its lines and labels, and its Legend group for the group and its labels",
|
||||
has_doc,
|
||||
style_break_link
|
||||
),
|
||||
@@ -364,6 +364,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let kinds = (shows(true), shows(false));
|
||||
super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false, false);
|
||||
// A label or graph line keeps its new rows of those kinds for its kind. The other kind, the object opacity and
|
||||
// the blend mode stay as the kind keeps them.
|
||||
super::graph::capture_label_kind_rows(d, &ids, kinds, false);
|
||||
} else {
|
||||
d.graphic_style_id(i);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
@@ -373,9 +376,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::appearance::clear_stood_for(d, &groups);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
// A label or graph line keeps its new rows for its kind.
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
}
|
||||
// A label keeps its new rows for its kind of label.
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -516,6 +516,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// The fill of `[Normal Character Style]` in `d`: black, or the fill a redefinition gave it. New
|
||||
/// type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
|
||||
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html):
|
||||
/// new type's defaults are changed by editing it), so it takes this fill, not the current fill
|
||||
/// left from the last shape (#7975).
|
||||
pub(crate) fn normal_char_fill(d: &Document) -> vectorcraft_color::Paint {
|
||||
let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default();
|
||||
with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill)
|
||||
}
|
||||
|
||||
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
|
||||
/// when they don't pass its checks.
|
||||
pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map<String, Value>) -> Option<Map<String, Value>> {
|
||||
|
||||
@@ -1038,7 +1038,17 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// not in a scaled label's own units).
|
||||
let mut labels_changed = false;
|
||||
if range.is_none() {
|
||||
labels_changed = super::graph::capture_label_styles(d, &ids, &|st| {
|
||||
let gives_character = font.is_some()
|
||||
|| style.is_some()
|
||||
|| size.is_some()
|
||||
|| leading.is_some()
|
||||
|| tracking.is_some()
|
||||
|| fill.is_some()
|
||||
|| stroke.is_some()
|
||||
|| !stroke_weight.is_empty()
|
||||
|| features.is_some()
|
||||
|| feature_changes.as_ref().is_some_and(|c| !c.is_empty());
|
||||
let change = |st: &mut vectorcraft_doc::CharStyle| {
|
||||
if let Some(f) = &font {
|
||||
st.font_family = f.clone();
|
||||
st.font_version = None;
|
||||
@@ -1079,7 +1089,13 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(c) = &feature_changes {
|
||||
st.features = super::textedit::change_features(&st.features, c);
|
||||
}
|
||||
});
|
||||
};
|
||||
// A command that gives character attributes keeps the style even when they equal the labels' own.
|
||||
labels_changed = if gives_character {
|
||||
super::graph::capture_label_styles_given(d, &ids, &change)
|
||||
} else {
|
||||
super::graph::capture_label_styles(d, &ids, &change)
|
||||
};
|
||||
}
|
||||
Ok(((), labels_changed))
|
||||
})?;
|
||||
|
||||
@@ -102,6 +102,34 @@ fn a_kept_graph_label_style_change_alone_records_one_undo_step() {
|
||||
records_nothing(&mut s, "text.setStyle", p);
|
||||
}
|
||||
|
||||
/// `text.setStyle` on a graph label with only `justify`, which the label already has, records no undo step and keeps no
|
||||
/// character style for its kind of label.
|
||||
#[test]
|
||||
fn a_justify_only_style_change_on_a_graph_label_records_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap();
|
||||
let label = legend
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|c| match &c.kind {
|
||||
NodeKind::Text(t) if t.plain_text() == "2025" => Some(c.id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
records_nothing(&mut s, "text.setStyle", json!({"ids": [label.0], "justify": "left"}));
|
||||
let kept = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone();
|
||||
assert!(kept.is_none(), "the legend keeps a style");
|
||||
}
|
||||
|
||||
/// `text.setText` with the text the type already has records no undo step; new text records one.
|
||||
#[test]
|
||||
fn the_same_text_records_no_undo_step() {
|
||||
|
||||
@@ -26,6 +26,9 @@ impl Session {
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Clicks inside a clip group fall in the region its clipping path's effects give it.
|
||||
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
|
||||
// Clicks and marquees find paths, compound paths, groups and layers where their geometry
|
||||
// effects draw them.
|
||||
vectorcraft_doc::hit::set_drawn_art(vectorcraft_render::effects::preview::drawn_art);
|
||||
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
|
||||
// evaluated again when the fonts, the hyphenation exceptions or the plug-ins change.
|
||||
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
|
||||
|
||||
@@ -5847,9 +5847,10 @@ fn add_image(s: &mut Session, r: &vectorcraft_trace::Raster, xf: Affine) -> Node
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The traced paths of an Image Trace object: its children but the image and the seam fills.
|
||||
/// The traced paths of an Image Trace object: its children but the image and the seam fills'
|
||||
/// clip group (a trace makes no other clip group).
|
||||
fn traced_paths(n: &Node) -> Vec<Arc<Node>> {
|
||||
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect()
|
||||
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_) | NodeKind::Group { clip: true, .. })).cloned().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -6550,7 +6551,12 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
assert!(matches!(kids[0].kind, NodeKind::Image(_)));
|
||||
let group = seams(&n).unwrap();
|
||||
assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths");
|
||||
let strokes = group.children().unwrap();
|
||||
assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }), "{group:?}");
|
||||
// The two paths cover the image, so the strokes are clipped to its box.
|
||||
let (clip, strokes) = group.children().unwrap().split_first().unwrap();
|
||||
assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}");
|
||||
let cb = outline(clip).0.bounds().unwrap();
|
||||
assert!([cb.x0, cb.y0, cb.x1 - 80.0, cb.y1 - 40.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}");
|
||||
assert_eq!(strokes.len(), 1);
|
||||
assert_eq!(strokes[0].appearance.fill_paint(), Paint::None);
|
||||
let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) };
|
||||
@@ -6568,6 +6574,14 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
assert_eq!(names.len(), 3, "{names:?}");
|
||||
assert_eq!(names[0], "Edges", "{names:?}");
|
||||
assert_eq!(n.children().unwrap()[0].id, group.id);
|
||||
// Above a path, the seam fills' group is refused by name, not as an Auto Grouping group.
|
||||
let (mut s, _, r) = made("abutting", "imageTrace.make", false);
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
let kids = node(&s, g).children().unwrap().clone();
|
||||
s.execute("object.arrange.bringToFront", &json!({"ids": [kids[1].id.0]})).unwrap();
|
||||
assert_eq!(node(&s, g).children().unwrap().last().map(|c| c.id), Some(kids[1].id));
|
||||
let e = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("seam fills") && !e.contains("Auto Grouping"), "{e}");
|
||||
let (mut s, img, _) = made("abutting", "imageTrace.make", false);
|
||||
assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]);
|
||||
// Make and Expand by color too.
|
||||
@@ -6577,13 +6591,126 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
// Overlapping paths are stacked: no seam fills.
|
||||
let (s, _, r) = made("overlapping", "imageTrace.make", false);
|
||||
assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none());
|
||||
// An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale.
|
||||
}
|
||||
|
||||
/// With white left out, the seam fills are clipped to the image's box within the traced paths'
|
||||
/// box, so the expanded trace measures as its paths do, also on a turned image.
|
||||
#[test]
|
||||
fn image_trace_seam_fills_stay_within_the_traced_paths_box() {
|
||||
let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned();
|
||||
let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) {
|
||||
(false, _) => [255; 4],
|
||||
(true, true) => [200, 30, 30, 255],
|
||||
(true, false) => [30, 30, 200, 255],
|
||||
});
|
||||
for xf in [Affine::IDENTITY, Affine::translate((100.0, 100.0)) * Affine::rotate(0.5)] {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &band, xf);
|
||||
let r = s
|
||||
.execute(
|
||||
"imageTrace.makeAndExpand",
|
||||
&json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["paths"], 2, "{r}");
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let group = seams(&n).unwrap();
|
||||
let clip = &group.children().unwrap()[0];
|
||||
assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}");
|
||||
let cb = outline(clip).0.bounds().unwrap();
|
||||
let paths = n.children().unwrap()[1..].iter().filter_map(|c| c.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert_eq!(n.geometric_bounds(), Some(paths), "{xf:?}");
|
||||
assert!(cb.x0 >= paths.x0 - 1e-9 && cb.y0 >= paths.y0 - 1e-9 && cb.x1 <= paths.x1 + 1e-9 && cb.y1 <= paths.y1 + 1e-9, "{xf:?}: {cb:?}");
|
||||
if xf == Affine::IDENTITY {
|
||||
assert!([cb.x0, cb.y0 - 4.0, cb.x1 - 24.0, cb.y1 - 12.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On an image stretched more one way than another, the seam fills are the strokes' outlines in
|
||||
/// image pixels, filled: on an image stretched 20× across, the one along a horizontal edge covers
|
||||
/// 0.75 image pixels on each side of it, as on an image scaled alike both ways, and does not reach
|
||||
/// across the transparent rows above the edge.
|
||||
#[test]
|
||||
fn image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge() {
|
||||
// Red beside blue, the edge between them anti-aliased, on an image stretched 3× across and
|
||||
// squeezed to half height: the outline is 1.5 pixels (4.5 points) across the vertical edge.
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| {
|
||||
let share = (16.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap();
|
||||
let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") };
|
||||
assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width);
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let kids = n.children().unwrap();
|
||||
assert_eq!(kids[1].name.as_deref(), Some("Seam Fills"));
|
||||
let fill = &kids[1].children().unwrap()[1];
|
||||
assert_eq!(fill.appearance.stroke_paint(), Paint::None, "{:?}", fill.appearance);
|
||||
assert_eq!(fill.appearance.fill_paint(), kids[2].appearance.fill_paint(), "the lower path's color");
|
||||
let bb = outline(fill).0.bounds().unwrap();
|
||||
assert!((bb.width() - 4.5).abs() < 0.05 && bb.y0.abs() < 1e-6 && (bb.y1 - 10.0).abs() < 1e-6, "{bb:?}");
|
||||
// Rows 0 to 5 transparent, 5 to 10 red, 10 to 20 blue.
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |_, y| match y {
|
||||
0..5 => [0, 0, 0, 0],
|
||||
5..10 => [200, 30, 30, 255],
|
||||
_ => [30, 30, 200, 255],
|
||||
});
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale_non_uniform(20.0, 1.0));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let group = n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned().unwrap();
|
||||
let (_, members) = group.children().unwrap().split_first().unwrap();
|
||||
assert!(!members.is_empty(), "{group:?}");
|
||||
for m in members {
|
||||
// What the member covers: its outline, grown by half its stroke's width.
|
||||
let half = m.appearance.items.iter().fold(0.0_f64, |w, it| match it {
|
||||
AppearanceItem::Stroke(l) => w.max(l.width / 2.0),
|
||||
_ => w,
|
||||
});
|
||||
let bb = outline(m).0.bounds().unwrap();
|
||||
let (y0, y1) = (bb.y0 - half, bb.y1 + half);
|
||||
assert!(y0 > 9.25 - 1e-6 && y1 < 10.75 + 1e-6, "covers y {y0} to {y1}: {m:?}");
|
||||
}
|
||||
// Renamed, the group of filled outlines is still the seam fills: Expand by color keeps it under
|
||||
// every color's group.
|
||||
s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": n.id.0, "byColor": true})).unwrap();
|
||||
assert_eq!(node(&s, n.id).children().unwrap()[0].id, group.id);
|
||||
}
|
||||
|
||||
/// A trace made before the seam fills were clipped holds them in a group without a clip: Expand by
|
||||
/// color keeps that group under every color's group too, named or renamed.
|
||||
#[test]
|
||||
fn image_trace_expand_by_color_keeps_unclipped_seam_fills() {
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| {
|
||||
let share = (16.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
for name in [Some("Seam Fills"), None] {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale(2.0));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
// The seam fills as such a trace holds them: the strokes alone, in a plain group.
|
||||
let seams = node(&s, g).children().unwrap()[1].clone();
|
||||
let NodeKind::Group { clip: true, children } = &seams.kind else { panic!("{seams:?}") };
|
||||
let mut legacy = Node::group(seams.id, children[1..].to_vec());
|
||||
legacy.name = name.map(Into::into);
|
||||
s.edit("legacy", |d, _| {
|
||||
let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("trace group") };
|
||||
children[1] = Arc::new(legacy);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
|
||||
let kids = node(&s, g).children().unwrap().clone();
|
||||
assert_eq!(kids.len(), 3, "{name:?}: {kids:?}");
|
||||
assert_eq!(kids[0].id, seams.id, "{name:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand by color: each color's paths in a group of their own, named by the color, the groups
|
||||
@@ -7646,6 +7773,51 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills
|
||||
/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines), renamed
|
||||
/// too.
|
||||
#[test]
|
||||
fn image_trace_outline_view_leaves_out_the_seam_fills() {
|
||||
// Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×,
|
||||
// or 2× across and 2.5× down.
|
||||
let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) {
|
||||
(false, _) => [0, 0, 0, 0],
|
||||
(true, true) => [200, 30, 30, 255],
|
||||
(true, false) => [30, 30, 200, 255],
|
||||
});
|
||||
for (scale, stretched) in [(Affine::scale(2.0), false), (Affine::scale_non_uniform(2.0, 2.5), true)] {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * scale);
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
let seams =
|
||||
node(&s, g).children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })).cloned().expect("seam fills");
|
||||
// Strokes, or on the stretched image their outlines, filled.
|
||||
let members = &seams.children().unwrap()[1..];
|
||||
assert!(!members.is_empty());
|
||||
for m in members {
|
||||
let (fill, stroke) = (m.appearance.fill_paint(), m.appearance.stroke_paint());
|
||||
assert_eq!((fill != Paint::None, stroke != Paint::None), (stretched, !stretched), "{scale:?}: {fill:?}, {stroke:?}");
|
||||
}
|
||||
s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap();
|
||||
let screen = render_doc(&s, true);
|
||||
// The image's top edge (y = 50), away from the art: nothing drawn.
|
||||
for x in [60, 110, 160] {
|
||||
assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 50));
|
||||
}
|
||||
// The art's left edge (x = 70) is outlined.
|
||||
assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128), "{scale:?}");
|
||||
// Beside the red and blue paths' shared edge (x = 110), inside the seam band (1.5 units
|
||||
// each side on the stretched image) but off the traced outlines (x = 109 and 110): nothing.
|
||||
for x in [108, 111] {
|
||||
assert!(screen.pixel(x, 100)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 100));
|
||||
}
|
||||
// Renamed, the group is still left out: the view draws as it did.
|
||||
s.execute("layer.setProps", &json!({"id": seams.id.0, "name": "Edges"})).unwrap();
|
||||
assert!(render_doc(&s, true).pixels == screen.pixels, "{scale:?}: renamed seam fills drawn");
|
||||
}
|
||||
}
|
||||
|
||||
/// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals
|
||||
/// overlapping) merges every region the drags touch into one shape whose outline is only the
|
||||
/// merged area's border: no edge between merged regions stays in, as a stray line or a spur.
|
||||
|
||||
@@ -512,3 +512,21 @@ fn keep_plain_text_preference_drops_pasted_formatting() {
|
||||
assert_eq!(paste_copied_range(false), 40.0, "Keep Formatting");
|
||||
assert_eq!(paste_copied_range(true), 10.0, "Keep Plain Text");
|
||||
}
|
||||
|
||||
/// #7975: pasted plain text is new type, filled as [Normal Character Style] is, not with the
|
||||
/// current fill.
|
||||
#[test]
|
||||
fn pasted_plain_text_takes_the_normal_character_style_fill() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "clipboard.importText", json!({"text": "Plain"}));
|
||||
run(&mut s, "edit.paste", json!({"center": [200, 150]}));
|
||||
assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, Paint::solid(Color::BLACK));
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let attrs = crate::cmd::textstyles::char_attrs(&vectorcraft_doc::CharStyle { fill: blue.clone(), ..Default::default() });
|
||||
run(&mut s, "charStyle.setAttrs", json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}}));
|
||||
run(&mut s, "clipboard.importText", json!({"text": "Plain"}));
|
||||
run(&mut s, "edit.paste", json!({"center": [200, 150]}));
|
||||
assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, blue);
|
||||
}
|
||||
@@ -677,16 +677,16 @@ fn the_eraser_tip_varies_with_its_modes() {
|
||||
assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line");
|
||||
let level_tip = left_of_line(json!([]));
|
||||
assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line");
|
||||
// A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed.
|
||||
// A 1000 pt tip on Tilt erases 1000 pt across with a mouse, as it does on Fixed.
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 4000.0, 4000.0);
|
||||
let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10});
|
||||
let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1000, "sizeMode": "tilt", "sizeVariation": 10});
|
||||
s.execute("path.eraseRegion", &big).unwrap();
|
||||
let filled =
|
||||
|x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)));
|
||||
assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip");
|
||||
assert_eq!((filled(2000.0, 2490.0), filled(2000.0, 2510.0)), (false, true), "a 1000 pt tip");
|
||||
// A Size Variation kept while Size is Fixed leaves the size alone.
|
||||
let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000}));
|
||||
let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000}));
|
||||
assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation");
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
@@ -2882,6 +2882,116 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() {
|
||||
s.execute("path.eraseRegion", &sized).unwrap();
|
||||
}
|
||||
|
||||
/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90
|
||||
/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six
|
||||
/// numbers, naming the point; the document, the selection and the undo history stay as they were.
|
||||
/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw.
|
||||
#[test]
|
||||
fn pen_values_outside_their_ranges_are_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let good = [json!([90, 150]), json!([150, 150]), json!([210, 150])];
|
||||
let cmds = [
|
||||
"path.freehand",
|
||||
"brush.freehand",
|
||||
"path.knife",
|
||||
"path.eraseRegion",
|
||||
"path.eraseSegments",
|
||||
"path.smoothRegion",
|
||||
"path.joinScrub",
|
||||
"path.blob",
|
||||
];
|
||||
let pressure = "`pressure` must be from 0 to 1";
|
||||
let tilt_x = "`tiltX` must be from -90 to 90";
|
||||
let tilt_y = "`tiltY` must be from -90 to 90";
|
||||
let rotation = "`rotation` must be from 0 to 360";
|
||||
let entries = "`points[3]` must be an array of at most 6 entries";
|
||||
for cmd in cmds {
|
||||
for (bad, want) in [
|
||||
(json!([150, 150, -0.01]), pressure),
|
||||
(json!([150, 150, 1.5]), pressure),
|
||||
(json!({"x": 150, "y": 150, "pressure": 1e300}), pressure),
|
||||
(json!([150, 150, 0.5, -90.5]), tilt_x),
|
||||
(json!([150, 150, 0.5, 91, 0]), tilt_x),
|
||||
(json!({"x": 150, "y": 150, "tiltX": -1e300}), tilt_x),
|
||||
(json!([150, 150, null, 0, -1e300]), tilt_y),
|
||||
(json!({"x": 150, "y": 150, "tiltY": 90.01}), tilt_y),
|
||||
(json!([150, 150, null, null, null, -1]), rotation),
|
||||
(json!({"x": 150, "y": 150, "rotation": 360.5}), rotation),
|
||||
(json!([150, 150, null, null, null, 720]), rotation),
|
||||
(json!([150, 150, 0.5, 0, 0, 0, 1]), entries),
|
||||
(json!([150, 150, null, null, null, null, null]), entries),
|
||||
] {
|
||||
let points: Vec<_> = good.iter().cloned().chain([bad]).collect();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, cmd, &json!({"points": points}), want);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {points:?} changed the selection");
|
||||
}
|
||||
}
|
||||
for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() {
|
||||
let y = 300.0 + 50.0 * row as f64;
|
||||
let points = json!([
|
||||
[100, y, 0, -90, 90, 0],
|
||||
[150, y, 1, 90, -90, 360],
|
||||
[200, y, 0.5, null, 30],
|
||||
{"x": 250, "y": y, "tiltX": -45, "pressure": null},
|
||||
[300, y],
|
||||
{"x": 350, "y": y, "rotation": 359.99},
|
||||
]);
|
||||
s.execute(cmd, &json!({"points": points})).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
let mouse = json!([[100, y + 20.0], [200, y + 20.0], [300, y + 25.0]]);
|
||||
s.execute(cmd, &json!({"points": mouse})).unwrap_or_else(|e| panic!("{cmd} with mouse points: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt and a `sizeVariation`
|
||||
/// outside 0 to 1000 pt, in every `sizeMode` each takes and with it left out, and a `sizeVariation`
|
||||
/// that is not a number with Fixed too; nothing changes. The ends of each range and null still draw.
|
||||
#[test]
|
||||
fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let stroke = json!({"points": [[90, 150, 0.2, 30, 0, 45], [150, 150, 0.6, 0, 30, 90], [210, 150, 1, -30, 0, 180]]});
|
||||
let size = "`size` must be from 0.1 to 1000";
|
||||
let variation = "`sizeVariation` must be from 0 to 1000";
|
||||
let blob_modes = [json!(null), json!("fixed"), json!("pressure")];
|
||||
let eraser_modes = [json!(null), json!("fixed"), json!("random"), json!("pressure"), json!("tilt"), json!("bearing"), json!("rotation")];
|
||||
// The Eraser keeps its own message for a negative Size Variation.
|
||||
for (cmd, modes, negative) in
|
||||
[("path.blob", &blob_modes[..], variation), ("path.eraseRegion", &eraser_modes[..], "sizeVariation must be 0 or more")]
|
||||
{
|
||||
for x in [json!(0.09), json!(0), json!(-1), json!(1000.5), json!(1e300)] {
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, cmd, &with(&stroke, json!({"size": x})), size);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{cmd} size {x} changed the selection");
|
||||
}
|
||||
for mode in modes {
|
||||
for (x, want) in [(json!(-0.5), negative), (json!(1000.01), variation), (json!(1e300), variation)] {
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, cmd, &with(&stroke, json!({"sizeMode": mode, "sizeVariation": x})), want);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {mode} sizeVariation {x} changed the selection");
|
||||
}
|
||||
let text = json!({"sizeMode": mode, "sizeVariation": "8"});
|
||||
refuses_with(&mut s, cmd, &with(&stroke, text), "`sizeVariation` must be a number, not \"8\"");
|
||||
}
|
||||
}
|
||||
for (row, (cmd, modes)) in [("path.blob", &blob_modes[..]), ("path.eraseRegion", &eraser_modes[..])].into_iter().enumerate() {
|
||||
let y = 300.0 + 100.0 * row as f64;
|
||||
let at = |p: serde_json::Value| with(&json!({"points": [[100, y, 0.2, 30, 0, 0], [200, y, 0.6, 0, 30, 90], [300, y, 1, -30, 0, 360]]}), p);
|
||||
for extra in [json!({"size": 0.1}), json!({"size": 1000}), json!({"size": null, "sizeVariation": null, "sizeMode": null})] {
|
||||
s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}"));
|
||||
}
|
||||
for mode in modes {
|
||||
for x in [0, 1000] {
|
||||
let extra = json!({"sizeMode": mode, "sizeVariation": x});
|
||||
s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
|
||||
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
|
||||
/// nothing; null is read as the key left out.
|
||||
|
||||
@@ -408,6 +408,35 @@ fn a_members_offset_path_applies_before_its_painted_groups_copies() {
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
}
|
||||
|
||||
/// Each copy of type's Transform effect draws the drop shadow listed before the effect under
|
||||
/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 %
|
||||
/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's
|
||||
/// own 20 pt.
|
||||
#[test]
|
||||
fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() {
|
||||
let mut s = session();
|
||||
let t = run(&mut s, "text.create", json!({"x": 20, "y": 60, "text": "I", "size": 40}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}}));
|
||||
let before = render(&s);
|
||||
if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) {
|
||||
eprintln!("skipped: built without a font that draws the type");
|
||||
return;
|
||||
}
|
||||
// The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow.
|
||||
let red =
|
||||
(100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0);
|
||||
let (x, y) = red.expect("the copy");
|
||||
assert_eq!(before.pixel(x + 38, y), [0, 255, 0, 255], "the copy's shadow, 40 pt to the right of ({x}, {y})");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let after = render(&s);
|
||||
let diff = differing(&before, &after, 64);
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
}
|
||||
|
||||
/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on
|
||||
/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide.
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Clicks, hovers and marquees with the selection tools leave out the area that raster effects
|
||||
//! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the
|
||||
//! effect, or nothing.
|
||||
//! effect, or nothing. Clicks and marquees take art where its geometry effects draw it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
@@ -391,3 +391,107 @@ fn group_selection_hover_over_a_drop_shadow_marks_nothing() {
|
||||
}
|
||||
assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]);
|
||||
}
|
||||
|
||||
/// A rectangle that a Transform effect moves 100 pt to the right is selected by a click and by a
|
||||
/// marquee where it is drawn, and not at its own place, which it no longer paints. The same holds
|
||||
/// for a group whose own Transform effect moves it.
|
||||
#[test]
|
||||
fn a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0, 20.0, 40.0, 40.0, "#ff0000");
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [a.0], "params": {"moveH": 100}, "item": null}));
|
||||
assert_eq!(pixel(&s, 140, 40), [255, 0, 0, 255], "drawn where it moved");
|
||||
assert_eq!(pixel(&s, 40, 40), WHITE, "not drawn at its own place");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(click(&mut s, 40.0, 40.0).is_empty());
|
||||
assert_eq!(click(&mut s, 140.0, 40.0), [a]);
|
||||
assert_eq!(press(&mut s, "selection", (110.0, 10.0), (130.0, 30.0), Mods::default()), [a], "a marquee across its drawn corner");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(press(&mut s, "selection", (10.0, 10.0), (30.0, 30.0), Mods::default()).is_empty(), "a marquee across its own corner");
|
||||
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [g.0], "params": {"moveH": 100}, "item": null}));
|
||||
assert_eq!(pixel(&s, 140, 140), BLUE, "the group drawn where it moved");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(click(&mut s, 40.0, 140.0).is_empty());
|
||||
assert_eq!(click(&mut s, 140.0, 140.0), [g]);
|
||||
assert_eq!(press(&mut s, "selection", (110.0, 110.0), (130.0, 130.0), Mods::default()), [g]);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(press(&mut s, "selection", (10.0, 110.0), (30.0, 130.0), Mods::default()).is_empty());
|
||||
}
|
||||
|
||||
/// A group's own fill paints its member's shape before the member's own Transform effect moves the
|
||||
/// member: a click there selects the group, and a click on the moved member selects it too. A
|
||||
/// Direct Selection marquee takes the group there and the member where it moved.
|
||||
#[test]
|
||||
fn a_click_selects_a_group_where_its_own_fill_paints_a_moved_member() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveH": 100}, "item": null}));
|
||||
assert_eq!(pixel(&s, 40, 140), [255, 0, 0, 255], "the group's fill at the member's own place");
|
||||
assert_eq!(pixel(&s, 140, 140), BLUE, "the member where it moved");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(click(&mut s, 40.0, 140.0), [g]);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(click(&mut s, 140.0, 140.0), [g]);
|
||||
// A marquee across the edge of the group's fill takes the group, and one across the moved
|
||||
// member's edge takes the member.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]);
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(110.0, 130.0, 130.0, 150.0), None, true), [b]);
|
||||
}
|
||||
|
||||
/// An inner group's own fill paints its member's shape before the member's own Transform effect
|
||||
/// moves the member, and so does an outer group's own fill around it: a Direct Selection marquee
|
||||
/// across the edge of those fills takes both groups, and one across the moved member takes it.
|
||||
#[test]
|
||||
fn a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null}));
|
||||
run(&mut s, "select.set", json!({"ids": [g.0]}));
|
||||
let o = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#00ff00"}));
|
||||
assert_eq!(pixel(&s, 40, 140), [0, 255, 0, 255], "the outer group's fill at the member's own place");
|
||||
assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [o, g]);
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]);
|
||||
}
|
||||
|
||||
/// A group's own fill paints its member's shape before the member's own Transform effect moves
|
||||
/// the member, and so does its layer's own fill around it: a Direct Selection marquee across the
|
||||
/// edge of the group's fill takes the group, and one across the moved member takes it.
|
||||
#[test]
|
||||
fn a_marquee_takes_a_groups_own_fill_inside_a_painted_layer() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null}));
|
||||
let l = s.doc().unwrap().doc.layers[0].id;
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [l.0]}));
|
||||
assert!(!s.doc().unwrap().doc.layers[0].appearance.items.is_empty(), "the layer has a fill of its own");
|
||||
assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]);
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]);
|
||||
}
|
||||
@@ -262,8 +262,8 @@ fn document_color_mode_converts_effect_colors() {
|
||||
assert_eq!((object(&s), style(&s)), before);
|
||||
}
|
||||
|
||||
/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn
|
||||
/// again after the switch paints its series and labels in the new mode.
|
||||
/// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a
|
||||
/// graph drawn again after the switch paints its series, labels and lines in the new mode.
|
||||
#[test]
|
||||
fn document_color_mode_converts_the_paints_a_graph_keeps() {
|
||||
let mut s = session();
|
||||
@@ -284,22 +284,26 @@ fn document_color_mode_converts_the_paints_a_graph_keeps() {
|
||||
}
|
||||
// A fill row on the label, which the graph keeps with the label's rows.
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [label.0]}));
|
||||
// A stroke on an axis line, which the graph keeps for its axis lines and tick marks.
|
||||
let line = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })).unwrap().id;
|
||||
run(&mut s, "paint.setStroke", json!({"color": "#ff0000", "ids": [line.0]}));
|
||||
let kept = |s: &Session| -> Vec<Color> {
|
||||
let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone();
|
||||
let rows = [&g.label_styles.values_rows, &g.label_styles.categories_rows, &g.label_styles.legend_rows];
|
||||
let rows: Vec<Color> = rows.into_iter().flatten().filter_map(|r| r.paint.fill.as_ref()?.color()).collect();
|
||||
let lines = g.label_styles.axis_rows.iter().filter_map(|r| r.paint.stroke.as_ref()?.color());
|
||||
let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend];
|
||||
let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap());
|
||||
g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).collect()
|
||||
g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).chain(lines).collect()
|
||||
};
|
||||
let before = kept(&s);
|
||||
assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 3]);
|
||||
assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 4]);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
|
||||
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
|
||||
let cmyk = first_fill(doc(&s).node(red).unwrap());
|
||||
assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}");
|
||||
assert_eq!(kept(&s), [cmyk; 3]);
|
||||
assert_eq!(kept(&s), [cmyk; 4]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
// Drawn again from new data, the series keeps the converted color.
|
||||
run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]}));
|
||||
|
||||
@@ -4027,3 +4027,35 @@ fn apply_fill_to_stroke_with_characters_selected_changes_only_them() {
|
||||
let labels = undo_labels(&s);
|
||||
assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke")));
|
||||
}
|
||||
|
||||
/// Redefines `[Normal Character Style]` with `fill` (`charStyle.setAttrs`).
|
||||
fn set_normal_fill(s: &mut Session, fill: vectorcraft_color::Paint) {
|
||||
let attrs = crate::cmd::textstyles::char_attrs(&CharStyle { fill, ..CharStyle::default() });
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}})).unwrap();
|
||||
}
|
||||
|
||||
/// #7975: type the Type tool starts is filled as [Normal Character Style] is, black unless it was
|
||||
/// redefined, not with the current fill a shape left behind.
|
||||
#[test]
|
||||
fn new_type_takes_the_normal_character_style_fill_not_the_current_fill() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert_eq!(s.paint.fill, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "the current fill is red");
|
||||
s.select_tool("type", v).unwrap();
|
||||
click(&mut s, 200.0, 200.0);
|
||||
s.tool_text("Black", v).unwrap();
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(obj(&s, id).runs[0].style.fill, Paint::solid(Color::BLACK));
|
||||
// A redefined [Normal Character Style] gives new type its fill.
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
set_normal_fill(&mut s, blue.clone());
|
||||
let made = s.execute("text.create", &json!({"x": 100, "y": 300, "text": "Blue"})).unwrap();
|
||||
assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, blue);
|
||||
// A color given to the command still wins.
|
||||
let made = s.execute("text.create", &json!({"x": 100, "y": 400, "text": "Green", "color": "#00ff00"})).unwrap();
|
||||
assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
}
|
||||
@@ -963,6 +963,13 @@ fn structured_junk() {
|
||||
("addon.pathtools.trim", json!({"points": [[0, 0], [1e7, 1e7], [-1e7, 5], [0, 0]]})),
|
||||
("addon.pathtools.trim", json!({"points": [[0, 0], [1, "y"], null]})),
|
||||
("addon.pathtools.trim", json!({"at": [50, 50], "tolerance": 100})),
|
||||
// Path Precision Tools: Tangent Circle.
|
||||
("addon.pathtools.tangentCircle", json!({"ids": [2, 3], "radius": 1e6, "circle": u64::MAX})),
|
||||
("addon.pathtools.tangentCircle", json!({"ids": [2, 3, 4], "radius": f64::MIN_POSITIVE, "circle": -1})),
|
||||
("addon.pathtools.tangentCircle", json!({"ids": [2, 2], "radius": "1 mm"})),
|
||||
("addon.pathtools.tangentCircle", json!({"ids": [2, 3], "radius": 0.01, "circle": 64})),
|
||||
("addon.pathtools.tangentCircle", json!({"ids": [2, 3, 4]})),
|
||||
("addon.pathtools.tangentCircle", json!({"ids": "x", "radius": f64::NAN, "circle": 1.5})),
|
||||
// Arrange Tools add-on.
|
||||
("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})),
|
||||
("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})),
|
||||
|
||||
@@ -579,6 +579,29 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() {
|
||||
assert!(failures.is_empty(), "{failures:#?}");
|
||||
}
|
||||
|
||||
/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two
|
||||
/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its
|
||||
/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by
|
||||
/// no more than 4, and no alpha is off.
|
||||
#[test]
|
||||
fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() {
|
||||
let lights = json!([
|
||||
{"color":"#ff0000","rotation":135,"height":35,"intensity":70},
|
||||
{"color":"#0000ff","rotation":-35,"height":25,"intensity":65}
|
||||
]);
|
||||
let (mut s, _) = setup("threeD.inflate");
|
||||
let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}});
|
||||
s.execute("effect.setParams", &change).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap();
|
||||
let image = render(doc(&s));
|
||||
let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image);
|
||||
assert!(measured > 2_000, "{measured} pixels inside");
|
||||
assert!(
|
||||
holes == 0 && color <= 1 && max <= 4,
|
||||
"of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at
|
||||
/// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the
|
||||
/// live art.
|
||||
|
||||
@@ -12338,8 +12338,8 @@ fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() {
|
||||
}
|
||||
|
||||
/// A clipping path inside art cut to a clipping object is written as its fills and its strokes,
|
||||
/// two objects: its text wrap options are written once, whether it has both or only strokes, and
|
||||
/// with its strokes when the region outside leaves nothing of its fills.
|
||||
/// two objects: its text wrap options are written once, whether it has both, only strokes, or
|
||||
/// fills the region outside leaves nothing of.
|
||||
#[test]
|
||||
fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
|
||||
for (fill, left, width) in [(solid(Color::gray(0.5)), 20.0, 2.0), (Paint::None, 20.0, 2.0), (solid(Color::gray(0.5)), 101.0, 4.0)] {
|
||||
@@ -12450,3 +12450,151 @@ fn a_graph_with_art_left_out_is_written_without_records() {
|
||||
assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{max}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The wrap shapes [`vectorcraft_doc::text::resolve_wrap`] gives the area type in `doc`.
|
||||
fn area_wrap(doc: &Document) -> Vec<vectorcraft_doc::WrapShape> {
|
||||
let mut d = doc.clone();
|
||||
vectorcraft_doc::text::resolve_wrap(None, &mut d);
|
||||
let mut out = vec![];
|
||||
d.layers[0].walk(&mut |n| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })
|
||||
{
|
||||
out.clone_from(&t.wrap);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// `got` and `want` are the same wrap shapes: the same options, offsets within `1e-6`, and the
|
||||
/// same subpaths with anchors within `1e-3`.
|
||||
fn same_shapes(got: &[vectorcraft_doc::WrapShape], want: &[vectorcraft_doc::WrapShape], case: &str) {
|
||||
let same = got.len() == want.len()
|
||||
&& got.iter().zip(want).all(|(g, w)| {
|
||||
g.wrap.invert == w.wrap.invert
|
||||
&& (g.wrap.offset - w.wrap.offset).abs() < 1e-6
|
||||
&& g.path.subpaths.len() == w.path.subpaths.len()
|
||||
&& g.path.subpaths.iter().zip(&w.path.subpaths).all(|(a, b)| {
|
||||
a.closed == b.closed
|
||||
&& a.anchors.len() == b.anchors.len()
|
||||
&& a.anchors.iter().zip(&b.anchors).all(|(p, q)| (p.p - q.p).hypot() < 1e-3)
|
||||
})
|
||||
});
|
||||
assert!(same, "{case}\n{got:?}\n{want:?}");
|
||||
}
|
||||
|
||||
/// A clipping object that isn't written as an object of its own (a group, an image, a symbol
|
||||
/// instance, a path or compound path without paint in art cut to a clipping object) or is written
|
||||
/// as its outlines or cut (type, a path the outer clipping object cuts) keeps its text wrap options on one unpainted object
|
||||
/// of its wrap outline: area type below it wraps alike after a round trip, and the object stays
|
||||
/// locked or hidden as it was. A clipping object without options gets no such object.
|
||||
#[test]
|
||||
fn a_clipping_object_not_written_whole_keeps_its_text_wrap() {
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
let cases = ["group", "hidden", "locked", "image", "instance", "type", "unpainted path", "unpainted compound", "cut path", "no options"];
|
||||
for case in cases {
|
||||
let mut doc = Document::new(400.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let st = style(10.0, Color::BLACK);
|
||||
let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone());
|
||||
area.runs = vec![TextRun::new("One two three four five six", st)];
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 200.0)) };
|
||||
area.xf = Affine::IDENTITY;
|
||||
let area = text_node(&mut doc, area);
|
||||
doc.insert(Some(layer), usize::MAX, area).unwrap();
|
||||
let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
|
||||
let mut cutter = match case {
|
||||
"group" | "hidden" | "locked" | "no options" => {
|
||||
let mut off = square(&mut doc, Rect::new(200.0, 20.0, 230.0, 60.0), Color::gray(0.5));
|
||||
off.visible = false;
|
||||
let members = vec![
|
||||
square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)),
|
||||
square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)),
|
||||
off,
|
||||
];
|
||||
group(&mut doc, members, false)
|
||||
}
|
||||
"image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None),
|
||||
"instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))),
|
||||
"type" => {
|
||||
let label = TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK));
|
||||
text_node(&mut doc, label)
|
||||
}
|
||||
"unpainted path" => clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0))),
|
||||
"unpainted compound" => {
|
||||
let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Appearance::default());
|
||||
let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default());
|
||||
Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd })
|
||||
}
|
||||
_ => {
|
||||
let mut c = clipping(&mut doc, shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 80.0)));
|
||||
c.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into();
|
||||
c
|
||||
}
|
||||
};
|
||||
cutter.visible = case != "hidden";
|
||||
cutter.locked = case == "locked";
|
||||
let cutter = if case == "no options" { cutter } else { wrapped(cutter, -4.5, true) };
|
||||
let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let mut top = group(&mut doc, vec![cutter, member], true);
|
||||
if matches!(case, "unpainted path" | "unpainted compound" | "cut path") {
|
||||
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
|
||||
let frame = group(&mut doc, vec![frame], false);
|
||||
top = group(&mut doc, vec![frame, top], true);
|
||||
}
|
||||
doc.insert(Some(layer), usize::MAX, top).unwrap();
|
||||
let text = program(&doc);
|
||||
let back = read_back(&doc);
|
||||
if case == "no options" {
|
||||
assert!(!text.contains("(AI11TextWrapOffset)"), "{text}");
|
||||
assert!(wraps(back.layers[0].children().unwrap()).is_empty());
|
||||
continue;
|
||||
}
|
||||
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{case}\n{text}");
|
||||
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(None, -4.5, true)]);
|
||||
let mut carrier = None;
|
||||
back.layers[0].walk(&mut |n| {
|
||||
if n.extras().wrap.is_some() {
|
||||
carrier = Some((n.locked, n.visible));
|
||||
}
|
||||
});
|
||||
assert_eq!(carrier, Some((case == "locked", case != "hidden")), "{case}");
|
||||
let want = area_wrap(&doc);
|
||||
assert_eq!(want.is_empty(), case == "hidden", "{case}");
|
||||
same_shapes(&area_wrap(&back), &want, case);
|
||||
}
|
||||
}
|
||||
|
||||
/// With too little room for the unpainted object that carries a clipping object's text wrap
|
||||
/// options, the options are left out, never written on another object, and the data stays readable.
|
||||
#[test]
|
||||
fn a_clipping_objects_text_wrap_is_left_out_without_room() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let members = vec![
|
||||
square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)),
|
||||
square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)),
|
||||
];
|
||||
let cutter = wrapped(group(&mut doc, members, false), 2.0, false);
|
||||
let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let top = group(&mut doc, vec![cutter, member], true);
|
||||
doc.insert(Some(layer), usize::MAX, top).unwrap();
|
||||
let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
|
||||
for room in 0..=all {
|
||||
let out = export_within(&doc, &opts(), room).unwrap();
|
||||
assert!(crate::import::objects_read(&out.program).unwrap() <= room);
|
||||
let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
|
||||
// The group, then the compound path of the two squares (three objects): with room for all four
|
||||
// the options are written, on that compound path.
|
||||
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), usize::from(room >= 4), "{room}\n{text}");
|
||||
let (back, _) = crate::ai_alone(&out.program).unwrap();
|
||||
let mut carriers = vec![];
|
||||
back.layers[0].walk(&mut |n| {
|
||||
if n.extras().wrap.is_some() {
|
||||
carriers.push(matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty());
|
||||
}
|
||||
});
|
||||
assert_eq!(carriers, if room >= 4 { vec![true] } else { vec![] }, "{room}\n{text}");
|
||||
}
|
||||
}
|
||||
@@ -1232,25 +1232,22 @@ impl<'a> Writer<'a> {
|
||||
|
||||
/// A container's members, the first one's outline cutting the others: its fills painted
|
||||
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text
|
||||
/// wrap options are written once: with its fills, or with its strokes when no fill object is
|
||||
/// written (it has no fills, or the region outside leaves nothing of them).
|
||||
/// wrap options are written once, under them all ([`Self::wrap_carrier`]), and not with its fills
|
||||
/// or strokes, which may be cut or left out.
|
||||
fn clip_contents(&mut self, children: &[Arc<Node>]) {
|
||||
let Some((first, rest)) = children.split_first() else { return };
|
||||
self.wrap_carrier(first);
|
||||
// Nothing to clip by hides the clipped art.
|
||||
let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return };
|
||||
let mut paint = first.clip_paint();
|
||||
for part in [&mut paint.fill, &mut paint.stroke].into_iter().flatten() {
|
||||
part.extras_mut().wrap = None;
|
||||
}
|
||||
let outer = self.clip.clone();
|
||||
let region = self.cut(&PathData::from_bezpath(&outline), rule);
|
||||
self.clip = Some(region);
|
||||
if let Some(fill) = &paint.fill {
|
||||
let objects = self.objects;
|
||||
self.node(fill);
|
||||
if self.objects > objects
|
||||
&& let Some(stroke) = &mut paint.stroke
|
||||
&& stroke.extras().wrap.is_some()
|
||||
{
|
||||
stroke.extras_mut().wrap = None;
|
||||
}
|
||||
}
|
||||
for c in rest {
|
||||
self.node(c);
|
||||
@@ -1261,6 +1258,28 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The text wrap options of clipping object `first`, when it has them, on an unpainted path
|
||||
/// (a compound path for several subpaths) of the outline area type wraps around
|
||||
/// ([`vectorcraft_doc::text::wrap_outline`]), uncut, locked and hidden as `first` is. Nothing is
|
||||
/// written for an empty outline or without room for the path ([`Self::take_objects`]).
|
||||
fn wrap_carrier(&mut self, first: &Node) {
|
||||
let Some(wrap) = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return };
|
||||
let outline = vectorcraft_doc::text::wrap_outline(first);
|
||||
if outline.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.state(first.locked, !first.visible);
|
||||
let start = self.body.len();
|
||||
self.plain_object(&outline, FillRule::NonZero, None, None, Xy::of(first).object());
|
||||
if self.body.len() == start {
|
||||
return;
|
||||
}
|
||||
self.block_end = usize::MAX;
|
||||
self.body.push_str("%_/ArtDictionary :\n");
|
||||
self.text_wrap(wrap);
|
||||
self.body.push_str("%_;\n%_\n");
|
||||
}
|
||||
|
||||
/// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path.
|
||||
fn cut(&self, path: &PathData, rule: FillRule) -> PathData {
|
||||
match &self.clip {
|
||||
|
||||
+43
-31
@@ -310,6 +310,10 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16;
|
||||
/// The estimated bytes of a name's entries in the list and the set `for-in` builds.
|
||||
const KEY_ENTRY_BYTES: usize = 32;
|
||||
|
||||
/// The most units of a computed property name an error about a property of `null` or `undefined`
|
||||
/// names; a longer name is left out of the message.
|
||||
const NAMED_KEY_UNITS: usize = 256;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at.
|
||||
@@ -1077,8 +1081,8 @@ impl Interp {
|
||||
}
|
||||
|
||||
fn not_defined(&mut self, name: &[u16]) -> Abrupt {
|
||||
let message = format!("{} is not defined", String::from_utf16_lossy(name));
|
||||
self.throw(ErrorType::Reference, &message)
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
self.throw(ErrorType::Reference, &format!("{ident} is not defined"))
|
||||
}
|
||||
|
||||
fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> {
|
||||
@@ -1332,12 +1336,9 @@ impl Interp {
|
||||
Value::Number(_) => Ok(self.intrinsics.number_proto),
|
||||
Value::Bool(_) => Ok(self.intrinsics.boolean_proto),
|
||||
Value::Undefined | Value::Null => {
|
||||
let message = format!(
|
||||
"cannot read property '{}' of {}",
|
||||
String::from_utf16_lossy(k),
|
||||
if matches!(v, Value::Null) { "null" } else { "undefined" }
|
||||
);
|
||||
Err(self.type_error(&message))
|
||||
let key = String::from_utf16_lossy(k);
|
||||
let base = if matches!(v, Value::Null) { "null" } else { "undefined" };
|
||||
Err(self.type_error(&format!("cannot read property '{key}' of {base}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1434,8 +1435,8 @@ impl Interp {
|
||||
|
||||
fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
|
||||
if throw {
|
||||
let message = format!("cannot define property '{}': {why}", String::from_utf16_lossy(k));
|
||||
return Err(self.type_error(&message));
|
||||
let key = String::from_utf16_lossy(k);
|
||||
return Err(self.type_error(&format!("cannot define property '{key}': {why}")));
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
@@ -1588,8 +1589,8 @@ impl Interp {
|
||||
|
||||
fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> {
|
||||
if throw {
|
||||
let message = format!("cannot assign to property '{}': {why}", String::from_utf16_lossy(k));
|
||||
return Err(self.type_error(&message));
|
||||
let key = String::from_utf16_lossy(k);
|
||||
return Err(self.type_error(&format!("cannot assign to property '{key}': {why}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1684,8 +1685,8 @@ impl Interp {
|
||||
Ok(true)
|
||||
}
|
||||
Some(_) if throw => {
|
||||
let message = format!("cannot delete property '{}'", String::from_utf16_lossy(k));
|
||||
Err(self.type_error(&message))
|
||||
let key = String::from_utf16_lossy(k);
|
||||
Err(self.type_error(&format!("cannot delete property '{key}'")))
|
||||
}
|
||||
Some(_) => Ok(false),
|
||||
}
|
||||
@@ -1703,12 +1704,9 @@ impl Interp {
|
||||
self.put(*o, k, v, throw)
|
||||
}
|
||||
Value::Undefined | Value::Null => {
|
||||
let message = format!(
|
||||
"cannot set property '{}' of {}",
|
||||
String::from_utf16_lossy(&k),
|
||||
if matches!(base, Value::Null) { "null" } else { "undefined" }
|
||||
);
|
||||
Err(self.type_error(&message))
|
||||
let key = String::from_utf16_lossy(&k);
|
||||
let base = if matches!(base, Value::Null) { "null" } else { "undefined" };
|
||||
Err(self.type_error(&format!("cannot set property '{key}' of {base}")))
|
||||
}
|
||||
_ => {
|
||||
let proto = self.primitive_proto(base, &k)?;
|
||||
@@ -1742,16 +1740,30 @@ impl Interp {
|
||||
self.replace(2, v)
|
||||
}
|
||||
|
||||
fn check_coercible(&mut self, base: &Value, k: &[u16]) -> JsResult<()> {
|
||||
if base.is_nullish() {
|
||||
self.primitive_proto(base, k)?;
|
||||
/// Throws when `base` is `null` or `undefined`, naming the property `k` when it is a primitive
|
||||
/// of at most [`NAMED_KEY_UNITS`] units, which converts without running script code, and the
|
||||
/// access as a read, or as a write when `set`.
|
||||
fn check_coercible(&mut self, base: &Value, k: Option<&Value>, set: bool) -> JsResult<()> {
|
||||
if !base.is_nullish() {
|
||||
return Ok(());
|
||||
}
|
||||
Ok(())
|
||||
let key = match k {
|
||||
Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None,
|
||||
Some(Value::Object(_)) | None => None,
|
||||
Some(k) => Some(self.to_str(k)?.to_rust_string()),
|
||||
};
|
||||
let base = if matches!(base, Value::Null) { "null" } else { "undefined" };
|
||||
Err(match (key, set) {
|
||||
(Some(key), false) => self.type_error(&format!("cannot read property '{key}' of {base}")),
|
||||
(Some(key), true) => self.type_error(&format!("cannot set property '{key}' of {base}")),
|
||||
(None, false) => self.type_error(&format!("cannot read a property of {base}")),
|
||||
(None, true) => self.type_error(&format!("cannot set a property of {base}")),
|
||||
})
|
||||
}
|
||||
|
||||
fn op_check_object(&mut self) -> JsResult<()> {
|
||||
let base = self.peek(0)?;
|
||||
self.check_coercible(&base, &[])
|
||||
self.check_coercible(&base, None, true)
|
||||
}
|
||||
|
||||
fn op_to_key(&mut self) -> JsResult<()> {
|
||||
@@ -1760,7 +1772,7 @@ impl Interp {
|
||||
if self.is_xml_access(&base, &k) {
|
||||
return Ok(());
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
self.check_coercible(&base, Some(&k), true)?;
|
||||
let name = self.to_key(&k)?;
|
||||
self.replace(1, Value::String(Str::from_rc(name)))
|
||||
}
|
||||
@@ -1778,7 +1790,7 @@ impl Interp {
|
||||
let v = self.xml_get(&base, &k)?;
|
||||
return self.replace(2, v);
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
self.check_coercible(&base, Some(&k), false)?;
|
||||
let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?;
|
||||
self.replace(2, v)?;
|
||||
if with_this { self.push(base) } else { Ok(()) }
|
||||
@@ -1817,7 +1829,7 @@ impl Interp {
|
||||
let r = self.xml_delete(&base, &k)?;
|
||||
return self.replace(2, Value::Bool(r));
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
self.check_coercible(&base, Some(&k), false)?;
|
||||
let name = self.to_key(&k)?;
|
||||
let o = self.to_object(&base)?;
|
||||
let strict = self.strict();
|
||||
@@ -1850,7 +1862,7 @@ impl Interp {
|
||||
self.xml_put(&base, &k, &Value::Number(new))?;
|
||||
return self.replace(2, Value::Number(if prefix { new } else { old }));
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
self.check_coercible(&base, Some(&k), false)?;
|
||||
let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?;
|
||||
self.replace(2, r)
|
||||
}
|
||||
@@ -2573,8 +2585,8 @@ impl Interp {
|
||||
self.put(object, name.clone(), v, true)
|
||||
}
|
||||
Some(_) => {
|
||||
let message = format!("cannot declare function {}", String::from_utf16_lossy(name));
|
||||
Err(self.type_error(&message))
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
Err(self.type_error(&format!("cannot declare function {ident}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,6 +239,27 @@ fn errors_carry_line_and_column() {
|
||||
assert_eq!(e.message, "42");
|
||||
}
|
||||
|
||||
/// An error about a property of `null` or `undefined` names a computed property whose name is a
|
||||
/// primitive, and says whether the script read or set it, never naming an empty property; a
|
||||
/// member assignment, an object key and a long name leave the name out.
|
||||
#[test]
|
||||
fn errors_about_null_and_undefined_name_the_property() {
|
||||
for (source, message) in [
|
||||
("null[1]", "TypeError: cannot read property '1' of null"),
|
||||
("var u; u['k'] += 1", "TypeError: cannot set property 'k' of undefined"),
|
||||
("var u; u['k']++", "TypeError: cannot read property 'k' of undefined"),
|
||||
("delete null[true]", "TypeError: cannot read property 'true' of null"),
|
||||
("var u; u['k'] = 1", "TypeError: cannot set property 'k' of undefined"),
|
||||
("null.x", "TypeError: cannot read property 'x' of null"),
|
||||
("var u; u.y = 1", "TypeError: cannot set a property of undefined"),
|
||||
("var u; u[{}] = 1", "TypeError: cannot set a property of undefined"),
|
||||
("null[new Array(300).join('a')]", "TypeError: cannot read a property of null"),
|
||||
] {
|
||||
assert_eq!(fail(source).message, message, "{source}");
|
||||
}
|
||||
truth("var k = {toString: function () { throw 1; }}; try { null[k]; false } catch (e) { e instanceof TypeError }");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_functions_receive_arguments_and_return_values() {
|
||||
let mut realm = Realm::new();
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places
|
||||
//! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along
|
||||
//! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes
|
||||
//! ([`divide_dashes`]) and the Parametric Shape Tool's shapes ([`shapes`]).
|
||||
//! ([`divide_dashes`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch
|
||||
//! two or three shapes ([`tangent_circles`]).
|
||||
|
||||
mod crossings;
|
||||
mod dashes;
|
||||
@@ -12,6 +13,7 @@ mod extend;
|
||||
pub mod shapes;
|
||||
mod shared_edge;
|
||||
mod slide;
|
||||
mod tangent_circle;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod trim;
|
||||
@@ -28,6 +30,7 @@ pub use shared_edge::{
|
||||
COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at,
|
||||
};
|
||||
pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at};
|
||||
pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLES, TangentCircleError, tangent_circle_segments, tangent_circles};
|
||||
pub use trim::{Span, slice, span_at, spans, without_spans};
|
||||
|
||||
use crate::fit::{end_tangent, start_tangent};
|
||||
|
||||
@@ -226,6 +226,27 @@ impl Default for Work {
|
||||
}
|
||||
}
|
||||
|
||||
impl Work {
|
||||
/// One `n`th of the work of [`Work::default`] (all of it for `n` of 0 or 1).
|
||||
pub const fn share(n: usize) -> Work {
|
||||
let n = if n == 0 { 1 } else { n };
|
||||
Work { pairs: MAX_PAIRS / n, steps: MAX_STEPS / n }
|
||||
}
|
||||
|
||||
/// The work done since the budget was `before`.
|
||||
pub fn spent_since(self, before: Work) -> Work {
|
||||
Work { pairs: before.pairs.saturating_sub(self.pairs), steps: before.steps.saturating_sub(self.steps) }
|
||||
}
|
||||
|
||||
/// Take `cost` (from [`Work::spent_since`]) out of what is left, as if that work were done
|
||||
/// again. `None`, leaving the budget as it was, when less than `cost` is left.
|
||||
pub fn draw(&mut self, cost: Work) -> Option<()> {
|
||||
let (pairs, steps) = (self.pairs.checked_sub(cost.pairs)?, self.steps.checked_sub(cost.steps)?);
|
||||
*self = Work { pairs, steps };
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself
|
||||
/// included): the places on `path`, in order, within the work of [`Work::default`].
|
||||
pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> {
|
||||
|
||||
@@ -0,0 +1,744 @@
|
||||
//! Tangent Circle: the circles that touch two shapes and have a given radius, or that touch three
|
||||
//! shapes. A circle touches a shape when it meets the shape's outline without crossing it: the
|
||||
//! whole outline lies outside the circle (its nearest point is on the circle) or inside it (its
|
||||
//! farthest point is on the circle). At a smooth point of the outline the circle is tangent there;
|
||||
//! at a corner or an open end it passes through that point.
|
||||
//!
|
||||
//! When every shape is a four-segment Bézier circle the answer is closed-form (the problem of
|
||||
//! Apollonius for three), then moved onto the drawn outlines.
|
||||
//! Otherwise the centers are isolated on a grid that is split where a root can be: the distance
|
||||
//! from a point to an outline changes by at most the distance the point moves, so a cell whose
|
||||
//! center is too far from every condition holds no center and is dropped. The cells left are
|
||||
//! refined with Newton's method on the exact curves.
|
||||
|
||||
use kurbo::{CubicBez, ParamCurve, Point, Vec2};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Most segments the shapes may hold together, counted by [`tangent_circle_segments`].
|
||||
pub const MAX_TANGENT_CIRCLE_SEGMENTS: usize = 2_000;
|
||||
|
||||
/// The segments of `p`'s subpaths, a lone anchor counting as one.
|
||||
pub fn tangent_circle_segments(p: &PathData) -> usize {
|
||||
p.subpaths.iter().map(|sp| sp.segment_count().max(usize::from(!sp.anchors.is_empty()))).sum()
|
||||
}
|
||||
/// Most circles one call returns.
|
||||
pub const MAX_TANGENT_CIRCLES: usize = 64;
|
||||
/// With three shapes, the largest radius looked for, as a multiple of the diagonal of the box
|
||||
/// around the shapes' anchors and handles.
|
||||
const MAX_RADIUS_FACTOR: f64 = 64.0;
|
||||
|
||||
/// A circle by its center and radius.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Circle {
|
||||
pub center: Point,
|
||||
pub radius: f64,
|
||||
}
|
||||
|
||||
/// Why [`tangent_circles`] gives no answer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TangentCircleError {
|
||||
/// Not two shapes with a radius above 0, nor three shapes without one; or a shape with no
|
||||
/// outline, or values that are not finite.
|
||||
BadInput,
|
||||
/// More than [`MAX_TANGENT_CIRCLE_SEGMENTS`] segments, or a search that would take too long.
|
||||
TooComplex,
|
||||
/// More than [`MAX_TANGENT_CIRCLES`] circles: the shapes may be touched along a whole curve
|
||||
/// (two concentric circles, for example).
|
||||
TooMany,
|
||||
}
|
||||
|
||||
/// The circles that touch every one of `shapes` (document coordinates): two shapes and `radius`,
|
||||
/// or three shapes and no radius. They are listed by radius, then top to bottom, then left to
|
||||
/// right; an empty list when no circle touches them all.
|
||||
pub fn tangent_circles(shapes: &[&PathData], radius: Option<f64>) -> Result<Vec<Circle>, TangentCircleError> {
|
||||
use TangentCircleError::*;
|
||||
match (shapes.len(), radius) {
|
||||
(2, Some(r)) if r.is_finite() && r > 0.0 => {}
|
||||
(3, None) => {}
|
||||
_ => return Err(BadInput),
|
||||
}
|
||||
if shapes.iter().map(|p| tangent_circle_segments(p)).sum::<usize>() > MAX_TANGENT_CIRCLE_SEGMENTS {
|
||||
return Err(TooComplex);
|
||||
}
|
||||
let mut bounds = None::<kurbo::Rect>;
|
||||
// The smallest shape's diagonal.
|
||||
let mut smallest = f64::INFINITY;
|
||||
for p in shapes {
|
||||
if p.subpaths.iter().all(|sp| sp.anchors.is_empty()) {
|
||||
return Err(BadInput);
|
||||
}
|
||||
let b = p.control_bounds().ok_or(BadInput)?;
|
||||
smallest = smallest.min(b.width().hypot(b.height()));
|
||||
bounds = Some(bounds.map_or(b, |a| a.union(b)));
|
||||
}
|
||||
let bounds = bounds.ok_or(BadInput)?;
|
||||
let finite = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite());
|
||||
// The work is done about the bounds' center and in units of their diagonal.
|
||||
let origin = bounds.center();
|
||||
let scale = bounds.width().hypot(bounds.height());
|
||||
if !finite || !scale.is_finite() || scale <= 0.0 {
|
||||
return Err(BadInput);
|
||||
}
|
||||
let local = |p: Point| Point::new((p.x - origin.x) / scale, (p.y - origin.y) / scale);
|
||||
let r = radius.map(|r| r / scale);
|
||||
if r.is_some_and(|r| !r.is_finite()) {
|
||||
// Shapes so small that the radius is past any number in their units.
|
||||
return Err(BadInput);
|
||||
}
|
||||
let circles: Option<Vec<Circle>> =
|
||||
shapes.iter().map(|p| as_circle(p).map(|c| Circle { center: local(c.center), radius: c.radius / scale })).collect();
|
||||
// Two of three shapes the same circle up to rounding, or two copies of the same path: every
|
||||
// circle touching it and the third touches all three.
|
||||
let same = |a: &Circle, b: &Circle| (a.center - b.center).hypot() <= COPY && (a.radius - b.radius).abs() <= COPY;
|
||||
if shapes.len() == 3
|
||||
&& (0..3).any(|i| match &circles {
|
||||
Some(c) => same(&c[i], &c[(i + 1) % 3]),
|
||||
None => shapes[i] == shapes[(i + 1) % 3],
|
||||
})
|
||||
{
|
||||
return Err(TooMany);
|
||||
}
|
||||
let outlines: Vec<Outline> = shapes.iter().map(|p| Outline::new(p, &local)).collect();
|
||||
let found = match circles {
|
||||
Some(c) => {
|
||||
let exact = match r {
|
||||
Some(r) => two_circles(c[0], c[1], r)?,
|
||||
None => apollonius(c[0], c[1], c[2]).into_iter().filter(|c| c.radius <= MAX_RADIUS_FACTOR).collect(),
|
||||
};
|
||||
// The paths are Bézier circles: each answer is polished on their outlines.
|
||||
exact.into_iter().map(|found| on_outlines(&outlines, &c, r, found)).collect()
|
||||
}
|
||||
None => numeric(&outlines, r)?,
|
||||
};
|
||||
// Answers about a shape far smaller than the gaps between the shapes can be closer together than
|
||||
// `SAME`: the tolerance shrinks with that shape.
|
||||
let tolerance = SAME.min(smallest / scale * 1e-3).max(COPY);
|
||||
let mut out = dedup(found, tolerance);
|
||||
if out.len() > MAX_TANGENT_CIRCLES {
|
||||
return Err(TooMany);
|
||||
}
|
||||
sort(&mut out, tolerance);
|
||||
Ok(out
|
||||
.into_iter()
|
||||
.map(|c| Circle { center: Point::new(origin.x + c.center.x * scale, origin.y + c.center.y * scale), radius: c.radius * scale })
|
||||
.filter(|c| c.center.x.is_finite() && c.center.y.is_finite() && c.radius.is_finite())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `found`, an answer for the ideal circles `ideal`, moved by Newton's method to touch the
|
||||
/// `outlines` of the paths themselves in the same way: each circle's outline lies outside the answer
|
||||
/// (nearest point), or inside it when the answer holds that circle (farthest point). `found` as it
|
||||
/// is when the method does not settle nearby: where the answer is within the Bézier circles' own
|
||||
/// error (0.0273% of the radius) of touching them in two places or none, it follows the true
|
||||
/// circles.
|
||||
fn on_outlines(outlines: &[Outline], ideal: &[Circle], r: Option<f64>, found: Circle) -> Circle {
|
||||
let mut combo = 0;
|
||||
for (i, c) in ideal.iter().enumerate() {
|
||||
let d = (found.center - c.center).hypot();
|
||||
let holds = (d + c.radius - found.radius).abs();
|
||||
if holds < (d - c.radius - found.radius).abs() && holds < (c.radius - d - found.radius).abs() {
|
||||
combo |= 1 << i;
|
||||
}
|
||||
}
|
||||
newton(outlines, r, combo, found.center, 1e-4, &mut 0.0)
|
||||
.filter(|c| (c.center - found.center).hypot() <= 1e-3 && (c.radius - found.radius).abs() <= 1e-3)
|
||||
.unwrap_or(found)
|
||||
}
|
||||
|
||||
/// `path` as a circle when it is a four-segment Bézier circle: one closed subpath of four curved
|
||||
/// segments with a square bounding box, lying within 0.03% of the radius of a circle (its largest
|
||||
/// error is 0.0273%).
|
||||
fn as_circle(path: &PathData) -> Option<Circle> {
|
||||
let [sp] = path.subpaths.as_slice() else { return None };
|
||||
if !sp.closed || sp.segment_count() != 4 || (0..4).any(|i| sp.segment_is_line(i)) {
|
||||
return None;
|
||||
}
|
||||
let b = path.bounds()?;
|
||||
let radius = (b.width() + b.height()) / 4.0;
|
||||
if !radius.is_finite() || radius <= 0.0 || (b.width() - b.height()).abs() > 1e-6 * radius {
|
||||
return None;
|
||||
}
|
||||
let center = b.center();
|
||||
let near = |p: Point| ((p - center).hypot() - radius).abs() <= 3e-4 * radius;
|
||||
let round = (0..sp.segment_count()).all(|i| {
|
||||
let seg = sp.segment(i);
|
||||
(0..=16).all(|k| near(seg.eval(k as f64 / 16.0)))
|
||||
});
|
||||
round.then_some(Circle { center, radius })
|
||||
}
|
||||
|
||||
/// Below this (in units of the bounds' diagonal) two values are the same.
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
/// The circles of radius `r` touching circles `a` and `b`: their centers are `a.radius + r` from
|
||||
/// `a`'s center (outside it) or `|a.radius - r|` (inside it, or holding it), and the same for `b`.
|
||||
/// A distance of 0 (`r` equal to that circle's radius) puts the center on that circle's center.
|
||||
/// Concentric circles at a distance both allow touch along a whole circle: [`TangentCircleError::TooMany`].
|
||||
fn two_circles(a: Circle, b: Circle, r: f64) -> Result<Vec<Circle>, TangentCircleError> {
|
||||
let mut out = vec![];
|
||||
let apart = (a.center - b.center).hypot();
|
||||
let only = |ok: bool, p: Point| if ok { vec![p] } else { vec![] };
|
||||
for da in [a.radius + r, (a.radius - r).abs()] {
|
||||
for db in [b.radius + r, (b.radius - r).abs()] {
|
||||
let centers = match (da <= EPS, db <= EPS) {
|
||||
(true, true) => only(apart <= EPS, a.center),
|
||||
(true, false) => only((apart - db).abs() <= EPS, a.center),
|
||||
(false, true) => only((apart - da).abs() <= EPS, b.center),
|
||||
(false, false) if apart <= EPS && (da - db).abs() <= EPS => return Err(TangentCircleError::TooMany),
|
||||
(false, false) => circle_crossings(a.center, da, b.center, db),
|
||||
};
|
||||
out.extend(centers.into_iter().map(|center| Circle { center, radius: r }));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where the circle about `c1` of radius `r1` meets the one about `c2` of radius `r2`: none, one
|
||||
/// where they touch, or two.
|
||||
fn circle_crossings(c1: Point, r1: f64, c2: Point, r2: f64) -> Vec<Point> {
|
||||
let v = c2 - c1;
|
||||
let d = v.hypot();
|
||||
if d <= EPS || d > r1 + r2 + EPS || d < (r1 - r2).abs() - EPS {
|
||||
return vec![];
|
||||
}
|
||||
let along = (d * d + r1 * r1 - r2 * r2) / (2.0 * d);
|
||||
let h2 = r1 * r1 - along * along;
|
||||
let u = v / d;
|
||||
let foot = c1 + u * along;
|
||||
// Only rounding takes a touching pair below 0; two crossings closer than `SAME` become one later.
|
||||
if h2 <= 0.0 {
|
||||
return vec![foot];
|
||||
}
|
||||
let n = Vec2::new(-u.y, u.x) * h2.sqrt();
|
||||
vec![foot + n, foot - n]
|
||||
}
|
||||
|
||||
/// The circles touching circles `c` (the problem of Apollonius): for each choice of outside (+)
|
||||
/// or inside (−) per circle, `|center − cᵢ|² = (r ± rᵢ)²`. Subtracting the first equation from the
|
||||
/// others leaves two linear equations in x, y and r; two of the three unknowns follow from the
|
||||
/// third, and the first equation gives a quadratic in it.
|
||||
fn apollonius(a: Circle, b: Circle, c: Circle) -> Vec<Circle> {
|
||||
let cs = [a, b, c];
|
||||
let mut out = vec![];
|
||||
for signs in 0..8u8 {
|
||||
let s = [0, 1, 2].map(|i| if signs & (1 << i) == 0 { 1.0 } else { -1.0 });
|
||||
let (x1, y1, r1) = (cs[0].center.x, cs[0].center.y, cs[0].radius * s[0]);
|
||||
let row = |i: usize| {
|
||||
let (x, y, ri) = (cs[i].center.x, cs[i].center.y, cs[i].radius * s[i]);
|
||||
([2.0 * (x - x1), 2.0 * (y - y1), 2.0 * (ri - r1)], (x * x + y * y - ri * ri) - (x1 * x1 + y1 * y1 - r1 * r1))
|
||||
};
|
||||
let (m1, b1) = row(1);
|
||||
let (m2, b2) = row(2);
|
||||
// Keep the third unknown free whose 2×2 minor is largest.
|
||||
let minor = |i: usize, j: usize| m1[i] * m2[j] - m1[j] * m2[i];
|
||||
let Some((free, (i, j))) =
|
||||
[(2, (0, 1)), (1, (0, 2)), (0, (1, 2))].into_iter().max_by(|p, q| minor(p.1.0, p.1.1).abs().total_cmp(&minor(q.1.0, q.1.1).abs()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let det = minor(i, j);
|
||||
if det.abs() <= EPS {
|
||||
continue;
|
||||
}
|
||||
// vᵢ = αᵢ + βᵢ t, vⱼ = αⱼ + βⱼ t, with t the free unknown.
|
||||
let alpha_i = (b1 * m2[j] - b2 * m1[j]) / det;
|
||||
let beta_i = (-m1[free] * m2[j] + m2[free] * m1[j]) / det;
|
||||
let alpha_j = (m1[i] * b2 - m2[i] * b1) / det;
|
||||
let beta_j = (-m1[i] * m2[free] + m2[i] * m1[free]) / det;
|
||||
let unknowns = |t: f64| {
|
||||
let mut v = [0.0; 3];
|
||||
v[free] = t;
|
||||
v[i] = alpha_i + beta_i * t;
|
||||
v[j] = alpha_j + beta_j * t;
|
||||
v
|
||||
};
|
||||
// (x − x1)² + (y − y1)² − (r + r1)² as a quadratic in t.
|
||||
let [v0, v1] = [unknowns(0.0), unknowns(1.0)];
|
||||
let lin = [v0[0] - x1, v0[1] - y1, v0[2] + r1];
|
||||
let dir = [v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]];
|
||||
let qa = dir[0] * dir[0] + dir[1] * dir[1] - dir[2] * dir[2];
|
||||
let qb = 2.0 * (lin[0] * dir[0] + lin[1] * dir[1] - lin[2] * dir[2]);
|
||||
let qc = lin[0] * lin[0] + lin[1] * lin[1] - lin[2] * lin[2];
|
||||
for t in quadratic_roots(qa, qb, qc) {
|
||||
let [x, y, r] = unknowns(t);
|
||||
if r > EPS && [x, y, r].iter().all(|v| v.is_finite()) {
|
||||
out.push(Circle { center: Point::new(x, y), radius: r });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The real roots of `a t² + b t + c`, a double root once; none when every coefficient is 0.
|
||||
fn quadratic_roots(a: f64, b: f64, c: f64) -> Vec<f64> {
|
||||
let size = a.abs().max(b.abs()).max(c.abs());
|
||||
if size == 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
let (a, b, c) = (a / size, b / size, c / size);
|
||||
if a.abs() <= EPS {
|
||||
return if b.abs() <= EPS { vec![] } else { vec![-c / b] };
|
||||
}
|
||||
let disc = b * b - 4.0 * a * c;
|
||||
if disc < -1e-12 {
|
||||
return vec![];
|
||||
}
|
||||
if disc <= 1e-12 {
|
||||
return vec![-b / (2.0 * a)];
|
||||
}
|
||||
// The root that adds magnitudes first; with b = 0 either sign does.
|
||||
let q = if b < 0.0 { -0.5 * (b - disc.sqrt()) } else { -0.5 * (b + disc.sqrt()) };
|
||||
vec![q / a, c / q]
|
||||
}
|
||||
|
||||
/// Circles closer than this (in units of the bounds' diagonal) are one.
|
||||
const SAME: f64 = 1e-6;
|
||||
/// Given circles closer than this (in units of the bounds' diagonal) are copies of one circle.
|
||||
const COPY: f64 = 1e-12;
|
||||
|
||||
/// Sorts `circles` (local units) by radius, then top to bottom, then left to right. Values within
|
||||
/// `tolerance` of each other (the radii of mirror images, for example) sort as equal.
|
||||
fn sort(circles: &mut [Circle], tolerance: f64) {
|
||||
let key = |v: f64| (v / tolerance).round();
|
||||
circles.sort_by(|a, b| {
|
||||
key(a.radius).total_cmp(&key(b.radius)).then(key(a.center.y).total_cmp(&key(b.center.y))).then(key(a.center.x).total_cmp(&key(b.center.x)))
|
||||
});
|
||||
}
|
||||
|
||||
/// `found` with each circle within `tolerance` of an earlier one left out.
|
||||
fn dedup(found: Vec<Circle>, tolerance: f64) -> Vec<Circle> {
|
||||
let mut out: Vec<Circle> = vec![];
|
||||
for c in found {
|
||||
if !out.iter().any(|o| (o.center - c.center).hypot() <= tolerance && (o.radius - c.radius).abs() <= tolerance) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A shape's outline, in local units: its segments, and chords that lie within `slack` of them.
|
||||
struct Outline {
|
||||
segments: Vec<CubicBez>,
|
||||
/// Each segment's neighbors along its subpath (before, after), where it has them.
|
||||
beside: Vec<(Option<usize>, Option<usize>)>,
|
||||
/// (start, end, segment, t at start, t at end).
|
||||
chords: Vec<(Point, Point, usize, f64, f64)>,
|
||||
/// The farthest the chords are from the segments.
|
||||
slack: f64,
|
||||
}
|
||||
|
||||
/// How far chords may stray from their segment, at most (local units); each segment is cut into
|
||||
/// at most [`MAX_CHORDS`] chords, so a tightly bent one may stray more.
|
||||
const CHORD_SLACK: f64 = 1e-3;
|
||||
const MAX_CHORDS: usize = 64;
|
||||
|
||||
impl Outline {
|
||||
fn new(path: &PathData, local: &dyn Fn(Point) -> Point) -> Self {
|
||||
let mut o = Outline { segments: vec![], beside: vec![], chords: vec![], slack: 0.0 };
|
||||
for sp in &path.subpaths {
|
||||
let n = sp.segment_count();
|
||||
if n == 0 {
|
||||
if let Some(a) = sp.anchors.first() {
|
||||
// A lone anchor: a segment that stays on its point.
|
||||
let p = local(a.p);
|
||||
o.segments.push(CubicBez::new(p, p, p, p));
|
||||
o.beside.push((None, None));
|
||||
o.chords.push((p, p, o.segments.len() - 1, 0.0, 1.0));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let first = o.segments.len();
|
||||
for i in 0..n {
|
||||
let s = sp.segment(i);
|
||||
let seg = CubicBez::new(local(s.p0), local(s.p1), local(s.p2), local(s.p3));
|
||||
let k = o.segments.len();
|
||||
let before = if i > 0 { Some(k - 1) } else { sp.closed.then_some(first + n - 1) };
|
||||
let after = if i + 1 < n { Some(k + 1) } else { sp.closed.then_some(first) };
|
||||
// |B''| is at most 6 × the larger second difference; a chord over a parameter step
|
||||
// h strays at most |B''| h² / 8.
|
||||
let bend = 6.0
|
||||
* (seg.p0.to_vec2() - 2.0 * seg.p1.to_vec2() + seg.p2.to_vec2())
|
||||
.hypot()
|
||||
.max((seg.p1.to_vec2() - 2.0 * seg.p2.to_vec2() + seg.p3.to_vec2()).hypot());
|
||||
let pieces = ((bend / (8.0 * CHORD_SLACK)).sqrt().ceil() as usize).clamp(1, MAX_CHORDS);
|
||||
o.slack = o.slack.max(bend / (8.0 * (pieces * pieces) as f64));
|
||||
let mut prev = seg.p0;
|
||||
for j in 1..=pieces {
|
||||
let t = j as f64 / pieces as f64;
|
||||
let p = if j == pieces { seg.p3 } else { seg.eval(t) };
|
||||
o.chords.push((prev, p, k, (j - 1) as f64 / pieces as f64, t));
|
||||
prev = p;
|
||||
}
|
||||
o.segments.push(seg);
|
||||
o.beside.push((before, after));
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// The chords' nearest and farthest distance from `q`.
|
||||
fn reach(&self, q: Point) -> Reach {
|
||||
let mut r = Reach { near: f64::INFINITY, far: -1.0 };
|
||||
for &(a, b, ..) in &self.chords {
|
||||
r.near = r.near.min(chord_near(q, a, b).0);
|
||||
r.far = r.far.max((q - a).hypot()).max((q - b).hypot());
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The point of the curves nearest `q` (or farthest, `far`) and its distance. Every segment
|
||||
/// whose chords come within twice the slack of the chords' best answer may hold the true one,
|
||||
/// so each is polished from its own best chord point, and the best result is kept.
|
||||
fn extreme(&self, q: Point, far: bool) -> (Point, f64) {
|
||||
let better = |a: f64, b: f64| if far { a > b } else { a < b };
|
||||
let worst = if far { -1.0 } else { f64::INFINITY };
|
||||
// Each segment's best chord distance and the parameter where it is reached.
|
||||
let mut per = vec![(worst, 0.0); self.segments.len()];
|
||||
for &(a, b, seg, t0, t1) in &self.chords {
|
||||
let (d, u) = if far {
|
||||
let (da, db) = ((q - a).hypot(), (q - b).hypot());
|
||||
if db > da { (db, 1.0) } else { (da, 0.0) }
|
||||
} else {
|
||||
chord_near(q, a, b)
|
||||
};
|
||||
if let Some(slot) = per.get_mut(seg)
|
||||
&& better(d, slot.0)
|
||||
{
|
||||
*slot = (d, t0 + (t1 - t0) * u);
|
||||
}
|
||||
}
|
||||
let best = per.iter().fold(worst, |m, p| if better(p.0, m) { p.0 } else { m });
|
||||
let window = 2.0 * self.slack + 1e-12;
|
||||
let mut out: Option<(Point, f64)> = None;
|
||||
for (seg, &(d, t)) in per.iter().enumerate() {
|
||||
if (d - best).abs() > window {
|
||||
continue;
|
||||
}
|
||||
let mut tries = vec![(seg, t)];
|
||||
let (before, after) = self.beside.get(seg).copied().unwrap_or((None, None));
|
||||
if t <= 0.0
|
||||
&& let Some(b) = before
|
||||
{
|
||||
tries.push((b, 1.0));
|
||||
}
|
||||
if t >= 1.0
|
||||
&& let Some(a) = after
|
||||
{
|
||||
tries.push((a, 0.0));
|
||||
}
|
||||
for (s, t) in tries {
|
||||
let Some(curve) = self.segments.get(s) else { continue };
|
||||
let (p, d) = polish(*curve, q, t, far);
|
||||
if out.is_none_or(|(_, od)| better(d, od)) {
|
||||
out = Some((p, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.unwrap_or((q, 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// The distance from `q` to the chord from `a` to `b`, and the parameter along it where it is reached.
|
||||
fn chord_near(q: Point, a: Point, b: Point) -> (f64, f64) {
|
||||
let ab = b - a;
|
||||
let len2 = ab.hypot2();
|
||||
let u = if len2 > 0.0 { ((q - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
((q - (a + ab * u)).hypot(), u)
|
||||
}
|
||||
|
||||
struct Reach {
|
||||
near: f64,
|
||||
far: f64,
|
||||
}
|
||||
|
||||
/// The nearest (or farthest) point to `q` on `seg` near parameter `t`: Newton's method on
|
||||
/// (B(t) − q)·B′(t) = 0, kept in 0..1, keeping only steps that improve the distance.
|
||||
fn polish(seg: CubicBez, q: Point, t: f64, far: bool) -> (Point, f64) {
|
||||
let dist = |t: f64| (seg.eval(t) - q).hypot();
|
||||
let better = |a: f64, b: f64| if far { a > b } else { a < b };
|
||||
let (mut t, mut d) = (t, dist(t));
|
||||
let [p0, p1, p2, p3] = [seg.p0, seg.p1, seg.p2, seg.p3].map(Point::to_vec2);
|
||||
for _ in 0..16 {
|
||||
let mt = 1.0 - t;
|
||||
let d1 = 3.0 * (mt * mt * (p1 - p0) + 2.0 * mt * t * (p2 - p1) + t * t * (p3 - p2));
|
||||
let d2 = 6.0 * (mt * (p2 - 2.0 * p1 + p0) + t * (p3 - 2.0 * p2 + p1));
|
||||
let w = seg.eval(t) - q;
|
||||
let f = w.dot(d1);
|
||||
let df = d1.hypot2() + w.dot(d2);
|
||||
if df == 0.0 || !df.is_finite() {
|
||||
break;
|
||||
}
|
||||
let next = (t - f / df).clamp(0.0, 1.0);
|
||||
let nd = dist(next);
|
||||
if !better(nd, d) && nd != d {
|
||||
break;
|
||||
}
|
||||
let moved = (next - t).abs();
|
||||
(t, d) = (next, nd);
|
||||
if moved < 1e-15 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(seg.eval(t), d)
|
||||
}
|
||||
|
||||
/// Most grid cells the search looks at, over all levels.
|
||||
const MAX_CELLS: usize = 400_000;
|
||||
/// Most cells × chords the search may measure.
|
||||
const MAX_WORK: f64 = 1.5e8;
|
||||
/// Most cells Newton's method starts from.
|
||||
const MAX_TRIES: usize = 4_000;
|
||||
/// Most chords Newton's method may measure, over all its starts.
|
||||
const MAX_NEWTON_WORK: f64 = 1.5e8;
|
||||
|
||||
/// Which of a shape's two distances a condition uses: the nearest point (the outline outside the
|
||||
/// circle) or the farthest (the outline inside it).
|
||||
fn far_of(combo: usize, shape: usize) -> bool {
|
||||
combo & (1 << shape) != 0
|
||||
}
|
||||
|
||||
/// The circles touching `outlines` (local units): two outlines and radius `r`, or three and none.
|
||||
fn numeric(outlines: &[Outline], r: Option<f64>) -> Result<Vec<Circle>, TangentCircleError> {
|
||||
let n = outlines.len();
|
||||
let combos = 1usize << n;
|
||||
let slack = outlines.iter().map(|o| o.slack).fold(0.0, f64::max);
|
||||
let chords: usize = outlines.iter().map(|o| o.chords.len()).sum();
|
||||
let reach = match r {
|
||||
Some(r) => r,
|
||||
None => MAX_RADIUS_FACTOR,
|
||||
};
|
||||
// A center is within the radius of a point of every outline, so within its bounds grown by it.
|
||||
let mut area: Option<kurbo::Rect> = None;
|
||||
let mut whole: Option<kurbo::Rect> = None;
|
||||
for o in outlines {
|
||||
let b = o.chords.iter().fold(None::<kurbo::Rect>, |b, &(p, q, ..)| {
|
||||
let c = kurbo::Rect::from_points(p, q);
|
||||
Some(b.map_or(c, |b| b.union(c)))
|
||||
});
|
||||
let Some(b) = b else { return Err(TangentCircleError::BadInput) };
|
||||
whole = Some(whole.map_or(b, |w| w.union(b)));
|
||||
let b = b.inflate(reach + slack, reach + slack);
|
||||
area = Some(area.map_or(b, |a| a.intersect(b)));
|
||||
}
|
||||
let whole = whole.ok_or(TangentCircleError::BadInput)?.inflate(slack, slack);
|
||||
let span = whole.width().hypot(whole.height());
|
||||
let Some(area) = area.filter(|a| a.width() >= 0.0 && a.height() >= 0.0) else { return Ok(vec![]) };
|
||||
let side = area.width().max(area.height()).max(1e-12);
|
||||
let leaf = 2.0 * slack.max(1e-4);
|
||||
let mut half = side / 2.0;
|
||||
// The cells alive at the current level: (center, combos still possible).
|
||||
let all = (1u32 << combos) - 1;
|
||||
let mut cells = vec![(area.center(), all)];
|
||||
let mut looked = 0usize;
|
||||
let test = |c: Point, half: f64, alive: u32| -> u32 {
|
||||
let corner = half * std::f64::consts::SQRT_2;
|
||||
let e = corner + slack;
|
||||
// Seen from far off, the directions to any two points of the outlines differ little, and
|
||||
// so do the gradients of their distances: the difference of two distances changes by at
|
||||
// most 2 × span / (distance to the outlines) per unit moved, rather than 2.
|
||||
let off = {
|
||||
let dx = (whole.x0 - c.x).max(c.x - whole.x1).max(0.0);
|
||||
let dy = (whole.y0 - c.y).max(c.y - whole.y1).max(0.0);
|
||||
dx.hypot(dy) - corner
|
||||
};
|
||||
let steep = if off > 0.0 { (2.0 * span / off).min(2.0) } else { 2.0 };
|
||||
let apart = steep * corner + 2.0 * slack;
|
||||
let reach: Vec<Reach> = outlines.iter().map(|o| o.reach(c)).collect();
|
||||
let d = |i: usize, combo: usize| if far_of(combo, i) { reach[i].far } else { reach[i].near };
|
||||
let mut keep = 0;
|
||||
for combo in 0..combos {
|
||||
if alive & (1 << combo) == 0 {
|
||||
continue;
|
||||
}
|
||||
let ok = match r {
|
||||
Some(r) => (0..n).all(|i| (d(i, combo) - r).abs() <= e),
|
||||
None => {
|
||||
let (d0, d1, d2) = (d(0, combo), d(1, combo), d(2, combo));
|
||||
(d0 - d1).abs() <= apart && (d0 - d2).abs() <= apart && (d1 - d2).abs() <= apart && d0 - e <= MAX_RADIUS_FACTOR
|
||||
}
|
||||
};
|
||||
if ok {
|
||||
keep |= 1 << combo;
|
||||
}
|
||||
}
|
||||
keep
|
||||
};
|
||||
loop {
|
||||
looked += cells.len();
|
||||
if looked > MAX_CELLS || looked as f64 * chords as f64 > MAX_WORK {
|
||||
return Err(TangentCircleError::TooComplex);
|
||||
}
|
||||
cells = cells.into_iter().filter_map(|(c, alive)| Some((c, test(c, half, alive))).filter(|x| x.1 != 0)).collect();
|
||||
if half * std::f64::consts::SQRT_2 <= leaf || cells.is_empty() {
|
||||
break;
|
||||
}
|
||||
let q = half / 2.0;
|
||||
cells = cells
|
||||
.into_iter()
|
||||
.flat_map(|(c, alive)| [(-q, -q), (q, -q), (-q, q), (q, q)].map(|(dx, dy)| (Point::new(c.x + dx, c.y + dy), alive)))
|
||||
.collect();
|
||||
half = q;
|
||||
}
|
||||
// The leaf cells of each combination, in clusters of touching cells. Newton's method starts
|
||||
// from up to [`SEEDS`] cells of each cluster, each the farthest from those before it. A cluster
|
||||
// around one center (or two that nearly meet) gives one or two circles; three or more far apart
|
||||
// mean the shapes are touched along a whole curve.
|
||||
let step = 2.0 * half;
|
||||
let mut out = vec![];
|
||||
let mut tries = 0usize;
|
||||
let mut work = 0.0;
|
||||
let same = |a: &Circle, b: &Circle| (a.center - b.center).hypot() <= SAME && (a.radius - b.radius).abs() <= SAME;
|
||||
let mut solve = |seed: Point, combo: usize| -> Result<Option<Circle>, TangentCircleError> {
|
||||
tries += 1;
|
||||
let c = newton(outlines, r, combo, seed, half, &mut work);
|
||||
if tries > MAX_TRIES || work > MAX_NEWTON_WORK {
|
||||
return Err(TangentCircleError::TooComplex);
|
||||
}
|
||||
Ok(c)
|
||||
};
|
||||
for combo in 0..combos {
|
||||
let leaves: Vec<Point> = cells.iter().filter(|(_, a)| a & (1 << combo) != 0).map(|(c, _)| *c).collect();
|
||||
let mut found: Vec<Circle> = vec![];
|
||||
for cluster in clusters(&leaves, step) {
|
||||
let mut seeds: Vec<Point> = vec![];
|
||||
let mut here: Vec<Circle> = vec![];
|
||||
while seeds.len() < SEEDS {
|
||||
let next = cluster
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|c| (c, seeds.iter().map(|s| (*s - c).hypot()).fold(f64::INFINITY, f64::min)))
|
||||
.max_by(|a, b| a.1.total_cmp(&b.1));
|
||||
let Some((seed, gap)) = next else { break };
|
||||
if !seeds.is_empty() && gap <= 2.0 * step {
|
||||
break;
|
||||
}
|
||||
seeds.push(seed);
|
||||
if let Some(c) = solve(seed, combo)?
|
||||
&& !here.iter().any(|o| same(o, &c))
|
||||
{
|
||||
here.push(c);
|
||||
}
|
||||
}
|
||||
if here.len() > 2 {
|
||||
return Err(TangentCircleError::TooMany);
|
||||
}
|
||||
for c in here {
|
||||
if !found.iter().any(|o| same(o, &c)) {
|
||||
found.push(c);
|
||||
}
|
||||
}
|
||||
if found.len() > MAX_TANGENT_CIRCLES {
|
||||
return Err(TangentCircleError::TooMany);
|
||||
}
|
||||
}
|
||||
out.extend(found);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Seeds Newton's method starts from in one cluster of cells, at most.
|
||||
const SEEDS: usize = 4;
|
||||
|
||||
/// `cells`, centers on a grid `step` apart, in groups of cells that touch (sides or corners).
|
||||
fn clusters(cells: &[Point], step: f64) -> Vec<Vec<Point>> {
|
||||
use std::collections::HashMap;
|
||||
let Some(first) = cells.first() else { return vec![] };
|
||||
let key = |p: &Point| (((p.x - first.x) / step).round() as i64, ((p.y - first.y) / step).round() as i64);
|
||||
let mut at: HashMap<(i64, i64), usize> = cells.iter().enumerate().map(|(i, p)| (key(p), i)).collect();
|
||||
let mut out = vec![];
|
||||
for p in cells {
|
||||
let Some(start) = at.remove(&key(p)) else { continue };
|
||||
let mut group = vec![];
|
||||
let mut stack = vec![start];
|
||||
while let Some(i) = stack.pop() {
|
||||
let Some(c) = cells.get(i) else { continue };
|
||||
group.push(*c);
|
||||
let (kx, ky) = key(c);
|
||||
for dx in -1..=1 {
|
||||
for dy in -1..=1 {
|
||||
if let Some(j) = at.remove(&(kx + dx, ky + dy)) {
|
||||
stack.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(group);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Newton's method from `seed` on the conditions of `combo`: with `r`, distance(i) = r for both
|
||||
/// outlines; without, the three distances equal (the radius). Adds the chords it measures to `work`.
|
||||
fn newton(outlines: &[Outline], r: Option<f64>, combo: usize, seed: Point, step: f64, work: &mut f64) -> Option<Circle> {
|
||||
let mut c = seed;
|
||||
let n = outlines.len();
|
||||
let cost: f64 = outlines.iter().map(|o| o.chords.len() as f64).sum();
|
||||
let limit = (step * 8.0).max(1e-3);
|
||||
// A radius the search sets itself (three shapes) is kept within its limit.
|
||||
let fits = |radius: f64| radius > EPS && (r.is_some() || radius <= MAX_RADIUS_FACTOR);
|
||||
for _ in 0..60 {
|
||||
*work += cost;
|
||||
let mut d = [0.0; 3];
|
||||
let mut u = [Vec2::ZERO; 3];
|
||||
for i in 0..n {
|
||||
let (p, di) = outlines[i].extreme(c, far_of(combo, i));
|
||||
if di <= EPS {
|
||||
return None;
|
||||
}
|
||||
d[i] = di;
|
||||
u[i] = (c - p) / di;
|
||||
}
|
||||
let (f, rows, radius) = match r {
|
||||
Some(r) => ([d[0] - r, d[1] - r], [u[0], u[1]], r),
|
||||
None => ([d[0] - d[1], d[0] - d[2]], [u[0] - u[1], u[0] - u[2]], d[0]),
|
||||
};
|
||||
if f[0].abs().max(f[1].abs()) <= 1e-12 {
|
||||
return fits(radius).then_some(Circle { center: c, radius });
|
||||
}
|
||||
let det = rows[0].cross(rows[1]);
|
||||
let mut delta = if det.abs() > 1e-9 {
|
||||
// J Δ = −f, with J's rows the gradients.
|
||||
Vec2::new(-(f[0] * rows[1].y - f[1] * rows[0].y) / det, -(rows[0].x * f[1] - rows[1].x * f[0]) / det)
|
||||
} else {
|
||||
// Rows (nearly) parallel: the least-squares step (JᵀJ + λI) Δ = −Jᵀf, which still
|
||||
// closes the residual along the rows' direction.
|
||||
let g = rows[0] * f[0] + rows[1] * f[1];
|
||||
let lambda = 1e-12;
|
||||
let (a, b, d) = (
|
||||
rows[0].x * rows[0].x + rows[1].x * rows[1].x + lambda,
|
||||
rows[0].x * rows[0].y + rows[1].x * rows[1].y,
|
||||
rows[0].y * rows[0].y + rows[1].y * rows[1].y + lambda,
|
||||
);
|
||||
let m = a * d - b * b;
|
||||
if !m.is_finite() || m == 0.0 {
|
||||
break;
|
||||
}
|
||||
Vec2::new(-(d * g.x - b * g.y) / m, -(a * g.y - b * g.x) / m)
|
||||
};
|
||||
let len = delta.hypot();
|
||||
if !len.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if len > limit {
|
||||
delta *= limit / len;
|
||||
}
|
||||
c += delta;
|
||||
if delta.hypot() <= 1e-15 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Stopped short of 1e-12: keep it only when it is close (a double root converges slowly).
|
||||
*work += cost;
|
||||
let mut d = [0.0; 3];
|
||||
for i in 0..n {
|
||||
d[i] = outlines[i].extreme(c, far_of(combo, i)).1;
|
||||
}
|
||||
let (worst, radius) = match r {
|
||||
Some(r) => ((d[0] - r).abs().max((d[1] - r).abs()), r),
|
||||
None => ((d[0] - d[1]).abs().max((d[0] - d[2]).abs()), d[0]),
|
||||
};
|
||||
(worst <= 1e-8 && fits(radius)).then_some(Circle { center: c, radius })
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
use kurbo::{Affine, Point, Rect};
|
||||
use vectorcraft_geom::{PathData, SubPath, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn circle(x: f64, y: f64, r: f64) -> PathData {
|
||||
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r))
|
||||
}
|
||||
|
||||
fn square(x: f64, y: f64, half: f64) -> PathData {
|
||||
shapes::rectangle(Rect::new(x - half, y - half, x + half, y + half))
|
||||
}
|
||||
|
||||
/// Is `c` touching the ideal circle about `center` of radius `r`: `|c − center| = c.r ± r`?
|
||||
fn touches_circle(c: &Circle, center: Point, r: f64, tol: f64) -> bool {
|
||||
let d = (c.center - center).hypot();
|
||||
(d - (c.radius + r)).abs() <= tol || (d - (c.radius - r).abs()).abs() <= tol
|
||||
}
|
||||
|
||||
/// The nearest and farthest distance from `q` to points `pts`, a dense sampling of a curve.
|
||||
fn reach(pts: &[Point], q: Point) -> (f64, f64) {
|
||||
pts.iter().fold((f64::INFINITY, 0.0), |(lo, hi), p| {
|
||||
let d = (*p - q).hypot();
|
||||
(lo.min(d), hi.max(d))
|
||||
})
|
||||
}
|
||||
|
||||
/// Does circle `c` touch the densely sampled outline `pts`: its nearest or farthest point on the circle?
|
||||
fn touches(c: &Circle, pts: &[Point], tol: f64) -> bool {
|
||||
let (lo, hi) = reach(pts, c.center);
|
||||
(lo - c.radius).abs() <= tol || (hi - c.radius).abs() <= tol
|
||||
}
|
||||
|
||||
/// Points along every segment of `path`, `n` per segment.
|
||||
fn samples(path: &PathData, n: usize) -> Vec<Point> {
|
||||
path.subpaths
|
||||
.iter()
|
||||
.flat_map(|sp| (0..sp.segment_count()).flat_map(move |i| (0..n).map(move |k| sp.segment(i).eval(k as f64 / n as f64))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn has(found: &[Circle], center: Point, r: f64, tol: f64) -> bool {
|
||||
found.iter().any(|c| (c.center - center).hypot() <= tol && (c.radius - r).abs() <= tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_circles_give_the_eight_apollonius_circles() {
|
||||
// Equal circles about the corners of a 3-4-5 triangle: the circumcenter (2, 1.5) at 2.5 from
|
||||
// each center gives the circle outside all three (r = 2.5 − 1) and the one holding all three
|
||||
// (r = 2.5 + 1).
|
||||
let shapes = [circle(0.0, 0.0, 1.0), circle(4.0, 0.0, 1.0), circle(0.0, 3.0, 1.0)];
|
||||
let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap();
|
||||
// The answers are polished on the Bézier circles, which stray up to 0.0273% of their radius
|
||||
// from the ideal ones.
|
||||
let tol = 2e-3;
|
||||
assert_eq!(found.len(), 8, "{found:?}");
|
||||
assert!(has(&found, Point::new(2.0, 1.5), 1.5, tol), "{found:?}");
|
||||
assert!(has(&found, Point::new(2.0, 1.5), 3.5, tol), "{found:?}");
|
||||
for c in &found {
|
||||
for (center, r) in [(Point::new(0.0, 0.0), 1.0), (Point::new(4.0, 0.0), 1.0), (Point::new(0.0, 3.0), 1.0)] {
|
||||
assert!(touches_circle(c, center, r, tol), "{c:?} and {center:?}");
|
||||
}
|
||||
}
|
||||
// Listed by radius.
|
||||
assert!(found.windows(2).all(|w| w[0].radius <= w[1].radius + 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_for_circles_touch_the_drawn_bezier_outlines() {
|
||||
// Radius-100 Bézier circles stray up to 0.027 pt from the ideal circles; the answers touch the
|
||||
// drawn outlines far closer than that.
|
||||
let shapes = [circle(0.0, 0.0, 100.0), circle(500.0, 40.0, 100.0), circle(180.0, 420.0, 100.0)];
|
||||
let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap();
|
||||
assert_eq!(found.len(), 8, "{found:?}");
|
||||
let dense: Vec<Vec<Point>> = shapes.iter().map(|s| samples(s, 20_000)).collect();
|
||||
for c in &found {
|
||||
for pts in &dense {
|
||||
assert!(touches(c, pts, 1e-3), "{c:?}");
|
||||
}
|
||||
}
|
||||
let pair = tangent_circles(&[&shapes[0], &shapes[1]], Some(250.0)).unwrap();
|
||||
assert!(!pair.is_empty());
|
||||
for c in &pair {
|
||||
assert!(touches(c, &dense[0], 1e-3) && touches(c, &dense[1], 1e-3), "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_circles_of_different_sizes() {
|
||||
// A worked case: circles (0,0) r 1, (10,0) r 2, (5,8) r 3. Every answer satisfies the
|
||||
// tangency equations, and there are eight since no circle holds or crosses another.
|
||||
let defs = [(0.0, 0.0, 1.0), (10.0, 0.0, 2.0), (5.0, 8.0, 3.0)];
|
||||
let shapes = defs.map(|(x, y, r)| circle(x, y, r));
|
||||
let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap();
|
||||
assert_eq!(found.len(), 8, "{found:?}");
|
||||
for c in &found {
|
||||
for (x, y, r) in defs {
|
||||
assert!(touches_circle(c, Point::new(x, y), r, 5e-3), "{c:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_true_circles_take_the_closed_form() {
|
||||
assert!(as_circle(&circle(0.0, 0.0, 100.0)).is_some());
|
||||
// Turned, a Bézier circle keeps its square box.
|
||||
assert!(as_circle(&circle(0.0, 0.0, 100.0).transformed(Affine::rotate(0.35))).is_some());
|
||||
// A 200 × 200.1 ellipse is searched along its own outline.
|
||||
assert!(as_circle(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.1))).is_none());
|
||||
assert!(as_circle(&square(0.0, 0.0, 10.0)).is_none());
|
||||
// A 720-sided polygon lies within 0.03% of its circle, but is searched as drawn.
|
||||
let polygon: Vec<Point> = (0..720)
|
||||
.map(|k| Point::new(100.0 * (k as f64 / 360.0 * std::f64::consts::PI).cos(), 100.0 * (k as f64 / 360.0 * std::f64::consts::PI).sin()))
|
||||
.collect();
|
||||
assert!(as_circle(&PathData::single(SubPath::polyline(&polygon, true))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quadratics_without_a_linear_term_give_both_roots() {
|
||||
let mut roots = quadratic_roots(1.0, 0.0, -1.0);
|
||||
roots.sort_by(f64::total_cmp);
|
||||
assert_eq!(roots, vec![-1.0, 1.0]);
|
||||
let mut roots = quadratic_roots(2.0, -0.0, -8.0);
|
||||
roots.sort_by(f64::total_cmp);
|
||||
assert_eq!(roots, vec![-2.0, 2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_circles_keep_the_radius_limit() {
|
||||
// Nearly in a row: some answers have radii near 1250, past 64 × the bounds' diagonal (about 770).
|
||||
let shapes = [circle(0.0, 0.0, 1.0), circle(10.0, 0.0, 1.0), circle(5.0, 0.01, 1.0)];
|
||||
let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap();
|
||||
let b = shapes.iter().map(|s| s.control_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap();
|
||||
let limit = MAX_RADIUS_FACTOR * b.width().hypot(b.height());
|
||||
assert!(!found.is_empty() && found.len() < 8, "{found:?}");
|
||||
assert!(found.iter().all(|c| c.radius <= limit), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_and_a_radius() {
|
||||
let a = circle(0.0, 0.0, 10.0);
|
||||
let b = circle(30.0, 0.0, 10.0);
|
||||
// Polished on the Bézier circles (see above).
|
||||
let tol = 0.02;
|
||||
// Radius 5: only the circle in the gap, touching both at once.
|
||||
let found = tangent_circles(&[&a, &b], Some(5.0)).unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(has(&found, Point::new(15.0, 0.0), 5.0, tol));
|
||||
// Radius 20: two outside both, two holding the first and two holding the second.
|
||||
let found = tangent_circles(&[&a, &b], Some(20.0)).unwrap();
|
||||
assert_eq!(found.len(), 6, "{found:?}");
|
||||
let h = (30.0f64 * 30.0 - 15.0 * 15.0).sqrt();
|
||||
assert!(has(&found, Point::new(15.0, -h), 20.0, tol) && has(&found, Point::new(15.0, h), 20.0, tol));
|
||||
for c in &found {
|
||||
assert!(touches_circle(c, Point::new(0.0, 0.0), 10.0, tol) && touches_circle(c, Point::new(30.0, 0.0), 10.0, tol));
|
||||
}
|
||||
// Top to bottom for one radius.
|
||||
assert!(found.windows(2).all(|w| w[0].center.y <= w[1].center.y + 1e-9));
|
||||
// Radius 10, the circles' own, 20 apart: each circle itself touches the other at one point; with
|
||||
// the two outside both, four in all.
|
||||
let c = circle(20.0, 0.0, 10.0);
|
||||
let found = tangent_circles(&[&a, &c], Some(10.0)).unwrap();
|
||||
assert_eq!(found.len(), 4, "{found:?}");
|
||||
assert!(has(&found, Point::new(0.0, 0.0), 10.0, tol) && has(&found, Point::new(20.0, 0.0), 10.0, tol), "{found:?}");
|
||||
for f in &found {
|
||||
assert!(touches_circle(f, Point::new(0.0, 0.0), 10.0, tol) && touches_circle(f, Point::new(20.0, 0.0), 10.0, tol), "{f:?}");
|
||||
}
|
||||
// Too small to reach across: none.
|
||||
let far = circle(100.0, 0.0, 10.0);
|
||||
assert_eq!(tangent_circles(&[&a, &far], Some(5.0)).unwrap(), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_numeric_search_agrees_with_the_closed_form() {
|
||||
// The grid search and Newton on the Bézier outlines find what the closed form finds, within
|
||||
// the Bézier circle's own error (0.03% of the radius).
|
||||
let defs = [(0.0, 0.0, 10.0), (35.0, 5.0, 6.0), (12.0, 30.0, 4.0)];
|
||||
let shapes = defs.map(|(x, y, r)| circle(x, y, r));
|
||||
let refs = [&shapes[0], &shapes[1], &shapes[2]];
|
||||
let closed = tangent_circles(&refs, None).unwrap();
|
||||
let b = shapes.iter().map(|s| s.control_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap();
|
||||
let (o, s) = (b.center(), b.width().hypot(b.height()));
|
||||
let local = |p: Point| Point::new((p.x - o.x) / s, (p.y - o.y) / s);
|
||||
let outlines: Vec<Outline> = refs.iter().map(|p| Outline::new(p, &local)).collect();
|
||||
let numeric3 = dedup(numeric(&outlines, None).unwrap(), SAME);
|
||||
assert_eq!(numeric3.len(), closed.len(), "{numeric3:?} vs {closed:?}");
|
||||
for c in &closed {
|
||||
let tol = 1e-3 * c.radius.max(10.0) / s;
|
||||
assert!(has(&numeric3, local(c.center), c.radius / s, tol), "{c:?} missing from {numeric3:?}");
|
||||
}
|
||||
let closed2 = tangent_circles(&refs[..2], Some(12.0)).unwrap();
|
||||
let numeric2 = dedup(numeric(&outlines[..2], Some(12.0 / s)).unwrap(), SAME);
|
||||
assert_eq!(numeric2.len(), closed2.len(), "{numeric2:?} vs {closed2:?}");
|
||||
for c in &closed2 {
|
||||
assert!(has(&numeric2, local(c.center), c.radius / s, 1e-2 / s), "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An ellipse with semi-axes `a` and `b` about the origin, mapped by `m`: its Bézier path and its
|
||||
/// exact points by angle.
|
||||
fn mapped_ellipse(a: f64, b: f64, m: Affine) -> (PathData, impl Fn(f64) -> Point + Copy) {
|
||||
let path = shapes::ellipse(Rect::new(-a, -b, a, b)).transformed(m);
|
||||
let exact = move |th: f64| m * Point::new(a * th.cos(), b * th.sin());
|
||||
(path, exact)
|
||||
}
|
||||
|
||||
/// Independently of the code under test: the centers of the circles of radius `r` that touch the
|
||||
/// exact convex curve `exact` (about `middle`) and the circle about `cc` of radius `rc`, in every
|
||||
/// combination. A center lies on the curve's normal at `r` (outward or inward) where its distance to
|
||||
/// `cc` is `rc + r` or `|rc − r|`; it counts when the curve's nearest or farthest point from it is
|
||||
/// at `r`.
|
||||
fn independent_centers(exact: impl Fn(f64) -> Point + Copy, middle: Point, cc: Point, rc: f64, r: f64) -> Vec<Point> {
|
||||
let tau = std::f64::consts::TAU;
|
||||
let dense: Vec<Point> = (0..100_000).map(|k| exact(k as f64 / 100_000.0 * tau)).collect();
|
||||
let n = 200_000;
|
||||
let mut out: Vec<Point> = vec![];
|
||||
for side in [1.0, -1.0] {
|
||||
let normal = move |th: f64| {
|
||||
let p = exact(th);
|
||||
let t = (exact(th + 1e-7) - exact(th - 1e-7)).normalize();
|
||||
let mut nrm = Vec2::new(t.y, -t.x);
|
||||
if nrm.dot(p - middle) < 0.0 {
|
||||
nrm = -nrm;
|
||||
}
|
||||
p + nrm * (side * r)
|
||||
};
|
||||
for target in [rc + r, (rc - r).abs()] {
|
||||
let g = |th: f64| (normal(th) - cc).hypot() - target;
|
||||
for k in 0..n {
|
||||
let (mut a, mut b) = (k as f64 / n as f64 * tau, (k + 1) as f64 / n as f64 * tau);
|
||||
if g(a) * g(b) < 0.0 {
|
||||
for _ in 0..60 {
|
||||
let m = (a + b) / 2.0;
|
||||
if g(a) * g(m) <= 0.0 { b = m } else { a = m }
|
||||
}
|
||||
let q = normal(a);
|
||||
let (lo, hi) = reach(&dense, q);
|
||||
let touching = (lo - r).abs() <= 1e-3 || (hi - r).abs() <= 1e-3;
|
||||
if touching && !out.iter().any(|o| (*o - q).hypot() <= 1e-6) {
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `found` and `independent` are the same centers, within `tol`.
|
||||
fn same_centers(found: &[Circle], independent: &[Point], tol: f64) {
|
||||
assert_eq!(found.len(), independent.len(), "{found:?} vs {independent:?}");
|
||||
for p in independent {
|
||||
assert!(found.iter().any(|c| (c.center - *p).hypot() <= tol), "{p:?} missing from {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_ellipse_and_a_circle_match_an_independent_solve() {
|
||||
let (ellipse, exact) = mapped_ellipse(40.0, 20.0, Affine::rotate(30f64.to_radians()));
|
||||
let (cc, rc, r) = (Point::new(70.0, 10.0), 12.0, 15.0);
|
||||
let disc = circle(cc.x, cc.y, rc);
|
||||
let found = tangent_circles(&[&ellipse, &disc], Some(r)).unwrap();
|
||||
// Every circle touches the analytic ellipse and the circle (Bézier error: 0.03% of 40 pt).
|
||||
let dense: Vec<Point> = (0..200_000).map(|k| exact(k as f64 / 200_000.0 * std::f64::consts::TAU)).collect();
|
||||
for c in &found {
|
||||
assert!(touches(c, &dense, 0.03), "{c:?}");
|
||||
assert!(touches_circle(c, cc, rc, 0.01), "{c:?}");
|
||||
}
|
||||
// Every combination (outside both, holding the circle, holding the ellipse, inside it) solved
|
||||
// independently: the same circles.
|
||||
same_centers(&found, &independent_centers(exact, Point::ZERO, cc, rc, r), 0.05);
|
||||
// A circle overlapping the ellipse, with a radius large enough to hold either.
|
||||
let (cc, rc, r) = (Point::new(30.0, 5.0), 15.0, 50.0);
|
||||
let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap();
|
||||
same_centers(&found, &independent_centers(exact, Point::ZERO, cc, rc, r), 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_and_skewed_ellipse_matches_an_independent_solve() {
|
||||
let m = Affine::translate((-20.0, 15.0)) * Affine::skew(0.4, 0.0) * Affine::rotate(-0.7);
|
||||
let (ellipse, exact) = mapped_ellipse(30.0, 12.0, m);
|
||||
let (cc, rc, r) = (Point::new(15.0, 30.0), 8.0, 20.0);
|
||||
let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap();
|
||||
let independent = independent_centers(exact, m * Point::ZERO, cc, rc, r);
|
||||
assert!(!independent.is_empty());
|
||||
same_centers(&found, &independent, 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_centers_close_together_are_both_found() {
|
||||
// An ellipse 20 × 10 about (100, 0) and a circle of radius 10 about the origin: a circle of
|
||||
// radius 35 fits the 70 pt gap between them on the axis. At 35.000003 two circles touch both
|
||||
// from outside, about 0.011 pt above and below the axis.
|
||||
let (ellipse, exact) = mapped_ellipse(20.0, 10.0, Affine::translate((100.0, 0.0)));
|
||||
let (cc, rc, r) = (Point::ZERO, 10.0, 35.000003);
|
||||
let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap();
|
||||
let independent = independent_centers(exact, Point::new(100.0, 0.0), cc, rc, r);
|
||||
assert_eq!(independent.iter().filter(|p| (p.x - 45.0).abs() < 1.0).count(), 2, "{independent:?}");
|
||||
same_centers(&found, &independent, 0.005);
|
||||
// Two tiny circles a million points apart, and a radius just past half the gap: the two
|
||||
// answers are about 22.36 pt above and below the axis, close together in units of the gap.
|
||||
let (a, b) = (circle(0.0, 0.0, 0.01), circle(1e6, 0.0, 0.01));
|
||||
let found = tangent_circles(&[&a, &b], Some(499999.9905)).unwrap();
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
for c in &found {
|
||||
assert!((c.center.x - 5e5).abs() < 0.1 && (c.center.y.abs() - 500f64.sqrt()).abs() < 0.1, "{found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_circles_give_eight_distinct_circles_in_a_steady_order() {
|
||||
// Mirror-image pairs about y = 0 have radii equal up to rounding: the upper one comes first.
|
||||
let defs = [(0.0, -5.0, 1.0), (0.0, 5.0, 1.0), (12.0, 0.0, 2.0)];
|
||||
let shapes = defs.map(|(x, y, r)| circle(x, y, r));
|
||||
let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap();
|
||||
for (i, a) in found.iter().enumerate() {
|
||||
for b in &found[i + 1..] {
|
||||
assert!((a.center - b.center).hypot() + (a.radius - b.radius).abs() > 1e-3, "{a:?} twice in {found:?}");
|
||||
}
|
||||
}
|
||||
for w in found.windows(2) {
|
||||
if (w[0].radius - w[1].radius).abs() <= 1e-9 {
|
||||
assert!(w[0].center.y < w[1].center.y, "{found:?}");
|
||||
}
|
||||
}
|
||||
// The selection mirrored left to right: the same circles mirrored, in the same order.
|
||||
let flip = Affine::scale_non_uniform(-1.0, 1.0);
|
||||
let mirrored = shapes.clone().map(|s| s.transformed(flip));
|
||||
let again = tangent_circles(&[&mirrored[0], &mirrored[1], &mirrored[2]], None).unwrap();
|
||||
assert_eq!(again.len(), found.len());
|
||||
for (a, b) in found.iter().zip(&again) {
|
||||
assert!((flip * a.center - b.center).hypot() <= 1e-6 && (a.radius - b.radius).abs() <= 1e-6, "{found:?} vs {again:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radii_equal_up_to_rounding_sort_top_to_bottom() {
|
||||
let lower = Circle { center: Point::new(0.0, 0.2), radius: 0.1 };
|
||||
let upper = Circle { center: Point::new(0.0, -0.2), radius: 0.1 + 1e-13 };
|
||||
let wider = Circle { center: Point::new(0.0, -0.5), radius: 0.2 };
|
||||
let mut v = [wider, lower, upper];
|
||||
sort(&mut v, SAME);
|
||||
assert_eq!(v, [upper, lower, wider]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_point_is_looked_for_on_every_segment_it_may_be_on() {
|
||||
// An arc bulging to y = −0.3 whose one chord lies on y = 0, and a line on y = −0.25. Seen from
|
||||
// (0, −1), the line's chord is nearer (0.75 against 1.0), but the arc itself is (0.7).
|
||||
let arc = CubicBez::new((-1.0, 0.0), (-1.0, -0.4), (1.0, -0.4), (1.0, 0.0));
|
||||
let line = CubicBez::new((-0.5, -0.25), (-0.2, -0.25), (0.2, -0.25), (0.5, -0.25));
|
||||
let outline = Outline {
|
||||
segments: vec![arc, line],
|
||||
beside: vec![(None, None), (None, None)],
|
||||
chords: vec![(arc.p0, arc.p3, 0, 0.0, 1.0), (line.p0, line.p3, 1, 0.0, 1.0)],
|
||||
slack: 0.3,
|
||||
};
|
||||
let (p, d) = outline.extreme(Point::new(0.0, -1.0), false);
|
||||
assert!((d - 0.7).abs() <= 1e-9 && (p - Point::new(0.0, -0.3)).hypot() <= 1e-9, "{p:?} {d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_among_three_shapes_are_a_whole_family() {
|
||||
use TangentCircleError::*;
|
||||
// A circle turned and turned back differs from itself by rounding only.
|
||||
let b = circle(3.0, 7.0, 20.0);
|
||||
let turned = b.transformed(Affine::rotate(0.3)).transformed(Affine::rotate(-0.3));
|
||||
assert_ne!(b, turned);
|
||||
assert_eq!(tangent_circles(&[&b, &turned, &circle(100.0, 0.0, 5.0)], None), Err(TooMany));
|
||||
// Two copies of a square.
|
||||
let sq = square(0.0, 0.0, 10.0);
|
||||
assert_eq!(tangent_circles(&[&sq, &sq.clone(), &square(60.0, 0.0, 10.0)], None), Err(TooMany));
|
||||
// Two circles half a point apart, a million points from the third, are not copies.
|
||||
let far = [circle(0.0, 0.0, 10.0), circle(0.0, 0.5, 10.0), circle(1e6, 0.0, 10.0)];
|
||||
assert_ne!(tangent_circles(&[&far[0], &far[1], &far[2]], None), Err(TooMany));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_squares_are_solved_numerically() {
|
||||
let shapes = [square(0.0, 0.0, 10.0), square(60.0, 0.0, 10.0), square(30.0, 50.0, 10.0)];
|
||||
let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap();
|
||||
assert!(!found.is_empty());
|
||||
let dense: Vec<Vec<Point>> = shapes.iter().map(|s| samples(s, 4000)).collect();
|
||||
for c in &found {
|
||||
for pts in &dense {
|
||||
assert!(touches(c, pts, 0.01), "{c:?}");
|
||||
}
|
||||
}
|
||||
// By symmetry, the circle in the middle touching all three from outside is centered on x = 30.
|
||||
let inner = found.iter().find(|c| (c.center.x - 30.0).abs() < 1e-6 && c.center.y > 0.0 && c.center.y < 40.0);
|
||||
assert!(inner.is_some(), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_and_far_off_paths_give_the_same_circles_moved() {
|
||||
// A ring (two subpaths of one path) and a small square in its hole.
|
||||
let mut ring = circle(0.0, 0.0, 50.0);
|
||||
ring.subpaths.extend(circle(0.0, 0.0, 30.0).subpaths);
|
||||
let dot = square(0.0, 0.0, 5.0);
|
||||
// Radius 12: in the hole 18 from the center, and 12 from a corner of the square: two by each
|
||||
// corner.
|
||||
let found = tangent_circles(&[&ring, &dot], Some(12.0)).unwrap();
|
||||
assert_eq!(found.len(), 8, "{found:?}");
|
||||
let (ring_pts, dot_pts) = (samples(&ring, 4000), samples(&dot, 4000));
|
||||
for c in &found {
|
||||
assert!(touches(c, &ring_pts, 0.02) && touches(c, &dot_pts, 0.02), "{c:?}");
|
||||
}
|
||||
// Moved far off and scaled: the same circles, moved and scaled.
|
||||
let m = Affine::translate((1e6, -2e6)) * Affine::scale(3.0);
|
||||
let (ring2, dot2) = (ring.transformed(m), dot.transformed(m));
|
||||
let moved = tangent_circles(&[&ring2, &dot2], Some(36.0)).unwrap();
|
||||
assert_eq!(moved.len(), found.len(), "{moved:?} vs {found:?}");
|
||||
for c in &found {
|
||||
assert!(has(&moved, m * c.center, 3.0 * c.radius, 1e-4), "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_paths_and_no_answer() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false));
|
||||
let disc = circle(50.0, 40.0, 10.0);
|
||||
// Radius 10: a center 10 from the line is at least 30 from the disc's center, never 20.
|
||||
assert_eq!(tangent_circles(&[&line, &disc], Some(10.0)).unwrap(), vec![]);
|
||||
// Radius 20: centers on y = 20, 30 from (50, 40): x = 50 ± √500.
|
||||
let found = tangent_circles(&[&line, &disc], Some(20.0)).unwrap();
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
let dx = 500f64.sqrt();
|
||||
assert!(has(&found, Point::new(50.0 - dx, 20.0), 20.0, 0.05) && has(&found, Point::new(50.0 + dx, 20.0), 20.0, 0.05), "{found:?}");
|
||||
// A given radius far past 64 × the bounds' diagonal: two short segments 10 apart and radius
|
||||
// 1000 (the limit applies only when three shapes set the radius).
|
||||
let left = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(1.0, 0.0)], false));
|
||||
let right = PathData::single(SubPath::polyline(&[Point::new(10.0, 0.0), Point::new(11.0, 0.0)], false));
|
||||
let found = tangent_circles(&[&left, &right], Some(1000.0)).unwrap();
|
||||
assert!(!found.is_empty());
|
||||
let (lp, rp) = (samples(&left, 4000), samples(&right, 4000));
|
||||
for c in &found {
|
||||
assert!(c.radius == 1000.0 && touches(c, &lp, 1e-3) && touches(c, &rp, 1e-3), "{c:?}");
|
||||
}
|
||||
// Two squares far apart with a small radius: none.
|
||||
let (a, b) = (square(0.0, 0.0, 10.0), square(500.0, 0.0, 10.0));
|
||||
assert_eq!(tangent_circles(&[&a, &b], Some(5.0)).unwrap(), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_curves_of_answers_and_bad_input_are_errors() {
|
||||
use TangentCircleError::*;
|
||||
let (a, b) = (circle(0.0, 0.0, 50.0), circle(0.0, 0.0, 20.0));
|
||||
assert_eq!(tangent_circles(&[&a, &b], Some(15.0)), Err(TooMany));
|
||||
let (outer, inner) = (square(0.0, 0.0, 50.0), square(0.0, 0.0, 20.0));
|
||||
assert_eq!(tangent_circles(&[&outer, &inner], Some(15.0)), Err(TooMany));
|
||||
assert_eq!(tangent_circles(&[&a], Some(1.0)), Err(BadInput));
|
||||
assert_eq!(tangent_circles(&[&a, &b], None), Err(BadInput));
|
||||
assert_eq!(tangent_circles(&[&a, &b, &a], Some(1.0)), Err(BadInput));
|
||||
assert_eq!(tangent_circles(&[&a, &b], Some(0.0)), Err(BadInput));
|
||||
assert_eq!(tangent_circles(&[&a, &b], Some(f64::NAN)), Err(BadInput));
|
||||
// Two of three circles the same: a whole family touches all three.
|
||||
let third = circle(100.0, 0.0, 5.0);
|
||||
assert_eq!(tangent_circles(&[&b, &b.clone(), &third], None), Err(TooMany));
|
||||
let mut reversed = b.clone();
|
||||
reversed.reverse();
|
||||
assert_eq!(tangent_circles(&[&b, &reversed, &third], None), Err(TooMany));
|
||||
// Shapes so tiny that the radius overflows in their units.
|
||||
let (tiny_a, tiny_b) = (circle(0.0, 0.0, 1e-305), circle(1e-304, 0.0, 1e-305));
|
||||
assert_eq!(tangent_circles(&[&tiny_a, &tiny_b], Some(1e6)), Err(BadInput));
|
||||
let empty = PathData::new(vec![]);
|
||||
assert_eq!(tangent_circles(&[&a, &empty], Some(1.0)), Err(BadInput));
|
||||
let big = PathData::single(SubPath::polyline(&(0..2001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect::<Vec<_>>(), false));
|
||||
assert_eq!(tangent_circles(&[&a, &big], Some(1.0)), Err(TooComplex));
|
||||
// Lone anchors count as segments.
|
||||
let dots = PathData::new((0..2001).map(|i| SubPath::polyline(&[Point::new(i as f64, 0.0)], false)).collect());
|
||||
assert_eq!(tangent_circle_segments(&dots), 2001);
|
||||
assert_eq!(tangent_circles(&[&a, &dots], Some(1.0)), Err(TooComplex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_about_a_tiny_shape_far_away_stay_apart() {
|
||||
// Each tiny circle is touched from outside and from inside: answers 0.02 pt apart on each side,
|
||||
// eight in all.
|
||||
let (a, b) = (circle(0.0, 0.0, 0.01), circle(1e6, 0.0, 0.01));
|
||||
let found = tangent_circles(&[&a, &b], Some(1e6)).unwrap();
|
||||
assert_eq!(found.len(), 8, "{found:?}");
|
||||
// All of one radius: top to bottom, then left to right.
|
||||
for w in found.windows(2) {
|
||||
let (a, b) = (w[0].center, w[1].center);
|
||||
assert!(a.y < b.y - 1e-3 || ((a.y - b.y).abs() <= 1e-3 && a.x < b.x), "{found:?}");
|
||||
}
|
||||
}
|
||||
@@ -515,6 +515,29 @@ fn one_work_budget_bounds_several_calls_together() {
|
||||
assert!(crossings_on(&path, &[]).is_some(), "a call of its own has its own budget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_done_once_can_be_drawn_again_from_another_budget() {
|
||||
let row: Vec<(f64, f64)> = (0..=1000).map(|i| (i as f64, 0.0)).collect();
|
||||
let path = PathData::single(line(&row, false));
|
||||
let start = Work::default();
|
||||
let mut work = start;
|
||||
crossings_on_within(&path, &[], &mut work).unwrap();
|
||||
let cost = work.spent_since(start);
|
||||
// Drawing a call's cost leaves what the call itself leaves, 120 times and no more.
|
||||
let mut again = Work::default();
|
||||
assert_eq!(again.draw(cost), Some(()));
|
||||
assert_eq!(again, work);
|
||||
let draws = (1..200).take_while(|_| again.draw(cost).is_some()).count();
|
||||
assert_eq!(draws, 119);
|
||||
let left = again;
|
||||
assert_eq!(again.draw(cost), None);
|
||||
assert_eq!(again, left, "a draw that fails takes nothing");
|
||||
// A twentieth of the budget pays for the call 6 times.
|
||||
assert_eq!((Work::share(0), Work::share(1)), (Work::default(), Work::default()));
|
||||
let mut part = Work::share(20);
|
||||
assert_eq!((0..200).take_while(|_| part.draw(cost).is_some()).count(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_that_loops_over_itself_crosses_itself() {
|
||||
// One cubic that meets itself at t = 0.25 and t = 0.75.
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod gif;
|
||||
pub mod jpeg;
|
||||
pub mod png;
|
||||
pub mod psd;
|
||||
mod psd_type;
|
||||
pub mod quantize;
|
||||
pub mod tga;
|
||||
pub mod tiff;
|
||||
|
||||
@@ -7,13 +7,15 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, cms};
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use super::jpeg::{self, ColorModel};
|
||||
use super::psd_type;
|
||||
use super::tiff::packbits;
|
||||
use super::{RasterExportOptions, RasterFormat, on_white};
|
||||
use crate::{RenderOptions, Rendered, Renderer, fx};
|
||||
use crate::{AntiAlias, RenderOptions, Rendered, Renderer, fx};
|
||||
|
||||
/// Most pixels a side of a PSD can have (larger images need the format's large-document variant).
|
||||
pub const MAX_SIDE: u32 = 30_000;
|
||||
@@ -33,6 +35,11 @@ pub struct PsdOptions {
|
||||
/// its objects together (a clipping mask, an opacity mask, its own appearance, knockout) stays
|
||||
/// one pixel layer.
|
||||
pub max_editability: bool,
|
||||
/// With `layers`: horizontal and vertical point type in layers and sublayers is written as type
|
||||
/// layers that a reader can edit, each with its pixels: type in solid colours without strokes,
|
||||
/// effects or an appearance of its own. A layer that holds such type becomes a group of its type
|
||||
/// layers and pixel layers of the art between them.
|
||||
pub preserve_text: bool,
|
||||
/// With `layers`: hidden layers (and hidden objects) are written as hidden layers instead of
|
||||
/// being left out.
|
||||
pub hidden_layers: bool,
|
||||
@@ -42,7 +49,7 @@ pub struct PsdOptions {
|
||||
|
||||
impl Default for PsdOptions {
|
||||
fn default() -> Self {
|
||||
Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, hidden_layers: false, embed_icc: true }
|
||||
Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, preserve_text: false, hidden_layers: false, embed_icc: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +148,8 @@ struct Record {
|
||||
hidden: bool,
|
||||
/// Section divider: [`OPEN_GROUP`] or [`END_GROUP`].
|
||||
divider: Option<u32>,
|
||||
/// A type layer's type tool object (`TySh`).
|
||||
type_tool: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Section divider kinds.
|
||||
@@ -159,6 +168,7 @@ impl Record {
|
||||
opacity: 255,
|
||||
hidden: false,
|
||||
divider: None,
|
||||
type_tool: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,6 +248,9 @@ impl Record {
|
||||
if let Some(kind) = self.divider {
|
||||
block(&mut extra, b"lsct", &[&kind.to_be_bytes()[..], b"8BIM", &self.blend].concat())?;
|
||||
}
|
||||
if let Some(data) = &self.type_tool {
|
||||
block(&mut extra, b"TySh", data)?;
|
||||
}
|
||||
out.extend(len32(extra.len())?.to_be_bytes());
|
||||
out.extend(extra);
|
||||
Ok(())
|
||||
@@ -451,13 +464,40 @@ impl Parts<'_> {
|
||||
return;
|
||||
}
|
||||
let (hidden, opacity) = (!n.visible, opacity_byte(n.opacity));
|
||||
if self.o.max_editability
|
||||
if self.o.preserve_text
|
||||
&& let Some(t) = psd_type::editable(n)
|
||||
{
|
||||
let record = self.draw(n);
|
||||
let [top, left, bottom, right] = record.rect.map(f64::from);
|
||||
let origin = Point::new(self.region.x0, self.region.y0);
|
||||
let aa = if self.ro.anti_alias == AntiAlias::None { TypeAntiAlias::None } else { t.anti_alias };
|
||||
let type_tool = Some(psd_type::type_block(t, origin, self.scale, Rect::new(left, top, right, bottom), aa));
|
||||
self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, type_tool, ..record });
|
||||
return;
|
||||
}
|
||||
let per_object = self.o.max_editability;
|
||||
let hidden_layers = self.o.hidden_layers;
|
||||
if (per_object || self.o.preserve_text && holds_type(n, hidden_layers))
|
||||
&& splits(n)
|
||||
&& let Some(children) = n.children()
|
||||
{
|
||||
self.records.push(Record { divider: Some(END_GROUP), ..Record::empty(GROUP_END.into(), self.colors()) });
|
||||
for c in children {
|
||||
self.add(c);
|
||||
if per_object {
|
||||
for c in children {
|
||||
self.add(c);
|
||||
}
|
||||
} else {
|
||||
// The art between type layers stays together, one pixel layer per stretch.
|
||||
let mut stretch: Vec<Arc<Node>> = vec![];
|
||||
for c in children {
|
||||
if type_layer(c, hidden_layers) {
|
||||
self.add_stretch(n, std::mem::take(&mut stretch));
|
||||
self.add(c);
|
||||
} else {
|
||||
stretch.push(c.clone());
|
||||
}
|
||||
}
|
||||
self.add_stretch(n, stretch);
|
||||
}
|
||||
// A group in normal blending lets its layers blend with what is below it.
|
||||
let blend = if n.blend == BlendMode::Normal && !n.isolate { *b"pass" } else { blend_key(n.blend) };
|
||||
@@ -468,6 +508,22 @@ impl Parts<'_> {
|
||||
self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, ..record });
|
||||
}
|
||||
|
||||
/// `nodes`, children of layer `layer` next to each other, drawn together as one pixel layer
|
||||
/// named after the layer (nothing when they paint nothing).
|
||||
fn add_stretch(&mut self, layer: &Node, nodes: Vec<Arc<Node>>) {
|
||||
if nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut part = layer.clone();
|
||||
if let Some(children) = part.children_mut() {
|
||||
*children = nodes;
|
||||
}
|
||||
let record = self.draw(&part);
|
||||
if record.rect != [0; 4] {
|
||||
self.records.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` drawn alone, visible, at full opacity in normal blending (its record carries those).
|
||||
fn draw(&mut self, n: &Node) -> Record {
|
||||
let name = n.display_name();
|
||||
@@ -532,6 +588,30 @@ fn splits(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { clip: false, .. }) && n.extras().mask.is_none() && n.knockout != Knockout::On && !fx::has_object_fx(n)
|
||||
}
|
||||
|
||||
/// Does layer `n`, or a sublayer that can be written as a group, hold point type that can be a type
|
||||
/// layer? Not when other art in it blends in a mode other than normal (the object, or a fill or
|
||||
/// stroke of it, as [`Node::blends_through`] sees it): drawn as a pixel layer of its own, it would no
|
||||
/// longer blend with the type or the art below. Hidden type counts only when `hidden` (Include
|
||||
/// Hidden Layers) writes it.
|
||||
fn holds_type(n: &Node, hidden: bool) -> bool {
|
||||
let Some(children) = n.children().filter(|_| splits(n)) else { return false };
|
||||
let mut held = false;
|
||||
for c in children {
|
||||
if type_layer(c, hidden) {
|
||||
held = true;
|
||||
} else if Node::children_blend(std::slice::from_ref(c), &mut |c| c.blends_through()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
held
|
||||
}
|
||||
|
||||
/// Is child `c` written as a type layer, or as a group holding one ([`holds_type`])? A hidden child
|
||||
/// is written only when `hidden`.
|
||||
fn type_layer(c: &Node, hidden: bool) -> bool {
|
||||
(c.visible || hidden) && (psd_type::editable(c).is_some() || holds_type(c, hidden))
|
||||
}
|
||||
|
||||
/// Does anything in `n` carry effects of its own that may paint outside the art's bounds?
|
||||
fn reaches_beyond(n: &Node) -> bool {
|
||||
fx::has_object_fx(n) || n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c)))
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
//! Type layers of PSD export: point type as a type tool object (the `TySh` block of the format's
|
||||
//! public specification), so a reader can edit the text. The block holds the text's transform, the
|
||||
//! text descriptor (the text, its orientation and bounds, and its `EngineData`: the runs of
|
||||
//! character and paragraph attributes with the fonts they use) and an unwarped warp descriptor.
|
||||
//! The layer keeps its pixels for readers that show them.
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
use vectorcraft_doc::{CharStyle, Composer, Justify, Node, NodeKind, ParaStyle, TextKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
/// Point type that a type layer draws as `n` draws: horizontal or vertical point type with text,
|
||||
/// whose characters use only the attributes a type layer carries ([`carried`]) in solid colours
|
||||
/// with whole-number tracking, each drawn with its own font (no fallback font), without strokes or
|
||||
/// inline graphics, whose paragraphs set only an alignment ([`flat`]) and run left to right, and
|
||||
/// without System Layout, Optical Margin Alignment, ruby, an appearance of its own, effects or an
|
||||
/// opacity mask. Other type stays pixels.
|
||||
pub(super) fn editable(n: &Node) -> Option<&TextObject> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let text = t.plain_text();
|
||||
let has_cjk = text.chars().any(cjk);
|
||||
let flat = |p: &ParaStyle| flat(p, has_cjk);
|
||||
let plain = matches!(t.kind, TextKind::Point)
|
||||
&& !text.is_empty()
|
||||
&& !t.system_layout
|
||||
&& !t.optical_margin
|
||||
&& t.ruby.is_empty()
|
||||
&& !t.stacks_warichu()
|
||||
&& flat(&t.para)
|
||||
&& t.paras.iter().all(flat)
|
||||
&& text.split('\n').enumerate().all(|(i, p)| !vectorcraft_text::paragraph_is_rtl(p, t.para_at(i).direction))
|
||||
&& n.appearance.items.is_empty()
|
||||
&& n.appearance.effects.is_empty()
|
||||
&& n.extras().mask.is_none()
|
||||
&& !crate::fx::has_object_fx(n)
|
||||
&& t.runs
|
||||
.iter()
|
||||
.all(|r| r.inline.is_none() && matches!(r.style.fill, Paint::Solid { .. }) && matches!(r.style.stroke, Paint::None) && carried(&r.style))
|
||||
// A type layer's tracking is a whole number of thousandths of an em.
|
||||
&& t.runs.iter().all(|r| r.style.tracking.fract() == 0.0)
|
||||
// The type layer names one font per run: a character its font lacks would be drawn with
|
||||
// another. Breaks, joiners and variation selectors draw no glyph of their own (as the
|
||||
// shaper's `drawn_chars` counts them).
|
||||
&& t.runs.iter().all(|r| face(&r.style).is_some_and(|f| r.text.chars().all(|c| !drawn(c) || f.covers(c))));
|
||||
plain.then_some(&**t)
|
||||
}
|
||||
|
||||
/// Does `c` need a glyph of its own: not a control character (tab, line or paragraph break), a
|
||||
/// line separator, a joiner or a variation selector?
|
||||
fn drawn(c: char) -> bool {
|
||||
!(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'))
|
||||
}
|
||||
|
||||
/// The face the text of style `s` is drawn with: its font version when that is installed.
|
||||
fn face(s: &CharStyle) -> Option<std::sync::Arc<vectorcraft_text::FontFace>> {
|
||||
vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref())
|
||||
}
|
||||
|
||||
/// Does paragraph `p` set only its alignment, the others being at their defaults (no indents,
|
||||
/// spacing, tabs, bullets or numbers, direction, Auto Leading, word or letter spacing, glyph scaling
|
||||
/// or hanging punctuation)? Settings that only choose where area type breaks its lines or what
|
||||
/// hangs where it breaks them (hyphenation, the single-line or every-line composer, kinsoku,
|
||||
/// Burasagari, Bunri-Kinshi, breaking Korean anywhere) and the paragraph style's name may be set,
|
||||
/// and so may Mojikumi when `cjk` is false (it spaces only Chinese, Japanese and Korean characters).
|
||||
/// A paragraph set to a Standard composer is not flat.
|
||||
fn flat(p: &ParaStyle, cjk: bool) -> bool {
|
||||
let only = ParaStyle {
|
||||
justify: p.justify,
|
||||
style_name: p.style_name.clone(),
|
||||
hyphenate: p.hyphenate,
|
||||
hyphenation: p.hyphenation.clone(),
|
||||
composer: if matches!(p.composer, Composer::SingleLine | Composer::EveryLine) { p.composer } else { ParaStyle::default().composer },
|
||||
kinsoku: p.kinsoku,
|
||||
kinsoku_type: p.kinsoku_type,
|
||||
burasagari: p.burasagari,
|
||||
bunri_kinshi: p.bunri_kinshi,
|
||||
korean_line_break_anywhere: p.korean_line_break_anywhere,
|
||||
mojikumi: if cjk { ParaStyle::default().mojikumi } else { p.mojikumi },
|
||||
..ParaStyle::default()
|
||||
};
|
||||
only == *p
|
||||
}
|
||||
|
||||
/// Is `c` in a block of Chinese, Japanese or Korean characters or their punctuation?
|
||||
fn cjk(c: char) -> bool {
|
||||
matches!(c, '\u{1100}'..='\u{11FF}' | '\u{2E80}'..='\u{9FFF}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{F900}'..='\u{FAFF}' | '\u{FE30}'..='\u{FE4F}' | '\u{FF00}'..='\u{FFEF}' | '\u{20000}'..='\u{3FFFF}')
|
||||
}
|
||||
|
||||
/// Does `s` set only attributes a type layer carries (font and its version, size, leading,
|
||||
/// tracking, scaling, baseline shift, all caps, underline, strikethrough, fill), the others being
|
||||
/// at their defaults? Attributes that change nothing drawn without a stroke (the stroke's own
|
||||
/// settings, overprint, the character style's name) may be set, and so may the language when it
|
||||
/// is the default, English: USA. The type layer does not record the language, so type in another
|
||||
/// language stays pixels.
|
||||
fn carried(s: &CharStyle) -> bool {
|
||||
if !s.language.as_deref().is_none_or(|l| l.eq_ignore_ascii_case("en-US")) {
|
||||
return false;
|
||||
}
|
||||
let only = CharStyle {
|
||||
language: s.language.clone(),
|
||||
font_family: s.font_family.clone(),
|
||||
font_style: s.font_style.clone(),
|
||||
font_version: s.font_version.clone(),
|
||||
size: s.size,
|
||||
leading: s.leading,
|
||||
tracking: s.tracking,
|
||||
baseline_shift: s.baseline_shift,
|
||||
h_scale: s.h_scale,
|
||||
v_scale: s.v_scale,
|
||||
fill: s.fill.clone(),
|
||||
stroke: s.stroke.clone(),
|
||||
stroke_width: s.stroke_width,
|
||||
stroke_cap: s.stroke_cap,
|
||||
stroke_join: s.stroke_join,
|
||||
stroke_miter_limit: s.stroke_miter_limit,
|
||||
stroke_dash: s.stroke_dash.clone(),
|
||||
stroke_align: s.stroke_align,
|
||||
overprint_fill: s.overprint_fill,
|
||||
overprint_stroke: s.overprint_stroke,
|
||||
style_name: s.style_name.clone(),
|
||||
underline: s.underline,
|
||||
strikethrough: s.strikethrough,
|
||||
all_caps: s.all_caps,
|
||||
..CharStyle::default()
|
||||
};
|
||||
only == *s
|
||||
}
|
||||
|
||||
/// A value of the `EngineData` text engine document.
|
||||
enum E {
|
||||
Dict(Vec<(&'static str, E)>),
|
||||
Array(Vec<E>),
|
||||
Str(String),
|
||||
Int(i64),
|
||||
Real(f64),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
impl E {
|
||||
fn is_container(&self) -> bool {
|
||||
match self {
|
||||
E::Dict(_) => true,
|
||||
E::Array(a) => a.iter().any(|v| matches!(v, E::Dict(_) | E::Array(_))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the value with tab indents and a key per line.
|
||||
fn write(&self, depth: usize, out: &mut Vec<u8>) {
|
||||
let tabs = |out: &mut Vec<u8>, n: usize| out.extend(std::iter::repeat_n(b'\t', n));
|
||||
match self {
|
||||
E::Dict(items) => {
|
||||
out.extend(b"<<\n");
|
||||
for (k, v) in items {
|
||||
tabs(out, depth + 1);
|
||||
out.push(b'/');
|
||||
out.extend(k.as_bytes());
|
||||
if v.is_container() {
|
||||
out.push(b'\n');
|
||||
tabs(out, depth + 1);
|
||||
} else {
|
||||
out.push(b' ');
|
||||
}
|
||||
v.write(depth + 1, out);
|
||||
out.push(b'\n');
|
||||
}
|
||||
tabs(out, depth);
|
||||
out.extend(b">>");
|
||||
}
|
||||
E::Array(items) if self.is_container() => {
|
||||
out.extend(b"[\n");
|
||||
for v in items {
|
||||
tabs(out, depth);
|
||||
v.write(depth, out);
|
||||
out.push(b'\n');
|
||||
}
|
||||
tabs(out, depth);
|
||||
out.push(b']');
|
||||
}
|
||||
E::Array(items) => {
|
||||
out.push(b'[');
|
||||
for v in items {
|
||||
out.push(b' ');
|
||||
v.write(depth, out);
|
||||
}
|
||||
out.extend(b" ]");
|
||||
}
|
||||
// UTF-16BE after a byte order mark, with `(`, `)` and `\` escaped.
|
||||
E::Str(s) => {
|
||||
out.push(b'(');
|
||||
for b in [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)) {
|
||||
if matches!(b, b'(' | b')' | b'\\') {
|
||||
out.push(b'\\');
|
||||
}
|
||||
out.push(b);
|
||||
}
|
||||
out.push(b')');
|
||||
}
|
||||
E::Int(i) => out.extend(i.to_string().as_bytes()),
|
||||
E::Real(r) => out.extend(real(*r).as_bytes()),
|
||||
E::Bool(b) => out.extend(if *b { &b"true"[..] } else { b"false" }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A number as the text engine writes it: `12.0`, `.5`, `-.25`; at most five decimals.
|
||||
fn real(r: f64) -> String {
|
||||
if !r.is_finite() {
|
||||
return "0.0".into();
|
||||
}
|
||||
let mut s = format!("{r:.5}");
|
||||
while s.ends_with('0') {
|
||||
s.pop();
|
||||
}
|
||||
if s.ends_with('.') {
|
||||
s.push('0');
|
||||
}
|
||||
if s == "-0.0" {
|
||||
s = "0.0".into();
|
||||
}
|
||||
match (s.strip_prefix("0."), s.strip_prefix("-0.")) {
|
||||
(Some(rest), _) if rest != "0" => format!(".{rest}"),
|
||||
(_, Some(rest)) => format!("-.{rest}"),
|
||||
_ => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// A descriptor value (the format's ActionDescriptor items).
|
||||
enum V {
|
||||
Text(String),
|
||||
Enum(&'static str, &'static str),
|
||||
Long(i32),
|
||||
Doub(f64),
|
||||
/// A unit (`#Pnt`: points) and its value.
|
||||
UntF(&'static [u8; 4], f64),
|
||||
Objc(&'static str, Vec<(&'static str, V)>),
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
/// A class, key or enumeration id: a four-character code after a zero length, else its length and
|
||||
/// bytes. `warp` is written as a string, as readers look it up.
|
||||
fn id(out: &mut Vec<u8>, s: &str) {
|
||||
if s.len() == 4 && s != "warp" {
|
||||
out.extend(0u32.to_be_bytes());
|
||||
} else {
|
||||
out.extend((s.len() as u32).to_be_bytes());
|
||||
}
|
||||
out.extend(s.as_bytes());
|
||||
}
|
||||
|
||||
/// A Unicode string: its UTF-16 unit count, then the units (`nul`: a terminating zero counted).
|
||||
fn unicode(out: &mut Vec<u8>, s: &str, nul: bool) {
|
||||
let units: Vec<u16> = s.encode_utf16().chain(nul.then_some(0)).collect();
|
||||
out.extend((units.len() as u32).to_be_bytes());
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
}
|
||||
|
||||
/// A descriptor: an empty class name, the class id, then its items.
|
||||
fn descriptor(out: &mut Vec<u8>, class: &str, items: &[(&str, V)]) {
|
||||
unicode(out, "", false);
|
||||
id(out, class);
|
||||
out.extend((items.len() as u32).to_be_bytes());
|
||||
for (key, v) in items {
|
||||
id(out, key);
|
||||
match v {
|
||||
V::Text(s) => {
|
||||
out.extend(b"TEXT");
|
||||
unicode(out, s, true);
|
||||
}
|
||||
V::Enum(ty, value) => {
|
||||
out.extend(b"enum");
|
||||
id(out, ty);
|
||||
id(out, value);
|
||||
}
|
||||
V::Long(i) => {
|
||||
out.extend(b"long");
|
||||
out.extend(i.to_be_bytes());
|
||||
}
|
||||
V::Doub(d) => {
|
||||
out.extend(b"doub");
|
||||
out.extend(d.to_be_bytes());
|
||||
}
|
||||
V::UntF(unit, d) => {
|
||||
out.extend(b"UntF");
|
||||
out.extend(*unit);
|
||||
out.extend(d.to_be_bytes());
|
||||
}
|
||||
V::Objc(class, items) => {
|
||||
out.extend(b"Objc");
|
||||
descriptor(out, class, items);
|
||||
}
|
||||
V::Raw(data) => {
|
||||
out.extend(b"tdta");
|
||||
out.extend((data.len() as u32).to_be_bytes());
|
||||
out.extend(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The PostScript name of the face the text is drawn with (the style's font version when that is
|
||||
/// installed), as type layers name fonts; without the face installed, its family and style without
|
||||
/// spaces.
|
||||
fn postscript(s: &CharStyle) -> String {
|
||||
if let Some(face) = face(s) {
|
||||
return face.postscript_name();
|
||||
}
|
||||
let squeeze = |s: &str| -> String { s.chars().filter(|c| c.is_ascii_graphic() && !"[](){}<>/%".contains(*c)).collect() };
|
||||
match s.font_style.as_str() {
|
||||
"" | "Regular" => squeeze(&s.font_family),
|
||||
style => format!("{}-{}", squeeze(&s.font_family), squeeze(style)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The character attributes of `s` at `px` pixels per point, its font being `font` in the font set.
|
||||
fn style_data(s: &CharStyle, font: usize, px: f64) -> E {
|
||||
let rgb = match &s.fill {
|
||||
Paint::Solid { color, .. } => color.to_rgb(),
|
||||
_ => [0.0; 3],
|
||||
};
|
||||
E::Dict(vec![
|
||||
("Font", E::Int(font as i64)),
|
||||
("FontSize", E::Real(s.size * px)),
|
||||
("FauxBold", E::Bool(false)),
|
||||
("FauxItalic", E::Bool(false)),
|
||||
("AutoLeading", E::Bool(s.leading.is_none())),
|
||||
("Leading", E::Real(s.leading.unwrap_or(0.0) * px)),
|
||||
("HorizontalScale", E::Real(s.h_scale / 100.0)),
|
||||
("VerticalScale", E::Real(s.v_scale / 100.0)),
|
||||
("Tracking", E::Int(s.tracking.round() as i64)),
|
||||
("AutoKerning", E::Bool(true)),
|
||||
("Kerning", E::Int(0)),
|
||||
("BaselineShift", E::Real(s.baseline_shift * px)),
|
||||
("FontCaps", E::Int(if s.all_caps { 2 } else { 0 })),
|
||||
("Underline", E::Bool(s.underline)),
|
||||
("Strikethrough", E::Bool(s.strikethrough)),
|
||||
("FillFlag", E::Bool(true)),
|
||||
("FillColor", E::Dict(vec![("Type", E::Int(1)), ("Values", E::Array([1.0, rgb[0], rgb[1], rgb[2]].map(|v| E::Real(f64::from(v))).into()))])),
|
||||
])
|
||||
}
|
||||
|
||||
/// The paragraph attributes of alignment `j`.
|
||||
fn paragraph_data(j: Justify) -> E {
|
||||
let n = match j {
|
||||
Justify::Auto | Justify::Left => 0,
|
||||
Justify::Right => 1,
|
||||
Justify::Center => 2,
|
||||
Justify::JustifyLeft => 3,
|
||||
Justify::JustifyRight => 4,
|
||||
Justify::JustifyCenter => 5,
|
||||
Justify::JustifyAll => 6,
|
||||
};
|
||||
E::Dict(vec![("Justification", E::Int(n)), ("AutoLeading", E::Real(1.2)), ("LeadingType", E::Int(0))])
|
||||
}
|
||||
|
||||
/// The anti-aliasing method `aa` as the text descriptor's `AntA` value and the `EngineData`
|
||||
/// `AntiAlias` number.
|
||||
fn anti_alias(aa: TypeAntiAlias) -> (&'static str, i64) {
|
||||
match aa {
|
||||
TypeAntiAlias::None => ("Anno", 0),
|
||||
TypeAntiAlias::Crisp => ("AnCr", 1),
|
||||
TypeAntiAlias::Strong => ("AnSt", 2),
|
||||
TypeAntiAlias::Sharp => ("AnSh", 4),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `EngineData` of `t` at `px` pixels per point, drawn with anti-aliasing `aa`: the text with a
|
||||
/// `\r` after each paragraph, a style run per text run and a paragraph run per paragraph (lengths in
|
||||
/// UTF-16 units), point type's shape, and the fonts.
|
||||
fn engine_data(t: &TextObject, px: f64, aa: TypeAntiAlias) -> Vec<u8> {
|
||||
let text = t.plain_text().replace('\n', "\r");
|
||||
let mut fonts: Vec<String> = vec![];
|
||||
let (mut styles, mut lengths) = (vec![], vec![]);
|
||||
let runs: Vec<_> = t.runs.iter().filter(|r| !r.text.is_empty()).collect();
|
||||
for (i, r) in runs.iter().enumerate() {
|
||||
let name = postscript(&r.style);
|
||||
let font = fonts.iter().position(|f| *f == name).unwrap_or_else(|| {
|
||||
fonts.push(name);
|
||||
fonts.len() - 1
|
||||
});
|
||||
styles.push(E::Dict(vec![("StyleSheet", E::Dict(vec![("StyleSheetData", style_data(&r.style, font, px))]))]));
|
||||
// The closing `\r` belongs to the last run.
|
||||
lengths.push(E::Int(r.text.encode_utf16().count() as i64 + i64::from(i + 1 == runs.len())));
|
||||
}
|
||||
let (mut paras, mut para_lengths) = (vec![], vec![]);
|
||||
for (i, p) in text.split('\r').enumerate() {
|
||||
paras.push(E::Dict(vec![(
|
||||
"ParagraphSheet",
|
||||
E::Dict(vec![("DefaultStyleSheet", E::Int(0)), ("Properties", paragraph_data(t.para_at(i).justify))]),
|
||||
)]));
|
||||
para_lengths.push(E::Int(p.encode_utf16().count() as i64 + 1));
|
||||
}
|
||||
let (writing, procession) = if t.vertical { (2, 1) } else { (0, 0) };
|
||||
let point = |x: f64, y: f64| E::Array(vec![E::Real(x), E::Real(y)]);
|
||||
let shape = E::Dict(vec![
|
||||
("ShapeType", E::Int(0)),
|
||||
("Procession", E::Int(procession)),
|
||||
("Lines", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![]))])),
|
||||
(
|
||||
"Cookie",
|
||||
E::Dict(vec![(
|
||||
"Photoshop", // brand-ok: the key's name in the files
|
||||
E::Dict(vec![
|
||||
("ShapeType", E::Int(0)),
|
||||
("PointBase", point(0.0, 0.0)),
|
||||
(
|
||||
"Base",
|
||||
E::Dict(vec![
|
||||
("ShapeType", E::Int(0)),
|
||||
("TransformPoint0", point(1.0, 0.0)),
|
||||
("TransformPoint1", point(0.0, 1.0)),
|
||||
("TransformPoint2", point(0.0, 0.0)),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)]),
|
||||
),
|
||||
]);
|
||||
let first = runs.first().map_or_else(|| style_data(&CharStyle::default(), 0, px), |r| style_data(&r.style, 0, px));
|
||||
let resources = || {
|
||||
E::Dict(vec![
|
||||
(
|
||||
"FontSet",
|
||||
E::Array(
|
||||
fonts
|
||||
.iter()
|
||||
.map(|f| E::Dict(vec![("Name", E::Str(f.clone())), ("Script", E::Int(0)), ("FontType", E::Int(1)), ("Synthetic", E::Int(0))]))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
("StyleSheetSet", E::Array(vec![E::Dict(vec![("Name", E::Str("Normal RGB".into())), ("StyleSheetData", E::Dict(vec![]))])])),
|
||||
(
|
||||
"ParagraphSheetSet",
|
||||
E::Array(vec![E::Dict(vec![
|
||||
("Name", E::Str("Normal RGB".into())),
|
||||
("DefaultStyleSheet", E::Int(0)),
|
||||
("Properties", paragraph_data(Justify::Left)),
|
||||
])]),
|
||||
),
|
||||
("TheNormalStyleSheet", E::Int(0)),
|
||||
("TheNormalParagraphSheet", E::Int(0)),
|
||||
])
|
||||
};
|
||||
let mut normal = resources();
|
||||
// The normal style sheet holds the first run's attributes.
|
||||
if let E::Dict(items) = &mut normal
|
||||
&& let Some((_, E::Array(sheets))) = items.iter_mut().find(|(k, _)| *k == "StyleSheetSet")
|
||||
&& let Some(E::Dict(sheet)) = sheets.first_mut()
|
||||
&& let Some((_, data)) = sheet.iter_mut().find(|(k, _)| *k == "StyleSheetData")
|
||||
{
|
||||
*data = first;
|
||||
}
|
||||
let doc = E::Dict(vec![
|
||||
(
|
||||
"EngineDict",
|
||||
E::Dict(vec![
|
||||
("Editor", E::Dict(vec![("Text", E::Str(format!("{text}\r")))])),
|
||||
("ParagraphRun", E::Dict(vec![("RunArray", E::Array(paras)), ("RunLengthArray", E::Array(para_lengths)), ("IsJoinable", E::Int(1))])),
|
||||
("StyleRun", E::Dict(vec![("RunArray", E::Array(styles)), ("RunLengthArray", E::Array(lengths)), ("IsJoinable", E::Int(2))])),
|
||||
("AntiAlias", E::Int(anti_alias(aa).1)),
|
||||
("UseFractionalGlyphWidths", E::Bool(t.fractional_widths)),
|
||||
(
|
||||
"Rendered",
|
||||
E::Dict(vec![
|
||||
("Version", E::Int(1)),
|
||||
("Shapes", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![shape]))])),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
("ResourceDict", resources()),
|
||||
("DocumentResources", normal),
|
||||
]);
|
||||
let mut out = b"\n\n".to_vec();
|
||||
doc.write(0, &mut out);
|
||||
out.push(b'\n');
|
||||
out
|
||||
}
|
||||
|
||||
/// The `TySh` block of point type `t`, drawn into a canvas whose top left is `origin` (document
|
||||
/// points) at `px` pixels per point with anti-aliasing `aa`; `ink` is what the layer paints, in
|
||||
/// canvas pixels. The transform maps the text's own space, in pixels with its origin at the first
|
||||
/// baseline's start, to the canvas.
|
||||
pub(super) fn type_block(t: &TextObject, origin: Point, px: f64, ink: Rect, aa: TypeAntiAlias) -> Vec<u8> {
|
||||
let [a, b, c, d, e, f] = t.xf.as_coeffs();
|
||||
let xf = Affine::new([a, b, c, d, (e - origin.x) * px, (f - origin.y) * px]);
|
||||
// The ink in text space: the canvas rectangle taken back through the transform.
|
||||
let bounds = if xf.determinant().abs() > 1e-12 && [ink.x0, ink.y0, ink.x1, ink.y1].iter().all(|v| v.is_finite()) {
|
||||
let inv = xf.inverse();
|
||||
let pts = [(ink.x0, ink.y0), (ink.x1, ink.y0), (ink.x0, ink.y1), (ink.x1, ink.y1)].map(|(x, y)| inv * Point::new(x, y));
|
||||
let (xs, ys) = (pts.map(|p| p.x), pts.map(|p| p.y));
|
||||
let (min, max) = (|v: [f64; 4]| v.into_iter().fold(f64::INFINITY, f64::min), |v: [f64; 4]| v.into_iter().fold(f64::NEG_INFINITY, f64::max));
|
||||
[min(xs), min(ys), max(xs), max(ys)]
|
||||
} else {
|
||||
[0.0; 4]
|
||||
};
|
||||
let rect = |class: &'static str| {
|
||||
V::Objc(
|
||||
class,
|
||||
vec![
|
||||
("Left", V::UntF(b"#Pnt", bounds[0])),
|
||||
("Top ", V::UntF(b"#Pnt", bounds[1])),
|
||||
("Rght", V::UntF(b"#Pnt", bounds[2])),
|
||||
("Btom", V::UntF(b"#Pnt", bounds[3])),
|
||||
],
|
||||
)
|
||||
};
|
||||
let orientation = if t.vertical { "Vrtc" } else { "Hrzn" };
|
||||
let mut out = 1u16.to_be_bytes().to_vec();
|
||||
for v in xf.as_coeffs() {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
// Text version 50, descriptor version 16.
|
||||
out.extend(50u16.to_be_bytes());
|
||||
out.extend(16u32.to_be_bytes());
|
||||
descriptor(
|
||||
&mut out,
|
||||
"TxLr",
|
||||
&[
|
||||
("Txt ", V::Text(t.plain_text().replace('\n', "\r"))),
|
||||
("textGridding", V::Enum("textGridding", "None")),
|
||||
("Ornt", V::Enum("Ornt", orientation)),
|
||||
("AntA", V::Enum("Annt", anti_alias(aa).0)),
|
||||
("bounds", rect("bounds")),
|
||||
("boundingBox", rect("boundingBox")),
|
||||
("TextIndex", V::Long(0)),
|
||||
("EngineData", V::Raw(engine_data(t, px, aa))),
|
||||
],
|
||||
);
|
||||
// Warp version 1, descriptor version 16: no warp.
|
||||
out.extend(1u16.to_be_bytes());
|
||||
out.extend(16u32.to_be_bytes());
|
||||
descriptor(
|
||||
&mut out,
|
||||
"warp",
|
||||
&[
|
||||
("warpStyle", V::Enum("warpStyle", "warpNone")),
|
||||
("warpValue", V::Doub(0.0)),
|
||||
("warpPerspective", V::Doub(0.0)),
|
||||
("warpPerspectiveOther", V::Doub(0.0)),
|
||||
("warpRotate", V::Enum("Ornt", "Hrzn")),
|
||||
],
|
||||
);
|
||||
// The warped bounds: zeros without a warp.
|
||||
out.extend([0u8; 16]);
|
||||
out
|
||||
}
|
||||
@@ -58,6 +58,8 @@ struct Rec {
|
||||
opacity: u8,
|
||||
hidden: bool,
|
||||
divider: Option<usize>,
|
||||
/// The type tool object of a type layer.
|
||||
type_tool: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The file: header channels, colour mode, image resources, layer count and records.
|
||||
@@ -95,7 +97,7 @@ fn parse(f: &[u8]) -> Parsed<'_> {
|
||||
let end = p + 16 + u32_at(f, p + 12);
|
||||
let mut q = p + 16 + 8;
|
||||
q += (1 + f[q] as usize).next_multiple_of(4);
|
||||
let (mut name, mut divider) = (String::new(), None);
|
||||
let (mut name, mut divider, mut type_tool) = (String::new(), None, None);
|
||||
while q < end {
|
||||
assert_eq!(&f[q..q + 4], b"8BIM");
|
||||
let len = u32_at(f, q + 8);
|
||||
@@ -103,11 +105,12 @@ fn parse(f: &[u8]) -> Parsed<'_> {
|
||||
match &f[q + 4..q + 8] {
|
||||
b"luni" => name = String::from_utf16(&(0..u32_at(data, 0)).map(|i| u16_at(data, 4 + i * 2)).collect::<Vec<_>>()).unwrap(),
|
||||
b"lsct" => divider = Some(u32_at(data, 0)),
|
||||
b"TySh" => type_tool = Some(data.to_vec()),
|
||||
_ => {}
|
||||
}
|
||||
q += 12 + len;
|
||||
}
|
||||
out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider });
|
||||
out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider, type_tool });
|
||||
p = end;
|
||||
}
|
||||
out
|
||||
@@ -357,6 +360,373 @@ fn the_profile_and_the_size_limit() {
|
||||
assert!(err.contains(&MAX_SIDE.to_string()), "{err}");
|
||||
}
|
||||
|
||||
/// A descriptor value as the format's specification lays it out.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Item {
|
||||
Text(String),
|
||||
Enum(String, String),
|
||||
Long(i32),
|
||||
Doub(f64),
|
||||
Unit(String, f64),
|
||||
Object(String, Vec<(String, Item)>),
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
/// Reads an id (a four-character code after a zero length, else a length and its bytes) at `at`.
|
||||
fn read_id(d: &[u8], at: &mut usize) -> String {
|
||||
let n = u32_at(d, *at);
|
||||
let len = if n == 0 { 4 } else { n };
|
||||
let s = String::from_utf8(d[*at + 4..*at + 4 + len].to_vec()).unwrap();
|
||||
*at += 4 + len;
|
||||
s
|
||||
}
|
||||
|
||||
fn read_unicode(d: &[u8], at: &mut usize) -> String {
|
||||
let n = u32_at(d, *at);
|
||||
let units: Vec<u16> = (0..n).map(|i| u16_at(d, *at + 4 + i * 2)).collect();
|
||||
*at += 4 + n * 2;
|
||||
String::from_utf16(&units).unwrap().trim_end_matches('\0').to_string()
|
||||
}
|
||||
|
||||
/// Reads a descriptor at `at`: its class and items.
|
||||
fn read_descriptor(d: &[u8], at: &mut usize) -> (String, Vec<(String, Item)>) {
|
||||
read_unicode(d, at);
|
||||
let class = read_id(d, at);
|
||||
let count = u32_at(d, *at);
|
||||
*at += 4;
|
||||
let mut items = vec![];
|
||||
for _ in 0..count {
|
||||
let key = read_id(d, at);
|
||||
let ty = d[*at..*at + 4].to_vec();
|
||||
*at += 4;
|
||||
let f64_at = |at: usize| f64::from_be_bytes(d[at..at + 8].try_into().unwrap());
|
||||
let v = match &ty[..] {
|
||||
b"TEXT" => Item::Text(read_unicode(d, at)),
|
||||
b"enum" => Item::Enum(read_id(d, at), read_id(d, at)),
|
||||
b"long" => {
|
||||
*at += 4;
|
||||
Item::Long(u32_at(d, *at - 4) as i32)
|
||||
}
|
||||
b"doub" => {
|
||||
*at += 8;
|
||||
Item::Doub(f64_at(*at - 8))
|
||||
}
|
||||
b"UntF" => {
|
||||
let unit = String::from_utf8(d[*at..*at + 4].to_vec()).unwrap();
|
||||
*at += 12;
|
||||
Item::Unit(unit, f64_at(*at - 8))
|
||||
}
|
||||
b"Objc" => {
|
||||
let (class, items) = read_descriptor(d, at);
|
||||
Item::Object(class, items)
|
||||
}
|
||||
b"tdta" => {
|
||||
let n = u32_at(d, *at);
|
||||
*at += 4 + n;
|
||||
Item::Raw(d[*at - n..*at].to_vec())
|
||||
}
|
||||
other => panic!("unexpected item type {other:?}"),
|
||||
};
|
||||
items.push((key, v));
|
||||
}
|
||||
(class, items)
|
||||
}
|
||||
|
||||
/// A type tool object: its transform, its text descriptor and its warp descriptor.
|
||||
struct TypeTool {
|
||||
transform: [f64; 6],
|
||||
text: Vec<(String, Item)>,
|
||||
warp: (String, Vec<(String, Item)>),
|
||||
}
|
||||
|
||||
fn type_tool(d: &[u8]) -> TypeTool {
|
||||
assert_eq!(u16_at(d, 0), 1, "version");
|
||||
let transform = std::array::from_fn(|i| f64::from_be_bytes(d[2 + i * 8..10 + i * 8].try_into().unwrap()));
|
||||
assert_eq!((u16_at(d, 50), u32_at(d, 52)), (50, 16), "text and descriptor versions");
|
||||
let mut at = 56;
|
||||
let (class, text) = read_descriptor(d, &mut at);
|
||||
assert_eq!(class, "TxLr");
|
||||
assert_eq!((u16_at(d, at), u32_at(d, at + 2)), (1, 16), "warp and descriptor versions");
|
||||
at += 6;
|
||||
let warp = read_descriptor(d, &mut at);
|
||||
assert_eq!(d.len(), (at + 16).next_multiple_of(2), "the four warped bounds end the block (padded to an even length)");
|
||||
TypeTool { transform, text, warp }
|
||||
}
|
||||
|
||||
fn item<'a>(items: &'a [(String, Item)], key: &str) -> &'a Item {
|
||||
&items.iter().find(|(k, _)| k == key).unwrap_or_else(|| panic!("no {key}")).1
|
||||
}
|
||||
|
||||
/// `s` as the text engine stores a string: UTF-16BE after a byte order mark.
|
||||
fn engine_string(s: &str) -> Vec<u8> {
|
||||
[0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)).collect()
|
||||
}
|
||||
|
||||
fn type_node(b: &mut DocBuilder, origin: (f64, f64), text: &str, f: impl FnOnce(&mut vectorcraft_doc::TextObject)) -> Node {
|
||||
use vectorcraft_doc::{CharStyle, NodeKind, TextObject};
|
||||
let style = CharStyle { size: 12.0, fill: vectorcraft_color::Paint::solid(Color::rgb8(0, 0, 0)), ..CharStyle::default() };
|
||||
let mut t = TextObject::point(vectorcraft_geom::Point::new(origin.0, origin.1), text, style);
|
||||
f(&mut t);
|
||||
Node::new(b.alloc(), NodeKind::Text(Box::new(t)))
|
||||
}
|
||||
|
||||
/// Layer 1: a red square, point type, a blue square.
|
||||
fn type_doc() -> Document {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {});
|
||||
let t = type_node(&mut b, (20.0, 40.0), "Hi\nyou", |_| {});
|
||||
b.add(t);
|
||||
b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {});
|
||||
b.build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserve_text_writes_point_type_as_a_type_layer_between_pixel_layers() {
|
||||
let doc = type_doc();
|
||||
let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }) };
|
||||
let file = export(&doc, &o);
|
||||
let p = parse(&file);
|
||||
let rows: Vec<(&str, Option<usize>, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.divider, r.type_tool.is_some())).collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("</Layer group>", Some(3), false),
|
||||
("Layer 1", None, false),
|
||||
("Hi\nyou", None, true),
|
||||
("Layer 1", None, false),
|
||||
("Layer 1", Some(1), false),
|
||||
],
|
||||
"the layer becomes a group: the art below the type, the type layer, the art above it"
|
||||
);
|
||||
assert_eq!(p.records[1].rect, [0, 0, 60, 60], "the red square alone, at 2 pixels a point");
|
||||
assert_eq!(p.records[3].rect, [20, 120, 80, 180], "the blue square alone");
|
||||
assert_ne!(p.records[2].rect, [0; 4], "the type layer keeps its pixels");
|
||||
|
||||
let t = type_tool(p.records[2].type_tool.as_deref().unwrap());
|
||||
assert_eq!(t.transform, [1.0, 0.0, 0.0, 1.0, 40.0, 80.0], "the first baseline's start, in pixels");
|
||||
assert_eq!(item(&t.text, "Txt "), &Item::Text("Hi\ryou".into()));
|
||||
assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Hrzn".into()));
|
||||
let Item::Object(_, bounds) = item(&t.text, "bounds") else { panic!("bounds") };
|
||||
let [l, top, r, bottom] = ["Left", "Top ", "Rght", "Btom"].map(|k| match item(bounds, k) {
|
||||
Item::Unit(_, v) => *v,
|
||||
other => panic!("{other:?}"),
|
||||
});
|
||||
assert!(l < 4.0 && top < 0.0 && r > l && bottom > 24.0, "the ink around the baselines: {l} {top} {r} {bottom}");
|
||||
assert_eq!(t.warp.0, "warp");
|
||||
assert_eq!(item(&t.warp.1, "warpStyle"), &Item::Enum("warpStyle".into(), "warpNone".into()));
|
||||
|
||||
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
|
||||
let has = |needle: &[u8]| engine.windows(needle.len()).any(|w| w == needle);
|
||||
assert!(has(&engine_string("Hi\ryou\r")), "the text ends with a paragraph break");
|
||||
assert!(has(b"/FontSize 24.0"), "the size in pixels at 144 ppi");
|
||||
assert!(has(b"/RunLengthArray [ 3 4 ]"), "a paragraph run per paragraph, breaks counted");
|
||||
assert!(has(b"/RunLengthArray [ 7 ]"), "one style run over the text and the closing break");
|
||||
assert!(has(b"/Values [ 1.0 0.0 0.0 0.0 ]"), "black");
|
||||
assert!(has(b"/ShapeType 0"), "point type");
|
||||
assert!(has(b"/UseFractionalGlyphWidths true"), "Fractional Widths on");
|
||||
|
||||
// A reader takes the file, and the merged image is the same render.
|
||||
assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().layers().len(), p.records.len());
|
||||
let plain = export(&doc, &RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) });
|
||||
assert_eq!(merged(&file), merged(&plain));
|
||||
assert_eq!(parse(&plain).records.iter().filter(|r| r.type_tool.is_some()).count(), 0, "off: no type layers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_a_type_layer_cant_draw_stays_pixels() {
|
||||
use vectorcraft_doc::{NodeKind, TextKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
let area = type_node(&mut b, (10.0, 20.0), "Area", |t| {
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(5.0, 5.0, 60.0, 50.0), 0.1)) };
|
||||
});
|
||||
b.add(area);
|
||||
let stroked = type_node(&mut b, (10.0, 50.0), "Stroked", |t| {
|
||||
t.runs[0].style.stroke = vectorcraft_color::Paint::solid(Color::rgb8(255, 0, 0));
|
||||
t.runs[0].style.stroke_width = 1.0;
|
||||
});
|
||||
b.add(stroked);
|
||||
let kerned = type_node(&mut b, (40.0, 50.0), "Kerned", |t| t.runs[0].style.kerning = Some(50.0));
|
||||
b.add(kerned);
|
||||
let indented = type_node(&mut b, (70.0, 50.0), "Indented", |t| t.para.first_line_indent = 4.0);
|
||||
b.add(indented);
|
||||
let listed = type_node(&mut b, (10.0, 35.0), "Listed", |t| t.para.list = Some(vectorcraft_doc::text::ParaList::default()));
|
||||
b.add(listed);
|
||||
let system = type_node(&mut b, (40.0, 35.0), "System", |t| t.system_layout = true);
|
||||
b.add(system);
|
||||
let hanging = type_node(&mut b, (70.0, 35.0), "\"Hung\"", |t| t.optical_margin = true);
|
||||
b.add(hanging);
|
||||
let tabbed = type_node(&mut b, (10.0, 10.0), "a\tb", |t| {
|
||||
t.para.tabs = vec![vectorcraft_doc::TabStop { position: 30.0, align: Default::default(), leader: String::new(), align_on: '.' }];
|
||||
});
|
||||
b.add(tabbed);
|
||||
let leading = type_node(&mut b, (40.0, 10.0), "Auto", |t| t.para.justification.auto_leading = 150.0);
|
||||
b.add(leading);
|
||||
let standard = type_node(&mut b, (40.0, 20.0), "Std", |t| t.para.composer = vectorcraft_doc::Composer::StandardEveryLine);
|
||||
b.add(standard);
|
||||
// Hebrew: right to left from its first strong character, so Auto alignment is right. In an
|
||||
// installed font that covers it when there is one; otherwise its font lacks it.
|
||||
let hebrew_face = vectorcraft_text::FontDb::global().face_covering('ש');
|
||||
let hebrew = type_node(&mut b, (70.0, 10.0), "שלום", |t| {
|
||||
if let Some(f) = &hebrew_face {
|
||||
(t.runs[0].style.font_family, t.runs[0].style.font_style) = (f.family.clone(), f.style.clone());
|
||||
}
|
||||
});
|
||||
b.add(hebrew);
|
||||
let tracked = type_node(&mut b, (10.0, 58.0), "Tracked", |t| t.runs[0].style.tracking = 0.5);
|
||||
b.add(tracked);
|
||||
let british = type_node(&mut b, (70.0, 58.0), "Colour", |t| t.runs[0].style.language = Some("en-GB".into()));
|
||||
b.add(british);
|
||||
// Drawn partly with a fallback font: the bundled fonts have no 縦.
|
||||
let fallback = type_node(&mut b, (40.0, 58.0), "A縦", |_| {});
|
||||
b.add(fallback);
|
||||
let mut doc = b.build();
|
||||
let with = |o: PsdOptions| export(&doc, &opts(o));
|
||||
assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way");
|
||||
|
||||
// An empty point type object has no text to edit.
|
||||
let empty = Node::new(
|
||||
doc.alloc_id(),
|
||||
NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "", Default::default()))),
|
||||
);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, empty).unwrap();
|
||||
let file = export(&doc, &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }));
|
||||
assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_type_and_maximum_editability() {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
b.rect(Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb8(255, 0, 0), |_| {});
|
||||
let t = type_node(&mut b, (50.0, 10.0), "Up", |t| t.vertical = true);
|
||||
b.add(t);
|
||||
let hidden = type_node(&mut b, (10.0, 50.0), "Hidden", |_| {});
|
||||
b.add(Node { visible: false, ..hidden });
|
||||
let doc = b.build();
|
||||
let o = opts(PsdOptions { preserve_text: true, max_editability: true, hidden_layers: true, ..PsdOptions::default() });
|
||||
let file = export(&doc, &o);
|
||||
let p = parse(&file);
|
||||
let rows: Vec<(&str, bool, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.type_tool.is_some(), r.hidden)).collect();
|
||||
let square = doc.layers[0].children().unwrap()[0].display_name();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[("</Layer group>", false, false), (square.as_str(), false, false), ("Up", true, false), ("Hidden", true, true), ("Layer 1", false, false)],
|
||||
"each object a layer of its own; hidden type is a hidden type layer"
|
||||
);
|
||||
let t = type_tool(p.records[2].type_tool.as_deref().unwrap());
|
||||
assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Vrtc".into()));
|
||||
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
|
||||
assert!(engine.windows(19).any(|w| w == b"/WritingDirection 2"), "vertical writing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_layer_keeps_fractional_widths_off() {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
let t = type_node(&mut b, (10.0, 30.0), "Whole", |t| t.fractional_widths = false);
|
||||
b.add(t);
|
||||
let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }));
|
||||
let p = parse(&file);
|
||||
let record = p.records.iter().find(|r| r.type_tool.is_some()).expect("a type layer");
|
||||
let t = type_tool(record.type_tool.as_deref().unwrap());
|
||||
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
|
||||
let needle = b"/UseFractionalGlyphWidths false";
|
||||
assert!(engine.windows(needle.len()).any(|w| w == needle), "whole-point advances, as the pixels are drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_layer_keeps_the_anti_aliasing_method() {
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
let engine_anti_alias = |doc: &Document, o: &RasterExportOptions| {
|
||||
let file = export(doc, o);
|
||||
let p = parse(&file);
|
||||
let t = type_tool(p.records.iter().find_map(|r| r.type_tool.as_deref()).expect("a type layer"));
|
||||
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
|
||||
let at = engine.windows(11).position(|w| w == b"/AntiAlias ").expect("AntiAlias");
|
||||
let Item::Enum(_, method) = item(&t.text, "AntA") else { panic!("AntA") };
|
||||
(method.clone(), engine[at + 11])
|
||||
};
|
||||
let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() });
|
||||
for (aa, key, number) in [
|
||||
(TypeAntiAlias::None, "Anno", b'0'),
|
||||
(TypeAntiAlias::Sharp, "AnSh", b'4'),
|
||||
(TypeAntiAlias::Crisp, "AnCr", b'1'),
|
||||
(TypeAntiAlias::Strong, "AnSt", b'2'),
|
||||
] {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
let t = type_node(&mut b, (10.0, 30.0), "Edges", |t| t.anti_alias = aa);
|
||||
b.add(t);
|
||||
let doc = b.build();
|
||||
assert_eq!(engine_anti_alias(&doc, &o), (key.to_string(), number), "{aa:?}");
|
||||
let hard = RasterExportOptions { anti_alias: crate::AntiAlias::None, ..o.clone() };
|
||||
assert_eq!(engine_anti_alias(&doc, &hard), ("Anno".to_string(), b'0'), "{aa:?} exported without anti-aliasing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variation_selectors_and_joiners_need_no_glyph() {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
// In English: USA, the default language, given by its tag.
|
||||
let t = type_node(&mut b, (10.0, 30.0), "A\u{FE0F}\u{200D}B\u{E0100}", |t| t.runs[0].style.language = Some("en-US".into()));
|
||||
b.add(t);
|
||||
let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }));
|
||||
assert_eq!(parse(&file).records.iter().filter(|r| r.type_tool.is_some()).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_type_left_out_keeps_its_layer_whole() {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {});
|
||||
let t = type_node(&mut b, (20.0, 40.0), "Hidden", |_| {});
|
||||
b.add(Node { visible: false, ..t });
|
||||
b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {});
|
||||
let doc = b.build();
|
||||
let with = |o: PsdOptions| export(&doc, &opts(o));
|
||||
assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way");
|
||||
let shown = parse(&with(PsdOptions { preserve_text: true, hidden_layers: true, ..PsdOptions::default() }))
|
||||
.records
|
||||
.iter()
|
||||
.filter(|r| r.type_tool.is_some() && r.hidden)
|
||||
.count();
|
||||
assert_eq!(shown, 1, "with hidden layers: a hidden type layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blending_art_keeps_its_layer_whole() {
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::AppearanceItem;
|
||||
// The square's blend mode, on the object (`fill`: false) or on its fill.
|
||||
let build = |blend: BlendMode, above: bool, fill: bool| {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
let square = |b: &mut DocBuilder| {
|
||||
b.rect(Rect::new(0.0, 0.0, 60.0, 40.0), Color::rgb8(255, 0, 0), |n| {
|
||||
if !fill {
|
||||
n.blend = blend;
|
||||
} else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.blend = blend;
|
||||
}
|
||||
});
|
||||
};
|
||||
if !above {
|
||||
square(&mut b);
|
||||
}
|
||||
let t = type_node(&mut b, (10.0, 30.0), "Type", |_| {});
|
||||
b.add(t);
|
||||
if above {
|
||||
square(&mut b);
|
||||
}
|
||||
b.build()
|
||||
};
|
||||
let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() });
|
||||
for (above, fill) in [(true, false), (false, false), (true, true)] {
|
||||
let normal = export(&build(BlendMode::Normal, above, fill), &o);
|
||||
assert_eq!(parse(&normal).records.iter().filter(|r| r.type_tool.is_some()).count(), 1, "normal art (above: {above}): a type layer");
|
||||
let doc = build(BlendMode::Multiply, above, fill);
|
||||
let file = export(&doc, &o);
|
||||
assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none()), "multiplied art (above: {above}, fill: {fill}): one pixel layer");
|
||||
assert_eq!(file, export(&doc, &opts(PsdOptions::default())));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_unicode_name_is_cut_on_a_character_boundary() {
|
||||
let mut b = DocBuilder::new(100.0, 60.0);
|
||||
|
||||
@@ -688,6 +688,16 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
|
||||
_ => None,
|
||||
};
|
||||
let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref());
|
||||
// Copies that each carry the raster effects listed before their Transform effect reach
|
||||
// as far as each copy's raster effects paint, and the raster effects after it spread
|
||||
// them all: the art and each copy in it are groups with those raster effects, measured
|
||||
// with their reach ([`effects::has_container_appearance`]).
|
||||
if effects::outer_effects(n).len() < n.appearance.effects.len()
|
||||
&& let Some(r) = &reshaped
|
||||
{
|
||||
let a = live_content_reach(symbols, n);
|
||||
return cull_bounds_in(symbols, r, after_reshape, false).map(|b| b.inflate(a, a));
|
||||
}
|
||||
let b = match &reshaped {
|
||||
Some(r) if has_instance_row_effects(n) => instance_piece_bounds(symbols, r),
|
||||
Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => {
|
||||
|
||||
@@ -653,7 +653,20 @@ impl Renderer {
|
||||
if view.shows_outlines() {
|
||||
let opts = RenderOptions { outline: true, ..f.opts.clone() };
|
||||
let frame = Frame { opts: &opts, ..*f };
|
||||
for c in shapes {
|
||||
// An Abutting trace's seam fills hold no traced outline: a clip group of paths that are
|
||||
// each stroked without a fill or (on a stretched image, the strokes' outlines) filled
|
||||
// without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the
|
||||
// trace puts it.
|
||||
let seam_fills = |i: usize, c: &Arc<Node>| {
|
||||
let one_paint = |m: &Arc<Node>| {
|
||||
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& m.appearance.fill_paint().is_none() != m.appearance.stroke_paint().is_none()
|
||||
};
|
||||
(i == 0 || c.name.as_deref() == Some("Seam Fills"))
|
||||
&& matches!(&c.kind, NodeKind::Group { clip: true, children }
|
||||
if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(one_paint)))
|
||||
};
|
||||
for (_, c) in shapes.iter().enumerate().filter(|(i, c)| !seam_fills(*i, c)) {
|
||||
self.draw_outline_member(ctx, &frame, c);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1282,3 +1282,45 @@ fn each_copy_of_a_groups_or_layers_transform_effect_draws_its_own_shadow() {
|
||||
assert!((b.x1 - 80.0).abs() < 1e-9, "layer {layer}: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy of an image's Transform effect draws the drop shadow listed before the effect under
|
||||
/// itself, scaled with it: the red image (20..50) has its green shadow 10 pt to its right, and its
|
||||
/// copy scaled 50 % and moved 40 pt down (27.5..42.5 across, 67.5..82.5 down) has its own 5 pt to
|
||||
/// its right.
|
||||
#[test]
|
||||
fn each_copy_of_an_images_transform_effect_draws_its_own_shadow() {
|
||||
let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}));
|
||||
let copies = fx("distort.transform", json!({"scaleH": 50, "scaleV": 50, "moveV": 40, "copies": 1}));
|
||||
let img = render(&image_doc(vec![shadow, copies]));
|
||||
assert_eq!(img.pixel(35, 35), [255, 0, 0, 255], "the image");
|
||||
assert_eq!(img.pixel(55, 35), [0, 255, 0, 255], "the image's shadow");
|
||||
assert_eq!(img.pixel(35, 75), [255, 0, 0, 255], "the copy");
|
||||
assert_eq!(img.pixel(45, 75), [0, 255, 0, 255], "the copy's shadow, 5 pt to its right");
|
||||
assert_eq!(img.pixel(50, 75), [255, 255, 255, 255], "past the copy's shadow");
|
||||
}
|
||||
|
||||
/// Each copy of a symbol instance's Transform effect draws the drop shadow listed before the effect
|
||||
/// under itself, scaled with it: the black square (40..60) has its green shadow 10 pt to its right,
|
||||
/// and its copy scaled 150 % and moved 30 pt down (35..65 across, 65..95 down) has its own 15 pt to
|
||||
/// its right. The bounds reach as far as the copy's shadow, and as far as a shadow listed after the
|
||||
/// Transform effect paints below all of them.
|
||||
#[test]
|
||||
fn each_copy_of_a_symbol_instances_transform_effect_draws_its_own_shadow() {
|
||||
let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}));
|
||||
let copies = fx("distort.transform", json!({"scaleH": 150, "scaleV": 150, "moveV": 30, "copies": 1}));
|
||||
let below = fx("stylize.dropShadow", json!({"x": 0, "y": 20, "blur": 0, "opacity": 100, "mode": "normal", "color": "#0000ff"}));
|
||||
let d = symbol_doc(vec![shadow.clone(), copies.clone(), below]);
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), n).unwrap();
|
||||
assert!(b.x1 >= 80.0 - 1e-9 && b.y1 >= 115.0 - 1e-9, "{b:?}");
|
||||
let d = symbol_doc(vec![shadow, copies]);
|
||||
let img = render(&d);
|
||||
assert_eq!(img.pixel(50, 50), [0, 0, 0, 255], "the instance");
|
||||
assert_eq!(img.pixel(65, 50), [0, 255, 0, 255], "the instance's shadow");
|
||||
assert_eq!(img.pixel(50, 80), [0, 0, 0, 255], "the copy");
|
||||
assert_eq!(img.pixel(77, 80), [0, 255, 0, 255], "the copy's shadow, 15 pt to its right");
|
||||
assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "past the copy's shadow");
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), n).unwrap();
|
||||
assert!(b.x1 >= 80.0 - 1e-9, "{b:?}");
|
||||
}
|
||||
@@ -549,6 +549,13 @@ impl FontFace {
|
||||
self.gsub_index().by_input.get(&gid).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Do [`Self::substitutions`] of glyph `gid` give a glyph other than `gid` itself? It reads the
|
||||
/// face's index without copying the substitutions, so the Glyphs panel asks it for each cell it
|
||||
/// draws.
|
||||
pub fn has_alternates(&self, gid: u32) -> bool {
|
||||
self.gsub_index().by_input.get(&gid).is_some_and(|subs| subs.iter().any(|s| s.glyphs.iter().any(|&g| g != gid)))
|
||||
}
|
||||
|
||||
/// The feature of the `GSUB` table that gives glyph `gid` as a substitute (by a single,
|
||||
/// multiple, alternate or ligature substitution), a listed feature ([`Self::substitutions`])
|
||||
/// before another (`init`, `liga`), if any does. Not read through a contextual lookup.
|
||||
|
||||
@@ -40,6 +40,25 @@ fn alternates_come_in_feature_order_once_each() {
|
||||
assert!(bundled.alternates('a').iter().all(|a| a.gid < bundled.glyph_count()));
|
||||
}
|
||||
|
||||
/// A glyph has alternates when a listed feature gives it another glyph: `a` has them in both
|
||||
/// faces, `b` and the alternates of `a` have none, and a glyph past the face has none.
|
||||
#[test]
|
||||
fn has_alternates_follows_the_listed_substitutions() {
|
||||
let db = db();
|
||||
let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs");
|
||||
for aalt in [true, false] {
|
||||
let face = db.face(alternates_family(aalt), "Regular").expect("the test face");
|
||||
assert!(face.has_alternates(face.glyph_for('a')), "a, aalt {aalt}");
|
||||
assert!(!face.has_alternates(face.glyph_for('b')), "b, aalt {aalt}");
|
||||
assert!(!face.has_alternates(u1), "an alternate of a has none of its own, aalt {aalt}");
|
||||
assert!(!face.has_alternates(face.glyph_count() + 10), "a glyph past the face, aalt {aalt}");
|
||||
}
|
||||
let bundled = db.face(FALLBACK_FAMILY, "Regular").expect("the bundled face");
|
||||
let with = bundled.chars().into_iter().filter(|(_, g)| bundled.has_alternates(*g)).count();
|
||||
let listed = bundled.chars().into_iter().filter(|(c, g)| bundled.alternates(*c).iter().any(|a| a.gid != *g)).count();
|
||||
assert_eq!(with, listed, "the same characters as the alternates lists say");
|
||||
}
|
||||
|
||||
/// The cap on lookups read in all leaves out the lowest ranked features: `salt` is read even when
|
||||
/// the `cv01` records before it list more lookups than the cap.
|
||||
#[test]
|
||||
|
||||
+392
-14
@@ -3,10 +3,20 @@
|
||||
//! rectangle and removes every stretch it touches; an Alt-drag draws a freehand line and removes
|
||||
//! every stretch it crosses. Each runs `addon.pathtools.trim` on release, as one undo step, on
|
||||
//! every path that can be edited, selected or not. Escape during a drag removes nothing.
|
||||
//!
|
||||
//! Hovering shows in red the stretch a click would remove while finding its crossings takes at
|
||||
//! most a twentieth of the work a click may do ([`HOVER`]), and a drag shows what it would remove while
|
||||
//! it reaches few paths ([`PREVIEW`]).
|
||||
|
||||
pub mod plan;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_geom::{BezPath, PathData, Point, Rect};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
use self::plan::{Limits, Pick, Stretches};
|
||||
use crate::builder::HIGHLIGHT_RED;
|
||||
use crate::draw2::FEEDBACK;
|
||||
use crate::xform::polygon;
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
@@ -21,6 +31,18 @@ const MIN_DRAG_PX: f64 = 3.0;
|
||||
pub(crate) const MAX_POINTS: usize = 65_536;
|
||||
/// The command the tool runs.
|
||||
const COMMAND: &str = "addon.pathtools.trim";
|
||||
/// How much finding the crossings for a preview may take: a twentieth of what the command may.
|
||||
const PREVIEW_CROSSINGS: pt::Work = pt::Work::share(20);
|
||||
/// How much hovering may work out on each move: past it the hover shows no highlight, and a
|
||||
/// click still removes the stretch.
|
||||
pub const HOVER: Limits = Limits { crossings: PREVIEW_CROSSINGS, ..Limits::COMMAND };
|
||||
/// How much a drag's preview may work out on each move: past it the drag shows no preview, and
|
||||
/// the release still removes everything it reaches.
|
||||
pub const PREVIEW: Limits = Limits { paths: 32, box_tests: 10_000_000, line_tests: 1_000_000, crossings: PREVIEW_CROSSINGS };
|
||||
/// The most points a freehand line has for the drag to show a preview.
|
||||
const PREVIEW_POINTS: usize = 4_096;
|
||||
/// The preview's line width (screen pixels).
|
||||
const PREVIEW_PX: f32 = 3.0;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TrimTool {
|
||||
@@ -32,6 +54,27 @@ pub struct TrimTool {
|
||||
freehand: bool,
|
||||
/// The pointer went `MIN_DRAG_PX` or more from the press: the gesture is a drag from then on.
|
||||
moved: bool,
|
||||
/// The stretches the gesture would remove, and the document state they were found in.
|
||||
preview: Vec<BezPath>,
|
||||
preview_state: Option<State>,
|
||||
/// Finding the drag's crossings took more work than a preview may: it shows none until the
|
||||
/// next press.
|
||||
gave_up: bool,
|
||||
/// The stretches of the paths looked at so far, for the document state `seen`.
|
||||
stretches: Stretches,
|
||||
seen: Option<State>,
|
||||
}
|
||||
|
||||
/// The document's revision and its isolated object: what a pick is worked out for.
|
||||
type State = ((u64, u64), Option<NodeId>);
|
||||
|
||||
fn state(cx: &ToolContext) -> State {
|
||||
(cx.revision, cx.isolation)
|
||||
}
|
||||
|
||||
/// How near the pointer a click finds a path (pt).
|
||||
fn reach(cx: &ToolContext) -> f64 {
|
||||
cx.tol(REACH).min(100.0)
|
||||
}
|
||||
|
||||
impl TrimTool {
|
||||
@@ -40,6 +83,64 @@ impl TrimTool {
|
||||
self.line.clear();
|
||||
self.freehand = false;
|
||||
self.moved = false;
|
||||
self.gave_up = false;
|
||||
self.preview.clear();
|
||||
}
|
||||
|
||||
/// Work out what `pick` would remove, within `limits`, as the preview: nothing when it
|
||||
/// removes nothing or needs more work than that (then why).
|
||||
fn look(&mut self, cx: &ToolContext, pick: &Pick, limits: Limits) -> Option<plan::TooMuch> {
|
||||
if self.seen != Some(state(cx)) {
|
||||
self.stretches.clear();
|
||||
self.seen = Some(state(cx));
|
||||
}
|
||||
let root = crate::ordinary_isolation(cx.doc, cx.isolation);
|
||||
self.preview_state = Some(state(cx));
|
||||
match plan::plan(cx.doc, root, pick, limits, &mut self.stretches) {
|
||||
Ok(all) => {
|
||||
self.preview = all.into_iter().flat_map(|t| t.removed).map(|sp| PathData::single(sp).to_bezpath()).collect();
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
self.preview.clear();
|
||||
Some(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview of the drag as it is: its rectangle, or its freehand line to `to`.
|
||||
fn look_at_drag(&mut self, cx: &ToolContext, to: Point) {
|
||||
let Some(start) = self.start else { return };
|
||||
if self.gave_up {
|
||||
self.preview.clear();
|
||||
return;
|
||||
}
|
||||
if !self.freehand {
|
||||
self.look_or_give_up(cx, &Pick::Rect(Rect::from_points(start, to)));
|
||||
return;
|
||||
}
|
||||
if self.line.len() > PREVIEW_POINTS {
|
||||
self.preview.clear();
|
||||
return;
|
||||
}
|
||||
let mut pts = self.line.clone();
|
||||
if pts.last().is_some_and(|p| *p != to) {
|
||||
pts.push(to);
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
self.preview.clear();
|
||||
return;
|
||||
}
|
||||
let bounds = pts.iter().fold(Rect::from_points(to, to), |r, q| r.union_pt(*q));
|
||||
self.look_or_give_up(cx, &Pick::Line(pts, bounds));
|
||||
}
|
||||
|
||||
/// [`Self::look`] for a drag. A drag that reaches too many paths may come back to fewer; one
|
||||
/// whose crossings or line take too much work shows nothing more.
|
||||
fn look_or_give_up(&mut self, cx: &ToolContext, pick: &Pick) {
|
||||
if let Some(plan::TooMuch::Crossings | plan::TooMuch::Line) = self.look(cx, pick, PREVIEW) {
|
||||
self.gave_up = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,15 +158,22 @@ impl Tool for TrimTool {
|
||||
if ev.kind == PointerKind::Up {
|
||||
self.reset();
|
||||
}
|
||||
self.preview.clear();
|
||||
return vec![];
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
self.look(cx, &Pick::At(ev.pos, reach(cx)), HOVER);
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
self.start = Some(ev.pos);
|
||||
self.end = ev.pos;
|
||||
self.freehand = ev.mods.alt;
|
||||
self.moved = false;
|
||||
self.line = if self.freehand { vec![ev.pos] } else { vec![] };
|
||||
// Until the pointer moves away, the press is a click at this point.
|
||||
self.look(cx, &Pick::At(ev.pos, reach(cx)), HOVER);
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Drag if self.start.is_some() => {
|
||||
@@ -79,6 +187,9 @@ impl Tool for TrimTool {
|
||||
}
|
||||
self.line.push(ev.pos);
|
||||
}
|
||||
if self.moved {
|
||||
self.look_at_drag(cx, ev.pos);
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Up => {
|
||||
@@ -89,7 +200,7 @@ impl Tool for TrimTool {
|
||||
// A press that stayed near where it started is a click, even when a freehand line
|
||||
// took a few points on the way. One that went farther stays a drag when it comes back.
|
||||
if !moved && start.distance(ev.pos) < cx.tol(MIN_DRAG_PX) {
|
||||
return vec![Action::Exec(COMMAND.into(), json!({"at": [start.x, start.y], "tolerance": cx.tol(REACH).min(100.0)}))];
|
||||
return vec![Action::Exec(COMMAND.into(), json!({"at": [start.x, start.y], "tolerance": reach(cx)}))];
|
||||
}
|
||||
if !freehand {
|
||||
let r = Rect::from_points(start, ev.pos);
|
||||
@@ -116,16 +227,34 @@ impl Tool for TrimTool {
|
||||
self.start.is_some() && key == ToolKey::Escape
|
||||
}
|
||||
|
||||
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
|
||||
let Some(start) = self.start else { return vec![] };
|
||||
if self.freehand {
|
||||
return if self.line.len() < 2 {
|
||||
vec![]
|
||||
} else {
|
||||
vec![Overlay::Path { path: polygon(&self.line, false), color: FEEDBACK, width: 1.0, dashed: false }]
|
||||
};
|
||||
fn hover_ended(&mut self, _cx: &ToolContext) {
|
||||
if self.start.is_none() {
|
||||
self.preview.clear();
|
||||
}
|
||||
if self.moved { vec![Overlay::Marquee(Rect::from_points(start, self.end))] } else { vec![] }
|
||||
}
|
||||
|
||||
/// The highlight shows what lies under the pointer, which panning or an edit changes.
|
||||
fn wants_rehover(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
// A preview found in another revision of the document, or for another isolated object, is
|
||||
// out of date.
|
||||
let mut out: Vec<Overlay> = if self.preview_state == Some(state(cx)) {
|
||||
self.preview.iter().map(|p| Overlay::Path { path: p.clone(), color: HIGHLIGHT_RED, width: PREVIEW_PX, dashed: false }).collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let Some(start) = self.start else { return out };
|
||||
if self.freehand {
|
||||
if self.line.len() >= 2 {
|
||||
out.push(Overlay::Path { path: polygon(&self.line, false), color: FEEDBACK, width: 1.0, dashed: false });
|
||||
}
|
||||
} else if self.moved {
|
||||
out.push(Overlay::Marquee(Rect::from_points(start, self.end)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
|
||||
@@ -137,7 +266,9 @@ impl Tool for TrimTool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::Selection;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, Selection};
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, PathSeg};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent {
|
||||
PointerEvent::new(kind, x, y)
|
||||
@@ -151,7 +282,8 @@ mod tests {
|
||||
cx.zoom = 2.0;
|
||||
let mut t = TrimTool::default();
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)).is_empty());
|
||||
assert!(t.busy() && t.overlays(&cx).is_empty());
|
||||
// No marquee for a press; the rectangle, which nothing crosses, would go whole.
|
||||
assert!(t.busy() && matches!(t.overlays(&cx).as_slice(), [Overlay::Path { color: HIGHLIGHT_RED, .. }]));
|
||||
let up = t.pointer(&cx, &ev(PointerKind::Up, 100.5, 100.0));
|
||||
assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [100.0, 100.0], "tolerance": 2.0}))], "4 px at 200%");
|
||||
assert!(!t.busy());
|
||||
@@ -166,7 +298,10 @@ mod tests {
|
||||
let mut t = TrimTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 160.0, 130.0));
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Drag, 140.0, 90.0)).is_empty(), "nothing runs while dragging");
|
||||
assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(r)] if *r == Rect::new(140.0, 90.0, 160.0, 130.0)));
|
||||
assert!(matches!(
|
||||
t.overlays(&cx).as_slice(),
|
||||
[Overlay::Path { color: HIGHLIGHT_RED, .. }, Overlay::Marquee(r)] if *r == Rect::new(140.0, 90.0, 160.0, 130.0)
|
||||
));
|
||||
let up = t.pointer(&cx, &ev(PointerKind::Up, 140.0, 90.0));
|
||||
assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"rect": [140.0, 90.0, 20.0, 40.0]}))]);
|
||||
// Escape during a drag: nothing runs on release, and the key is the tool's only then.
|
||||
@@ -233,4 +368,247 @@ mod tests {
|
||||
assert!(!t.busy());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 0.0, 0.0)).is_empty());
|
||||
}
|
||||
|
||||
/// A document holding `paths`, bottom to top.
|
||||
fn doc_of(paths: Vec<PathData>) -> (Document, Vec<NodeId>) {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut ids = vec![];
|
||||
for (i, p) in paths.into_iter().enumerate() {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), i, Node::path(id, p, Appearance::default_art())).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
(d, ids)
|
||||
}
|
||||
|
||||
fn open(pts: &[(f64, f64)]) -> PathData {
|
||||
let mut b = BezPath::new();
|
||||
for (i, (x, y)) in pts.iter().enumerate() {
|
||||
if i == 0 { b.move_to((*x, *y)) } else { b.line_to((*x, *y)) }
|
||||
}
|
||||
PathData::from_bezpath(&b)
|
||||
}
|
||||
|
||||
/// The red stretches shown, each as its two ends.
|
||||
fn shown(t: &TrimTool, cx: &ToolContext) -> Vec<(Point, Point)> {
|
||||
t.overlays(cx)
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
Overlay::Path { path, color, .. } if *color == HIGHLIGHT_RED => {
|
||||
let segs: Vec<PathSeg> = path.segments().collect();
|
||||
Some((segs.first()?.start(), segs.last()?.end()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hover(t: &mut TrimTool, cx: &ToolContext, x: f64, y: f64) -> Vec<(Point, Point)> {
|
||||
assert!(t.pointer(cx, &ev(PointerKind::Move, x, y)).is_empty(), "hovering runs nothing");
|
||||
shown(t, cx)
|
||||
}
|
||||
|
||||
/// The two ends, either way round, are near (ax, ay) and (bx, by).
|
||||
fn ends_are(e: (Point, Point), (ax, ay): (f64, f64), (bx, by): (f64, f64)) -> bool {
|
||||
let near = |p: Point, x: f64, y: f64| p.distance(Point::new(x, y)) < 1e-3;
|
||||
(near(e.0, ax, ay) && near(e.1, bx, by)) || (near(e.0, bx, by) && near(e.1, ax, ay))
|
||||
}
|
||||
|
||||
/// What a click at (x, y) with the tool's reach removes, worked out as the command does.
|
||||
fn click_removes(d: &Document, cx: &ToolContext, x: f64, y: f64) -> Vec<BezPath> {
|
||||
let all = plan::plan(d, None, &Pick::At(Point::new(x, y), reach(cx)), Limits::COMMAND, &mut Stretches::default()).unwrap();
|
||||
all.into_iter().flat_map(|t| t.removed).map(|sp| PathData::single(sp).to_bezpath()).collect()
|
||||
}
|
||||
|
||||
fn red_paths(t: &TrimTool, cx: &ToolContext) -> Vec<BezPath> {
|
||||
t.overlays(cx)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Overlay::Path { path, color, .. } if color == HIGHLIGHT_RED => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_shows_the_stretch_a_click_removes_on_a_line_across_an_ellipse() {
|
||||
let ellipse = shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 200.0));
|
||||
let (d, _) = doc_of(vec![ellipse, open(&[(50.0, 150.0), (350.0, 150.0)])]);
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
// The ellipse's upper half, between the two places the line crosses it.
|
||||
let top = hover(&mut t, &cx, 200.0, 101.0);
|
||||
assert!(matches!(top.as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))), "{top:?}");
|
||||
assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 200.0, 101.0));
|
||||
// The line's end outside the ellipse, and its middle inside it.
|
||||
let end = hover(&mut t, &cx, 70.0, 150.0);
|
||||
assert!(matches!(end.as_slice(), [e] if ends_are(*e, (50.0, 150.0), (100.0, 150.0))), "{end:?}");
|
||||
let middle = hover(&mut t, &cx, 200.0, 151.0);
|
||||
assert!(matches!(middle.as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))), "{middle:?}");
|
||||
assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 200.0, 151.0));
|
||||
// Off every path: no highlight.
|
||||
assert!(hover(&mut t, &cx, 400.0, 400.0).is_empty());
|
||||
assert!(t.overlays(&cx).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_an_open_square_and_a_path_that_crosses_itself() {
|
||||
// Three sides of a square, crossed by an upright through the top and bottom sides.
|
||||
let square = open(&[(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)]);
|
||||
let (d, _) = doc_of(vec![square, open(&[(150.0, 50.0), (150.0, 250.0)])]);
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
let side = hover(&mut t, &cx, 201.0, 150.0);
|
||||
assert!(matches!(side.as_slice(), [e] if ends_are(*e, (150.0, 100.0), (150.0, 200.0))), "{side:?}");
|
||||
assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 201.0, 150.0));
|
||||
let corner = hover(&mut t, &cx, 110.0, 99.0);
|
||||
assert!(matches!(corner.as_slice(), [e] if ends_are(*e, (100.0, 100.0), (150.0, 100.0))), "{corner:?}");
|
||||
|
||||
// A Z drawn back over itself: its first and last sides cross at (50, 50).
|
||||
let (d, _) = doc_of(vec![open(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)])]);
|
||||
let cx = crate::testutil::cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
let lobe = hover(&mut t, &cx, 101.0, 50.0);
|
||||
assert!(matches!(lobe.as_slice(), [e] if ends_are(*e, (50.0, 50.0), (50.0, 50.0))), "{lobe:?}");
|
||||
assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 101.0, 50.0));
|
||||
let tail = hover(&mut t, &cx, 10.0, 11.0);
|
||||
assert!(matches!(tail.as_slice(), [e] if ends_are(*e, (0.0, 0.0), (50.0, 50.0))), "{tail:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_locked_paths_show_nothing_and_a_changed_document_drops_the_highlight() {
|
||||
let (mut d, ids) = doc_of(vec![open(&[(0.0, 100.0), (300.0, 100.0)]), open(&[(0.0, 200.0), (300.0, 200.0)])]);
|
||||
d.node_mut(ids[0]).unwrap().visible = false;
|
||||
d.node_mut(ids[1]).unwrap().locked = true;
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let mut cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
assert!(hover(&mut t, &cx, 150.0, 100.0).is_empty(), "hidden");
|
||||
assert!(hover(&mut t, &cx, 150.0, 200.0).is_empty(), "locked");
|
||||
|
||||
let (d, _) = doc_of(vec![open(&[(0.0, 100.0), (300.0, 100.0)])]);
|
||||
cx.doc = &d;
|
||||
assert_eq!(hover(&mut t, &cx, 150.0, 100.0).len(), 1);
|
||||
// Once the document changes, the highlight found before is not shown.
|
||||
cx.revision = (0, 1);
|
||||
assert!(shown(&t, &cx).is_empty());
|
||||
// Leaving the canvas clears it.
|
||||
cx.revision = (0, 0);
|
||||
t.hover_ended(&cx);
|
||||
assert!(shown(&t, &cx).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_isolation_mode_only_paths_inside_the_isolated_group_are_highlighted() {
|
||||
// A group holding a line across, and an upright outside it that crosses the line.
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let across = Node::path(d.alloc_id(), open(&[(0.0, 100.0), (300.0, 100.0)]), Appearance::default_art());
|
||||
let group = Node::group(d.alloc_id(), vec![std::sync::Arc::new(across)]);
|
||||
let g = group.id;
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
let upright = d.alloc_id();
|
||||
d.insert(Some(l), 1, Node::path(upright, open(&[(150.0, 0.0), (150.0, 300.0)]), Appearance::default_art())).unwrap();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let mut cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
// Outside isolation mode the upright is highlighted; entering it drops that highlight.
|
||||
assert_eq!(hover(&mut t, &cx, 151.0, 50.0).len(), 1);
|
||||
cx.isolation = Some(g);
|
||||
assert!(shown(&t, &cx).is_empty(), "found before the group was isolated");
|
||||
// The upright is not trimmed, and still crosses the line inside the group.
|
||||
assert!(hover(&mut t, &cx, 151.0, 50.0).is_empty());
|
||||
let left = hover(&mut t, &cx, 50.0, 101.0);
|
||||
assert!(matches!(left.as_slice(), [e] if ends_are(*e, (0.0, 100.0), (150.0, 100.0))), "{left:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_whose_crossings_take_more_than_a_hover_may_shows_nothing_and_a_click_still_trims_it() {
|
||||
// 2,500 segments crossing each other's boxes: about 3,125,000 pairs, more than a twentieth
|
||||
// of the 60,000,000 a click may look at.
|
||||
let row = open(&(0..=2500).map(|i| (i as f64 * 0.1, 100.0)).collect::<Vec<_>>());
|
||||
let (d, _) = doc_of(vec![row]);
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
assert!(hover(&mut t, &cx, 125.0, 100.0).is_empty());
|
||||
assert_eq!(click_removes(&d, &cx, 125.0, 100.0).len(), 1);
|
||||
let up = {
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 125.0, 100.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 125.0, 100.0))
|
||||
};
|
||||
assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [125.0, 100.0], "tolerance": 4.0}))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_drag_shows_what_it_would_remove_and_a_large_one_shows_nothing() {
|
||||
let ellipse = shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 200.0));
|
||||
let (d, _) = doc_of(vec![ellipse, open(&[(50.0, 150.0), (350.0, 150.0)])]);
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
// A rectangle across the ellipse's top: its upper half.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 190.0, 90.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 210.0, 110.0));
|
||||
assert!(matches!(shown(&t, &cx).as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 210.0, 110.0));
|
||||
assert!(shown(&t, &cx).is_empty(), "the release drops the preview");
|
||||
// An Alt line through the ellipse's left side and the line's left end.
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 60.0, 140.0).with_mods(alt));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 110.0, 160.0));
|
||||
assert_eq!(shown(&t, &cx).len(), 2, "the line's end and the ellipse's lower half");
|
||||
t.key(&cx, ToolKey::Escape, Mods::default());
|
||||
assert!(shown(&t, &cx).is_empty());
|
||||
|
||||
// A rectangle over more paths than the preview's limit shows nothing.
|
||||
let many: Vec<PathData> = (0..=PREVIEW.paths).map(|i| open(&[(0.0, i as f64 * 2.0), (100.0, i as f64 * 2.0)])).collect();
|
||||
let (d, _) = doc_of(many);
|
||||
let cx = crate::testutil::cx(&d, &sel, &p);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 50.0, -10.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 500.0));
|
||||
assert!(shown(&t, &cx).is_empty());
|
||||
assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(_)]));
|
||||
// What lies under a still pointer changes when the view pans: the canvas hovers again.
|
||||
assert!(t.wants_rehover());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossings_kept_from_earlier_picks_still_count_against_the_budget() {
|
||||
// Three rows of 7,000 segments, apart: each costs 24,500,000 pairs of the 60,000,000 a
|
||||
// pick may look at, so a rectangle over all three is refused.
|
||||
let row = |y: f64| open(&(0..=7000).map(|i| (i as f64 * 0.01, y)).collect::<Vec<_>>());
|
||||
let (d, _) = doc_of(vec![row(0.0), row(10.0), row(20.0)]);
|
||||
let rect = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 21.0));
|
||||
assert_eq!(plan::plan(&d, None, &rect, Limits::COMMAND, &mut Stretches::default()), Err(plan::TooMuch::Crossings));
|
||||
// Hovering two of them keeps their crossings; the rectangle is refused all the same.
|
||||
let mut kept = Stretches::default();
|
||||
for y in [0.0, 10.0] {
|
||||
assert_eq!(plan::plan(&d, None, &Pick::At(Point::new(35.0, y), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1));
|
||||
}
|
||||
assert_eq!(plan::plan(&d, None, &rect, Limits::COMMAND, &mut kept), Err(plan::TooMuch::Crossings));
|
||||
// A rectangle over two is not.
|
||||
let two = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 11.0));
|
||||
assert_eq!(plan::plan(&d, None, &two, Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(2));
|
||||
|
||||
// A drag whose crossings take too much shows nothing until the next press, even over less.
|
||||
// Rows of 1,500 segments cost 1,125,000 pairs each, so a preview has room for two.
|
||||
let row = |y: f64| open(&(0..=1500).map(|i| (i as f64 * 0.05, y)).collect::<Vec<_>>());
|
||||
let (d, _) = doc_of(vec![row(0.0), row(10.0), row(20.0)]);
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TrimTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, -1.0, -1.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 21.0));
|
||||
assert!(shown(&t, &cx).is_empty());
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 5.0));
|
||||
assert!(shown(&t, &cx).is_empty());
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 80.0, 5.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, -1.0, -1.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 5.0));
|
||||
assert_eq!(shown(&t, &cx).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
//! What Trim at Crossings removes: the stretch at a point, every stretch a rectangle touches, or
|
||||
//! every stretch a line through some points crosses, on every path that can be edited. The command
|
||||
//! `addon.pathtools.trim` applies it, and the tool shows it before a click or while a drag stays
|
||||
//! small, so the two always agree.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::{Line, PathSeg};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
/// What picks the stretches to remove.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Pick {
|
||||
/// The stretch of the nearest path within the tolerance (pt) of the point.
|
||||
At(Point, f64),
|
||||
/// Every stretch the rectangle touches.
|
||||
Rect(Rect),
|
||||
/// Every stretch the line through the points crosses, with the points' bounds.
|
||||
Line(Vec<Point>, Rect),
|
||||
}
|
||||
|
||||
/// Why a pick could not be worked out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TooMuch {
|
||||
/// Finding where the paths cross took more than its budget.
|
||||
Crossings,
|
||||
/// The line has too many pieces, or passes too many segments, to check.
|
||||
Line,
|
||||
/// The rectangle or line reaches more paths than the limit.
|
||||
Paths,
|
||||
}
|
||||
|
||||
impl TooMuch {
|
||||
/// The error message the command reports.
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
TooMuch::Crossings => "the paths are too many or too tangled to find where they cross",
|
||||
TooMuch::Line => "the line is too long, or the paths it passes too many, to check",
|
||||
TooMuch::Paths => "the rectangle or line reaches too many paths to check",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How much work one pick may take.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Most paths a rectangle or a line may reach.
|
||||
pub paths: usize,
|
||||
/// Most box tests between the paths to trim and the other paths.
|
||||
pub box_tests: usize,
|
||||
/// Most box tests between a line's pieces and the paths' segments.
|
||||
pub line_tests: usize,
|
||||
/// The crossing work of every path the pick trims together.
|
||||
pub crossings: pt::Work,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// The command's limits.
|
||||
pub const COMMAND: Limits = Limits { paths: usize::MAX, box_tests: 50_000_000, line_tests: 60_000_000, crossings: pt::Work::share(1) };
|
||||
}
|
||||
|
||||
/// One path the pick trims.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Trimmed {
|
||||
pub id: NodeId,
|
||||
/// What takes its place: a path per piece for a path of one subpath, one path holding the
|
||||
/// pieces for a path of more, nothing when no piece is left.
|
||||
pub pieces: Vec<PathData>,
|
||||
/// The stretches removed, each an open subpath.
|
||||
pub removed: Vec<SubPath>,
|
||||
/// How many stretches were removed.
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// The stretches of each subpath of a path between the places it is crossed, for the document as
|
||||
/// it was when they were found, with the crossing work finding them took. A pick fills it with the
|
||||
/// paths it looks at; one kept between picks on an unchanged document saves finding the same
|
||||
/// crossings again, and a pick still draws their work from its budget, so it fails where a pick
|
||||
/// without them would. It also keeps the paths whose crossings could not be found within the whole
|
||||
/// crossing work of the picks' limits (`whole`), which no pick with those limits can find either.
|
||||
#[derive(Default)]
|
||||
pub struct Stretches {
|
||||
by_path: HashMap<NodeId, (Vec<Vec<pt::Span>>, pt::Work)>,
|
||||
too_much: HashSet<NodeId>,
|
||||
whole: Option<pt::Work>,
|
||||
}
|
||||
|
||||
impl Stretches {
|
||||
pub fn clear(&mut self) {
|
||||
self.by_path.clear();
|
||||
self.too_much.clear();
|
||||
self.whole = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that takes part: its id, geometry and control-point box.
|
||||
type Part<'a> = (NodeId, &'a PathData, Rect);
|
||||
|
||||
/// The paths that take part, bottom to top: the ones that can be edited, without guides and
|
||||
/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the
|
||||
/// members of a compound clipping path included.
|
||||
fn parts(d: &Document) -> Vec<Part<'_>> {
|
||||
let editable = d.editable();
|
||||
let mut masks = HashSet::new();
|
||||
d.walk(|n| {
|
||||
if n.clips()
|
||||
&& let Some(first) = n.children().and_then(|c| c.first())
|
||||
{
|
||||
first.walk(&mut |m| {
|
||||
masks.insert(m.id);
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind
|
||||
&& !masks.contains(&n.id)
|
||||
&& let Some(b) = path.control_bounds()
|
||||
&& editable(n.id)
|
||||
{
|
||||
out.push((n.id, path, b));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`;
|
||||
/// `None` once it is spent.
|
||||
fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option<bool> {
|
||||
let segs: Vec<_> = (0..sp.segment_count())
|
||||
.map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9))
|
||||
})
|
||||
.collect();
|
||||
let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) };
|
||||
for w in pts.windows(2) {
|
||||
let [a, b] = w else { continue };
|
||||
let piece = Rect::from_points(*a, *b);
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if !reach.overlaps(piece) {
|
||||
continue;
|
||||
}
|
||||
for (c, r) in &segs {
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() {
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`.
|
||||
fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result<bool, TooMuch> {
|
||||
match pick {
|
||||
Pick::At(..) => Ok(false),
|
||||
Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)),
|
||||
Pick::Line(pts, _) => crossed_by_line(piece, pts, budget).ok_or(TooMuch::Line),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a trim leaves of a path: its subpaths, the stretches removed and how many.
|
||||
type Cut = (Vec<SubPath>, Vec<SubPath>, usize);
|
||||
|
||||
/// What trimming `path` by `pick` leaves (`on`: the place of `Pick::At` on it): its subpaths then,
|
||||
/// the stretches removed and how many. `None` when none goes. A rectangle or a line that touches
|
||||
/// no part of `path` leaves it out before its crossings are looked for.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn trimmed<'a>(
|
||||
id: NodeId,
|
||||
path: &PathData,
|
||||
others: &dyn Fn() -> Vec<&'a PathData>,
|
||||
pick: &Pick,
|
||||
on: Option<pt::Place>,
|
||||
budget: &mut usize,
|
||||
work: &mut pt::Work,
|
||||
stretches: &mut Stretches,
|
||||
) -> Result<Option<Cut>, TooMuch> {
|
||||
let reached = match pick {
|
||||
Pick::At(..) => true,
|
||||
Pick::Rect(r) => hit::intersects_rect(path, *r),
|
||||
Pick::Line(..) => {
|
||||
let mut any = false;
|
||||
for sp in &path.subpaths {
|
||||
if touches(sp, pick, budget)? {
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
};
|
||||
if !reached {
|
||||
return Ok(None);
|
||||
}
|
||||
let all = match stretches.by_path.get(&id) {
|
||||
Some((all, cost)) => {
|
||||
work.draw(*cost).ok_or(TooMuch::Crossings)?;
|
||||
all.clone()
|
||||
}
|
||||
None if stretches.too_much.contains(&id) => return Err(TooMuch::Crossings),
|
||||
None => {
|
||||
let before = *work;
|
||||
let Some(places) = pt::crossings_on_within(path, &others(), work) else {
|
||||
if Some(before) == stretches.whole {
|
||||
stretches.too_much.insert(id);
|
||||
}
|
||||
return Err(TooMuch::Crossings);
|
||||
};
|
||||
let all: Vec<Vec<pt::Span>> = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(si, sp)| {
|
||||
// The places come in subpath order: this subpath's are one run of them.
|
||||
let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si);
|
||||
let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect();
|
||||
pt::spans(sp, &here)
|
||||
})
|
||||
.collect();
|
||||
stretches.by_path.insert(id, (all.clone(), work.spent_since(before)));
|
||||
all
|
||||
}
|
||||
};
|
||||
let mut subs = vec![];
|
||||
let mut removed = vec![];
|
||||
let mut count = 0;
|
||||
for ((si, sp), spans) in path.subpaths.iter().enumerate().zip(&all) {
|
||||
let marks: Vec<bool> = match pick {
|
||||
Pick::At(..) => {
|
||||
let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, spans, seg, t));
|
||||
(0..spans.len()).map(|i| Some(i) == at).collect()
|
||||
}
|
||||
_ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::<Result<_, _>>()?,
|
||||
};
|
||||
match pt::without_spans(sp, spans, &marks) {
|
||||
Some(pieces) => {
|
||||
count += marks.iter().filter(|m| **m).count();
|
||||
removed.extend(spans.iter().zip(&marks).filter(|(_, m)| **m).map(|(s, _)| pt::slice(sp, *s)).filter(|p| p.anchors.len() >= 2));
|
||||
subs.extend(pieces);
|
||||
}
|
||||
None => subs.push(sp.clone()),
|
||||
}
|
||||
}
|
||||
Ok((count > 0).then_some((subs, removed, count)))
|
||||
}
|
||||
|
||||
/// What `pick` removes from the document's paths, bottom to top. With `isolation` (the isolated
|
||||
/// object in isolation mode, see [`crate::ordinary_isolation`]) only paths inside it are trimmed;
|
||||
/// paths outside it still cross them. `stretches` must hold only what it learned from this
|
||||
/// document as it is.
|
||||
pub fn plan(d: &Document, isolation: Option<NodeId>, pick: &Pick, limits: Limits, stretches: &mut Stretches) -> Result<Vec<Trimmed>, TooMuch> {
|
||||
let parts = parts(d);
|
||||
let in_scope = |id: NodeId| isolation.is_none_or(|r| id == r || d.ancestry(id).is_some_and(|a| a.contains(&r)));
|
||||
// The paths to trim, each with the place `at` falls on.
|
||||
let targets: Vec<(usize, Option<pt::Place>)> = match pick {
|
||||
Pick::At(at, tolerance) => {
|
||||
let mut best: Option<(usize, pt::Place, f64)> = None;
|
||||
for (i, (id, path, b)) in parts.iter().enumerate() {
|
||||
if !in_scope(*id) {
|
||||
continue;
|
||||
}
|
||||
let b = b.inflate(*tolerance, *tolerance);
|
||||
if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) {
|
||||
continue;
|
||||
}
|
||||
// Of paths equally near, the one on top.
|
||||
if let Some((si, seg, t, _, dist)) = path.nearest(*at)
|
||||
&& dist <= *tolerance
|
||||
&& best.is_none_or(|b| dist <= b.2)
|
||||
{
|
||||
best = Some((i, (si, seg, t), dist));
|
||||
}
|
||||
}
|
||||
best.map(|(i, on, _)| (i, Some(on))).into_iter().collect()
|
||||
}
|
||||
Pick::Rect(r) | Pick::Line(_, r) => {
|
||||
parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect()
|
||||
}
|
||||
};
|
||||
// Each path to trim has its box tested against every other path's.
|
||||
if targets.len() > limits.paths || targets.len().saturating_mul(parts.len()) > limits.box_tests {
|
||||
return Err(TooMuch::Paths);
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut budget = limits.line_tests;
|
||||
// A path that failed within a whole budget of another size may fit in this one.
|
||||
if stretches.whole != Some(limits.crossings) {
|
||||
stretches.too_much.clear();
|
||||
stretches.whole = Some(limits.crossings);
|
||||
}
|
||||
// One budget of crossing work for every path the pick trims.
|
||||
let mut work = limits.crossings;
|
||||
for (i, on) in targets {
|
||||
let Some((id, path, b)) = parts.get(i) else { continue };
|
||||
let reach = b.inflate(1e-3, 1e-3);
|
||||
let others = || parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect();
|
||||
let Some((subs, removed, count)) = trimmed(*id, path, &others, pick, on, &mut budget, &mut work, stretches)? else { continue };
|
||||
// A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths.
|
||||
let pieces = match (path.subpaths.len(), subs.is_empty()) {
|
||||
(_, true) => vec![],
|
||||
(1, false) => subs.into_iter().map(PathData::single).collect(),
|
||||
_ => vec![PathData::new(subs)],
|
||||
};
|
||||
out.push(Trimmed { id: *id, pieces, removed, count });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::{Appearance, Node};
|
||||
|
||||
fn row(y: f64, segments: usize) -> PathData {
|
||||
PathData::single(SubPath::polyline(&(0..=segments).map(|i| Point::new(i as f64 * 0.01, y)).collect::<Vec<_>>(), false))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_too_large_for_a_whole_budget_is_not_searched_again_and_one_cut_short_by_a_shared_budget_is() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut ids = vec![];
|
||||
for (i, p) in [row(0.0, 7000), row(10.0, 7000), row(20.0, 7000), row(30.0, 10_001)].into_iter().enumerate() {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), i, Node::path(id, p, Appearance::default_art())).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
let mut kept = Stretches::default();
|
||||
// More segments than a crossing search takes: no budget finds its crossings.
|
||||
assert_eq!(plan(&d, None, &Pick::At(Point::new(50.0, 30.0), 1.0), Limits::COMMAND, &mut kept), Err(TooMuch::Crossings));
|
||||
assert!(kept.too_much.contains(&ids[3]));
|
||||
// The third of three rows runs out of the budget the rectangle shares; alone it has enough.
|
||||
let rect = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 21.0));
|
||||
assert_eq!(plan(&d, None, &rect, Limits::COMMAND, &mut kept), Err(TooMuch::Crossings));
|
||||
assert!(!kept.too_much.contains(&ids[2]));
|
||||
assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 20.0), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1));
|
||||
// A row is too much for a twentieth of the budget, and is remembered only for picks with it.
|
||||
let small = Limits { crossings: pt::Work::share(20), ..Limits::COMMAND };
|
||||
let mut kept = Stretches::default();
|
||||
assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 10.0), 1.0), small, &mut kept), Err(TooMuch::Crossings));
|
||||
assert!(kept.too_much.contains(&ids[1]));
|
||||
assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 10.0), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1));
|
||||
assert!(!kept.too_much.contains(&ids[1]));
|
||||
kept.clear();
|
||||
assert!(kept.too_much.is_empty() && kept.by_path.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -164,6 +164,17 @@ pub enum PixelOp {
|
||||
Scaling,
|
||||
}
|
||||
|
||||
/// The isolated group, layer or object in isolation mode, of `isolation` (the document's isolated
|
||||
/// node). Pattern editing mode, opacity mask editing and symbol editing mode isolate their own
|
||||
/// layer, which does not count here; an object isolated inside them counts.
|
||||
pub fn ordinary_isolation(doc: &Document, isolation: Option<NodeId>) -> Option<NodeId> {
|
||||
isolation.filter(|l| {
|
||||
!doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read-only context a tool sees.
|
||||
pub struct ToolContext<'a> {
|
||||
pub doc: &'a Document,
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
//! gives there. The other tools
|
||||
//! collect the drag polyline (shown as an overlay) and run one command on release. With Shift
|
||||
//! held, the Blob Brush's points stay on the horizontal or
|
||||
//! vertical line through the press point. Alt held at the press, or before the Blob Brush's drag
|
||||
//! vertical line through the press point, and the Eraser's on the line from the press point at the
|
||||
//! nearest 45° step from the Constrain Angle. Alt held at the press, or before the Blob Brush's drag
|
||||
//! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths.
|
||||
//! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke
|
||||
//! begins closes the path on release.
|
||||
@@ -80,6 +81,9 @@ const BAND_WORK_PER_CALL: usize = 20_000;
|
||||
const PREVIEW_FIDELITY_PX: f64 = 0.5;
|
||||
/// The Smooth tool's Fidelity (screen pixels) until Smooth Tool Options sets another.
|
||||
const SMOOTH_FIDELITY: f64 = 2.5;
|
||||
/// How far the pointer goes from the press point, in screen pixels, before a Shift-drag of the
|
||||
/// Eraser takes the 45° step it lies nearest to.
|
||||
const ERASER_SHIFT_PX: f64 = 3.0;
|
||||
|
||||
/// The `fidelity` (points) the Pencil and the Paintbrush send `path.freehand` for `px` screen pixels
|
||||
/// at the current zoom, within the range the command takes
|
||||
@@ -176,7 +180,8 @@ pub struct GestureTool {
|
||||
/// The straight line is not constrained to 45° steps: the Pencil's Alt line, whose end snaps to
|
||||
/// Smart Guides as a stroke's end does, or the Knife's line while Shift is up.
|
||||
unconstrained: bool,
|
||||
/// Axis selected during the current uninterrupted Shift interval, in degrees.
|
||||
/// Axis selected during the current uninterrupted Shift interval, in degrees: the Blob Brush's
|
||||
/// horizontal or vertical, or the Eraser's 45° step.
|
||||
shift_line: Option<f64>,
|
||||
/// "Merge only with selection": a Blob Brush stroke merges only with selected paths.
|
||||
pub merge_only_selection: bool,
|
||||
@@ -1019,9 +1024,10 @@ impl GestureTool {
|
||||
}
|
||||
|
||||
/// Constrain a straight Pencil line from the Constrain Angle, a straight Knife cut from the
|
||||
/// canvas axes, or the current Blob Brush sample. Blob Brush chooses an
|
||||
/// axis once per uninterrupted Shift interval; samples already drawn never move.
|
||||
/// A smoothing drag follows the pointer without a Shift constraint.
|
||||
/// canvas axes, or the current Blob Brush or Eraser sample. The Blob Brush chooses an axis,
|
||||
/// and the Eraser a 45° step from the Constrain Angle, once per uninterrupted Shift interval;
|
||||
/// samples already drawn never move. A smoothing drag follows the pointer without a Shift
|
||||
/// constraint.
|
||||
fn constrained(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Point {
|
||||
if self.straight && self.unconstrained {
|
||||
return p;
|
||||
@@ -1032,10 +1038,21 @@ impl GestureTool {
|
||||
let origin = if self.id == "knife" { 0.0 } else { cx.constrain_angle };
|
||||
return start + vectorcraft_geom::constrain_angle_from(p - start, 45.0, origin);
|
||||
}
|
||||
let Some(&start) = self.points.first().filter(|_| self.id == "blobBrush" && m.shift && !self.smoothing) else {
|
||||
let shifts = (self.id == "blobBrush" && !self.smoothing) || self.id == "eraser";
|
||||
let Some(&start) = self.points.first().filter(|_| shifts && m.shift) else {
|
||||
self.shift_line = None;
|
||||
return p;
|
||||
};
|
||||
if self.id == "eraser" && self.shift_line.is_none() {
|
||||
// The step is taken once the pointer is clear of the press point, in screen pixels at
|
||||
// any zoom; until then the stroke waits at its last sample.
|
||||
let v = p - start;
|
||||
if v.hypot() * cx.zoom < ERASER_SHIFT_PX {
|
||||
return self.points.last().copied().unwrap_or(start);
|
||||
}
|
||||
let c = vectorcraft_geom::constrain_angle_from(v, 45.0, cx.constrain_angle);
|
||||
self.shift_line = Some(-c.y.atan2(c.x).to_degrees());
|
||||
}
|
||||
if self.shift_line.is_none() {
|
||||
// Raw press-to-pointer displacement in logical screen pixels along the constraint
|
||||
// axes. Zoom changes the document distance, not the activation tolerance.
|
||||
@@ -1055,6 +1072,16 @@ impl GestureTool {
|
||||
start + vectorcraft_geom::constrain_angle_from(p - start, 180.0, self.shift_line.unwrap_or(cx.constrain_angle))
|
||||
}
|
||||
|
||||
/// [`Self::constrained`] for a drag to `p`: the Eraser's tip outline shows where its stroke
|
||||
/// is, on the line of a Shift-drag.
|
||||
fn constrained_drag(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Point {
|
||||
let p = self.constrained(cx, p, m);
|
||||
if self.id == "eraser" && self.tip_at.is_some() {
|
||||
self.tip_at = Some(p);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline
|
||||
/// `size` across at its angle and roundness (the Eraser's as the pen varies them while it
|
||||
/// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on
|
||||
@@ -1612,7 +1639,7 @@ impl Tool for GestureTool {
|
||||
}
|
||||
self.knife_shift(ev.mods);
|
||||
self.moved |= self.points.first().is_some_and(|start| p.distance(*start) > vectorcraft_geom::EPS);
|
||||
let p = self.constrained(cx, p, ev.mods);
|
||||
let p = self.constrained_drag(cx, p, ev.mods);
|
||||
let mut end = p;
|
||||
if self.grid_snaps(cx) && !self.smoothing && !self.straight {
|
||||
// Where the stroke would end on the grid or a pixel: taken on release.
|
||||
|
||||
@@ -2032,6 +2032,76 @@ fn eraser_and_knife_exec_on_release() {
|
||||
assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.knife" && v["points"].as_array().unwrap().len() == 3));
|
||||
}
|
||||
|
||||
/// With Shift held the Eraser's stroke stays on the line from the press point at the 45° step,
|
||||
/// from the Constrain Angle, that the pointer lies nearest to once it is 3 screen pixels away:
|
||||
/// horizontal, vertical or diagonal. The step holds until Shift is released, the tip outline shows
|
||||
/// on the line, and the drag goes on freehand from the last sample on the line without moving it.
|
||||
#[test]
|
||||
fn eraser_shift_keeps_the_stroke_on_a_45_degree_line() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let mut cx = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = GestureTool::new("eraser");
|
||||
let ev = |k, x, y, m| PointerEvent::new(k, x, y).with_mods(m);
|
||||
let on_line = |q: Point, deg: f64| (q.x * deg.to_radians().sin() + q.y * deg.to_radians().cos()).abs() < 1e-9;
|
||||
for zoom in [0.5, 1.0, 4.0] {
|
||||
cx.zoom = zoom;
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 0.0, 0.0, shift));
|
||||
// Within 3 screen pixels of the press the stroke waits there, and so does its tip.
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 2.0 / zoom, 2.0 / zoom, shift));
|
||||
assert_eq!(t.points, vec![Point::ZERO]);
|
||||
assert_eq!(t.tip_at, Some(Point::ZERO));
|
||||
// 22° below the horizontal: the horizontal step, at the pointer's distance.
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 10.0 / zoom, 4.0 / zoom, shift));
|
||||
let first = t.points[1];
|
||||
assert!((first.x - 116f64.sqrt() / zoom).abs() < 1e-9 && first.y.abs() < 1e-9, "{first:?}");
|
||||
assert_eq!(t.tip_at, Some(first));
|
||||
// The step holds while Shift stays down.
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 3.0 / zoom, 20.0 / zoom, shift));
|
||||
assert!(t.points.iter().all(|q| q.y.abs() < 1e-9), "{:?}", t.points);
|
||||
// Released, the drag goes on freehand from there.
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 30.0 / zoom, 25.0 / zoom, Mods::default()));
|
||||
assert_eq!(t.points.last(), Some(&Point::new(30.0 / zoom, 25.0 / zoom)));
|
||||
assert_eq!(t.tip_at, Some(Point::new(30.0 / zoom, 25.0 / zoom)));
|
||||
assert_eq!(t.points[1], first);
|
||||
// Shift again takes a new step from the press point: the diagonal down and to the right.
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 40.0 / zoom, 36.0 / zoom, shift));
|
||||
let q = *t.points.last().unwrap();
|
||||
assert!((q.x - q.y).abs() < 1e-9 && q.x > 0.0, "{q:?}");
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 50.0 / zoom, 44.0 / zoom, shift));
|
||||
let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
assert_eq!(c, "path.eraseRegion");
|
||||
let last = v["points"].as_array().unwrap().last().unwrap().clone();
|
||||
let (x, y) = (last[0].as_f64().unwrap(), last[1].as_f64().unwrap());
|
||||
assert!((x - y).abs() < 1e-9 && x > 0.0, "{last}");
|
||||
}
|
||||
// The steps go from the Constrain Angle, counter-clockwise on the page: at 30°, a drag at 70°
|
||||
// takes the 75° step and one at 105° the 120° step, either way from the press.
|
||||
cx.zoom = 1.0;
|
||||
cx.constrain_angle = 30.0;
|
||||
for (drag, step) in [(70.0_f64, 75.0), (105.0, 120.0), (-150.0, -150.0), (40.0, 30.0)] {
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0, shift));
|
||||
let r = drag.to_radians();
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 100.0 + 20.0 * r.cos(), 100.0 - 20.0 * r.sin(), shift));
|
||||
let q = t.points[1] - Point::new(100.0, 100.0);
|
||||
assert!(on_line(Point::new(q.x, q.y), step), "drag {drag}: {q:?}");
|
||||
assert!((q.hypot() - 20.0).abs() < 1e-9);
|
||||
// Along the step's line both ways: back past the press stays on it.
|
||||
let r = (step + 180.0).to_radians();
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 100.0 + 5.0 * r.cos() + 3.0, 100.0 - 5.0 * r.sin(), shift));
|
||||
let q = *t.points.last().unwrap() - Point::new(100.0, 100.0);
|
||||
assert!(on_line(Point::new(q.x, q.y), step), "drag {drag} back: {q:?}");
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 100.0, 100.0, Mods::default()));
|
||||
}
|
||||
// A Shift-drag released within 3 pixels of the press erases at the press.
|
||||
cx.constrain_angle = 0.0;
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 20.0, 20.0, shift));
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 22.0, 21.0, shift));
|
||||
assert!(matches!(&acts[0], Action::Exec(c, v) if c == "path.eraseRegion" && v["points"] == json!([[20.0, 20.0]])), "{acts:?}");
|
||||
}
|
||||
|
||||
/// An Alt-drag with the Eraser shows a marquee from the press point to the pointer, without the
|
||||
/// tip outline, and the release erases that rectangle; a drag back up and left gives the same
|
||||
/// kind of rectangle, measured from its top-left corner.
|
||||
|
||||
@@ -59,7 +59,7 @@ mod cursor;
|
||||
mod input;
|
||||
mod readout;
|
||||
|
||||
pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext};
|
||||
pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext, ordinary_isolation};
|
||||
pub use cursor::Cursor;
|
||||
pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey};
|
||||
pub use readout::Readout;
|
||||
|
||||
@@ -72,7 +72,7 @@ pub use gradient::TracedGradient;
|
||||
pub use mosaic::mosaic;
|
||||
pub use opaque::{ALPHA_MAX_DECODE_BYTES, OUTLINE_MAX_ANCHORS, OUTLINE_MAX_PIXELS, decode_alpha, opaque_outline};
|
||||
pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize};
|
||||
pub use seam::{SEAM_WIDTH, seam_fills};
|
||||
pub use seam::{SeamFills, seam_fills};
|
||||
pub use shapes::TracedShape;
|
||||
use subpixel::Crack;
|
||||
|
||||
|
||||
+108
-43
@@ -6,19 +6,38 @@
|
||||
//! under every path, fills those pixels with that color: drawing the two paths over it then gives
|
||||
//! each pixel the colors of the two paths in the shares each covers. The paths themselves are not
|
||||
//! changed, and an edge a path shares with no other path (the image's border, a transparent area,
|
||||
//! a color left out) gets no stroke.
|
||||
//! a color left out) gets no stroke. The strokes are clipped to the image's box. Where a shared
|
||||
//! edge ends at, or runs within half the stroke's width of, a transparent area or a color left
|
||||
//! out, its stroke can reach that far into that area.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
use super::params::{Method, Mode, TraceParams};
|
||||
use super::pipeline::TracedPath;
|
||||
use crate::{Method, Mode, TraceParams, TracedPath};
|
||||
|
||||
/// How wide each seam fill's stroke is, in pixels: it covers every pixel the shared edge passes
|
||||
/// through, at any angle (a pixel's corner is up to 0.71 px from a line through it).
|
||||
pub const SEAM_WIDTH: f64 = 1.5;
|
||||
const SEAM_WIDTH: f64 = 1.5;
|
||||
|
||||
/// The seam fills of an Abutting trace ([`seam_fills`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SeamFills {
|
||||
/// For each color, one path stroked 1.5 pixels wide along the edges where a filled path of
|
||||
/// that color meets a filled path drawn after it, with `color` and `gradient` that path's; the
|
||||
/// paths with a gradient get one each. Bottom-most first, as the paths they lie under.
|
||||
pub strokes: Vec<TracedPath>,
|
||||
/// The area to clip `strokes` to, in the same pixel coordinates: the image's box.
|
||||
pub clip: PathData,
|
||||
}
|
||||
|
||||
impl SeamFills {
|
||||
/// The anchors of the strokes and the clip together.
|
||||
pub fn anchor_count(&self) -> usize {
|
||||
self.strokes.iter().map(|s| s.path.anchor_count()).sum::<usize>() + self.clip.anchor_count()
|
||||
}
|
||||
}
|
||||
|
||||
/// A segment, the same for the segment and the segment run backwards: two 64-bit hashes of its
|
||||
/// points' bits, 16 bytes a segment instead of 64. Two different segments with the same key would
|
||||
@@ -36,18 +55,23 @@ fn key(a: &Anchor, b: &Anchor) -> Key {
|
||||
(u128::from(hash(0)) << 64) | u128::from(hash(1))
|
||||
}
|
||||
|
||||
/// The seam fills of a trace made with `params`: for Abutting with Fills (not Flat Logo), thin
|
||||
/// strokes to draw under every path of `paths` (bottom-most first). For each color, one path
|
||||
/// stroked [`SEAM_WIDTH`] pixels wide along the edges where a filled path of that color meets a
|
||||
/// filled path drawn after it, with `color` and `gradient` that path's; the paths with a gradient
|
||||
/// get one each. Bottom-most first, as the paths they lie under. The stroke has at most as many
|
||||
/// anchors as `paths` (each of its segments is a segment of a path), and finding them keeps about
|
||||
/// 40 bytes for each segment of `paths` while it runs. Empty for any other trace.
|
||||
pub fn seam_fills(paths: &[TracedPath], params: &TraceParams) -> Vec<TracedPath> {
|
||||
/// The seam fills of a trace of a `size` (width, height in pixels) image made with `params`, for
|
||||
/// Abutting with Fills (not Flat Logo): strokes to draw under every path of `paths` (bottom-most
|
||||
/// first), clipped to the image's box. Filled paths that became a live shape (Shapes) take no part:
|
||||
/// their outline is not the traced one. The strokes have at most as many anchors as `paths` (each
|
||||
/// of their segments is a segment of a path), and the clip has four; finding them keeps about 40
|
||||
/// bytes for each segment of `paths` while it runs. `None` for any other trace, or when no filled
|
||||
/// paths share an edge.
|
||||
pub fn seam_fills(paths: &[TracedPath], params: &TraceParams, size: (u32, u32)) -> Option<SeamFills> {
|
||||
if params.method != Method::Abutting || !params.fills || params.mode == Mode::Logo {
|
||||
return vec![];
|
||||
return None;
|
||||
}
|
||||
fills(paths)
|
||||
fills(paths, size)
|
||||
}
|
||||
|
||||
/// Whether `p` takes part in the seam fills: filled, and drawn with its traced outline.
|
||||
fn filled(p: &TracedPath) -> bool {
|
||||
p.stroke.is_none() && p.shape.is_none()
|
||||
}
|
||||
|
||||
/// The segments of `sp`: each anchor and the one after it (back to the first, if closed).
|
||||
@@ -57,11 +81,11 @@ fn segments(sp: &SubPath) -> impl Iterator<Item = (&Anchor, &Anchor)> {
|
||||
(0..count).filter_map(move |k| Some((sp.anchors.get(k)?, sp.anchors.get((k + 1) % n)?)))
|
||||
}
|
||||
|
||||
/// [`seam_fills`] of Abutting `paths`, whatever the settings.
|
||||
fn fills(paths: &[TracedPath]) -> Vec<TracedPath> {
|
||||
/// [`seam_fills`] of Abutting `paths` traced from a `size` image, whatever the settings.
|
||||
fn fills(paths: &[TracedPath], size: (u32, u32)) -> Option<SeamFills> {
|
||||
// For each segment, the first path it is in, and whether another path has it too.
|
||||
let mut owner: HashMap<Key, (usize, bool)> = HashMap::new();
|
||||
for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) {
|
||||
for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) {
|
||||
for sp in &p.path.subpaths {
|
||||
for (a, b) in segments(sp).filter(|(a, b)| a.p != b.p) {
|
||||
let e = owner.entry(key(a, b)).or_insert((i, false));
|
||||
@@ -74,11 +98,10 @@ fn fills(paths: &[TracedPath]) -> Vec<TracedPath> {
|
||||
// One fill per color (per path, for a gradient), in the order of the first path it lies under.
|
||||
let mut out: Vec<TracedPath> = vec![];
|
||||
let mut by_color: HashMap<[u8; 3], usize> = HashMap::new();
|
||||
for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) {
|
||||
for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) {
|
||||
let mut runs: Vec<SubPath> = vec![];
|
||||
for sp in &p.path.subpaths {
|
||||
let lower = |a: &Anchor, b: &Anchor| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true));
|
||||
let marks: Vec<bool> = segments(sp).map(|(a, b)| lower(a, b)).collect();
|
||||
let marks: Vec<bool> = segments(sp).map(|(a, b)| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true))).collect();
|
||||
let n = sp.anchors.len();
|
||||
if marks.is_empty() {
|
||||
continue;
|
||||
@@ -129,7 +152,12 @@ fn fills(paths: &[TracedPath]) -> Vec<TracedPath> {
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
if out.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (f64::from(size.0), f64::from(size.1));
|
||||
let clip = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)], true));
|
||||
Some(SeamFills { strokes: out, clip })
|
||||
}
|
||||
|
||||
/// An open run of anchors: the last one has no handle out.
|
||||
@@ -143,13 +171,18 @@ fn open_run(mut run: Vec<Anchor>) -> SubPath {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Method, Mode, Raster, TraceParams, trace};
|
||||
use crate::{Method, Mode, Raster, TraceParams, TracedGradient, TracedShape, trace};
|
||||
|
||||
fn polygon(rings: &[&[(f64, f64)]], color: u8) -> TracedPath {
|
||||
let subpaths = rings.iter().map(|r| SubPath::polyline(&r.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), true)).collect();
|
||||
TracedPath { path: PathData::new(subpaths), color: [color; 3], pixels: 1, stroke: None, shape: None, gradient: None, square_caps: false }
|
||||
}
|
||||
|
||||
/// The strokes of [`fills`] for `paths` in a box that no test path reaches the border of.
|
||||
fn strokes(paths: &[TracedPath]) -> Vec<TracedPath> {
|
||||
fills(paths, (100, 100)).map(|f| f.strokes).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn points(sp: &SubPath) -> Vec<(f64, f64)> {
|
||||
sp.anchors.iter().map(|a| (a.p.x, a.p.y)).collect()
|
||||
}
|
||||
@@ -163,7 +196,7 @@ mod tests {
|
||||
fn a_shared_edge_gets_a_stroke_in_the_color_of_the_path_drawn_first() {
|
||||
let left = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10);
|
||||
let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20);
|
||||
let fills = fills(&[left.clone(), right.clone()]);
|
||||
let fills = strokes(&[left.clone(), right.clone()]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!((fills[0].color, fills[0].stroke, fills[0].gradient.as_ref()), ([10; 3], Some(SEAM_WIDTH), None));
|
||||
assert_eq!(fills[0].path.subpaths.len(), 1);
|
||||
@@ -171,7 +204,7 @@ mod tests {
|
||||
assert!(!sp.closed);
|
||||
assert_eq!(points(sp), [(2.0, 0.0), (2.0, 2.0)]);
|
||||
// Drawn the other way round, the stroke takes the other color.
|
||||
let swapped = super::fills(&[right, left]);
|
||||
let swapped = strokes(&[right, left]);
|
||||
assert_eq!(swapped.len(), 1);
|
||||
assert_eq!((swapped[0].color, points(&swapped[0].path.subpaths[0])), ([20; 3], vec![(2.0, 2.0), (2.0, 0.0)]));
|
||||
}
|
||||
@@ -181,7 +214,7 @@ mod tests {
|
||||
let hole: &[(f64, f64)] = &[(2.0, 2.0), (2.0, 4.0), (4.0, 4.0), (4.0, 2.0)];
|
||||
let around = polygon(&[&[(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)], hole], 10);
|
||||
let island = polygon(&[&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]], 20);
|
||||
let fills = fills(&[around, island]);
|
||||
let fills = strokes(&[around, island]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!(fills[0].color, [10; 3]);
|
||||
assert_eq!(fills[0].path.subpaths.len(), 1);
|
||||
@@ -195,7 +228,7 @@ mod tests {
|
||||
// at the same point.
|
||||
let left = polygon(&[&[(2.0, 1.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0), (2.0, 0.0)]], 10);
|
||||
let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0), (2.0, 1.0)]], 20);
|
||||
let fills = fills(&[left, right]);
|
||||
let fills = strokes(&[left, right]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!(fills[0].path.subpaths.len(), 1);
|
||||
assert_eq!(points(&fills[0].path.subpaths[0]), [(2.0, 0.0), (2.0, 1.0), (2.0, 2.0)]);
|
||||
@@ -204,11 +237,15 @@ mod tests {
|
||||
#[test]
|
||||
fn edges_shared_with_no_other_filled_path_get_no_stroke() {
|
||||
let square = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10);
|
||||
assert_eq!(fills(std::slice::from_ref(&square)), []);
|
||||
// A stroked line along the square's edge is not a filled neighbour.
|
||||
let mut line = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20);
|
||||
line.stroke = Some(1.0);
|
||||
assert_eq!(fills(&[square, line]), []);
|
||||
assert_eq!(fills(std::slice::from_ref(&square), (100, 100)), None);
|
||||
// A stroked path along the square's edge is not a filled neighbor.
|
||||
let mut stroked = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20);
|
||||
stroked.stroke = Some(1.0);
|
||||
assert_eq!(fills(&[square.clone(), stroked], (100, 100)), None);
|
||||
// Nor is a path drawn as a live shape, whose outline is not the traced one.
|
||||
let mut shape = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20);
|
||||
shape.shape = Some(TracedShape::Rectangle { center: Point::new(3.0, 1.0), width: 2.0, height: 2.0, radius: 0.0, rotation: 0.0 });
|
||||
assert_eq!(fills(&[square, shape], (100, 100)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -216,9 +253,34 @@ mod tests {
|
||||
let a = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10);
|
||||
let b = polygon(&[&[(0.0, 4.0), (2.0, 4.0), (2.0, 6.0), (0.0, 6.0)]], 10);
|
||||
let c = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 6.0), (2.0, 6.0), (2.0, 4.0), (2.0, 2.0)]], 20);
|
||||
let fills = fills(&[a, b, c]);
|
||||
let fills = strokes(&[a.clone(), b.clone(), c.clone()]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!(fills[0].path.subpaths.iter().map(points).collect::<Vec<_>>(), [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]]);
|
||||
// With a gradient each, the two paths of one color get a stroke each, with their gradient.
|
||||
let ramp = |to: u8| TracedGradient { start: Point::new(0.0, 0.0), end: Point::new(2.0, 0.0), stops: vec![(0.0, [10; 3]), (1.0, [to; 3])] };
|
||||
let (mut a, mut b) = (a, b);
|
||||
(a.gradient, b.gradient) = (Some(ramp(30)), Some(ramp(40)));
|
||||
let fills = strokes(&[a.clone(), b.clone(), c]);
|
||||
assert_eq!(fills.len(), 2, "{fills:?}");
|
||||
assert_eq!(fills.iter().map(|f| f.gradient.clone()).collect::<Vec<_>>(), [a.gradient, b.gradient]);
|
||||
assert_eq!(
|
||||
fills.iter().map(|f| points(&f.path.subpaths[0])).collect::<Vec<_>>(),
|
||||
[vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_strokes_are_clipped_to_the_images_box() {
|
||||
// A diagonal edge meeting the border: a corner of the stroke's butt end reaches past the
|
||||
// box, and the clip is the box.
|
||||
let lower = polygon(&[&[(0.0, 0.0), (3.0, 0.0), (1.0, 2.0), (0.0, 2.0)]], 10);
|
||||
let upper = polygon(&[&[(3.0, 0.0), (4.0, 0.0), (4.0, 2.0), (1.0, 2.0)]], 20);
|
||||
let diagonal = fills(&[lower, upper], (4, 2)).unwrap();
|
||||
assert_eq!(points(&diagonal.strokes[0].path.subpaths[0]), [(3.0, 0.0), (1.0, 2.0)]);
|
||||
assert_eq!(diagonal.clip.subpaths.len(), 1);
|
||||
assert!(diagonal.clip.subpaths[0].closed);
|
||||
assert_eq!(points(&diagonal.clip.subpaths[0]), [(0.0, 0.0), (4.0, 0.0), (4.0, 2.0), (0.0, 2.0)]);
|
||||
assert_eq!(diagonal.anchor_count(), 2 + 4);
|
||||
}
|
||||
|
||||
/// Two colors side by side, the edge between them anti-aliased at `x = 10.4`.
|
||||
@@ -239,9 +301,9 @@ mod tests {
|
||||
let params = color(Method::Abutting);
|
||||
let res = trace(&two_colors(), ¶ms);
|
||||
assert_eq!(res.paths.len(), 2, "{res:?}");
|
||||
let seams = seam_fills(&res.paths, ¶ms);
|
||||
assert_eq!(seams.len(), 1, "{seams:?}");
|
||||
let seam = &seams[0];
|
||||
let fills = seam_fills(&res.paths, ¶ms, (24, 16)).unwrap();
|
||||
assert_eq!(fills.strokes.len(), 1, "{fills:?}");
|
||||
let seam = &fills.strokes[0];
|
||||
assert_eq!((seam.color, seam.stroke), (res.paths[0].color, Some(SEAM_WIDTH)));
|
||||
// Every piece of the stroke is a piece of both paths, and it runs from the image's top to
|
||||
// its bottom along the edge, not along the image's border.
|
||||
@@ -253,25 +315,28 @@ mod tests {
|
||||
}
|
||||
let ys: Vec<f64> = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect();
|
||||
assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0));
|
||||
// The clip is the image's box.
|
||||
let corners: Vec<(f64, f64)> = fills.clip.subpaths.iter().flat_map(points).collect();
|
||||
assert_eq!(corners, [(0.0, 0.0), (24.0, 0.0), (24.0, 16.0), (0.0, 16.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_abutting_fills_get_seam_strokes() {
|
||||
let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params);
|
||||
let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params, (img.width, img.height));
|
||||
let img = two_colors();
|
||||
assert_eq!(seams(&img, &color(Method::Overlapping)), []);
|
||||
assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), []);
|
||||
assert_eq!(seams(&img, &color(Method::Overlapping)), None);
|
||||
assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), None);
|
||||
// Flat Logo's shapes are stacked, whatever the method says.
|
||||
let abutting = trace(&img, &color(Method::Abutting));
|
||||
assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }), []);
|
||||
// A color left out leaves no neighbour: a dark bar on white, with Ignore White.
|
||||
assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }, (24, 16)), None);
|
||||
// A color left out leaves no neighbor: a dark bar on white, with Ignore White.
|
||||
let bar = Raster::from_fn(24, 16, |x, _| if (8..16).contains(&x) { [0, 0, 0, 255] } else { [255; 4] });
|
||||
let bw = TraceParams { mode: Mode::BlackAndWhite, method: Method::Abutting, ignore_white: true, ..TraceParams::default() };
|
||||
let res = trace(&bar, &bw);
|
||||
assert_eq!(res.paths.len(), 1, "{res:?}");
|
||||
assert_eq!(seam_fills(&res.paths, &bw), []);
|
||||
assert_eq!(seam_fills(&res.paths, &bw, (24, 16)), None);
|
||||
// Both colors traced, the bar's two sides are shared.
|
||||
let both = seams(&bar, &TraceParams { ignore_white: false, ..bw });
|
||||
assert_eq!(both.iter().map(|s| s.path.subpaths.len()).sum::<usize>(), 2, "{both:?}");
|
||||
let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }).unwrap();
|
||||
assert_eq!(both.strokes.iter().map(|s| s.path.subpaths.len()).sum::<usize>(), 2, "{both:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools),
|
||||
//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into
|
||||
//! Dashes ([`dashes`]), Expand Dashes into Paths and Convert to Parametric Shape; the Anchor Inspector panel (the selected
|
||||
//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected
|
||||
//! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values,
|
||||
//! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel
|
||||
//! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and
|
||||
@@ -11,6 +11,7 @@ pub mod dashes;
|
||||
pub mod set_corners;
|
||||
pub mod shape;
|
||||
pub mod shared_edge;
|
||||
pub mod tangent_circle;
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -70,6 +71,7 @@ pub fn menu() -> Vec<Item> {
|
||||
Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null),
|
||||
Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})),
|
||||
Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})),
|
||||
Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Tangent Circle in the interface: its dialog (the radius, with two shapes selected, and which
|
||||
//! circle to draw, or all), which previews the circles on the canvas and runs
|
||||
//! `addon.pathtools.tangentCircle` on OK.
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::dialogs::{DialogSpec, form};
|
||||
use crate::state::Dialog;
|
||||
use crate::widgets;
|
||||
|
||||
/// The command, and its dialog's kind.
|
||||
pub const COMMAND: &str = "addon.pathtools.tangentCircle";
|
||||
pub const KIND: &str = "tangentCircle";
|
||||
/// The radius the command takes (pt).
|
||||
const RADII: std::ops::RangeInclusive<f64> = 0.01..=1e6;
|
||||
/// The most circles the command lists.
|
||||
const MAX_CIRCLES: u64 = 64;
|
||||
const LABEL_W: f32 = 60.0;
|
||||
const FIELD_W: f32 = 90.0;
|
||||
/// How many circles the last preview found (a private field).
|
||||
const FOUND: &str = "__found";
|
||||
/// The parameters the last preview ran with (a private field).
|
||||
const TRIED: &str = "__tried";
|
||||
|
||||
/// How many objects were selected when the dialog opened (a private field): two take a radius,
|
||||
/// three set it themselves. The preview selects the circles it draws, so the count is kept.
|
||||
const SHAPES: &str = "__shapes";
|
||||
|
||||
/// The dialog's fields to start with: a radius of 36 pt, every circle, Preview on (the Circle menu
|
||||
/// lists the circles the last preview found), and the selection's size.
|
||||
pub(crate) fn fields(app: &VectorcraftApp) -> Value {
|
||||
let shapes = app.session.active().map_or(0, |st| st.selection.objects.len());
|
||||
json!({ "radius": 36, "circle": 0, "preview": true, SHAPES: shapes })
|
||||
}
|
||||
|
||||
pub(crate) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Tangent Circle").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM };
|
||||
|
||||
fn shapes(d: &Dialog) -> u64 {
|
||||
d.fields.get(SHAPES).and_then(Value::as_u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The command's parameters: the radius only with two shapes.
|
||||
fn params(d: &Dialog) -> Value {
|
||||
let mut p = json!({ "circle": d.fields.get("circle").cloned().unwrap_or(json!(0)) });
|
||||
if shapes(d) == 2
|
||||
&& let (Some(o), Some(r)) = (p.as_object_mut(), d.fields.get("radius"))
|
||||
{
|
||||
o.insert("radius".into(), r.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
let unit = app.session.general_unit();
|
||||
widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| {
|
||||
ui.add_enabled_ui(shapes(d) == 2, |ui| form::length_within(ui, d, "radius", unit, FIELD_W, Some(RADII)));
|
||||
});
|
||||
// The command lists at most 64 circles; the menu never holds more.
|
||||
let found = d.fields.get(FOUND).and_then(Value::as_u64).unwrap_or(0).min(MAX_CIRCLES);
|
||||
let pick = d.fields.get("circle").and_then(Value::as_u64).unwrap_or(0).min(MAX_CIRCLES);
|
||||
let mut options = vec![tl!("All").to_string()];
|
||||
options.extend((1..=found.max(pick)).map(|n| n.to_string()));
|
||||
let names: Vec<&str> = options.iter().map(String::as_str).collect();
|
||||
let current = options.get(usize::try_from(pick).unwrap_or(0)).cloned().unwrap_or_default();
|
||||
widgets::label_row(ui, tl!("Circle:"), LABEL_W, |ui| {
|
||||
if let Some(i) = widgets::dropdown_names(ui, "tangent-circle-pick", ¤t, &names, FIELD_W) {
|
||||
d.fields.insert("circle".into(), json!(i));
|
||||
}
|
||||
});
|
||||
let p = params(d);
|
||||
let fresh = d.fields.get(TRIED) != Some(&p);
|
||||
match form::preview_result(app, ui, d, "Tangent Circle", COMMAND, p.clone()) {
|
||||
Some(r) => {
|
||||
d.fields.insert(FOUND.into(), r["found"].clone());
|
||||
}
|
||||
// A new radius or pick found nothing: the menu no longer lists the earlier circles, and a
|
||||
// pick past the circles left shows them all again.
|
||||
None if fresh && d.bool("preview") => {
|
||||
d.fields.insert(FOUND.into(), json!(0));
|
||||
if pick > 0 {
|
||||
d.fields.insert("circle".into(), json!(0));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
d.fields.insert(TRIED.into(), p);
|
||||
false
|
||||
}
|
||||
|
||||
/// OK: run the command (keep its preview) and close.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
form::commit_preview(app, COMMAND, params(d))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::tests_labels::painted_text;
|
||||
use crate::{VectorcraftApp, menus};
|
||||
|
||||
fn circle(app: &mut VectorcraftApp, cx: f64, cy: f64, r: f64) -> u64 {
|
||||
app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = circle(&mut app, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut app, 130.0, 100.0, 10.0);
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
let entries = menus::menu_entries(&app);
|
||||
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Tangent Circle…").unwrap();
|
||||
let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
|
||||
menus::invoke(&mut app, &cmd, p);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND));
|
||||
let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
for s in ["Tangent Circle", "Radius:", "Circle:", "All", "Preview"] {
|
||||
assert!(shown.contains(s), "{s} in {shown}");
|
||||
}
|
||||
let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
// Preview is on from the start: radius 36 gives eight circles, and the menu lists them.
|
||||
assert_eq!(count(&app), 10, "previewed on opening: {}", app.ui.status);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(8));
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("radius".into(), json!(20));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
// Six circles of radius 20 touch both: all previewed.
|
||||
assert_eq!(count(&app), 8, "previewed: {}", app.ui.status);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(6));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("circle".into(), json!(2));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert_eq!(count(&app), 3, "one previewed");
|
||||
// A pick past the circles found (a control request can set any number) goes back to All.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("circle".into(), json!(u64::MAX));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["circle"], json!(0));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(6));
|
||||
// Radius 2 cannot reach across the 10 pt gap: the menu lists no circles.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(2));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(0), "{}", app.ui.status);
|
||||
crate::dialogs::cancel(&mut app);
|
||||
assert_eq!(count(&app), 2, "rolled back");
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
menus::invoke(&mut app, &cmd, serde_json::Value::Null);
|
||||
let n = app.session.doc().unwrap().history.undo.len();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(5));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1);
|
||||
// Radius 5: the one circle in the gap.
|
||||
assert_eq!(count(&app), 3);
|
||||
}
|
||||
}
|
||||
@@ -472,6 +472,7 @@ registry! {
|
||||
RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC,
|
||||
PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC,
|
||||
DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC,
|
||||
TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC,
|
||||
SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC,
|
||||
NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC,
|
||||
SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC,
|
||||
|
||||
@@ -995,7 +995,7 @@ pub(crate) fn preview(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mu
|
||||
|
||||
/// As [`preview`], returning the command's result only when a new preview succeeds.
|
||||
/// A dialog can retain a small summary (such as point counts) in its private fields.
|
||||
pub(super) fn preview_result(
|
||||
pub(crate) fn preview_result(
|
||||
app: &mut crate::VectorcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
d: &mut Dialog,
|
||||
|
||||
@@ -344,5 +344,9 @@ pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, ids: &[&str],
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let (format, path) = (d.str("format"), d.str("path"));
|
||||
app.ui.dialog = None;
|
||||
io::export(app, Some(&format), Some(path), &super::export_as::exported(d, form::params(d)))
|
||||
let mut params = form::params(d);
|
||||
if format == "psd" {
|
||||
psd_options::drop_unused(&mut params);
|
||||
}
|
||||
io::export(app, Some(&format), Some(path), &super::export_as::exported(d, params))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The options of PSD (colour model, a flat image or layers, Maximum Editability, hidden layers,
|
||||
//! profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the
|
||||
//! The options of PSD (colour model, a flat image or layers, Preserve Text Editability, Maximum
|
||||
//! Editability, hidden layers, profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the
|
||||
//! `psdOptions` dialog.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -17,12 +17,23 @@ pub(super) fn defaults(cmyk: bool, o: &mut Map<String, Value>) {
|
||||
o.extend([
|
||||
("colorModel".into(), json!(model.id())),
|
||||
("layers".into(), json!(p.layers)),
|
||||
("preserveText".into(), json!(p.preserve_text)),
|
||||
("maxEditability".into(), json!(p.max_editability)),
|
||||
("hiddenLayers".into(), json!(p.hidden_layers)),
|
||||
("embedIcc".into(), json!(p.embed_icc)),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Flat Image writes no layers: the options that need them are left out of the export's params
|
||||
/// (`preserveText`, which the export refuses without layers).
|
||||
pub(super) fn drop_unused(p: &mut Value) {
|
||||
if p["layers"] == json!(false)
|
||||
&& let Some(o) = p.as_object_mut()
|
||||
{
|
||||
o.remove("preserveText");
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid rows of PSD's own options.
|
||||
pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Color Model:"));
|
||||
@@ -36,7 +47,11 @@ pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::
|
||||
d.fields.insert("layers".into(), json!(layers));
|
||||
}
|
||||
ui.add_enabled_ui(layers, |ui| {
|
||||
for (key, text) in [("maxEditability", tl!("Maximum Editability")), ("hiddenLayers", tl!("Include Hidden Layers"))] {
|
||||
for (key, text) in [
|
||||
("preserveText", tl!("Preserve Text Editability")),
|
||||
("maxEditability", tl!("Maximum Editability")),
|
||||
("hiddenLayers", tl!("Include Hidden Layers")),
|
||||
] {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(22.0);
|
||||
form::check(ui, d, key, text);
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
//! CMYK or Lab, and Tint when the new color is a spot color of the library), which edit the
|
||||
//! first selected row's new color (once they have, OK gives the art each new color in its own
|
||||
//! model), New Row (a row with no current colors above the first selected row, or at the top,
|
||||
//! with that row's new color; it recolors nothing until Merge moves colors into it), Merge and
|
||||
//! with that row's new color; it recolors nothing until Merge moves colors into it, and until then
|
||||
//! the Edit tab, the Color Theme Picker and Save All Colors leave it out), Merge and
|
||||
//! Separate, Randomize order or
|
||||
//! saturation and brightness, Find (with it on, the art of the selected rows shows as the preview
|
||||
//! shows it, their current colors with Preview off, and the rest of the selected art shows its
|
||||
@@ -38,9 +39,9 @@
|
||||
//! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an
|
||||
//! object takes the palette of the object a Selection tool click takes, a drag takes the palette
|
||||
//! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The
|
||||
//! rows that aren't excluded take the picked colors as their new colors, the most used color first
|
||||
//! and repeating when the rows outnumber them, and the art previews them; OK keeps them as one
|
||||
//! undo step. A new count of Colors keeps the picks: the new rows take them again.
|
||||
//! rows that aren't excluded and hold current colors take the picked colors as their new colors,
|
||||
//! the most used color first and repeating when the rows outnumber them, and the art previews
|
||||
//! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again.
|
||||
//!
|
||||
//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot
|
||||
//! color}]), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
|
||||
@@ -391,14 +392,15 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = &
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The New Color Group menu's request: save the new colors of the rows that aren't excluded (Save
|
||||
/// All Colors, in row order; a row without one gives its first current color) or of the Prominent Colors bar (Save Prominent Colors, in its order)
|
||||
/// as a new color group, a step of its own (`swatch.newGroup`).
|
||||
/// The New Color Group menu's request: save the new colors of the rows that aren't excluded and
|
||||
/// hold current colors (Save All Colors, in row order; a row without one gives its first current
|
||||
/// color) or of the Prominent Colors bar (Save Prominent Colors, in its order) as a new color
|
||||
/// group, a step of its own (`swatch.newGroup`).
|
||||
fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) {
|
||||
let rs = rows(d);
|
||||
let order: Vec<usize> = match which {
|
||||
"prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(),
|
||||
_ => (0..rs.len()).filter(|&i| !excluded(&rs[i])).collect(),
|
||||
_ => (0..rs.len()).filter(|&i| in_group(&rs[i])).collect(),
|
||||
};
|
||||
let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i)));
|
||||
if colors.is_empty() {
|
||||
@@ -417,10 +419,10 @@ const THEME_PICKER: &str = "themePicker";
|
||||
const THEME_PICKS: &str = "themePicks";
|
||||
const THEME_DONE: &str = "__themePicked";
|
||||
|
||||
/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded the
|
||||
/// palette of the art picked (`recolor.pickTheme`, as many colors as those rows), in row order;
|
||||
/// with fewer colors than rows, the colors repeat. Picks that touch no art leave the rows as they
|
||||
/// are.
|
||||
/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded and hold
|
||||
/// current colors the palette of the art picked (`recolor.pickTheme`, as many colors as those
|
||||
/// rows), in row order; with fewer colors than rows, the colors repeat. Picks that touch no art
|
||||
/// leave the rows as they are.
|
||||
fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) {
|
||||
let picks = d.fields.get(THEME_PICKS).cloned().unwrap_or(Value::Null);
|
||||
if !picks.as_array().is_some_and(|a| !a.is_empty()) || d.fields.get(THEME_DONE) == Some(&picks) {
|
||||
@@ -559,6 +561,18 @@ fn excluded(row: &Value) -> bool {
|
||||
row["exclude"].as_bool().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether `row` holds no current colors: a row made with New Row, until colors are merged into it.
|
||||
/// Its new color recolors nothing and is no color of a color group, the wheel or the harmony rules.
|
||||
fn empty(row: &Value) -> bool {
|
||||
row["from"].as_array().is_some_and(Vec::is_empty)
|
||||
}
|
||||
|
||||
/// Whether `row`'s new color is one of the colors a color group takes: the row isn't excluded and
|
||||
/// holds current colors.
|
||||
fn in_group(row: &Value) -> bool {
|
||||
!excluded(row) && !empty(row)
|
||||
}
|
||||
|
||||
/// The seed for the next Randomize: one past the last, held at `u64::MAX`.
|
||||
fn next_seed(d: &Dialog) -> u64 {
|
||||
(d.f64("__seed", 0.0) as u64).saturating_add(1)
|
||||
@@ -574,7 +588,7 @@ fn apply_params(d: &Dialog) -> Value {
|
||||
let rs = rows(d);
|
||||
let group = d.fields.get("group").and_then(Value::as_str).map(|g| {
|
||||
// A row made with New Row that holds no current colors gives the group no color.
|
||||
let filled: Vec<&Value> = rs.iter().filter(|r| !r["from"].as_array().is_some_and(Vec::is_empty)).map(|r| &r["to"]).collect();
|
||||
let filled: Vec<&Value> = rs.iter().filter(|r| !empty(r)).map(|r| &r["to"]).collect();
|
||||
let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art"));
|
||||
let rest = assign.map_or(&[][..], |a| a.get(filled.len()..).unwrap_or_default());
|
||||
let colors: Vec<&Value> = filled.into_iter().chain(rest).collect();
|
||||
@@ -787,7 +801,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
sync_theme(app, &mut d);
|
||||
sync_weights(app, &mut d);
|
||||
if d.bool("__newGroup") {
|
||||
let colors = group_colors(app, &d, rows(&d).iter().filter(|r| !excluded(r)));
|
||||
let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r)));
|
||||
return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}));
|
||||
}
|
||||
let r = form::commit_preview(app, CMD, apply_params(&d))?;
|
||||
@@ -1000,7 +1014,8 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target, false));
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
changed |= sliders(app, ui, d, rows);
|
||||
let row = first_selected(d, rows);
|
||||
changed |= sliders(app, ui, d, rows, row);
|
||||
ui.add_space(8.0);
|
||||
egui::Grid::new("recolor-options").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| {
|
||||
ui.label(egui::RichText::new(tl!("Method:")).color(t.text_dim));
|
||||
@@ -1131,8 +1146,13 @@ fn slider_values(d: &Dialog, rows: &[Value], i: usize, c: &Color, mode: Mode) ->
|
||||
v.filter(|v| v.len() == mode.labels().len()).unwrap_or_else(|| components(mode, c))
|
||||
}
|
||||
|
||||
/// What the color sliders edit: the first selected row, its new color, and the name of the
|
||||
/// library's spot color that color is.
|
||||
/// The first selected row of `rows`.
|
||||
fn first_selected(d: &Dialog, rows: &[Value]) -> Option<usize> {
|
||||
selection(d).into_iter().filter(|i| *i < rows.len()).min()
|
||||
}
|
||||
|
||||
/// What the color sliders edit: a row (the first selected row on the Assign tab, the base color's
|
||||
/// row on the Edit tab), its new color, and the name of the library's spot color that color is.
|
||||
struct SliderTarget {
|
||||
row: Option<usize>,
|
||||
color: Option<Color>,
|
||||
@@ -1141,7 +1161,12 @@ struct SliderTarget {
|
||||
|
||||
impl SliderTarget {
|
||||
fn of(app: &VectorcraftApp, d: &Dialog, rows: &[Value]) -> Self {
|
||||
let row = selection(d).into_iter().filter(|i| *i < rows.len()).min();
|
||||
Self::at(app, d, rows, first_selected(d, rows))
|
||||
}
|
||||
|
||||
/// What the color sliders edit when they edit row `row`.
|
||||
fn at(app: &VectorcraftApp, d: &Dialog, rows: &[Value], row: Option<usize>) -> Self {
|
||||
let row = row.filter(|i| *i < rows.len());
|
||||
let color = row.and_then(|i| to_color(&rows[i]));
|
||||
// A row tint acts only on art, so without art a spot color shows the process modes.
|
||||
let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c));
|
||||
@@ -1252,11 +1277,11 @@ fn slider_cell(
|
||||
dragged.map(|x| (lo + f64::from(x) * (hi - lo)).round()).or(keyed).or(typed).map(|v| v.clamp(lo, hi)).filter(|v| (v - value).abs() > 1e-6)
|
||||
}
|
||||
|
||||
/// The color sliders under the rows, two to a line: they edit the first selected row's new color
|
||||
/// (the others keep theirs) in the mode of [`mode_menu`], or its tint of a spot color of the
|
||||
/// library. Without a selected row they are disabled. Returns true when they changed a row.
|
||||
fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool {
|
||||
let target = SliderTarget::of(app, d, rows);
|
||||
/// The color sliders, two to a line: they edit row `row`'s new color (the others keep theirs) in
|
||||
/// the mode of [`mode_menu`], or its tint of a spot color of the library. Without a row they are
|
||||
/// disabled. Returns true when they changed a row.
|
||||
fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], row: Option<usize>) -> bool {
|
||||
let target = SliderTarget::at(app, d, rows, row);
|
||||
let mode = target.mode(d);
|
||||
let mut changed = false;
|
||||
let top = ui.cursor().top();
|
||||
@@ -1357,9 +1382,17 @@ fn new_row(rows: &mut Vec<Value>, sel: &[usize]) -> usize {
|
||||
at
|
||||
}
|
||||
|
||||
/// The rows the Edit tab shows: those with a new colour, not excluded.
|
||||
/// The rows the Edit tab shows, the harmony rules fill and the Color Theme Picker recolors: those
|
||||
/// with a new colour that aren't excluded and hold current colors.
|
||||
fn active_rows(rows: &[Value]) -> Vec<usize> {
|
||||
(0..rows.len()).filter(|i| !excluded(&rows[*i]) && to_color(&rows[*i]).is_some()).collect()
|
||||
(0..rows.len()).filter(|i| in_group(&rows[*i]) && to_color(&rows[*i]).is_some()).collect()
|
||||
}
|
||||
|
||||
/// The row the Edit tab's color sliders edit: the first selected row when the tab shows it (one of
|
||||
/// `active`), else the base color's row `base`. A selected row the tab does not show (excluded, or
|
||||
/// empty) is left as it is.
|
||||
fn edit_slider_row(d: &Dialog, rows: &[Value], active: &[usize], base: Option<usize>) -> Option<usize> {
|
||||
first_selected(d, rows).filter(|i| active.contains(i)).or(base)
|
||||
}
|
||||
|
||||
/// Set row `i`'s new colour to hue/saturation/brightness `hsb` ([`move_on_wheel`]: with `linked`
|
||||
@@ -1388,7 +1421,8 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
|
||||
let linked = d.bool("linked");
|
||||
let active = active_rows(rows);
|
||||
let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied());
|
||||
let target = SliderTarget::of(app, d, rows);
|
||||
let slider_row = edit_slider_row(d, rows, &active, base);
|
||||
let target = SliderTarget::at(app, d, rows, slider_row);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim));
|
||||
let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary);
|
||||
@@ -1411,7 +1445,7 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
|
||||
let button = widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0);
|
||||
let prominent = d.bool("__art") && !prominent_parts(d, rows).is_empty();
|
||||
let saved = egui::Popup::menu(&button).show(|ui| {
|
||||
if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(|r| !excluded(r)), false) {
|
||||
if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(in_group), false) {
|
||||
return Some("all");
|
||||
}
|
||||
widgets::menu_item_name(ui, tl!("Save Prominent Colors"), prominent, false).then_some("prominent")
|
||||
@@ -1489,7 +1523,7 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
|
||||
let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25));
|
||||
global_sliders(ui, d, sample);
|
||||
} else {
|
||||
changed |= sliders(app, ui, d, rows);
|
||||
changed |= sliders(app, ui, d, rows, slider_row);
|
||||
}
|
||||
// The new colours: click one to make it the base colour.
|
||||
let min_height = (TAB_H - (ui.cursor().top() - top)).max(0.0);
|
||||
@@ -1708,6 +1742,27 @@ mod tests {
|
||||
assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]));
|
||||
}
|
||||
|
||||
/// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the
|
||||
/// new color group, in row order: an empty row gives it no color.
|
||||
#[test]
|
||||
fn an_empty_row_gives_a_new_group_no_color() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run("ui.recolorDialog", json!({"colors": ["#ff8000", "#0080ff"]})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
let mut rs = super::rows(d);
|
||||
let at = new_row(&mut rs, &[1]);
|
||||
rs[at]["to"] = json!("rgb 255 0 255");
|
||||
d.fields.insert("rows".into(), Value::Array(rs));
|
||||
let d = d.clone();
|
||||
let groups = app.session.doc().unwrap().doc.swatch_groups.len();
|
||||
confirm(&mut app, &d).unwrap();
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
assert_eq!(doc.swatch_groups.len(), groups + 1, "a new color group");
|
||||
let colors: Vec<String> = doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
|
||||
assert_eq!(colors, ["#ff8000", "#0080ff"]);
|
||||
}
|
||||
|
||||
/// Randomize after a seed past `u64::MAX` keeps the largest seed.
|
||||
#[test]
|
||||
fn next_seed_holds_at_the_largest() {
|
||||
@@ -1740,6 +1795,27 @@ mod tests {
|
||||
assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"]], ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]);
|
||||
}
|
||||
|
||||
/// A row made with New Row is not on the Edit tab while it is empty: a harmony rule gives it
|
||||
/// no color and a linked move leaves its new color as it is.
|
||||
#[test]
|
||||
fn an_empty_row_takes_no_harmony_or_wheel_color() {
|
||||
let mut r = rows();
|
||||
new_row(&mut r, &[]);
|
||||
assert_eq!(r[0]["to"], "rgb 255 0 0");
|
||||
let active = active_rows(&r);
|
||||
assert_eq!(active, [1, 2, 3]);
|
||||
apply_rule(&mut r, Harmony::Triad, 1, Color::rgb(1.0, 0.0, 0.0), &active);
|
||||
assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"], &r[3]["to"]], ["rgb 255 0 0", "rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]);
|
||||
move_color(&mut r, 1, [120.0, 1.0, 1.0], true);
|
||||
assert_eq!(r[1]["to"], "rgb 0 255 0");
|
||||
assert_eq!(r[0]["to"], "rgb 255 0 0", "the empty row keeps its new color");
|
||||
// With the empty row selected, the sliders edit the base color's row instead.
|
||||
let sel = |s: Value| Dialog::new("recolor", json!({"__sel": s}));
|
||||
assert_eq!(edit_slider_row(&sel(json!([0])), &r, &active, Some(1)), Some(1));
|
||||
assert_eq!(edit_slider_row(&sel(json!([3, 2])), &r, &active, Some(3)), Some(2), "a shown row: the first selected");
|
||||
assert_eq!(edit_slider_row(&sel(json!([0])), &r, &[], None), None, "no row to edit");
|
||||
}
|
||||
|
||||
/// A rule or a wheel move that gives a row a new color drops the row's tint; a row whose
|
||||
/// color stays keeps it.
|
||||
#[test]
|
||||
@@ -1993,6 +2069,23 @@ mod tests {
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "the art is unchanged: no undo step");
|
||||
}
|
||||
|
||||
/// The Color Theme Picker gives its colors only to the rows that hold current colors: a row
|
||||
/// made with New Row keeps its new color and takes no place in the palette.
|
||||
#[test]
|
||||
fn theme_picks_leave_an_empty_row_out() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
theme_setup(&mut app, &ctx);
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
let mut rs = super::rows(d);
|
||||
let at = new_row(&mut rs, &[]);
|
||||
rs[at]["to"] = json!("rgb 9 9 9");
|
||||
d.fields.insert("rows".into(), Value::Array(rs));
|
||||
d.fields.insert(THEME_PICKS.into(), json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}]));
|
||||
frame(&mut app, &ctx, 0.1, vec![], 0);
|
||||
assert_eq!(new_colors(&app), [json!("rgb 9 9 9"), json!("rgb 0 255 0"), json!("rgb 255 255 0")]);
|
||||
}
|
||||
|
||||
/// A row made with New Row recolors nothing while it is empty, and OK keeps it; the blue art's
|
||||
/// color merged into it takes its new color, in the preview and at OK.
|
||||
#[test]
|
||||
@@ -2163,6 +2256,33 @@ mod tests {
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "a step for each group");
|
||||
}
|
||||
|
||||
/// Save All Colors leaves out a row made with New Row while it is empty; with only empty rows
|
||||
/// it saves no group and records no step.
|
||||
#[test]
|
||||
fn save_all_colors_leaves_an_empty_row_out() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
prominent_setup(&mut app, &ctx);
|
||||
let groups = |app: &VectorcraftApp| app.session.doc().unwrap().doc.swatch_groups.len();
|
||||
let (n, undo) = (groups(&app), app.session.doc().unwrap().history.undo.len());
|
||||
let save = |app: &mut VectorcraftApp, rows: Value, t: f64| {
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("rows".into(), rows);
|
||||
d.fields.insert(SAVE_GROUP.into(), json!("all"));
|
||||
frame(app, &ctx, t, vec![], 0);
|
||||
frame(app, &ctx, t + 0.01, vec![], 0);
|
||||
};
|
||||
let blank = json!({"from": [], "to": "rgb 255 0 255"});
|
||||
save(&mut app, json!([blank, {"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}]), 0.1);
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
let colors: Vec<String> = doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
|
||||
assert_eq!(colors, ["#ffff00", "#00ff00"]);
|
||||
assert_eq!(groups(&app), n + 1);
|
||||
save(&mut app, json!([blank, {"from": [BLUE, RED, PURPLE], "to": "rgb 0 255 0", "exclude": true}]), 0.2);
|
||||
assert_eq!(groups(&app), n + 1, "only an empty and an excluded row: no group");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "and no step");
|
||||
}
|
||||
|
||||
/// One frame with `modifiers` held.
|
||||
fn frame_with(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
|
||||
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
|
||||
|
||||
@@ -14,8 +14,8 @@ fn psd_options_pick_flat_or_layers_and_the_colour_model() {
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((spec(&d.kind).heading)(d), "PSD Options");
|
||||
assert_eq!(
|
||||
(d.str("colorModel"), d.bool("layers"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")),
|
||||
("rgb".into(), true, false, false, true)
|
||||
(d.str("colorModel"), d.bool("layers"), d.bool("preserveText"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")),
|
||||
("rgb".into(), true, false, false, false, true)
|
||||
);
|
||||
assert!(tiff_bmp_tga::keeps_alpha("psd", d), "layers keep transparency");
|
||||
frame(&mut app);
|
||||
@@ -30,9 +30,11 @@ fn psd_options_pick_flat_or_layers_and_the_colour_model() {
|
||||
assert_eq!(i16::from_be_bytes([psd[at + 8], psd[at + 9]]), -3);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
|
||||
// Flat: flattened on white, so the background list starts at White.
|
||||
// Flat: flattened on white, so the background list starts at White. Preserve Text
|
||||
// Editability, still ticked, isn't sent: the export refuses it without layers.
|
||||
app.run("file.exportAs", json!({"format": "psd"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
set(&mut app, "preserveText", json!(true));
|
||||
set(&mut app, "layers", json!(false));
|
||||
set(&mut app, "colorModel", json!("gray"));
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("psd", app.ui.dialog.as_ref().unwrap()));
|
||||
|
||||
@@ -681,11 +681,12 @@ const MESSAGE_DEPTH: usize = 5;
|
||||
|
||||
/// Translate a status or error message for display (see the module docs). Unknown messages, and
|
||||
/// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as
|
||||
/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a
|
||||
/// symbol's name), stay as they are. A part that starts with `{` is translated only when it is a
|
||||
/// whole message with an exact entry. A part that starts with `[` is translated when it has an
|
||||
/// exact entry, such as `[x, y] (two numbers)`, or when it fits a template that starts with `[`
|
||||
/// and an index of digits, such as an effect's refusal ``[0] `id`: {why}``.
|
||||
/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”`, `'…'` or backticks, such as a
|
||||
/// symbol's or a script property's name, and an `{ident}` placeholder's value, a script identifier),
|
||||
/// stay as they are. A part that starts with `{` is translated only when it is a whole message with
|
||||
/// an exact entry. A part that starts with `[` is translated when it has an exact entry, such as
|
||||
/// `[x, y] (two numbers)`, or when it fits a template that starts with `[` and an index of digits,
|
||||
/// such as an effect's refusal ``[0] `id`: {why}``.
|
||||
pub fn message(lang: Lang, s: &str) -> String {
|
||||
message_at(lang, s, MESSAGE_DEPTH)
|
||||
}
|
||||
@@ -701,9 +702,15 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures
|
||||
let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::<u64>().ok());
|
||||
let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1)));
|
||||
let Some(template) = forms.get(form) else { return s.to_string() };
|
||||
let quoted = |v: &str| [('"', '"'), ('“', '”'), ('`', '`')].iter().any(|(a, b)| s.contains(&format!("{a}{v}{b}")));
|
||||
// A value is quoted when quotes surround it at its own place in `s`. The same text quoted at
|
||||
// another place in `s` (a property named like the reason given for it) does not count.
|
||||
let quoted = |v: &str| {
|
||||
let at = (v.as_ptr() as usize).checked_sub(s.as_ptr() as usize);
|
||||
let Some((before, after)) = at.and_then(|at| Some((s.get(..at)?, s.get(at + v.len()..)?))) else { return false };
|
||||
[('"', '"'), ('“', '”'), ('\'', '\''), ('`', '`')].iter().any(|(a, b)| before.ends_with(*a) && after.starts_with(*b))
|
||||
};
|
||||
let nested = |v: &str| {
|
||||
if depth <= 1 || quoted(v) {
|
||||
if depth <= 1 || v.is_empty() || quoted(v) {
|
||||
v.to_string()
|
||||
} else if v.starts_with('{') {
|
||||
exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string())
|
||||
@@ -719,6 +726,7 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures
|
||||
.map(|(k, v)| match (&liquify, k) {
|
||||
(Some((tool, _)), "_1") => (k, tool.clone()),
|
||||
(Some((_, kinds)), "_2") => (k, kinds.clone()),
|
||||
(_, "ident") => (k, v.to_string()),
|
||||
_ => (k, nested(v)),
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -3176,6 +3176,8 @@ digits Malayalam Малаялам
|
||||
Search All Търсене във всички
|
||||
Search commands and tools Търсене на команди и инструменти
|
||||
Search commands and tools… Търсене на команди и инструменти…
|
||||
Recent Commands Последни команди
|
||||
No recent commands Няма последни команди
|
||||
Search Commands… Търсене на команди…
|
||||
Secondary Вторичен
|
||||
Section Symbol Символ за раздел
|
||||
@@ -6751,6 +6753,24 @@ breakText Glyphs Глифи
|
||||
# Path Precision Tools add-on: Expand Dashes into Paths.
|
||||
Expand Dashes into Paths Разширяване на тиретата в пътища
|
||||
@msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване
|
||||
# Path Precision Tools add-on: Tangent Circle.
|
||||
Tangent Circle… Допирателна окръжност…
|
||||
Tangent Circle Допирателна окръжност
|
||||
Circle: Окръжност:
|
||||
@msg `ids` names an object twice `ids` посочва обект два пъти
|
||||
@msg select two or three paths or compound paths изберете два или три пътя или съставни пътя
|
||||
@msg `radius` must be from 0.01 to 1000000 pt `radius` трябва да е от 0.01 до 1000000 pt
|
||||
@msg two shapes need a `radius` две форми изискват `radius`
|
||||
@msg three shapes set the radius themselves: leave `radius` out три форми сами задават радиуса: пропуснете `radius`
|
||||
@msg `circle` must be from 0 to 64 `circle` трябва да е от 0 до 64
|
||||
@msg a shape has no outline една от формите няма контур
|
||||
@msg the shapes are too complex: at most 2000 segments in all формите са твърде сложни: общо най-много 2000 сегмента
|
||||
@msg these shapes take too long to search търсенето за тези форми отнема твърде дълго
|
||||
@msg more than 64 circles touch these shapes: they may touch along a whole curve повече от 64 окръжности докосват тези форми: може да ги докосват по цяла крива
|
||||
@msg no circle touches these shapes никоя окръжност не докосва тези форми
|
||||
@msg `circle` is past the last circle found ({found}) `circle` е след последната намерена окръжност ({found})
|
||||
@msg object {value} is not a path or compound path обект {value} не е път или съставен път
|
||||
@msg these shapes are too small to measure тези форми са твърде малки, за да бъдат измерени
|
||||
# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy.
|
||||
Document Tools Инструменти за документи
|
||||
Save a Timestamped Copy Запазване на копие с дата и час
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4370,6 +4370,8 @@ font-technology Variable Varijabilni
|
||||
Saving Čuvanje
|
||||
Saving {} Čuvanje {}
|
||||
Search commands and tools… Pretraži naredbe i alate…
|
||||
Recent Commands Nedavne naredbe
|
||||
No recent commands Nema nedavnih naredbi
|
||||
Dashed Line Isprekidana linija
|
||||
Panel menu Meni panela
|
||||
Unembed… Poništi ugrađivanje…
|
||||
@@ -6803,6 +6805,24 @@ shape Open Otvoren
|
||||
# Path Precision Tools add-on: Expand Dashes into Paths.
|
||||
Expand Dashes into Paths Proširi crtice u putanje
|
||||
@msg select paths with dashed strokes to expand odaberite putanje s isprekidanim potezom za proširivanje
|
||||
# Path Precision Tools add-on: Tangent Circle.
|
||||
Tangent Circle… Tangentna kružnica…
|
||||
Tangent Circle Tangentna kružnica
|
||||
Circle: Kružnica:
|
||||
@msg `ids` names an object twice `ids` navodi objekat dvaput
|
||||
@msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje
|
||||
@msg `radius` must be from 0.01 to 1000000 pt `radius` mora biti od 0.01 do 1000000 pt
|
||||
@msg two shapes need a `radius` dva oblika trebaju `radius`
|
||||
@msg three shapes set the radius themselves: leave `radius` out tri oblika sama određuju poluprečnik: izostavite `radius`
|
||||
@msg `circle` must be from 0 to 64 `circle` mora biti od 0 do 64
|
||||
@msg a shape has no outline oblik nema obris
|
||||
@msg the shapes are too complex: at most 2000 segments in all oblici su previše složeni: najviše 2000 segmenata ukupno
|
||||
@msg these shapes take too long to search pretraga za ove oblike traje predugo
|
||||
@msg more than 64 circles touch these shapes: they may touch along a whole curve više od 64 kružnice dodiruje ove oblike: možda ih dodiruju duž cijele krivulje
|
||||
@msg no circle touches these shapes nijedna kružnica ne dodiruje ove oblike
|
||||
@msg `circle` is past the last circle found ({found}) `circle` je iza posljednje pronađene kružnice ({found})
|
||||
@msg object {value} is not a path or compound path objekat {value} nije putanja ni složena putanja
|
||||
@msg these shapes are too small to measure ovi oblici su premali za mjerenje
|
||||
# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy.
|
||||
Document Tools Alati za dokument
|
||||
Save a Timestamped Copy Sačuvaj kopiju s datumom i vremenom
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4103,6 +4103,8 @@ digits Malayalam Malaiàlam
|
||||
Search All Cerca a tot
|
||||
Search commands and tools Cerca ordres i eines
|
||||
Search commands and tools… Cerca ordres i eines…
|
||||
Recent Commands Ordres recents
|
||||
No recent commands No hi ha ordres recents
|
||||
Search Commands… Cerca ordres…
|
||||
Search Fonts Folder Cerca a la carpeta de tipus de lletra
|
||||
Searching… Cercant…
|
||||
@@ -5697,6 +5699,44 @@ digits Malayalam Malaiàlam
|
||||
@msg $.evalFile requires a file path $.evalFile requereix un camí de fitxer
|
||||
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el temps d'espera ha de ser un nombre finit de mil·lisegons, 0 o més
|
||||
@msg $.evalFile: takes a file path and a timeout $.evalFile: rep un camí de fitxer i un temps d'espera
|
||||
@msg assignment to a constant binding assignació a un enllaç constant
|
||||
@msg invalid array length longitud de matriu no vàlida
|
||||
@msg array literal too long el literal de matriu és massa llarg
|
||||
@msg the value is not a function el valor no és una funció
|
||||
@msg apply was called on a value that is not a function s'ha cridat apply sobre un valor que no és una funció
|
||||
@msg the argument list is not an object la llista d'arguments no és un objecte
|
||||
@msg too many arguments massa arguments
|
||||
@msg the value is not a constructor el valor no és un constructor
|
||||
@msg cannot convert the object to a primitive value no es pot convertir l'objecte en un valor primitiu
|
||||
@msg cannot convert undefined or null to an object no es pot convertir undefined ni null en un objecte
|
||||
@msg the right side of 'in' is not an object el costat dret de 'in' no és un objecte
|
||||
@msg the right side of 'instanceof' is not a function el costat dret de 'instanceof' no és una funció
|
||||
@msg the function's prototype is not an object el prototip de la funció no és un objecte
|
||||
@msg Error: {e} Error: {e}
|
||||
@msg TypeError: {e} TypeError: {e}
|
||||
@msg ReferenceError: {e} ReferenceError: {e}
|
||||
@msg RangeError: {e} RangeError: {e}
|
||||
@msg SyntaxError: {e} SyntaxError: {e}
|
||||
@msg EvalError: {e} EvalError: {e}
|
||||
@msg URIError: {e} URIError: {e}
|
||||
@msg {ident} is not defined {ident} no està definit
|
||||
@msg cannot read property '{key}' of {base} no es pot llegir la propietat '{key}' de {base}
|
||||
@msg cannot set property '{key}' of {base} no es pot establir la propietat '{key}' de {base}
|
||||
@msg cannot read a property of {base} no es pot llegir cap propietat de {base}
|
||||
@msg cannot set a property of {base} no es pot establir cap propietat de {base}
|
||||
@msg cannot define property '{key}': {why} no es pot definir la propietat '{key}': {why}
|
||||
@msg cannot assign to property '{key}': {why} no es pot assignar a la propietat '{key}': {why}
|
||||
@msg cannot delete property '{key}' no es pot suprimir la propietat '{key}'
|
||||
@msg cannot declare function {ident} no es pot declarar la funció {ident}
|
||||
@msg invalid assignment target destinació d'assignació no vàlida
|
||||
@msg the array's length is read-only la longitud de la matriu és només de lectura
|
||||
@msg the property cannot be redefined la propietat no es pot redefinir
|
||||
@msg the object is not extensible l'objecte no és extensible
|
||||
@msg the length cannot be redefined la longitud no es pot redefinir
|
||||
@msg it is read-only és només de lectura
|
||||
@msg an element cannot be deleted no es pot suprimir un element
|
||||
@msg it has only a getter només té un getter
|
||||
@msg the value is a primitive el valor és primitiu
|
||||
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línia {line}, columna {column} de {file}: {e} (llançat)
|
||||
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: línia {line}, columna {column}: {e} (llançat)
|
||||
@msg {name}: {e} (thrown) {name}: {e} (llançat)
|
||||
@@ -7414,6 +7454,24 @@ breakText Glyphs Glifs
|
||||
# Path Precision Tools add-on: Expand Dashes into Paths.
|
||||
Expand Dashes into Paths Expandeix els guions en camins
|
||||
@msg select paths with dashed strokes to expand seleccioneu camins amb traç discontinu per expandir
|
||||
# Path Precision Tools add-on: Tangent Circle.
|
||||
Tangent Circle… Cercle tangent…
|
||||
Tangent Circle Cercle tangent
|
||||
Circle: Cercle:
|
||||
@msg `ids` names an object twice `ids` indica un objecte dues vegades
|
||||
@msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos
|
||||
@msg `radius` must be from 0.01 to 1000000 pt `radius` ha de ser de 0.01 a 1000000 pt
|
||||
@msg two shapes need a `radius` dues formes necessiten un `radius`
|
||||
@msg three shapes set the radius themselves: leave `radius` out tres formes fixen el radi per si mateixes: ometeu `radius`
|
||||
@msg `circle` must be from 0 to 64 `circle` ha de ser de 0 a 64
|
||||
@msg a shape has no outline una forma no té contorn
|
||||
@msg the shapes are too complex: at most 2000 segments in all les formes són massa complexes: com a màxim 2000 segments en total
|
||||
@msg these shapes take too long to search la cerca triga massa amb aquestes formes
|
||||
@msg more than 64 circles touch these shapes: they may touch along a whole curve més de 64 cercles toquen aquestes formes: potser les toquen al llarg de tota una corba
|
||||
@msg no circle touches these shapes cap cercle no toca aquestes formes
|
||||
@msg `circle` is past the last circle found ({found}) `circle` passa de l’últim cercle trobat ({found})
|
||||
@msg object {value} is not a path or compound path l’objecte {value} no és un camí ni un camí compost
|
||||
@msg these shapes are too small to measure aquestes formes són massa petites per mesurar-les
|
||||
# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy.
|
||||
Document Tools Eines del document
|
||||
Save a Timestamped Copy Desa una còpia amb data i hora
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -92,17 +92,19 @@ impl Template {
|
||||
/// The placeholder values if `s` is an instance of this template.
|
||||
fn captures<'a>(&self, s: &'a str) -> Option<Vec<(&str, &'a str)>> {
|
||||
let mut out = Vec::new();
|
||||
match_pieces(&self.pieces, s, self.counted, &mut out).then_some(out)
|
||||
match_pieces(&self.pieces, s, self.counted, &mut out, None).then_some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Match `s` against `pieces`, a placeholder taking the shortest non-empty text that lets the
|
||||
/// rest match (the last one takes what remains). With `counted`, `{n}` takes only a count. A
|
||||
/// placeholder that occurs twice takes the same text both times.
|
||||
fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>) -> bool {
|
||||
/// rest match (the last one takes what remains). A placeholder between two of the same quote
|
||||
/// (`'{key}'`, `"{key}"` or `` `{key}` ``) may also take no text, as for a property named by the
|
||||
/// empty string. With `counted`, `{n}` takes only a count. A placeholder that occurs twice takes
|
||||
/// the same text both times. `before` is the last character of the text piece before `pieces`.
|
||||
fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>, before: Option<char>) -> bool {
|
||||
let Some((first, rest)) = pieces.split_first() else { return s.is_empty() };
|
||||
match first {
|
||||
Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out)),
|
||||
Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out, t.chars().last())),
|
||||
Piece::Hole(name) => {
|
||||
let earlier = out.iter().find(|(n, _)| *n == name.as_str()).map(|&(_, v)| v);
|
||||
let fits = |value: &str| (!(counted && name == "n") || value.parse::<u64>().is_ok()) && earlier.is_none_or(|e| e == value);
|
||||
@@ -114,7 +116,19 @@ fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mu
|
||||
return true;
|
||||
};
|
||||
let Piece::Text(next) = next else { return false };
|
||||
// Every place the next literal occurs, nearest first (the hole is never empty).
|
||||
let quoted = before.is_some_and(|q| matches!(q, '\'' | '"' | '`') && next.starts_with(q));
|
||||
if quoted
|
||||
&& fits("")
|
||||
&& let Some(tail) = s.strip_prefix(next.as_str())
|
||||
{
|
||||
let mark = out.len();
|
||||
out.push((name.as_str(), ""));
|
||||
if match_pieces(after, tail, counted, out, next.chars().last()) {
|
||||
return true;
|
||||
}
|
||||
out.truncate(mark);
|
||||
}
|
||||
// Every other place the next literal occurs, nearest first.
|
||||
let mut from = s.chars().next().map_or(1, char::len_utf8);
|
||||
while let Some(at) = s.get(from..).and_then(|tail| tail.find(next.as_str())).map(|i| i + from) {
|
||||
let (Some(value), Some(tail)) = (s.get(..at), s.get(at + next.len()..)) else { return false };
|
||||
@@ -124,7 +138,7 @@ fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mu
|
||||
}
|
||||
let mark = out.len();
|
||||
out.push((name.as_str(), value));
|
||||
if match_pieces(after, tail, counted, out) {
|
||||
if match_pieces(after, tail, counted, out, next.chars().last()) {
|
||||
return true;
|
||||
}
|
||||
out.truncate(mark);
|
||||
|
||||
@@ -4475,6 +4475,8 @@ font-technology Variable Variabilní
|
||||
Saving Ukládání
|
||||
Saving {} Ukládání {}
|
||||
Search commands and tools… Hledat příkazy a nástroje…
|
||||
Recent Commands Nedávné příkazy
|
||||
No recent commands Žádné nedávné příkazy
|
||||
Dashed Line Čárkovaná čára
|
||||
Panel menu Nabídka panelu
|
||||
Unembed… Zrušit vložení…
|
||||
@@ -4785,6 +4787,31 @@ imageTrace Outline Obrys
|
||||
@msg $.evalFile requires a file path $.evalFile vyžaduje cestu k souboru
|
||||
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: časový limit musí být konečný počet milisekund, 0 nebo více
|
||||
@msg $.evalFile: takes a file path and a timeout $.evalFile: přijímá cestu k souboru a časový limit
|
||||
@msg Error: {e} Error: {e}
|
||||
@msg TypeError: {e} TypeError: {e}
|
||||
@msg ReferenceError: {e} ReferenceError: {e}
|
||||
@msg RangeError: {e} RangeError: {e}
|
||||
@msg SyntaxError: {e} SyntaxError: {e}
|
||||
@msg EvalError: {e} EvalError: {e}
|
||||
@msg URIError: {e} URIError: {e}
|
||||
@msg {ident} is not defined {ident} není definováno
|
||||
@msg cannot read property '{key}' of {base} nelze číst vlastnost '{key}' hodnoty {base}
|
||||
@msg cannot set property '{key}' of {base} nelze nastavit vlastnost '{key}' hodnoty {base}
|
||||
@msg cannot read a property of {base} nelze číst vlastnost hodnoty {base}
|
||||
@msg cannot set a property of {base} nelze nastavit vlastnost hodnoty {base}
|
||||
@msg cannot define property '{key}': {why} nelze definovat vlastnost '{key}': {why}
|
||||
@msg cannot assign to property '{key}': {why} nelze přiřadit do vlastnosti '{key}': {why}
|
||||
@msg cannot delete property '{key}' nelze odstranit vlastnost '{key}'
|
||||
@msg cannot declare function {ident} nelze deklarovat funkci {ident}
|
||||
@msg invalid assignment target neplatný cíl přiřazení
|
||||
@msg the array's length is read-only délka pole je jen pro čtení
|
||||
@msg the property cannot be redefined vlastnost nelze znovu definovat
|
||||
@msg the object is not extensible objekt nelze rozšiřovat
|
||||
@msg the length cannot be redefined délku nelze znovu definovat
|
||||
@msg it is read-only je jen pro čtení
|
||||
@msg an element cannot be deleted prvek nelze odstranit
|
||||
@msg it has only a getter má pouze getter
|
||||
@msg the value is a primitive hodnota je primitivní
|
||||
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: řádek {line}, sloupec {column} v {file}: {e} (vyvolána výjimka)
|
||||
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: řádek {line}, sloupec {column}: {e} (vyvolána výjimka)
|
||||
@msg {name}: {e} (thrown) {name}: {e} (vyvolána výjimka)
|
||||
@@ -7418,6 +7445,24 @@ breakText Glyphs Glyfy
|
||||
# Path Precision Tools add-on: Expand Dashes into Paths.
|
||||
Expand Dashes into Paths Rozložit čárky na cesty
|
||||
@msg select paths with dashed strokes to expand vyberte cesty s čárkovaným tahem k rozložení
|
||||
# Path Precision Tools add-on: Tangent Circle.
|
||||
Tangent Circle… Tečná kružnice…
|
||||
Tangent Circle Tečná kružnice
|
||||
Circle: Kružnice:
|
||||
@msg `ids` names an object twice `ids` uvádí některý objekt dvakrát
|
||||
@msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty
|
||||
@msg `radius` must be from 0.01 to 1000000 pt `radius` musí být od 0.01 do 1000000 pt
|
||||
@msg two shapes need a `radius` dva tvary potřebují `radius`
|
||||
@msg three shapes set the radius themselves: leave `radius` out tři tvary určují poloměr samy: vynechte `radius`
|
||||
@msg `circle` must be from 0 to 64 `circle` musí být od 0 do 64
|
||||
@msg a shape has no outline tvar nemá obrys
|
||||
@msg the shapes are too complex: at most 2000 segments in all tvary jsou příliš složité: celkem nejvýše 2000 segmentů
|
||||
@msg these shapes take too long to search hledání pro tyto tvary trvá příliš dlouho
|
||||
@msg more than 64 circles touch these shapes: they may touch along a whole curve těchto tvarů se dotýká více než 64 kružnic: mohou se jich dotýkat podél celé křivky
|
||||
@msg no circle touches these shapes žádná kružnice se těchto tvarů nedotýká
|
||||
@msg `circle` is past the last circle found ({found}) `circle` je za poslední nalezenou kružnicí ({found})
|
||||
@msg object {value} is not a path or compound path objekt {value} není cesta ani složená cesta
|
||||
@msg these shapes are too small to measure tyto tvary jsou příliš malé na měření
|
||||
# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy.
|
||||
Document Tools Nástroje dokumentu
|
||||
Save a Timestamped Copy Uložit kopii s datem a časem
|
||||
|
||||
|
Can't render this file because it is too large.
|
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user