mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 22:33:08 +00:00
Merge main into fix/i18n-adjacent-placeholders
This commit is contained in:
@@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -142,9 +143,12 @@ 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.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
|
||||
@@ -444,8 +444,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
|
||||
return Err("the export region is not finite".into());
|
||||
}
|
||||
// Symbols' art is placed without clipping, as the scene places it.
|
||||
let baked =
|
||||
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
Ok(scene::Scene::new(doc, opts).run())
|
||||
}
|
||||
|
||||
+29
-1
@@ -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 {
|
||||
@@ -483,6 +491,10 @@ pub struct GraphSpec {
|
||||
pub first_column_in_front: bool,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub filled_lines: bool,
|
||||
/// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws
|
||||
/// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_width: Option<f64>,
|
||||
/// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the
|
||||
/// legend in rows above the plot instead of a column on its right).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -557,6 +569,21 @@ fn is_zero(n: &usize) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and
|
||||
/// greatest widths a graph takes, in points.
|
||||
pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0;
|
||||
pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01;
|
||||
pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0;
|
||||
|
||||
impl GraphSpec {
|
||||
/// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A
|
||||
/// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the
|
||||
/// default.
|
||||
pub fn filled_line_width(&self) -> f64 {
|
||||
self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH)
|
||||
}
|
||||
}
|
||||
|
||||
/// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then.
|
||||
fn edge_to_edge_before_the_option() -> bool {
|
||||
true
|
||||
@@ -696,6 +723,7 @@ impl Default for GraphSpec {
|
||||
first_row_in_front: false,
|
||||
first_column_in_front: false,
|
||||
filled_lines: false,
|
||||
line_width: None,
|
||||
drop_shadow: false,
|
||||
legend_across_top: false,
|
||||
pie_legend_in_wedges: false,
|
||||
|
||||
+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
|
||||
|
||||
@@ -96,8 +96,8 @@ pub use compound_shape::ShapeMode;
|
||||
pub use corners::LiveCorners;
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES,
|
||||
PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
|
||||
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH,
|
||||
MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
|
||||
};
|
||||
pub use hit::{Hit, HitKind};
|
||||
pub use links::{LinkInfo, PlacementOptions};
|
||||
|
||||
@@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
|
||||
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
|
||||
for h in &mut feed.0 {
|
||||
h.write_u8(u8::from(text.first_para_continues));
|
||||
h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from));
|
||||
for b in inline_bounds.clone() {
|
||||
match b {
|
||||
None => h.write_u8(0),
|
||||
|
||||
@@ -50,10 +50,10 @@ pub struct Selection {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
|
||||
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
|
||||
/// move the other selected points relative to it, and it stays in place. Never set with `key`
|
||||
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
|
||||
/// fewer than two points are selected.
|
||||
/// designated by clicking an already-selected anchor point without modifiers (path, anchor in
|
||||
/// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and
|
||||
/// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the
|
||||
/// point is no longer a selected anchor, or fewer than two points are selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_anchor: Option<(NodeId, AnchorRef)>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
@@ -311,7 +311,7 @@ impl Selection {
|
||||
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
|
||||
self.objects.contains(&id)
|
||||
&& !self.segments.contains_key(&id)
|
||||
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
|
||||
&& (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id))
|
||||
&& found
|
||||
.get(&id)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
|
||||
@@ -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`.
|
||||
///
|
||||
@@ -67,6 +67,12 @@ pub struct TextObject {
|
||||
/// it on a frame that leaves its thread and on a copy. Not saved.
|
||||
#[serde(skip)]
|
||||
pub first_para_continues: bool,
|
||||
/// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the
|
||||
/// last character of that paragraph in the frames before that a repeat mark could stand for
|
||||
/// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout
|
||||
/// reads it only while `first_para_continues` is on. Not saved.
|
||||
#[serde(skip)]
|
||||
pub first_para_lead: Option<char>,
|
||||
/// Area Type Options (area type only).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub area: AreaOptions,
|
||||
|
||||
@@ -94,6 +94,7 @@ impl TextObject {
|
||||
para: ParaStyle::default(),
|
||||
paras: Vec::new(),
|
||||
first_para_continues: false,
|
||||
first_para_lead: None,
|
||||
area: AreaOptions::default(),
|
||||
path_effect: PathEffect::default(),
|
||||
path_align: PathAlign::default(),
|
||||
|
||||
@@ -271,6 +271,9 @@ pub struct ParaStyle {
|
||||
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
|
||||
/// with kinsoku None, where it has no effect. Off by default.
|
||||
pub bunri_kinshi: bool,
|
||||
/// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts
|
||||
/// a line is drawn as the character it repeats, and the text keeps the mark. Off by default.
|
||||
pub kurikaeshi_moji_shori: bool,
|
||||
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
|
||||
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
|
||||
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
|
||||
@@ -375,6 +378,8 @@ struct ParaStyleFile {
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
bunri_kinshi: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kurikaeshi_moji_shori: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
roman_hanging: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kashida: Kashida,
|
||||
@@ -412,6 +417,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -439,6 +445,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -470,6 +477,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -496,6 +504,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
|
||||
@@ -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),
|
||||
|
||||
+18
-12
@@ -167,7 +167,7 @@ struct Placing {
|
||||
layers: WrittenLayers,
|
||||
}
|
||||
|
||||
/// The layers an exporter writes besides the shown, printing ones
|
||||
/// The layers and objects an exporter writes besides the shown, printing ones
|
||||
/// ([`bake_document_placing_symbols`]). Template layers are never written.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct WrittenLayers {
|
||||
@@ -175,16 +175,19 @@ pub struct WrittenLayers {
|
||||
pub hidden: bool,
|
||||
/// Layers that do not print.
|
||||
pub non_printing: bool,
|
||||
/// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden
|
||||
/// layers).
|
||||
pub hidden_objects: bool,
|
||||
}
|
||||
|
||||
/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`]
|
||||
/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer
|
||||
/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer
|
||||
/// that does not print when the export leaves those out ([`WrittenLayers`]).
|
||||
fn unwritten(n: &Node) -> bool {
|
||||
PLACING.with(|p| {
|
||||
p.borrow().as_ref().is_some_and(|p| match n.kind {
|
||||
NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden),
|
||||
_ => !n.visible,
|
||||
_ => !(n.visible || p.layers.hidden_objects),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -680,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))?;
|
||||
@@ -1041,13 +1046,14 @@ pub fn bake_document(doc: &Document) -> Option<Document> {
|
||||
/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or
|
||||
/// in the art of the symbols it places) replaced by that art as the instance places it, baked
|
||||
/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For
|
||||
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than
|
||||
/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped
|
||||
/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the
|
||||
/// exporter places other instances. `layers`: the hidden layers and layers that do not print
|
||||
/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden
|
||||
/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The
|
||||
/// symbols' own art is left as it is.
|
||||
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and
|
||||
/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`:
|
||||
/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not
|
||||
/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`:
|
||||
/// the hidden layers, layers that do not print and hidden objects that the exporter writes.
|
||||
/// Instances the export does not write (template layers, and the hidden objects and layers
|
||||
/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as
|
||||
/// it is.
|
||||
pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option<Document> {
|
||||
bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers)))
|
||||
}
|
||||
|
||||
@@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() {
|
||||
}
|
||||
|
||||
/// Every layer written, as DXF writes them (template layers are never written).
|
||||
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true };
|
||||
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
|
||||
fn is_instance(d: &Document, id: u64) -> bool {
|
||||
d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
|
||||
@@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() {
|
||||
}
|
||||
// An export that writes the layers that do not print, or the hidden layers, places that
|
||||
// layer's instance first; the template layer's instance is never placed.
|
||||
for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] {
|
||||
for (layers, first) in
|
||||
[(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)]
|
||||
{
|
||||
let out = bake(&d, Some((true, each, layers))).unwrap();
|
||||
assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}");
|
||||
}
|
||||
// An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance
|
||||
// first, and the instance in the hidden group would come next; the hidden layer's instance
|
||||
// stays, since that layer is still left out.
|
||||
let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap();
|
||||
assert!(!is_instance(&out, 901), "the hidden instance is placed");
|
||||
for id in [900, 903, 911, 921, 931] {
|
||||
assert!(is_instance(&out, id), "{id} stays as it is");
|
||||
}
|
||||
}
|
||||
|
||||
/// `leaf` in `levels` groups, with ids from `id` up.
|
||||
|
||||
@@ -182,49 +182,49 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
"Rotate (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint the art keeps its paint and swatch link whether it is on or off)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -86,9 +86,9 @@ pub use raster::{
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
|
||||
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
|
||||
outline_text, paint_type_piece, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
|
||||
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
|
||||
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
@@ -103,8 +103,8 @@ pub use solids::{
|
||||
with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
|
||||
rename_appearance_graphic_symbol,
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
|
||||
graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
|
||||
@@ -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
|
||||
@@ -175,6 +231,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
|
||||
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
|
||||
/// in a clip of its footprint, neither with an opacity mask.
|
||||
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
let (clip, mut underlay) = underlay(id, faces)?;
|
||||
underlay.extend(faces.iter().cloned());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
||||
}
|
||||
|
||||
/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to,
|
||||
/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same
|
||||
/// conditions as [`sealed`].
|
||||
pub(crate) fn underlay(
|
||||
id: vectorcraft_doc::NodeId,
|
||||
faces: &[std::sync::Arc<vectorcraft_doc::Node>],
|
||||
) -> Option<(vectorcraft_doc::Node, Vec<std::sync::Arc<vectorcraft_doc::Node>>)> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
let mut outline = vectorcraft_geom::BezPath::new();
|
||||
@@ -207,15 +277,15 @@ pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vector
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default());
|
||||
underlay.extend(faces.iter().cloned());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
||||
Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), 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;
|
||||
@@ -239,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];
|
||||
@@ -274,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;
|
||||
@@ -517,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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+290
-57
@@ -107,24 +107,84 @@ fn reaches_appearance(e: &Effect) -> bool {
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
|
||||
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
|
||||
/// baked and expanded through that art ([`reshape`]).
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`],
|
||||
/// [`has_copied_row_raster`]), 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())
|
||||
|| has_copied_row_raster(n)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are
|
||||
/// carried by copies: one whose own effects list a Transform effect that makes copies after a
|
||||
/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes
|
||||
/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or
|
||||
/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`],
|
||||
/// [`follow_copies`]).
|
||||
pub fn has_copied_row_raster(n: &Node) -> bool {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
// Checked first: this runs for every object drawn.
|
||||
if !n.appearance.items.iter().any(follows_row_raster) {
|
||||
return false;
|
||||
}
|
||||
n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n)
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry a visible raster effect that follows a Transform effect
|
||||
/// ([`crate::raster::follows`])?
|
||||
fn follows_row_raster(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
}
|
||||
|
||||
/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries
|
||||
/// the raster effects listed before it: the index of the first visible Transform effect that makes
|
||||
/// copies (an earlier one that makes copies included) for which a visible raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible
|
||||
/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it
|
||||
/// that makes copies or moves at random holds those raster effects back
|
||||
/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it
|
||||
/// and before a later Transform effect that makes copies or moves at random, which would apply to
|
||||
/// the art that raster effect paints.
|
||||
fn copied_row_raster_at(fx: &[Effect]) -> Option<usize> {
|
||||
let copying =
|
||||
|e: &Effect| e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0;
|
||||
// Is a visible raster effect in `rest` listed before its last Transform effect that holds back?
|
||||
let raster_held = |rest: &[Effect]| {
|
||||
rest.iter().rposition(crate::raster::holds_back).is_some_and(|k| rest[..k].iter().any(|e| e.visible && crate::is_raster(&e.id)))
|
||||
};
|
||||
(0..fx.len()).find(|&t| {
|
||||
let before = &fx[..t];
|
||||
copying(&fx[t])
|
||||
&& !raster_held(&fx[t + 1..])
|
||||
&& crate::raster::held_back(before) == 0
|
||||
&& before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id))
|
||||
})
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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 +203,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)
|
||||
}
|
||||
|
||||
@@ -890,6 +951,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
|
||||
as_art(doc, n, symbol_art)
|
||||
}
|
||||
|
||||
/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the
|
||||
/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`]
|
||||
/// gives. `None` for other kinds of objects and for an instance without `symbol_art`.
|
||||
pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
return None;
|
||||
}
|
||||
as_art(doc, n, symbol_art)
|
||||
}
|
||||
|
||||
/// [`reshape`] without its checks (no geometry effects: just the art).
|
||||
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
@@ -921,7 +992,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 {
|
||||
@@ -978,7 +1050,7 @@ fn as_art_opts(
|
||||
}
|
||||
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
|
||||
};
|
||||
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
|
||||
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), paint_doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
@@ -1016,23 +1088,39 @@ 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);
|
||||
let rows = has_copied_row_raster(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
@@ -1073,17 +1161,18 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) ->
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc);
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
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`]).
|
||||
/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster
|
||||
/// effects listed before it ([`copied_raster_at`]).
|
||||
pub fn outer_effects(n: &Node) -> &[Effect] {
|
||||
match copied_raster_at(n) {
|
||||
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
|
||||
@@ -1119,7 +1208,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.
|
||||
@@ -1203,19 +1292,19 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
|
||||
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
|
||||
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
|
||||
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc);
|
||||
}
|
||||
|
||||
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
|
||||
/// strokes) follow the effects ([`crate::Carry`]).
|
||||
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc)
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, &[], budget, false, doc)
|
||||
reshape_leaves_apart(art, fx, &[], budget, (false, false), doc)
|
||||
}
|
||||
|
||||
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
|
||||
@@ -1236,7 +1325,10 @@ fn hoist_copies(art: &mut Node) {
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
|
||||
/// `apart`, a Transform effect's copies of each path are objects
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. With `rows`,
|
||||
/// so are the copies of a path with a fill or stroke whose raster effects follow a Transform effect
|
||||
/// ([`crate::raster::follows`]), and each copy's fills and strokes carry those raster effects moved,
|
||||
/// turned, reflected and scaled with it ([`follow_copies`]). A live-effect
|
||||
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
|
||||
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
|
||||
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
|
||||
@@ -1247,7 +1339,14 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
|
||||
fn reshape_leaves_apart(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
(apart, rows): (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
return whole;
|
||||
@@ -1284,7 +1383,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes, held };
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
@@ -1328,6 +1427,7 @@ struct Step<'a> {
|
||||
seed: u64,
|
||||
effect: Option<usize>,
|
||||
apart: bool,
|
||||
rows: bool,
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
held: bool,
|
||||
@@ -1492,8 +1592,12 @@ impl Step<'_> {
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
|
||||
// Each copy of a path with a linked mask carries the mask, moved with it.
|
||||
// With `rows`, each copy carries the raster effects of its fills and strokes,
|
||||
// following that copy's map.
|
||||
let rows = self.rows && copies > 0 && leaf.appearance.items.iter().any(follows_row_raster);
|
||||
let separate = copies > 0
|
||||
&& (self.apart
|
||||
|| rows
|
||||
|| leaf.appearance.has_unplaced_gradient()
|
||||
|| leaf.appearance.has_placed_gradient()
|
||||
|| paints_copies_apart(&leaf.appearance, rule)
|
||||
@@ -1501,9 +1605,12 @@ impl Step<'_> {
|
||||
// The copies of a path replace it by a group of them, the path included.
|
||||
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
|
||||
if options.reach_appearance() {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some() || rows, None);
|
||||
*used = used.minus(before).plus(made);
|
||||
took |= moved;
|
||||
if moved && rows {
|
||||
follow_copies(leaf, map, None);
|
||||
}
|
||||
if moved {
|
||||
// With Transform Objects off the path stays, and its mask takes the
|
||||
// effect's stroke and pattern changes as its own art.
|
||||
@@ -1519,6 +1626,9 @@ impl Step<'_> {
|
||||
if separate {
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
|
||||
if rows {
|
||||
follow_copies(leaf, m, None);
|
||||
}
|
||||
*used = used.minus(before).plus(made);
|
||||
took = true;
|
||||
moved_ids.insert(leaf.id);
|
||||
@@ -1910,7 +2020,7 @@ fn transform_leaf(
|
||||
kept: Kept,
|
||||
) -> (Budget, bool) {
|
||||
let mut scaling = copy_scaling(options);
|
||||
if follows && copies == 0 {
|
||||
if follows {
|
||||
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
|
||||
}
|
||||
if !options.objects {
|
||||
@@ -2226,7 +2336,8 @@ fn paint_piece(
|
||||
|
||||
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
|
||||
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
|
||||
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`item_transform_options`]) or makes copies that carry the raster effects before it
|
||||
/// ([`copied_row_raster_at`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
|
||||
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
|
||||
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
|
||||
@@ -2243,9 +2354,20 @@ fn makes_piece(e: &Effect) -> bool {
|
||||
reaches_appearance(e) || painted_plugin(e).is_some()
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that [`makes_piece`]?
|
||||
/// Where the fill's or stroke's own effects `fx` make its piece of a path an object of its own: the
|
||||
/// index of the first effect that [`makes_piece`], or of the Transform effect whose copies carry the
|
||||
/// raster effects before it ([`copied_row_raster_at`]), whichever is listed first.
|
||||
fn piece_at(fx: &[Effect]) -> Option<usize> {
|
||||
let copied = copied_row_raster_at(fx);
|
||||
match fx.iter().position(makes_piece) {
|
||||
Some(at) => Some(copied.map_or(at, |t| t.min(at))),
|
||||
None => copied,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that makes its piece an object of its own ([`piece_at`])?
|
||||
fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(makes_piece)
|
||||
crate::paints(item) && piece_at(item.effects()).is_some()
|
||||
}
|
||||
|
||||
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
|
||||
@@ -2255,12 +2377,17 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
|
||||
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
|
||||
/// pattern follow the map, and the raster effects before it that follow it take their followed
|
||||
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
|
||||
/// values ([`follow_piece`]), on each copy the values that copy's map gives them
|
||||
/// ([`follow_copies`]). The effects after it keep their values and apply to what it made
|
||||
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
|
||||
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
|
||||
/// stroke's own effects. The geometry effects after the Transform effect then
|
||||
/// stroke's own effects. A fill or stroke whose first such Transform effect makes copies that carry
|
||||
/// the raster effects before it ([`copied_row_raster_at`]) becomes a path of its own the same way,
|
||||
/// with neither option. The geometry effects after the Transform effect then
|
||||
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
|
||||
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
|
||||
/// effects stay on each of them, except that without either option the raster effects after a
|
||||
/// Transform effect that makes copies paint once around all of them ([`lift_later_raster`]). The
|
||||
/// other fills and strokes stay together on paths of the leaf's
|
||||
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
|
||||
/// what it has spent.
|
||||
///
|
||||
@@ -2306,7 +2433,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
|
||||
for (i, item) in original.appearance.items.iter().enumerate() {
|
||||
let fx = item.effects();
|
||||
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
|
||||
let Some(at) = piece_at(fx).filter(|_| crate::paints(item)) else {
|
||||
plain.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
@@ -2384,13 +2511,24 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
let after = kept_before.len();
|
||||
let keep = |k: usize| k >= after || !options.objects;
|
||||
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
|
||||
*used = used.plus(made);
|
||||
let from = crate::raster::held_back(before);
|
||||
if moved && !held_later {
|
||||
// Each copy carries the raster effects before the Transform effect, following that copy's
|
||||
// map, unless a Transform effect before or after it holds them back.
|
||||
let copied = copies > 0 && !held_later && from == 0;
|
||||
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, copied, Some((&rest, &keep)));
|
||||
*used = used.plus(made);
|
||||
if moved && copied {
|
||||
follow_copies(&mut p, map, Some(0..after));
|
||||
} else if moved && !held_later {
|
||||
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
|
||||
}
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
|
||||
// Without Transform Patterns and Scale Strokes & Effects, the raster effects after the
|
||||
// Transform effect paint once around all the copies, as they paint around the one path of
|
||||
// every copy.
|
||||
if copies > 0 && !options.reach_appearance() {
|
||||
lift_later_raster(&mut p, after);
|
||||
}
|
||||
pieces.push(Arc::new(p));
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
@@ -2441,6 +2579,7 @@ fn transform_piece(
|
||||
count = count.max(item.effects().len());
|
||||
}
|
||||
});
|
||||
let outer = held;
|
||||
// The effects before a Transform effect among the piece's effects that makes copies or moves at
|
||||
// random are held back from the Transform effects before it too.
|
||||
let mut held = held;
|
||||
@@ -2461,7 +2600,7 @@ fn transform_piece(
|
||||
let from = held.min(j);
|
||||
let mut holds = false;
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
|
||||
let at = PieceStage { j, from, seed, bounds, doc, stage };
|
||||
let at = PieceStage { j, from, outer, seed, bounds, doc, stage };
|
||||
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
|
||||
// counts each path it became so, or `None` when it stays as it was.
|
||||
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
|
||||
@@ -2682,12 +2821,14 @@ thread_local! {
|
||||
|
||||
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
|
||||
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
|
||||
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
|
||||
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
|
||||
/// plug-in is listed by.
|
||||
/// effect; `outer`, how many of the piece's effects a Transform effect before them holds back; the
|
||||
/// object's `seed`; the reference box `bounds` of all the piece's paths; the document that painted
|
||||
/// pieces' swatches and patterns must be in; and the `stage` a deferred live-effect plug-in is
|
||||
/// listed by.
|
||||
struct PieceStage<'a> {
|
||||
j: usize,
|
||||
from: usize,
|
||||
outer: usize,
|
||||
seed: u64,
|
||||
bounds: Rect,
|
||||
doc: Option<&'a Document>,
|
||||
@@ -2730,15 +2871,30 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage));
|
||||
}
|
||||
if reaches_appearance(e) {
|
||||
let copied = copies_carry(item.effects(), e, at);
|
||||
if reaches_appearance(e) || copied {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed);
|
||||
let j = at.j;
|
||||
let keep = |k: usize| k > j || (k < j && !options.objects);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
|
||||
if moved {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, copied, Some((item.effects(), &keep)));
|
||||
if moved && copied {
|
||||
// Each copy's raster effects before the Transform effect follow that copy's map. The
|
||||
// Transform effects before it have already moved them, so each run between two of
|
||||
// them follows on its own.
|
||||
let fx = item.effects();
|
||||
let mut start = 0;
|
||||
for k in 0..=j {
|
||||
if k == j || fx.get(k).is_some_and(|f| f.id == "distort.transform") {
|
||||
if start < k {
|
||||
follow_copies(leaf, map, Some(start..k));
|
||||
}
|
||||
start = k + 1;
|
||||
}
|
||||
}
|
||||
} else if moved {
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
}
|
||||
return Some(made);
|
||||
@@ -2763,6 +2919,37 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Does Transform effect `e`, at stage `at` of [`transform_piece`] of a fill or stroke whose effects
|
||||
/// are `fx`, make copies that each carry the raster effects listed before it, following that copy's
|
||||
/// map ([`follow_copies`]), as the copies of the piece's first Transform effect do
|
||||
/// ([`transform_item_leaf`])? It does when it makes copies with Transform Objects on, a visible
|
||||
/// raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed before it,
|
||||
/// and no Transform effect that makes copies or moves at random holds those raster effects back:
|
||||
/// none before the piece's effects, none listed before it after such a raster effect, and none
|
||||
/// after it. Without Transform Patterns and Scale Strokes & Effects, every other visible effect
|
||||
/// before it must also be a geometry effect or such a raster effect, and no visible raster effect
|
||||
/// may be listed after it, as for [`copied_row_raster_at`].
|
||||
fn copies_carry(fx: &[Effect], e: &Effect, at: &PieceStage) -> bool {
|
||||
if !e.visible || e.id != "distort.transform" || at.outer > 0 {
|
||||
return false;
|
||||
}
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
if !crate::distort::TransformOptions::of(¶ms).objects || crate::distort::transform_map(Rect::ZERO, ¶ms, 0).1 == 0 {
|
||||
return false;
|
||||
}
|
||||
let before = fx.get(..at.j).unwrap_or_default();
|
||||
let after = fx.get(at.j + 1..).unwrap_or_default();
|
||||
if crate::raster::held_back(before) > 0
|
||||
|| !before.iter().any(|f| f.visible && crate::raster::follows(&f.id))
|
||||
|| after.iter().any(crate::raster::holds_back)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
reaches_appearance(e)
|
||||
|| (before.iter().all(|f| !f.visible || is_geometry(&f.id) || crate::raster::follows(&f.id))
|
||||
&& !after.iter().any(|f| f.visible && crate::is_raster(&f.id)))
|
||||
}
|
||||
|
||||
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
|
||||
fn same_path(a: &Node, b: &Node) -> bool {
|
||||
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
@@ -2835,6 +3022,52 @@ fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the raster effects that follow a Transform effect ([`crate::raster::follows`]) on the fills
|
||||
/// and strokes of each copy [`copy_leaf`] made of `leaf` with map `m` follow that copy's map: the
|
||||
/// copy `k` places below the original takes the linear part of `m` `k` times
|
||||
/// ([`crate::raster::follow_contents`]), and the original, on top, keeps its effects. `range`, when
|
||||
/// given, is which of each fill's or stroke's effects follow; the others keep their values.
|
||||
fn follow_copies(leaf: &mut Node, m: Affine, range: Option<std::ops::Range<usize>>) {
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
let Some(children) = leaf.children_mut() else { return };
|
||||
let mut a = Affine::IDENTITY;
|
||||
for c in children.iter_mut().rev().skip(1) {
|
||||
a *= step;
|
||||
for item in &mut Arc::make_mut(c).appearance.items {
|
||||
let fx = item.effects_mut();
|
||||
let fx = match &range {
|
||||
Some(r) => fx.get_mut(r.clone()).unwrap_or_default(),
|
||||
None => fx.as_mut_slice(),
|
||||
};
|
||||
crate::raster::follow_contents(fx, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the raster effects from index `after` on of the fills and strokes of the paths under `p`,
|
||||
/// a group of copies of one fill or stroke with the same effects, onto `p` itself, so they paint
|
||||
/// once around all of the copies. The other effects stay where they are.
|
||||
fn lift_later_raster(p: &mut Node, after: usize) {
|
||||
if p.children().is_none() {
|
||||
return;
|
||||
}
|
||||
let mut lifted: Option<Vec<Effect>> = None;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
for item in &mut l.appearance.items {
|
||||
let fx = item.effects_mut();
|
||||
if fx.len() <= after {
|
||||
continue;
|
||||
}
|
||||
let (raster, other): (Vec<Effect>, Vec<Effect>) = fx.split_off(after).into_iter().partition(|e| crate::is_raster(&e.id));
|
||||
fx.extend(other);
|
||||
lifted.get_or_insert(raster);
|
||||
}
|
||||
});
|
||||
if let Some(raster) = lifted {
|
||||
p.appearance.effects.extend(raster);
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
|
||||
/// order. A group inside one of them is part of it.
|
||||
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
|
||||
|
||||
+330
-51
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
@@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
shade: flag(p, "shade", true),
|
||||
smooth_shading: true,
|
||||
cap_ends: flag(p, "cap", true),
|
||||
fill_rule: FillRule::NonZero,
|
||||
curve_samples: None,
|
||||
map_surface: false,
|
||||
}
|
||||
@@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
|
||||
return Ok(());
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ()))
|
||||
paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ()))
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
|
||||
@@ -296,11 +297,35 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize {
|
||||
faces.saturating_mul(4).saturating_mul(paint_bytes(paint))
|
||||
}
|
||||
|
||||
/// Do Revolve's `options` light its surface with colored lights?
|
||||
fn colored(options: &Revolve) -> bool {
|
||||
options.light_color != [1.0; 3] || options.lights.is_some()
|
||||
}
|
||||
|
||||
/// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under
|
||||
/// colored lights (`colored`), in a solid color or a gradient, when a face takes a smooth light
|
||||
/// ramp ([`crate::lighting::rgb_gradient_art`], [`crate::lighting::gradient_art`],
|
||||
/// [`crate::lighting::smooth_paint`]). Not in a gradient with transparent stops: its composed faces
|
||||
/// carry its opacity mask, which the underlay does not take ([`crate::lighting::underlay`]).
|
||||
fn seals(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> bool {
|
||||
colored
|
||||
&& (matches!(paint, Paint::Gradient(_)) || paint.color().is_some())
|
||||
&& faces.iter().any(|f| f.rgb_gradient.is_some() || f.light_gradient.is_some())
|
||||
&& crate::lighting::opaque_paint(paint).1.is_none()
|
||||
}
|
||||
|
||||
/// The bytes the copies of `paint` take on Revolve's `faces` ([`paint_copies`]), twice that when the
|
||||
/// faces lie over an underlay of themselves ([`seals`]).
|
||||
fn surface_copies(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> usize {
|
||||
let copies = paint_copies(faces.len(), paint);
|
||||
if seals(faces, paint, colored) { copies.saturating_mul(2) } else { copies }
|
||||
}
|
||||
|
||||
/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the
|
||||
/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`].
|
||||
fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> {
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options)?;
|
||||
*copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0)));
|
||||
*copies = copies.saturating_add(item.map_or(0, |i| surface_copies(&faces, &paint_of(i).0, colored(&options))));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into());
|
||||
}
|
||||
@@ -394,7 +419,7 @@ fn cast_surface(
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
|
||||
caster.revolve(path, options.fill_rule, b, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -425,7 +450,7 @@ fn group_shadow(
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?;
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
|
||||
@@ -438,7 +463,9 @@ fn group_shadow(
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last
|
||||
/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them
|
||||
/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
@@ -453,7 +480,7 @@ fn surface(
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
cast: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool)> {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
@@ -473,15 +500,16 @@ fn surface(
|
||||
let drawn =
|
||||
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false));
|
||||
}
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let colored = colored(&options);
|
||||
let (faces, kept) = if cast {
|
||||
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
|
||||
} else {
|
||||
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
|
||||
};
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
|
||||
let seal = seals(&faces, &paint, colored);
|
||||
copies.surfaces = copies.surfaces.saturating_add(surface_copies(&faces, &paint, colored));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
}
|
||||
@@ -604,7 +632,62 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some((keys, group, kept))
|
||||
Some((keys, group, kept, seal))
|
||||
}
|
||||
|
||||
/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal`
|
||||
/// ([`sealed_run`]), keeping the surface's opacity and blending mode.
|
||||
fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node {
|
||||
let NodeKind::Group { children, clip: false } = &surface.kind else { return surface };
|
||||
let Some(mut out) = seal.then(|| sealed_run(id, children)).flatten() else { return surface };
|
||||
out.opacity = surface.opacity;
|
||||
out.blend = surface.blend;
|
||||
out
|
||||
}
|
||||
|
||||
/// The faces `run` of one surface, in drawing order, over an underlay of themselves, all clipped
|
||||
/// once to the faces' outline, as [`crate::lighting::sealed`] draws them. A face drawn with a part
|
||||
/// of a graphic, a group of the face and that part, takes its face's underlay and stays in the
|
||||
/// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]),
|
||||
/// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces.
|
||||
fn sealed_run(id: NodeId, run: &[Arc<Node>]) -> Option<Node> {
|
||||
let faces: Vec<Arc<Node>> = run
|
||||
.iter()
|
||||
.map(|face| match &face.kind {
|
||||
NodeKind::Group { children, clip: false } => children.first().cloned(),
|
||||
_ => Some(face.clone()),
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
if faces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (clip, mut underlay) = crate::lighting::underlay(id, &faces)?;
|
||||
underlay.extend(run.iter().cloned());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
||||
}
|
||||
|
||||
/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive
|
||||
/// faces of one surface that `seal` takes lies over an underlay of its own faces ([`sealed_run`]),
|
||||
/// so no underlay reaches under another surface's faces, as Inflate's surfaces do
|
||||
/// (`crate::solids::underlaid_runs`). A run the underlay does not take keeps its faces.
|
||||
fn sealed_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, seal: impl Fn(usize) -> bool) -> Vec<Arc<Node>> {
|
||||
let mut out = Vec::with_capacity(faces.len());
|
||||
let mut run: Vec<Arc<Node>> = vec![];
|
||||
let mut faces = faces.into_iter().peekable();
|
||||
while let Some((surface, face)) = faces.next() {
|
||||
run.push(face);
|
||||
if faces.peek().is_some_and(|(next, _)| *next == surface) {
|
||||
continue;
|
||||
}
|
||||
match seal(surface).then(|| sealed_run(id, &run)).flatten() {
|
||||
Some(sealed) => {
|
||||
out.push(Arc::new(sealed));
|
||||
run.clear();
|
||||
}
|
||||
None => out.append(&mut run),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
|
||||
@@ -621,13 +704,16 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
|
||||
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
|
||||
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
|
||||
/// [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
/// A surface of one object about the bounds of `path`, filled with `rule`, built with options
|
||||
/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast
|
||||
/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of
|
||||
/// `doc`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn object_surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
fx: &Effect,
|
||||
item: &AppearanceItem,
|
||||
expand: bool,
|
||||
@@ -636,7 +722,14 @@ fn object_surface(
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
|
||||
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
|
||||
}
|
||||
|
||||
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
|
||||
/// leave open the holes `rule` leaves in the profile.
|
||||
fn rule_options(fx: &Effect, rule: FillRule) -> Revolve {
|
||||
Revolve { fill_rule: rule, ..fx_options(fx) }
|
||||
}
|
||||
|
||||
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
|
||||
@@ -757,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
let mut out = vec![];
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, fx, options)?);
|
||||
out.extend(faces(&s.path, b, fx, Revolve { fill_rule: s.rule, ..options })?);
|
||||
}
|
||||
// In wireframe mode the canvas draws no shadow.
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
|
||||
return Ok((out, shadow));
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let (path, rule) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
|
||||
@@ -771,8 +864,8 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&path, b, fx, fx_options(fx))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
|
||||
let surface = faces(&path, b, fx, rule_options(fx, rule))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None)? };
|
||||
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -783,7 +876,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&p, b, fx, fx_options(fx))?;
|
||||
let surface = faces(&p, b, fx, rule_options(fx, rule))?;
|
||||
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
|
||||
}
|
||||
}
|
||||
@@ -801,13 +894,14 @@ fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
}
|
||||
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
|
||||
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
|
||||
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with
|
||||
/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces
|
||||
/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge
|
||||
/// limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = (&'a PathData, FillRule)>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
let mut faces = vec![];
|
||||
for path in paths {
|
||||
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
|
||||
for (path, rule) in paths {
|
||||
faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path));
|
||||
}
|
||||
crate::solids::wireframe::wire_art(id, &faces)
|
||||
}
|
||||
@@ -857,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of the faces, with no shadow.
|
||||
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
|
||||
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
|
||||
} else {
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
@@ -887,18 +981,19 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
|
||||
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
|
||||
Arc::make_mut(&mut art).appearance.effects =
|
||||
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
children.push(art);
|
||||
continue;
|
||||
}
|
||||
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()?
|
||||
{
|
||||
shadow.appearance.effects = art.appearance.effects.clone();
|
||||
// The shadow keeps its own blur (the light's Softness) below the later effects.
|
||||
shadow.appearance.effects.extend(art.appearance.effects.iter().cloned());
|
||||
shadows.push(Arc::new(shadow));
|
||||
}
|
||||
children.push(Arc::new(art));
|
||||
@@ -1044,7 +1139,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of every member's faces, with no shadow.
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
|
||||
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
|
||||
@@ -1055,6 +1150,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let mut surfaces = vec![];
|
||||
// The faces each member's surface kept for the shadow, member by member.
|
||||
let mut kept = vec![];
|
||||
// Whether each member's faces lie over an underlay of themselves ([`surface`]).
|
||||
let mut seals = vec![];
|
||||
let mut opaque = true;
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
@@ -1072,10 +1169,15 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
let options = Revolve { fill_rule: s.rule, ..options };
|
||||
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
seals.push(seal);
|
||||
}
|
||||
// The faces of a member whose surface takes an underlay lie over one, run by run in the one
|
||||
// order of every member's faces ([`sealed_runs`]).
|
||||
let seal = |member: usize| seals.get(member) == Some(&true);
|
||||
if surfaces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -1101,7 +1203,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let order = crate::solids::surface_order(faces.iter().map(|(d, ..)| (d.points.as_slice(), d.plane, d.depth)));
|
||||
let faces = in_order(faces, &order);
|
||||
if opaque {
|
||||
vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))]
|
||||
vec![Arc::new(Node::group(n.id, sealed_runs(n.id, faces.into_iter().map(|(_, member, .., face)| (member, face)).collect(), seal)))]
|
||||
} else {
|
||||
// An opaque member's face goes in the order on its own. The faces of a member with
|
||||
// transparency share a run, one group with the opacity and blending mode of its fill or
|
||||
@@ -1110,6 +1212,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
// where one group can't be both behind and in front of another face.
|
||||
struct Run<'a> {
|
||||
member: Option<usize>,
|
||||
// The member the faces are of.
|
||||
of: usize,
|
||||
scopes: &'a [Scope],
|
||||
bounds: Rect,
|
||||
faces: Vec<Arc<Node>>,
|
||||
@@ -1125,12 +1229,12 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0);
|
||||
let Some(cover) = Coverage::of(&face).filter(|_| paints) else {
|
||||
// A face that paints nothing goes in the order on its own and overlaps nothing.
|
||||
runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
|
||||
runs.push(Run { member: None, of: member, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
|
||||
continue;
|
||||
};
|
||||
let masked = masks.get(member).is_some_and(Option::is_some);
|
||||
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked {
|
||||
runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
runs.push(Run { member: None, of: member, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
continue;
|
||||
}
|
||||
let mut clear = |r: &Run| {
|
||||
@@ -1153,24 +1257,49 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
if let Some(last) = last_run.get_mut(member) {
|
||||
*last = Some(runs.len());
|
||||
}
|
||||
runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
runs.push(Run {
|
||||
member: Some(member),
|
||||
of: member,
|
||||
scopes,
|
||||
bounds: cover.bounds,
|
||||
faces: vec![face],
|
||||
cover: vec![cover],
|
||||
opacity,
|
||||
blend,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let runs = runs.into_iter().filter_map(|mut r| {
|
||||
// Consecutive faces of opaque members on their own wait in `solo` and go over an
|
||||
// underlay of their member's faces, run by run ([`sealed_runs`]).
|
||||
let mut out: Vec<(&[Scope], Arc<Node>)> = Vec::with_capacity(runs.len());
|
||||
let mut solo: Vec<(usize, Arc<Node>)> = vec![];
|
||||
for mut r in runs {
|
||||
// A face on its own needs a group only for the opacity or blending mode of its fill or stroke.
|
||||
if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() {
|
||||
return r.faces.pop().map(|face| (r.scopes, face));
|
||||
let Some(face) = r.faces.pop() else { continue };
|
||||
if r.scopes.is_empty() && !r.cover.is_empty() {
|
||||
solo.push((r.of, face));
|
||||
} else {
|
||||
out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face)));
|
||||
out.push((r.scopes, face));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut group = Node::group(n.id, r.faces);
|
||||
out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face)));
|
||||
let mut group = match r.member.filter(|m| seal(*m)).and_then(|_| sealed_run(n.id, &r.faces)) {
|
||||
Some(sealed) => sealed,
|
||||
None => Node::group(n.id, r.faces),
|
||||
};
|
||||
group.opacity = r.opacity;
|
||||
group.blend = r.blend;
|
||||
if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() {
|
||||
group.extras_mut().mask = Some(mask);
|
||||
}
|
||||
Some((r.scopes, Arc::new(group)))
|
||||
});
|
||||
scoped(n.id, runs.collect(), 0)
|
||||
out.push((r.scopes, Arc::new(group)));
|
||||
}
|
||||
out.extend(sealed_runs(n.id, solo, seal).into_iter().map(|face| (&[][..], face)));
|
||||
scoped(n.id, out, 0)
|
||||
}
|
||||
};
|
||||
// One shadow for every member's surface, behind them all.
|
||||
@@ -1693,6 +1822,156 @@ mod tests {
|
||||
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
|
||||
let object = painted(3, 0.0, stops * 2);
|
||||
assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget");
|
||||
// Under a colored light the faces lie over an underlay of themselves, which copies their
|
||||
// paints again: the gradient that fits in white light is past the budget.
|
||||
let lit = json!({"lightColor": "#ff0000"});
|
||||
let object = painted(4, 0.0, stops);
|
||||
assert_eq!(validate_revolve(&object, &json!({})), Ok(()));
|
||||
let refused = validate_revolve(&object, &lit).unwrap_err();
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
let mut drawn = (*object).clone();
|
||||
drawn.appearance.effects.push(crate::new_effect(REVOLVE, &lit).unwrap());
|
||||
assert_eq!(revolve_art(&drawn), None, "past the budget the source draws");
|
||||
}
|
||||
|
||||
/// Is `u` the underlay [`crate::lighting::underlay`] draws for `face`, a face [`surface`] draws?
|
||||
fn underlies(u: &Node, face: &Node) -> bool {
|
||||
match (&u.kind, &face.kind) {
|
||||
(NodeKind::Path { .. }, NodeKind::Path { .. }) => {
|
||||
u.path_data() == face.path_data()
|
||||
&& u.appearance.items.iter().all(|i| !matches!(i, AppearanceItem::Stroke(s) if s.width != crate::lighting::UNDERLAY_SEAM))
|
||||
}
|
||||
(NodeKind::Group { children: under, clip: true }, NodeKind::Group { children, clip: true }) => {
|
||||
matches!((under.get(1), children.get(1)), (Some(a), Some(b)) if Arc::ptr_eq(a, b))
|
||||
}
|
||||
(_, NodeKind::Group { children, clip: false }) => children.first().is_some_and(|f| underlies(u, f)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The runs of faces in `art` that lie over an underlay of themselves ([`sealed_run`]), each
|
||||
/// run's faces in drawing order.
|
||||
pub(super) fn sealed_faces(art: &Node) -> Vec<Vec<Arc<Node>>> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
let NodeKind::Group { children, clip: true } = &n.kind else { return };
|
||||
let [clip, inner] = &children[..] else { return };
|
||||
let NodeKind::Group { children: drawn, clip: false } = &inner.kind else { return };
|
||||
let (under, faces) = drawn.split_at(drawn.len() / 2);
|
||||
if clip.path_data().is_some() && !inner.isolate && drawn.len() % 2 == 0 && under.iter().zip(faces).all(|(u, f)| underlies(u, f)) {
|
||||
out.push(faces.to_vec());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// `n`'s surface as [`surface`] draws it before its faces are sealed, and whether they are.
|
||||
fn unsealed(n: &Node) -> (Node, bool) {
|
||||
let path = n.path_data().unwrap();
|
||||
let fx = n.appearance.effects.first().unwrap();
|
||||
let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap());
|
||||
let (_, art, _, seal) =
|
||||
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap();
|
||||
(art, seal)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colored_light_faces_lie_over_an_underlay_of_themselves_once_per_surface() {
|
||||
use vectorcraft_doc::color::{BlendMode, Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let lit = |params: Value, paint: Paint| {
|
||||
let mut n = profile_node();
|
||||
n.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
|
||||
n.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap());
|
||||
n
|
||||
};
|
||||
let red = Paint::solid(Color::rgb(0.8, 0.2, 0.1));
|
||||
let ramp = |opacity: f32| {
|
||||
let stops = [Color::WHITE, Color::rgb(0.5, 0.5, 0.5)].into_iter().enumerate();
|
||||
let stops = stops.map(|(i, c)| GradientStop { opacity, ..GradientStop::new(i as f32, c) }).collect();
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))))
|
||||
};
|
||||
let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]);
|
||||
// In white light nothing is sealed.
|
||||
let white = lit(json!({}), red.clone());
|
||||
assert!(!unsealed(&white).1);
|
||||
assert!(sealed_faces(&revolve_art(&white).unwrap()).is_empty());
|
||||
for (name, n) in [
|
||||
("solid", lit(json!({"lightColor": "#ff0000"}), red.clone())),
|
||||
("gradient", lit(json!({"lightColor": "#ff0000"}), ramp(1.0))),
|
||||
("two lights", lit(json!({"lights": lights}), ramp(1.0))),
|
||||
("edge-on", lit(json!({"lightColor": "#ff0000", "rotationX": -80}), red.clone())),
|
||||
] {
|
||||
// Every face of the surface, in its order, lies over its underlay, once.
|
||||
let (plain, seal) = unsealed(&n);
|
||||
assert!(seal, "{name}");
|
||||
let faces = plain.children().unwrap().to_vec();
|
||||
assert_eq!(sealed_faces(&revolve_art(&n).unwrap()), vec![faces], "{name}");
|
||||
}
|
||||
// The surface's opacity and blending mode apply once, to the sealed surface.
|
||||
let mut n = lit(json!({"lightColor": "#ff0000"}), ramp(1.0));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = 0.5;
|
||||
f.blend = BlendMode::Multiply;
|
||||
}
|
||||
let art = revolve_art(&n).unwrap();
|
||||
assert_eq!(sealed_faces(&art).len(), 1);
|
||||
// Inside the surface only a face's own lit art blends (its light multiplied over its paint).
|
||||
let once = |chain: &Chain| chain.first() == Some(&(0.5, BlendMode::Multiply)) && chain.iter().skip(1).all(|(o, _)| *o == 1.0);
|
||||
let faces = faces_in_order(&art);
|
||||
assert!(faces.iter().all(|(_, chain)| once(chain)), "{:?}", faces.iter().map(|f| &f.1).find(|c| !once(c)));
|
||||
// Faces in a gradient with transparent stops carry its opacity mask, which the underlay
|
||||
// does not take: the surface keeps its faces as they are, and their paints are not
|
||||
// counted twice.
|
||||
let n = lit(json!({"lightColor": "#ff0000"}), ramp(0.6));
|
||||
let (plain, seal) = unsealed(&n);
|
||||
assert!(!seal);
|
||||
assert_eq!(sealed_surface(n.id, plain.clone(), true), plain);
|
||||
assert!(sealed_faces(&revolve_art(&n).unwrap()).is_empty());
|
||||
let path = n.path_data().unwrap();
|
||||
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), fx_options(&n.appearance.effects[0])).unwrap();
|
||||
assert_eq!(surface_copies(&faces, &ramp(0.6), true), paint_copies(faces.len(), &ramp(0.6)));
|
||||
assert_eq!(surface_copies(&faces, &ramp(1.0), true), 2 * paint_copies(faces.len(), &ramp(1.0)));
|
||||
// Revolve (Classic) takes no colored light, so none of its faces are sealed.
|
||||
assert!(!colored(&classic::options(&json!({"lightColor": "#ff0000"}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_members_run_of_faces_lies_over_an_underlay_of_its_own() {
|
||||
// Rings one above the other: their faces alternate in the one order, so each ring's
|
||||
// faces go over underlays run by run, and no run holds faces of both.
|
||||
let ring = |id, y: f64, opacity: f32| {
|
||||
let mut n = (*member(id, 40.0)).clone();
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
if let NodeKind::Path { path, .. } = &mut n.kind {
|
||||
*path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath()));
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let lit = json!({"segments": 16, "lightColor": "#ff0000"});
|
||||
for opacity in [1.0, 0.5] {
|
||||
let members = vec![ring(1, 0.0, 1.0), ring(2, 200.0, opacity)];
|
||||
let art = revolve_art(&group_with(lit.clone(), members.clone())).unwrap();
|
||||
let runs = sealed_faces(&art);
|
||||
assert!(runs.len() >= 2, "{opacity}: {} runs", runs.len());
|
||||
for run in &runs {
|
||||
let ys: Vec<f64> = run.iter().filter_map(|f| f.visual_bounds()).map(|b| b.center().y).collect();
|
||||
assert!(ys.iter().all(|y| *y < 100.0) || ys.iter().all(|y| *y > 100.0), "{opacity}: a run holds one ring's faces: {ys:?}");
|
||||
}
|
||||
// Each ring's opacity applies once, to its faces and their underlays; inside, only a
|
||||
// face's own lit art blends.
|
||||
let faded = |chain: &Chain| chain.iter().filter(|(o, _)| *o != 1.0).count();
|
||||
let chains: Vec<Chain> = faces_in_order(&art).into_iter().map(|(_, c)| c).collect();
|
||||
assert!(chains.iter().all(|c| faded(c) <= 1 && c.iter().all(|(o, _)| *o == 1.0 || *o == opacity)), "{opacity}");
|
||||
assert_eq!(chains.iter().any(|c| faded(c) == 1), opacity < 1.0, "{opacity}");
|
||||
if opacity == 1.0 {
|
||||
// Opaque rings share one order, and every face in it lies over an underlay.
|
||||
let white = revolve_art(&group_with(json!({"segments": 16}), members)).unwrap();
|
||||
let count = white.children().unwrap()[0].children().unwrap().len();
|
||||
assert_eq!(runs.iter().map(Vec::len).sum::<usize>(), count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1822,7 +2101,7 @@ mod tests {
|
||||
let mut fx = crate::new_effect(id, &json!({})).unwrap();
|
||||
fx.params = params.clone();
|
||||
let n = profile_node();
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let mut half = n.clone();
|
||||
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
|
||||
@@ -1830,9 +2109,9 @@ mod tests {
|
||||
}
|
||||
for n in [n, half] {
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap();
|
||||
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
@@ -1898,11 +2177,11 @@ mod tests {
|
||||
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
|
||||
f.opacity = bad;
|
||||
}
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
|
||||
let shadows = group_shadows(&group(bad));
|
||||
|
||||
@@ -164,6 +164,41 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Black Overprint every face keeps the blue, and the faces that darken get black over it,
|
||||
/// overprinting, as strong as the darkening of the shading color Black.
|
||||
#[test]
|
||||
fn black_overprint_keeps_the_blue_under_overprinting_black() {
|
||||
let darkened = revolved(json!({"surface": "diffuse"}));
|
||||
let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"}));
|
||||
let (darkened, drawn) = (faces(&darkened), faces(&art));
|
||||
assert_eq!(darkened.len(), drawn.len());
|
||||
let mut shaded = 0;
|
||||
for (face, black) in drawn.iter().zip(&darkened) {
|
||||
let fills: Vec<&vectorcraft_doc::FillLayer> = face
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false));
|
||||
let k = match fills.get(1) {
|
||||
Some(shadow) => {
|
||||
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
|
||||
assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true));
|
||||
shaded += 1;
|
||||
k
|
||||
}
|
||||
None => 0.0,
|
||||
};
|
||||
let b = fill(black).unwrap().to_rgb()[2];
|
||||
assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}");
|
||||
}
|
||||
assert!(shaded > 0, "faces turned from the light get black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_offset_edge_and_cap_shape_the_surface() {
|
||||
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
|
||||
|
||||
@@ -279,6 +279,23 @@ fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() {
|
||||
assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_a_colored_light_each_part_of_a_graphic_stays_right_after_its_face_over_the_underlay() {
|
||||
let d = document();
|
||||
let n = revolved(&CYLINDER, json!({"shade": true, "lightColor": "#ff8040", "graphics": [{"symbol": "Red"}]}));
|
||||
let art = revolve_art_in(Some(&d), &n).unwrap();
|
||||
// One run holds every face; a face with a part of the bar is a group of the face and that part.
|
||||
let runs = super::tests::sealed_faces(&art);
|
||||
assert_eq!(runs.len(), 1);
|
||||
let carrying: Vec<&Arc<Node>> = runs[0].iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).collect();
|
||||
assert!(!carrying.is_empty());
|
||||
assert!(carrying.iter().all(|f| f.children().is_some_and(|c| c.len() > 1 && parts(&c[0], false).is_empty())));
|
||||
// Every part of the bar is drawn in the run, after its face, and none in the underlay.
|
||||
let in_run: usize = carrying.iter().map(|f| parts(f, false).len()).sum();
|
||||
assert!(in_run > 0);
|
||||
assert_eq!(in_run, parts(&art, false).len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_past_the_point_limit_are_refused() {
|
||||
let mut d = document();
|
||||
|
||||
@@ -102,6 +102,21 @@ pub fn has_solid(n: &Node) -> bool {
|
||||
solid(&n.appearance.effects).is_some() || n.appearance.items.iter().any(|i| i.visible() && solid(i.effects()).is_some())
|
||||
}
|
||||
|
||||
/// Does `n` carry a 3D effect that [`three_d_meshes`] builds solids from: a visible Revolve, or
|
||||
/// else a visible Extrude & Bevel, Inflate or Rotate effect, which on a group or layer must be on
|
||||
/// the object itself (one on a group's fill or stroke draws nothing to export)? It does not build
|
||||
/// the solids, so [`three_d_meshes`] can still refuse an object it passes.
|
||||
pub fn exports_three_d(n: &Node) -> bool {
|
||||
let container = is_container(n);
|
||||
if crate::has_revolve(n) {
|
||||
!container || n.appearance.effects.iter().any(|e| e.visible && crate::is_revolve(&e.id))
|
||||
} else if container {
|
||||
solid(&n.appearance.effects).is_some()
|
||||
} else {
|
||||
has_solid(n)
|
||||
}
|
||||
}
|
||||
|
||||
/// The Position presets: (id, [rotation X, Y, Z]). Front, Back, Left, Right, Top and Bottom face
|
||||
/// the art that way; Off-Axis tilts each 20° down and 25° aside (showing the top and right);
|
||||
/// Isometric lays the art on the left, right, top or bottom plane of an isometric view (the
|
||||
@@ -2162,7 +2177,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Arc::make_mut(&mut art).appearance.effects = later.clone();
|
||||
art
|
||||
};
|
||||
shadows.extend(shadow.into_iter().map(with_later));
|
||||
// A shadow keeps its own blur (the light's Softness) below the later effects.
|
||||
shadows.extend(shadow.into_iter().map(|mut art| {
|
||||
Arc::make_mut(&mut art).appearance.effects.extend(later.iter().cloned());
|
||||
art
|
||||
}));
|
||||
children.extend(surfaces.into_iter().map(with_later));
|
||||
} else {
|
||||
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
|
||||
@@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"];
|
||||
/// The width of a Wireframe edge, in points.
|
||||
const WIRE: f64 = 0.5;
|
||||
|
||||
/// The Shading Color choices: black, a custom color, or none.
|
||||
pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"];
|
||||
/// The Shading Color choices: black, a custom color, none, or black overprinting the paint.
|
||||
pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"];
|
||||
|
||||
/// The surface settings of Extrude & Bevel (Classic)'s parameters.
|
||||
pub fn classic_shading(p: &Value) -> ClassicShading {
|
||||
@@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only
|
||||
/// the highlight lightens them).
|
||||
/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces
|
||||
/// keep their paint and only the highlight lightens them).
|
||||
fn shading_color(p: &Value) -> Option<Color> {
|
||||
match text(p, "shadingColor", "black") {
|
||||
"none" => None,
|
||||
@@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool {
|
||||
|
||||
/// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower
|
||||
/// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where
|
||||
/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`,
|
||||
/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam
|
||||
/// tone `tone` is below full light and the faces darken (`shade`), black over it as
|
||||
/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam
|
||||
/// stroke each layer draws around the face.
|
||||
fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option<Color>, seam: f64) -> Vec<AppearanceItem> {
|
||||
let Paint::Solid { color, swatch, tint } = paint else { return vec![] };
|
||||
let keep = (1.0 - spec).clamp(0.0, 1.0) as f32;
|
||||
let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep };
|
||||
let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))];
|
||||
if shade.is_some() && tone < 1.0 {
|
||||
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
|
||||
let mut layer = FillLayer::new(black.clone());
|
||||
layer.blend = BlendMode::Multiply;
|
||||
layer.overprint = true;
|
||||
let mut edge = crate::lighting::seam_stroke(black, seam);
|
||||
edge.blend = BlendMode::Multiply;
|
||||
edge.overprint = true;
|
||||
items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]);
|
||||
if shade.is_some() {
|
||||
items.extend(overprinting_black(tone, seam));
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// The black that shades a face at tone `tone` on the black plate, when the tone is below full
|
||||
/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam`
|
||||
/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a
|
||||
/// neighbor's, the face is not darkened twice.
|
||||
fn overprinting_black(tone: f64, seam: f64) -> Vec<AppearanceItem> {
|
||||
if tone >= 1.0 {
|
||||
return vec![];
|
||||
}
|
||||
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
|
||||
let mut layer = FillLayer::new(black.clone());
|
||||
layer.blend = BlendMode::Multiply;
|
||||
layer.overprint = true;
|
||||
let mut edge = crate::lighting::seam_stroke(black, seam);
|
||||
edge.blend = BlendMode::Darken;
|
||||
edge.overprint = true;
|
||||
vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]
|
||||
}
|
||||
|
||||
/// Whether the shading color of parameters `p` is Black Overprint.
|
||||
fn black_overprint(p: &Value) -> bool {
|
||||
text(p, "shadingColor", "black") == "blackOverprint"
|
||||
}
|
||||
|
||||
/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full
|
||||
/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they
|
||||
/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of
|
||||
/// the seam stroke each layer draws around the face.
|
||||
fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec<AppearanceItem> {
|
||||
let mut items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))];
|
||||
items.extend(overprinting_black(tone, seam));
|
||||
items
|
||||
}
|
||||
|
||||
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
|
||||
/// Wireframe, else the seam between faces.
|
||||
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
@@ -229,15 +256,17 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
|
||||
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
|
||||
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage; without a placement of its
|
||||
/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]).
|
||||
/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot
|
||||
/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops
|
||||
/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's
|
||||
/// coverage; without a placement of its own, it is placed once on all the faces
|
||||
/// ([`crate::lighting::opaque_surface_paint`]).
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let overprint = black_overprint(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
|
||||
let paint = &paint;
|
||||
@@ -252,6 +281,10 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
|
||||
let (tone, spec) = shading.tone(face.normal, &lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = super::seam_width(&face);
|
||||
if overprint {
|
||||
let items = overprinted_face(paint, tone, seam);
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }));
|
||||
}
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the
|
||||
//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it
|
||||
//! draws behind the solids.
|
||||
//! draws behind the solids, blurred by the first light's Softness.
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId};
|
||||
use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition};
|
||||
|
||||
use super::Scope;
|
||||
@@ -15,15 +15,21 @@ use crate::util::{flag, num, text};
|
||||
/// The shadow's paint: black at this opacity. VectorCraft's own values.
|
||||
const SHADOW_OPACITY: f32 = 0.5;
|
||||
|
||||
/// Blur radii below this, in points, leave the shadow hard-edged.
|
||||
const MIN_BLUR: f64 = 0.01;
|
||||
|
||||
/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing
|
||||
/// (Shading is off or its intensity is 0), so that no shadow is built.
|
||||
/// (Shading is off or its intensity is 0), so that no shadow is built. Its softness is the first
|
||||
/// light's.
|
||||
pub(crate) fn options(p: &Value) -> Option<Shadow> {
|
||||
let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0));
|
||||
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
|
||||
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
|
||||
let lit = flag(p, "shade", true) && intensity > 0.0;
|
||||
(lit && flag(p, "shadow", false)).then(|| Shadow {
|
||||
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
|
||||
distance: num(p, "shadowDistance", 0.0) / 100.0,
|
||||
bounds: num(p, "shadowBounds", 100.0) / 100.0,
|
||||
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,8 +70,9 @@ pub(crate) fn casts(opacity: f32) -> bool {
|
||||
}
|
||||
|
||||
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
|
||||
/// `None` when it casts nothing.
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule, and
|
||||
/// with the light's Softness a Gaussian Blur of the plane's radius ([`ShadowPlane::blur`]), which
|
||||
/// is drawn, measured, exported and expanded as that effect is; `None` when it casts nothing.
|
||||
pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> {
|
||||
let all = 0..caster.len();
|
||||
let all = std::slice::from_ref(&all);
|
||||
@@ -78,7 +85,9 @@ fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::BLACK));
|
||||
fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0);
|
||||
fill.blend = ink.blend;
|
||||
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
let blur = plane.blur();
|
||||
let effects = if blur >= MIN_BLUR { vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": blur}), visible: true }] } else { vec![] };
|
||||
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], effects, ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies).
|
||||
|
||||
@@ -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`.
|
||||
@@ -1908,6 +1921,89 @@ fn classic_shading_color_blend_steps_and_lights() {
|
||||
assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6);
|
||||
}
|
||||
|
||||
/// The fills, then the strokes, of face `face`.
|
||||
fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) {
|
||||
let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect();
|
||||
let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect();
|
||||
(fills, strokes)
|
||||
}
|
||||
|
||||
/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in
|
||||
/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice);
|
||||
/// `None` when the face has none.
|
||||
fn overprinted_black(face: &Node) -> Option<f32> {
|
||||
let (fills, strokes) = layers_of(face);
|
||||
assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke");
|
||||
let shadow = fills.get(1)?;
|
||||
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
|
||||
assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0));
|
||||
assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true));
|
||||
assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out");
|
||||
Some(k)
|
||||
}
|
||||
|
||||
/// Black Overprint keeps the paint on every face and draws the shading over it as black,
|
||||
/// overprinting, as strong as the darkening of the shading color Black; the
|
||||
/// highlight is not drawn, and No Shading adds no black.
|
||||
#[test]
|
||||
fn classic_black_overprint_keeps_the_paint_under_overprinting_black() {
|
||||
let diffuse = json!({"surface": "diffuse", "ambient": 20});
|
||||
let mut over = diffuse.clone();
|
||||
over["shadingColor"] = json!("blackOverprint");
|
||||
let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect();
|
||||
let faces = classic_faces(over);
|
||||
assert_eq!(faces.len(), darkened.len());
|
||||
let mut shaded = 0;
|
||||
for (face, rgb) in faces.iter().zip(&darkened) {
|
||||
assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept");
|
||||
let k = overprinted_black(face).unwrap_or(0.0);
|
||||
assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}");
|
||||
shaded += usize::from(k > 0.0);
|
||||
}
|
||||
assert!(shaded > 0, "faces turned from the light get black");
|
||||
// Plastic: no white layer for the highlight.
|
||||
let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
|
||||
for face in classic_faces(shiny) {
|
||||
let (fills, _) = layers_of(&face);
|
||||
assert_eq!(fills[0].paint, Paint::solid(RED));
|
||||
assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}");
|
||||
}
|
||||
// No Shading: the paint alone.
|
||||
for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) {
|
||||
assert_eq!(overprinted_black(&face), None);
|
||||
assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED));
|
||||
}
|
||||
}
|
||||
|
||||
/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate
|
||||
/// (Classic) draws its plane the same way.
|
||||
#[test]
|
||||
fn classic_black_overprint_keeps_gradients_and_shades_rotate() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint};
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)],
|
||||
))));
|
||||
let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = gradient.clone();
|
||||
}
|
||||
let art = solid_art(&n).unwrap();
|
||||
let mut shaded = 0;
|
||||
for face in faces(&art) {
|
||||
assert_eq!(layers_of(face).0[0].paint, gradient);
|
||||
shaded += usize::from(overprinted_black(face).is_some());
|
||||
}
|
||||
assert!(shaded > 0);
|
||||
// Rotate (Classic), turned from the light: red with black over it; facing it: red alone.
|
||||
let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"}));
|
||||
let face = &turned[0].children().unwrap()[0];
|
||||
assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED));
|
||||
assert!(overprinted_black(face).is_some_and(|k| k > 0.05));
|
||||
let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"}));
|
||||
assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_bevel_height_extent_and_cap_shape_the_solid() {
|
||||
let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap();
|
||||
@@ -2134,9 +2230,12 @@ fn classic_parameters_are_checked() {
|
||||
let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p));
|
||||
assert!(check(json!({})).is_ok());
|
||||
assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok());
|
||||
assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok());
|
||||
for (p, says) in [
|
||||
(json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"),
|
||||
(json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingColor": true}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"),
|
||||
@@ -2213,11 +2312,12 @@ fn classic_rotate_parameters_are_checked() {
|
||||
let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p));
|
||||
assert!(check(json!({})).is_ok());
|
||||
assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok());
|
||||
assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok());
|
||||
for (p, says) in [
|
||||
(json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"),
|
||||
(json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"),
|
||||
(json!({"surface": 2}), "`surface` must be one of"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"),
|
||||
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"),
|
||||
(json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"),
|
||||
|
||||
@@ -87,6 +87,40 @@ fn the_shadow_moves_with_its_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The radius of the Gaussian Blur on shadow `n`; `None` without one.
|
||||
fn shadow_blur(n: &Node) -> Option<f64> {
|
||||
match n.appearance.effects.as_slice() {
|
||||
[] => None,
|
||||
[e] if e.id == "blur.gaussian" && e.visible => e.params["radius"].as_f64(),
|
||||
other => panic!("unexpected effects on the shadow: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first light's Softness blurs the shadow, more with Softness and with Distance from Object;
|
||||
/// at 0 % it stays the hard-edged path. A list of lights takes the first light's Softness.
|
||||
#[test]
|
||||
fn the_first_lights_softness_blurs_the_shadow() {
|
||||
for id in CASTING {
|
||||
let blur = |params: Value| {
|
||||
let mut n = square_node(1, 0.0);
|
||||
n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap());
|
||||
let lit = art(&n, id).unwrap();
|
||||
let shadow = &lit.children().unwrap()[0];
|
||||
assert!(is_shadow(shadow), "{id} {params}");
|
||||
shadow_blur(shadow)
|
||||
};
|
||||
assert_eq!(blur(json!({"shadow": true})), None, "{id}: hard at 0 %");
|
||||
let soft = blur(json!({"shadow": true, "lightSoftness": 50})).unwrap_or_else(|| panic!("{id}"));
|
||||
let softer = blur(json!({"shadow": true, "lightSoftness": 100})).unwrap();
|
||||
let far = blur(json!({"shadow": true, "lightSoftness": 100, "shadowDistance": 100})).unwrap();
|
||||
assert!(soft > 0.0 && softer > soft && far > softer, "{id}: {soft} {softer} {far}");
|
||||
let first = json!({"shadow": true, "lightSoftness": 0, "lights": [{"softness": 100}, {"softness": 0}]});
|
||||
assert_eq!(blur(first), Some(softer), "{id}: the first light's");
|
||||
let second = json!({"shadow": true, "lightSoftness": 100, "lights": [{"softness": 0}, {"softness": 100}]});
|
||||
assert_eq!(blur(second), None, "{id}: only the first light casts");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() {
|
||||
for id in CASTING {
|
||||
@@ -203,6 +237,26 @@ fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's own 3D effect blurs its shadow by the light's Softness too, and the effects after it
|
||||
/// in the fill's list follow the blur.
|
||||
#[test]
|
||||
fn a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects() {
|
||||
for id in CASTING {
|
||||
for later in [None, Some(crate::new_effect("distort.roughen", &json!({})).unwrap())] {
|
||||
let mut n = square_node(1, 0.0);
|
||||
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
fill.effects_mut().push(crate::new_effect(id, &json!({"shadow": true, "lightSoftness": 100})).unwrap());
|
||||
fill.effects_mut().extend(later.clone());
|
||||
let lit = art(&n, id).unwrap_or_else(|| panic!("{id}"));
|
||||
let shadow = &lit.children().unwrap()[0];
|
||||
assert!(is_shadow(shadow), "{id}");
|
||||
let ids: Vec<&str> = shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
let want: Vec<&str> = std::iter::once("blur.gaussian").chain(later.as_ref().map(|e| e.id.as_str())).collect();
|
||||
assert_eq!(ids, want, "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_keeps_the_shadow_as_a_path() {
|
||||
for id in CASTING {
|
||||
|
||||
@@ -816,8 +816,8 @@ fn a_groups_transform_applies_after_its_members_own() {
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
|
||||
/// makes copies leaves them.
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. For one that
|
||||
/// makes copies, see [`each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`].
|
||||
#[test]
|
||||
fn an_objects_transform_moves_its_fills_shadows() {
|
||||
let cases = [
|
||||
@@ -825,7 +825,6 @@ fn an_objects_transform_moves_its_fills_shadows() {
|
||||
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
|
||||
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
|
||||
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
|
||||
@@ -1216,3 +1215,300 @@ fn copies_past_the_budget_each_keep_their_shadow() {
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
|
||||
/// `n` with only its fill (or only a 4 pt blue stroke, with `stroke`), whose own effects are
|
||||
/// `effects`.
|
||||
fn one_row(mut n: Node, stroke: bool, effects: Vec<Effect>) -> Node {
|
||||
let mut item = if stroke {
|
||||
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))
|
||||
} else {
|
||||
n.appearance.items.remove(0)
|
||||
};
|
||||
*item.effects_mut() = effects;
|
||||
n.appearance.items = vec![item];
|
||||
n
|
||||
}
|
||||
|
||||
/// A case of [`copying_cases`]: the params, each copy's offset and each copy's blur.
|
||||
type CopyingCase = (Value, Vec<(f64, f64)>, Vec<f64>);
|
||||
|
||||
/// The cases of a Transform effect that makes copies with a drop shadow (10, 0) and a blur of 4
|
||||
/// before it: the params, each copy's offset and each copy's blur, the last copy first.
|
||||
fn copying_cases() -> Vec<CopyingCase> {
|
||||
vec![
|
||||
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
|
||||
(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!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![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]),
|
||||
// Scale Strokes & Effects does not scale the shadow a second time, nor leave it unturned.
|
||||
(
|
||||
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "strokes": true}),
|
||||
vec![(0.0, -20.0), (10.0, 0.0)],
|
||||
vec![8.0, 4.0],
|
||||
),
|
||||
(
|
||||
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "patterns": true}),
|
||||
vec![(0.0, -20.0), (10.0, 0.0)],
|
||||
vec![8.0, 4.0],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Check that `n` is drawn, expanded and baked as `want.len()` paths, each with one shadow at the
|
||||
/// offset and blur `want` and `blurs` give it, the last copy first.
|
||||
fn assert_copies_carry(n: &Node, want: &[(f64, f64)], blurs: &[f64], what: &str) {
|
||||
assert!(crate::has_transform_art(n), "{what}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, n, None).unwrap()), ("expanded", expand_outlined(None, n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
assert_eq!(paths_in(&art), want.len(), "{what}: {how} {art:?}");
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, want), "{what}: {how} {drawn:?}");
|
||||
let b = shadow_blurs_in(&art);
|
||||
assert!(b.len() == blurs.len() && b.iter().zip(blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{what}: {how} blurs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's or stroke's own Transform effect that makes copies gives each copy the shadow listed
|
||||
/// before it in that fill's or stroke's effects, moved, turned, reflected and scaled with that copy,
|
||||
/// the last copy lowest: drawn, expanded and baked. The original keeps the shadow as it is.
|
||||
#[test]
|
||||
fn each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it() {
|
||||
for stroke in [false, true] {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
let n = one_row(square(95, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
// A Transform effect that makes copies before the shadow: its copies make one piece, which
|
||||
// the Transform effect after the shadow copies, each copy with its own shadow.
|
||||
let effects =
|
||||
vec![transform(json!({"moveV": 100, "copies": 1})), shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90, "moveH": 200, "copies": 1}))];
|
||||
let n = one_row(square(95, vec![]), stroke, effects);
|
||||
assert!(crate::has_transform_art(&n), "stroke {stroke}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, &[(0.0, -10.0), (10.0, 0.0)]), "stroke {stroke}: two copying Transform effects, {how} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that makes copies, listed after a fill's or stroke's first Transform effect
|
||||
/// with Transform Patterns on, gives each copy the shadow listed before it, as the first one's
|
||||
/// copies do, with or without options of its own: drawn, expanded and baked.
|
||||
#[test]
|
||||
fn each_copy_of_a_later_copying_transform_carries_the_shadow_before_it() {
|
||||
for stroke in [false, true] {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
let effects = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 4.0), transform(params.clone())];
|
||||
let n = one_row(square(102, vec![]), stroke, effects);
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's or stroke's shadow under its object's Transform effect that makes copies is carried by
|
||||
/// each copy, moved, turned, reflected and scaled with it: for a single fill, a single stroke, and
|
||||
/// a fill and a stroke that paint each copy below the one before. Drawn, expanded and baked.
|
||||
#[test]
|
||||
fn each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow() {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
for stroke in [false, true] {
|
||||
let mut n = one_row(square(96, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0)]);
|
||||
n.appearance.effects = vec![transform(params.clone())];
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
// Both a fill and a stroke: only the fill has the shadow.
|
||||
let mut n = square(97, vec![transform(params.clone())]);
|
||||
if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
|
||||
s.paint = Paint::solid(Color::BLACK);
|
||||
s.width = 2.0;
|
||||
}
|
||||
*n.appearance.items[0].effects_mut() = vec![shadow(10.0, 0.0, 4.0)];
|
||||
assert!(crate::has_transform_art(&n), "{params}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, &want), "layered {params}: {how} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shadow listed after a fill's own Transform effect that makes copies paints once around all of
|
||||
/// them, and one listed before it on each copy. A Transform effect that makes no copies, or has
|
||||
/// Transform Objects off, draws the fill as before, without art.
|
||||
#[test]
|
||||
fn a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies() {
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
|
||||
let n = one_row(square(98, vec![]), false, effects);
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{how}: {:?}", shadows_in(&art));
|
||||
assert_eq!(paths_in(&art), 2, "{how}");
|
||||
}
|
||||
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
|
||||
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
|
||||
assert!(!crate::has_transform_art(&n), "{params}");
|
||||
assert!(!crate::has_copied_row_raster(&n), "{params}");
|
||||
}
|
||||
// A shadow between two Transform effects that make copies paints on what the second one
|
||||
// copies, so the fill is drawn as before, without art.
|
||||
let copies = transform(json!({"rotate": 90, "copies": 1}));
|
||||
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), copies.clone(), shadow(0.0, 5.0, 0.0), copies]);
|
||||
assert!(!crate::has_copied_row_raster(&n));
|
||||
assert!(!crate::has_transform_art(&n));
|
||||
}
|
||||
|
||||
/// Copies of a fill's own Transform effect that stop at the effect budget each keep their shadow,
|
||||
/// and so do those of an object's Transform effect for its fill's shadow.
|
||||
#[test]
|
||||
fn row_copies_past_the_budget_each_keep_their_shadow() {
|
||||
let copies = transform(json!({"moveV": 50, "copies": 1000}));
|
||||
let own = one_row(path_node(100, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0), copies.clone()]);
|
||||
let mut owner = one_row(path_node(101, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0)]);
|
||||
owner.appearance.effects = vec![copies];
|
||||
for n in [own, owner] {
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
let paths = paths_in(&art);
|
||||
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);
|
||||
}
|
||||
|
||||
/// Type whose own fill's Transform effect makes copies is drawn as its outlines, and each copy
|
||||
/// carries the shadow listed before that Transform effect, as a path's copies do: for the fill's
|
||||
/// first Transform effect and for one listed after a Transform effect with Transform Patterns on.
|
||||
/// Drawn, expanded and baked.
|
||||
#[test]
|
||||
fn type_carries_its_fills_shadow_on_each_copy() {
|
||||
let filled = |mut n: Node, effects: Vec<Effect>| {
|
||||
n.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
|
||||
effects,
|
||||
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
|
||||
}));
|
||||
n
|
||||
};
|
||||
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let later = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
for (what, effects) in [("first", copying), ("later", later)] {
|
||||
let n = filled(type_node(95, vec![]), effects);
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None)), ("expanded", expand_outlined(None, &n, None)), ("baked", Some(baked(n.clone())))]
|
||||
{
|
||||
let art = art.unwrap_or_else(|| panic!("{what}: {how}"));
|
||||
assert!(near(&shadows_in(&art), &[(10.0, 0.0), (10.0, 0.0)]), "{what}: {how} {:?}", shadows_in(&art));
|
||||
// The two shadows are on two objects 100 pt apart: the type and its copy.
|
||||
let mut lefts = vec![];
|
||||
art.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
let shadows = lists.map(|l| l.iter().filter(|e| e.id == "stylize.dropShadow").count()).sum::<usize>();
|
||||
if let Some(b) = m.geometric_bounds() {
|
||||
lefts.extend(std::iter::repeat_n(b.x0, shadows));
|
||||
}
|
||||
});
|
||||
lefts.sort_by(f64::total_cmp);
|
||||
assert!(lefts.len() == 2 && (lefts[1] - lefts[0] - 100.0).abs() < 1e-6, "{what}: {how} {lefts:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,8 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths and Trim at Crossings ([`trim`]).
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
@@ -12,6 +13,8 @@ mod corners;
|
||||
mod effect_tests;
|
||||
mod shape;
|
||||
mod shared_edge;
|
||||
mod tangent_circle;
|
||||
mod tangents;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod trim;
|
||||
@@ -180,6 +183,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(corners::specs());
|
||||
v.extend(shared_edge::specs());
|
||||
v.extend(trim::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::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"));
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
|
||||
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
|
||||
//! crossing into either, added as separate open paths, with the line joining their centers if
|
||||
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::Affine;
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The command's id.
|
||||
pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents";
|
||||
/// The undo step's name.
|
||||
const LABEL: &str = "Common Tangents";
|
||||
/// The kinds of tangent `tangents` picks.
|
||||
const KINDS: [&str; 3] = ["external", "internal", "all"];
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.commonTangents",
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
|
||||
/// else the path's one closed convex subpath.
|
||||
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
|
||||
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
if span < 1e-9 || 360.0 - span < 1e-9 {
|
||||
let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]);
|
||||
return pt::Outline::ellipse(unit).map_err(refusal);
|
||||
}
|
||||
}
|
||||
pt::Outline::convex(sp).map_err(refusal)
|
||||
}
|
||||
|
||||
fn refusal(e: pt::OutlineError) -> EngineError {
|
||||
bad(
|
||||
COMMON_TANGENTS,
|
||||
match e {
|
||||
pt::OutlineError::Open => "a selected path is open",
|
||||
pt::OutlineError::NotConvex => "a selected path is not convex",
|
||||
pt::OutlineError::Empty => "a selected path has no area",
|
||||
pt::OutlineError::TooComplex => "a selected path has more than 10000 segments",
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all");
|
||||
let centerline = switch_or(p, "centerline", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let ordered = d.paint_order(roots.iter().copied());
|
||||
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
|
||||
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
|
||||
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
|
||||
let keep = |t: &&pt::Tangent| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
};
|
||||
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
|
||||
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
|
||||
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
if lines.is_empty() {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
|
||||
// external tangent means one path lies inside the other and touches it there; paths that
|
||||
// overlap without one inside the other have at least two.
|
||||
let warning = match external {
|
||||
0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()),
|
||||
1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()),
|
||||
_ => EngineError::Other("The paths overlap, so they have no internal tangents".into()),
|
||||
};
|
||||
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
|
||||
}
|
||||
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center()));
|
||||
let fill = Paint::None;
|
||||
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
|
||||
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
|
||||
// The new art's look may carry more fills than the top one: none of them is kept.
|
||||
look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
|
||||
let top = *second;
|
||||
let (ids, center_id) = s.edit(LABEL, |d, sel| {
|
||||
let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
|
||||
let mut ids = vec![];
|
||||
let mut center_id = None;
|
||||
for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() {
|
||||
let id = d.alloc_id();
|
||||
let path = PathData::single(SubPath::polyline(&[from, to], false));
|
||||
let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false });
|
||||
look.apply(d, &mut n);
|
||||
d.insert(parent, idx + 1 + k, n)?;
|
||||
if k == lines.len() {
|
||||
center_id = Some(id);
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok((ids, center_id))
|
||||
})?;
|
||||
Ok(json!({
|
||||
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"external": external_kept,
|
||||
"internal": internal_kept,
|
||||
"centerline": center_id.map(|i| i.0),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline,
|
||||
//! the paint, one undo step, the cases with no tangent, and refused selections and params.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Vec2};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = super::COMMON_TANGENTS;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The ends of each new line, as `ids` lists them.
|
||||
fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
r["ids"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let n = d.node(NodeId(v.as_u64().unwrap())).unwrap();
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") };
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
let sp = &path.subpaths[0];
|
||||
assert!(!sp.closed);
|
||||
assert_eq!(sp.anchors.len(), 2);
|
||||
(sp.anchors[0].p, sp.anchors[1].p)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn near(p: Point, q: Point) -> bool {
|
||||
p.distance(q) < 1e-6
|
||||
}
|
||||
|
||||
fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool {
|
||||
found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 200.0, 20.0);
|
||||
let b = circle(&mut s, 300.0, 200.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 4);
|
||||
let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
|
||||
// External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3.
|
||||
for (nx, external) in [(-0.1f64, true), (0.3, false)] {
|
||||
for sy in [1.0, -1.0] {
|
||||
let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt());
|
||||
let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 };
|
||||
assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}");
|
||||
}
|
||||
}
|
||||
// The lines are the selection, above the two circles.
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), 4);
|
||||
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
|
||||
let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied()));
|
||||
assert_eq!(&order[..2], &[a, b]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_ellipses_are_measured_exactly() {
|
||||
let mut s = session();
|
||||
let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap();
|
||||
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap());
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
let r = s.execute(C, &json!({"tangents": "all"})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
|
||||
// Each end lies on its ellipse, where the ellipse runs along the line: turned back about the
|
||||
// center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line.
|
||||
let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| {
|
||||
let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians());
|
||||
// `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms.
|
||||
let page = |v: Vec2| Vec2::new(v.x, -v.y);
|
||||
let q = page((turn * page(p - center).to_point()).to_vec2());
|
||||
let d = page((turn * page(dir).to_point()).to_vec2());
|
||||
let value = (q.x / rx).powi(2) + (q.y / ry).powi(2);
|
||||
let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry));
|
||||
(value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7
|
||||
};
|
||||
for (p, q) in lines(&s, &r) {
|
||||
let dir = q - p;
|
||||
assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse");
|
||||
assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_convex_bezier_path_and_the_centerline() {
|
||||
let mut s = session();
|
||||
let anchors = json!([
|
||||
{"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]},
|
||||
{"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]},
|
||||
{"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]},
|
||||
{"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]}
|
||||
]);
|
||||
let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap());
|
||||
let round = circle(&mut s, 300.0, 200.0, 30.0);
|
||||
let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 5, "four tangents and the centerline");
|
||||
// The centerline is the last line and its id is given: from the blob's center of area to the
|
||||
// circle's center.
|
||||
assert_eq!(r["centerline"], r["ids"][4]);
|
||||
let (from, to) = found[4];
|
||||
assert!(near(to, Point::new(300.0, 200.0)), "{to:?}");
|
||||
assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}");
|
||||
// A tangent touches without crossing: every point of both paths is on one side of it.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let points = |id: NodeId| {
|
||||
let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
|
||||
let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect();
|
||||
segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::<Vec<_>>()
|
||||
};
|
||||
let (pa, pb) = (points(blob), points(round));
|
||||
for (p, q) in &found[..4] {
|
||||
let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize();
|
||||
for pts in [&pa, &pb] {
|
||||
let side: Vec<f64> = pts.iter().map(|x| (*x - *p).dot(n)).collect();
|
||||
let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
|
||||
// The circle is measured as an exact circle, which its four curves follow to within
|
||||
// about 0.03% of the radius.
|
||||
assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lines_take_the_current_stroke_and_no_fill() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 300.0, 100.0, 20.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for v in r["ids"].as_array().unwrap() {
|
||||
let n = d.node(NodeId(v.as_u64().unwrap())).unwrap();
|
||||
assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill");
|
||||
let st = n.appearance.stroke().expect("stroked");
|
||||
assert!(!st.paint.is_none(), "black when the stroke is None");
|
||||
}
|
||||
// A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill.
|
||||
let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0);
|
||||
let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
|
||||
look.items.push(fill);
|
||||
s.paint.appearance = Some(look);
|
||||
s.paint.inherited = false;
|
||||
let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap();
|
||||
let d2 = &s.doc().unwrap().doc;
|
||||
for v in r2["ids"].as_array().unwrap() {
|
||||
let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap();
|
||||
assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all");
|
||||
assert!(n.appearance.stroke().is_some());
|
||||
}
|
||||
// Two equal circles: the external tangents run along their tops and bottoms.
|
||||
assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0)));
|
||||
assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_and_overlapping_paths_change_nothing_and_say_why() {
|
||||
let mut s = session();
|
||||
let big = circle(&mut s, 200.0, 200.0, 100.0);
|
||||
let small = circle(&mut s, 220.0, 200.0, 20.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
// Overlapping circles have external tangents only.
|
||||
let a = circle(&mut s, 100.0, 100.0, 30.0);
|
||||
let b = circle(&mut s, 140.0, 100.0, 30.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap();
|
||||
assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before);
|
||||
let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
// Circles that touch share the tangent where they touch.
|
||||
let c = circle(&mut s, 100.0, 300.0, 10.0);
|
||||
let e = circle(&mut s, 130.0, 300.0, 20.0);
|
||||
let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap();
|
||||
assert_eq!(r["internal"].as_u64(), Some(1), "{r}");
|
||||
let (p, q) = lines(&s, &r)[0];
|
||||
assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}");
|
||||
// A circle touching the inside of a larger one: no internal tangent, and the message says the
|
||||
// one lies inside the other rather than that they overlap.
|
||||
let outer = circle(&mut s, 400.0, 200.0, 50.0);
|
||||
let inner = circle(&mut s, 430.0, 200.0, 20.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before);
|
||||
let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_selections_and_params_are_refused() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 300.0, 100.0, 20.0);
|
||||
let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap());
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
|
||||
let group_of = |s: &mut Session, ids: &[NodeId]| {
|
||||
select(s, ids);
|
||||
id_of(&s.execute("object.group", &json!({})).unwrap())
|
||||
};
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused");
|
||||
assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open"));
|
||||
assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap());
|
||||
assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline"));
|
||||
let g = group_of(&mut s, &[b]);
|
||||
assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths"));
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::collections::HashSet;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
|
||||
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Object",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}",
|
||||
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object in ids without such an effect is refused. Without ids, the selected objects without one (on a group or layer, one on its fill or stroke draws nothing and does not count), and a selected object inside another selected object that has one, are left out; refused when none is left → {assets: [asset id…] (in order), added: n}",
|
||||
has_doc,
|
||||
add_3d
|
||||
),
|
||||
@@ -203,10 +203,36 @@ fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The selected objects `assets.add3D` collects without `ids`: those with a 3D effect it exports
|
||||
/// ([`vectorcraft_render::effects::exports_three_d`]; a path of a compound path counts as the
|
||||
/// compound path), layers included, in tree order, dropping
|
||||
/// each one inside another of them (that one's asset holds it). Refused while an object of a
|
||||
/// dynamic symbol instance's art is selected, as [`selected_roots`] is.
|
||||
fn selected_3d_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
// A path of a compound path stands for the compound path, which holds the paint and effects.
|
||||
let found = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.map(|id| super::path::compound_or_self(&st.doc, *id))
|
||||
.filter(|id| st.doc.node(*id).is_some_and(vectorcraft_render::effects::exports_three_d));
|
||||
let mut paths: Vec<(Vec<usize>, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect();
|
||||
paths.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let mut kept: Vec<(Vec<usize>, NodeId)> = Vec::with_capacity(paths.len());
|
||||
for (path, id) in paths {
|
||||
if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) {
|
||||
kept.push((path, id));
|
||||
}
|
||||
}
|
||||
Ok(kept.into_iter().map(|(_, id)| id).collect())
|
||||
}
|
||||
|
||||
fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.add3D";
|
||||
let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?;
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? };
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_3d_roots(s)? };
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select an object with a 3D effect (or give its ids)"));
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -173,7 +173,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clipboard Formats",
|
||||
[],
|
||||
None,
|
||||
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut",
|
||||
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); under read roots, SVG and its markup as text are left out when clipboard.exportSvg would refuse; the app publishes them on Copy and Cut",
|
||||
always,
|
||||
flavours
|
||||
),
|
||||
@@ -369,13 +369,20 @@ impl Session {
|
||||
|
||||
/// The MIME types of [`Self::clipboard_flavours`], without making them.
|
||||
pub fn clipboard_flavour_types(&self) -> Vec<&'static str> {
|
||||
self.clipboard.flavour_types(self.prefs.copy_as_svg, self.prefs.copy_as_pdf)
|
||||
self.clipboard.flavour_types(self.clipboard_svg_offered(), self.prefs.copy_as_pdf)
|
||||
}
|
||||
|
||||
/// What Copy offers other apps, best first (see `clipboard.flavours`): [`Clipboard::flavours`]
|
||||
/// by the Clipboard Handling preferences.
|
||||
/// by the Clipboard Handling preferences, without the SVG (and the SVG markup as text) that
|
||||
/// [`Self::clipboard_svg_refused`] withholds from the caller asking now.
|
||||
pub fn clipboard_flavours(&self) -> Vec<Flavour> {
|
||||
self.clipboard.flavours(self.prefs.copy_as_svg, self.prefs.copy_as_pdf)
|
||||
self.clipboard.flavours(self.clipboard_svg_offered(), self.prefs.copy_as_pdf)
|
||||
}
|
||||
|
||||
/// Does Copy offer the SVG: Include SVG Code is on and the SVG is not withheld from the caller
|
||||
/// asking now.
|
||||
fn clipboard_svg_offered(&self) -> bool {
|
||||
self.prefs.copy_as_svg && !self.clipboard_svg_refused()
|
||||
}
|
||||
|
||||
/// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first
|
||||
|
||||
@@ -703,7 +703,7 @@ impl Relink {
|
||||
self.name(Res::ParaStyle, s);
|
||||
}
|
||||
}
|
||||
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten() {
|
||||
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() {
|
||||
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Path",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}",
|
||||
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
|
||||
has_doc,
|
||||
split
|
||||
),
|
||||
@@ -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, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths 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,
|
||||
@@ -196,6 +196,9 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) {
|
||||
return Err(bad(C, "invalid t"));
|
||||
}
|
||||
if !(0.0..=1.0).contains(&t) {
|
||||
return Err(bad(C, "`t` must be from 0 to 1"));
|
||||
}
|
||||
let ids = s.edit("Split Path", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
@@ -293,12 +296,15 @@ 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)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
}
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !(1.0..=100.0).contains(&roundness) {
|
||||
return Err(bad(C, "`roundness` must be from 1 to 100%"));
|
||||
}
|
||||
let vary = eraser_variations(p, C)?;
|
||||
if varies_beyond_size_pressure(&vary) {
|
||||
return erase_varied(s, &samples, [angle, roundness, size], vary);
|
||||
@@ -308,7 +314,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0));
|
||||
let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0;
|
||||
let short = narrowest * roundness / 100.0;
|
||||
let st = s.doc()?;
|
||||
// A point is under the tip when, with the tip squashed back into a circle, it is within the
|
||||
// circle's radius of the squashed drag.
|
||||
@@ -401,12 +407,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 +426,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() {
|
||||
|
||||
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool {
|
||||
|
||||
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at
|
||||
/// the document's raster effects resolution or a Rasterize effect's finer one, with whether they
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them). A group's or
|
||||
/// layer's image leaves out its members' raster effects, which are expanded with them. `None`
|
||||
/// when it has none.
|
||||
fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them, and paints with
|
||||
/// their blend mode when they all use one). A group's or layer's image leaves out its members'
|
||||
/// raster effects, which are expanded with them. `None` when it has none.
|
||||
/// `Err` when that image would take `budget` past its limits: the object then stays as it is.
|
||||
fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result<Option<(Node, bool)>, OverBudget> {
|
||||
let fx = rasterfx::raster_fx(n);
|
||||
if fx.is_empty() {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
let below = fx.iter().all(effects::RasterFx::is_below);
|
||||
Some((rasterfx::raster_image(d, n, below, true)?, below))
|
||||
let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?;
|
||||
let mut image = rasterfx::raster_image(d, n, below, true);
|
||||
if image.is_none() {
|
||||
// No image was made: it takes nothing from the budget.
|
||||
budget.images += 1;
|
||||
budget.pixels += pixels;
|
||||
}
|
||||
// Rendered alone, over nothing, the shadows and glows can't blend with the art below the
|
||||
// object, so the image does, as the canvas draws them.
|
||||
let mut modes = fx.iter().filter_map(effects::RasterFx::mode);
|
||||
if below
|
||||
&& let (Some(mode), Some(image)) = (modes.next(), image.as_mut())
|
||||
&& modes.all(|m| m == mode)
|
||||
{
|
||||
image.blend = mode;
|
||||
}
|
||||
Ok(image.map(|image| (image, below)))
|
||||
}
|
||||
|
||||
/// The most images of raster effects one Expand Appearance makes.
|
||||
const MAX_RASTER_IMAGES: u32 = 1_024;
|
||||
|
||||
/// The most pixels the images of raster effects one Expand Appearance makes hold in all.
|
||||
const MAX_RASTER_PIXELS: u64 = 256_000_000;
|
||||
|
||||
/// The note when objects keep their raster effects because their images would take an Expand
|
||||
/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`].
|
||||
pub(crate) const RASTER_EFFECTS_LEFT: &str =
|
||||
"some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all";
|
||||
|
||||
/// An image of raster effects that would take a [`RasterBudget`] past its limits.
|
||||
#[derive(Debug)]
|
||||
struct OverBudget;
|
||||
|
||||
/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the
|
||||
/// objects whose raster effects it left as they are because their images would go past them.
|
||||
pub(crate) struct RasterBudget {
|
||||
images: u32,
|
||||
pixels: u64,
|
||||
pub(crate) left: usize,
|
||||
}
|
||||
|
||||
impl RasterBudget {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 }
|
||||
}
|
||||
|
||||
/// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return
|
||||
/// them; `Err`, with its object counted in `left`, when it would go past what is left.
|
||||
fn take(&mut self, pixels: u64) -> std::result::Result<u64, OverBudget> {
|
||||
if self.images == 0 || pixels > self.pixels {
|
||||
self.left += 1;
|
||||
return Err(OverBudget);
|
||||
}
|
||||
self.images -= 1;
|
||||
self.pixels -= pixels;
|
||||
Ok(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
|
||||
@@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
m: &mut Node,
|
||||
@@ -991,6 +1050,7 @@ fn expand_pieces(
|
||||
skip: &[NodeId],
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
@@ -1005,7 +1065,7 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip));
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1029,38 +1089,87 @@ fn expand_pieces(
|
||||
expanded
|
||||
}
|
||||
|
||||
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
|
||||
/// shadow blurred by the light's Softness) expanded as Expand Appearance expands it on its own:
|
||||
/// a blurred shadow becomes an image. Groups in `m` without effects that hold such an object are
|
||||
/// looked into; the rest are left as they are. The objects `skip` lists are not expanded.
|
||||
fn expand_raster_pieces(d: &mut Document, mut m: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Node {
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
if !c.appearance.effects.is_empty() {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, &mut vec![], raster) {
|
||||
*c = Arc::new(e);
|
||||
}
|
||||
} else if c.children().is_some() {
|
||||
let mut holds = false;
|
||||
c.walk(&mut |n| holds |= !n.appearance.effects.is_empty());
|
||||
if holds {
|
||||
*c = Arc::new(expand_raster_pieces(d, (**c).clone(), brushes, skip, raster));
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
|
||||
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
|
||||
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
|
||||
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
|
||||
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
|
||||
/// would take the objects placed so far past `budget`.
|
||||
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
|
||||
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
|
||||
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
|
||||
/// that art in turn, so [`expand_pieces`] bakes their effects with the rest.
|
||||
fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) {
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
|
||||
if c.children().is_some() {
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
continue;
|
||||
}
|
||||
*budget -= count;
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget);
|
||||
if let Some(a) = expanded_instance(d, c, depth, budget, raster) {
|
||||
*c = Arc::new(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster
|
||||
/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art
|
||||
/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as
|
||||
/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when
|
||||
/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance
|
||||
/// staying as it is, when its active fill and stroke have no such effect, it is more than
|
||||
/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would
|
||||
/// take the objects placed so far past `budget`, or the image of its raster effects would take
|
||||
/// `raster` past its limits. When that image can't be made, they stay on the art its geometry
|
||||
/// effects make, and without one it stays as it is.
|
||||
fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None };
|
||||
let has_raster = effects::has_instance_row_raster(c);
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) {
|
||||
return None;
|
||||
}
|
||||
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
return None;
|
||||
}
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
let image = if has_raster { raster_image(d, c, raster).ok()? } else { None };
|
||||
*budget -= count;
|
||||
let mut v = c.clone();
|
||||
if image.is_some() {
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
}
|
||||
let below = match image {
|
||||
Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)),
|
||||
Some((image, true)) => Some(image),
|
||||
None => None,
|
||||
};
|
||||
let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art))
|
||||
.or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?;
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget, raster);
|
||||
if let Some(image) = below {
|
||||
rasterfx::put_below(d, &mut a, image);
|
||||
}
|
||||
Some(a)
|
||||
}
|
||||
|
||||
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
|
||||
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
@@ -1075,9 +1184,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
type Listed = (NodeId, usize);
|
||||
|
||||
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec<Listed> {
|
||||
let mut listed = vec![];
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) {
|
||||
*c = e;
|
||||
}
|
||||
listed
|
||||
@@ -1099,18 +1208,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
|
||||
/// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and
|
||||
/// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art),
|
||||
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
|
||||
/// transparency.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
|
||||
expand_node_except(d, id, brushes, &[], out);
|
||||
/// transparency. An object whose raster effects' image would take `raster` past its limits stays
|
||||
/// as it is, with what is inside it.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>, raster: &mut RasterBudget) {
|
||||
expand_node_except(d, id, brushes, &[], out, raster);
|
||||
}
|
||||
|
||||
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
|
||||
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
|
||||
/// copies of it that such an effect makes are left as they are too.
|
||||
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
|
||||
fn expand_node_except(
|
||||
d: &mut Document,
|
||||
id: NodeId,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<NodeId>,
|
||||
raster: &mut RasterBudget,
|
||||
) {
|
||||
let Some(n) = d.node(id).cloned() else { return };
|
||||
let mut listed = vec![];
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed);
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed, raster);
|
||||
out.extend(listed.into_iter().map(|(id, _)| id));
|
||||
if let Some(mut m) = m {
|
||||
// Art made from type takes its emoji's pixels into the document.
|
||||
@@ -1124,11 +1241,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
fn expanded_node(
|
||||
d: &mut Document,
|
||||
mut n: Node,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<Listed>,
|
||||
raster: &mut RasterBudget,
|
||||
) -> Option<Node> {
|
||||
let id = n.id;
|
||||
if skip.contains(&id) || !expandable(&n) {
|
||||
return None;
|
||||
}
|
||||
// What `out` held before `n`: an object left by the raster budget lists nothing.
|
||||
let listed_before = out.len();
|
||||
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
|
||||
// recoloured copy), then the rest of the appearance expands.
|
||||
let mut changed = false;
|
||||
@@ -1141,6 +1267,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
|
||||
// is: the recolored copies the adjustment adds then go again.
|
||||
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1163,7 +1293,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
expanded = expand_in_place(d, c, brushes, skip);
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1186,7 +1316,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let image = raster_image(d, &n);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
|
||||
let Ok(image) = raster_image(d, &n, raster) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
let mut stroke_art =
|
||||
@@ -1206,7 +1344,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
@@ -1224,13 +1362,21 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
// A symbol instance whose active fill or stroke has only effects that paint below it
|
||||
// (now in the image) becomes its art as well.
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
};
|
||||
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
|
||||
// expands in turn, to an image.
|
||||
let m = if effects::has_solid(&v) || effects::has_revolve(&v) { m.map(|m| expand_raster_pieces(d, m, brushes, skip, raster)) } else { m };
|
||||
match image {
|
||||
Some((image, _)) => {
|
||||
let mut m = m.unwrap_or(v);
|
||||
@@ -1262,7 +1408,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
None => {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) {
|
||||
*c = Arc::new(e);
|
||||
changed = true;
|
||||
}
|
||||
@@ -1336,6 +1482,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let mut raster = RasterBudget::new();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
let before = d.clone();
|
||||
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
|
||||
@@ -1351,7 +1498,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out);
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster);
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
@@ -1360,6 +1507,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// stays type under a new id takes its frame's place.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
if out.is_empty() || (kept && d.layers == before.layers) {
|
||||
if raster.left > 0 {
|
||||
return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into()));
|
||||
}
|
||||
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
|
||||
}
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
|
||||
@@ -1367,8 +1517,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
let mut out = json!({ "ids": ids_json(&ids) });
|
||||
// Raster effects become images rendered from the art.
|
||||
if let Some(w) = rasterfx::undecoded_warning(failed) {
|
||||
out["warning"] = json!(w);
|
||||
let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
if raster.left > 0 {
|
||||
out["rasterLeft"] = json!(raster.left);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1017,6 +1017,49 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
|
||||
assert_eq!(shadows, 1);
|
||||
}
|
||||
|
||||
/// With the light's Softness, the 3D shadow is blurred: the canvas paints past the hard shadow's
|
||||
/// edge, the object's bounds take the blur in, SVG export blurs it as it does a Gaussian Blur
|
||||
/// effect, and Expand Appearance keeps it as an image with no live effect left.
|
||||
#[test]
|
||||
fn a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap();
|
||||
let set = |s: &mut Session, params: serde_json::Value| {
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap();
|
||||
};
|
||||
let draw = |s: &Session| {
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let bounds = |s: &Session| {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
vectorcraft_render::effect_bounds(&doc.symbol_boxes(), doc.node(id).unwrap()).unwrap()
|
||||
};
|
||||
let blurs = |s: &mut Session| {
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
svg.matches("<feGaussianBlur").count()
|
||||
};
|
||||
let none = draw(&s);
|
||||
set(&mut s, json!({"shadow": true, "shadowDistance": 50}));
|
||||
let (hard, hard_bounds, hard_blurs) = (draw(&s), bounds(&s), blurs(&mut s));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
set(&mut s, json!({"lightSoftness": 100}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
let (soft, soft_bounds) = (draw(&s), bounds(&s));
|
||||
// Pixels the hard shadow leaves as they are, the soft one paints.
|
||||
let spread = none.chunks(4).zip(hard.chunks(4)).zip(soft.chunks(4)).filter(|((n, h), s)| n == h && n != s).count();
|
||||
assert!(spread > 100, "{spread}");
|
||||
assert!(soft_bounds.contains_rect(hard_bounds) && soft_bounds.area() > hard_bounds.area(), "{hard_bounds:?} {soft_bounds:?}");
|
||||
assert_eq!(blurs(&mut s), hard_blurs + 1, "SVG export blurs the shadow as a Gaussian Blur effect");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
let (mut live, mut pictures) = (0, 0);
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
live += usize::from(!n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()));
|
||||
pictures += usize::from(matches!(n.kind, NodeKind::Image(_)));
|
||||
});
|
||||
assert_eq!((live, pictures), (0, 1), "the blurred shadow expands to an image");
|
||||
}
|
||||
|
||||
/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
|
||||
/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
|
||||
#[test]
|
||||
@@ -1082,3 +1125,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
|
||||
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
|
||||
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
|
||||
}
|
||||
|
||||
/// The raster budget charges each image its pixels before it is made: an image past what is left
|
||||
/// is refused and counted, and the object keeps its blur.
|
||||
#[test]
|
||||
fn an_image_past_the_pixels_left_stays_unmade() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap();
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let n = d.node(id).cloned().unwrap();
|
||||
let pixels = super::rasterfx::raster_pixels(&d, &n, false, true);
|
||||
assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err());
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels, left: 0 };
|
||||
let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made");
|
||||
let NodeKind::Image(img) = &image.kind else { panic!("not an image") };
|
||||
assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size");
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0));
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
|
||||
}
|
||||
|
||||
@@ -129,9 +129,9 @@ mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
pub(crate) use access::check_images_in;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{check_images_in, check_scripts_of};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
|
||||
@@ -121,22 +121,54 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
|
||||
/// The error for a file that would name a JavaScript file the document links outside the read roots.
|
||||
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
|
||||
/// and those too unless read roots are in force and the document links a JavaScript file outside
|
||||
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
|
||||
/// which the file's `<script>` element would name. The error names no file or folder.
|
||||
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
/// `cmd` may write `st`'s document in format `format` (a format id) with options `p` (presets
|
||||
/// written out): always, unless read roots are in force, the document links a JavaScript file
|
||||
/// outside them (`svg_scripts`, a relative path taken from the document's folder; a URL is not
|
||||
/// checked) and the file names it ([`names_linked_scripts`], with the artboards `p` picks counted
|
||||
/// in `st`'s document): an SVG's `<script>` element, or the native document that a native file, a
|
||||
/// `.ai` file, an EPS file or a PDF with Preserve Editing carries. The error names no file or folder.
|
||||
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState, p: &Value) -> Result<()> {
|
||||
check_scripts_of(cmd, &st.doc, st.path.as_deref(), || names_linked_scripts(cmd, format, p, st.doc.artboards.len()))
|
||||
}
|
||||
|
||||
/// `doc`, saved at `doc_path`, may be written by `cmd` in a file that names its linked JavaScript
|
||||
/// files when `names` says so: as [`check_linked_scripts`] allows it.
|
||||
pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_path: Option<&str>, names: impl FnOnce() -> bool) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) || !names() {
|
||||
return Ok(());
|
||||
}
|
||||
let doc_path = st.path.as_deref();
|
||||
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
|
||||
return Err(bad(cmd, SCRIPT_OUTSIDE));
|
||||
Err(bad(cmd, SCRIPT_OUTSIDE))
|
||||
}
|
||||
|
||||
/// Does a file of a document with `artboards` artboards, written in format `format` with options
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
|
||||
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
|
||||
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
|
||||
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
|
||||
/// refuses count as naming them.
|
||||
pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards: usize) -> bool {
|
||||
use serde::Deserialize;
|
||||
let every_artboard = || {
|
||||
let pick = if p.is_object() { super::ArtboardPick::deserialize(p).ok() } else { Some(super::ArtboardPick::default()) };
|
||||
pick.and_then(|pick| pick.resolve(artboards).ok()).is_none_or(|v| v.is_none_or(|v| v.iter().copied().eq(0..artboards)))
|
||||
};
|
||||
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
|
||||
match format {
|
||||
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
|
||||
"ai" | "ait" => {
|
||||
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
|
||||
!legacy && !(format == "ai" && art_page()) && every_artboard()
|
||||
}
|
||||
"pdf" => {
|
||||
let editing = super::pdf::settings(cmd, p).ok().is_none_or(|s| s.preserve_editing);
|
||||
editing && !art_page() && every_artboard()
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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(()),
|
||||
|
||||
@@ -53,10 +53,10 @@ pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool {
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes("document.serialize", f, p);
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
check_linked_scripts("document.serialize", f.id, s.doc()?, &p)?;
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
let doc = &*doc;
|
||||
let mut q = p.clone();
|
||||
@@ -97,10 +97,10 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
check_linked_scripts("document.export", f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes("document.export", f, p);
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
check_linked_scripts("document.export", f.id, s.doc()?, &p)?;
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
let doc = &*doc;
|
||||
let mut q = p.clone();
|
||||
@@ -375,10 +375,11 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
check_linked_scripts(C, f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes(C, f, p);
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
// The selection is written on one artboard of its own: every artboard, whatever `p` picks.
|
||||
check_linked_scripts(C, f.id, s.doc()?, &without_artboards(&p))?;
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The selected objects' links are looked for from the document they are in.
|
||||
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
|
||||
|
||||
@@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption {
|
||||
name: "layers",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent",
|
||||
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way",
|
||||
};
|
||||
|
||||
const MAX_EDITABILITY: FormatOption = FormatOption {
|
||||
@@ -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,
|
||||
|
||||
@@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
let one = super::save::artboard_doc(doc, b);
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(&one);
|
||||
let mut d = full.into_owned();
|
||||
expand_appearances(&mut d);
|
||||
if expand_appearances(&mut d) {
|
||||
note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT);
|
||||
}
|
||||
if mode == SeeThrough::Flatten {
|
||||
expand_image_patterns(&mut d)?;
|
||||
}
|
||||
@@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold.
|
||||
fn expand_appearances(d: &mut Document) {
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether
|
||||
/// objects kept raster effects whose images would go past Expand Appearance's limits.
|
||||
fn expand_appearances(d: &mut Document) -> bool {
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
|
||||
let mut out = vec![];
|
||||
let mut raster = super::super::effectcmd::RasterBudget::new();
|
||||
for id in layers {
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out);
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster);
|
||||
}
|
||||
raster.left > 0
|
||||
}
|
||||
|
||||
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -889,7 +889,6 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
|
||||
|
||||
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
@@ -934,6 +933,14 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
o.insert("range".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
// A saved `.ai` or `.ait` file has the artboards as its pages, whatever `useArtboards` says.
|
||||
let checked = match (¶ms, plan.format.id) {
|
||||
(Value::Object(o), "ai" | "ait") => {
|
||||
std::borrow::Cow::Owned(Value::Object(o.iter().filter(|(k, _)| *k != "useArtboards").map(|(k, v)| (k.clone(), v.clone())).collect()))
|
||||
}
|
||||
_ => std::borrow::Cow::Borrowed(¶ms),
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
}
|
||||
|
||||
@@ -1318,7 +1325,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
@@ -1345,7 +1352,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save as Template…",
|
||||
["File"],
|
||||
None,
|
||||
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
|
||||
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}. Under automation read roots, it is refused, before any file is written, while the document links a JavaScript file outside them, as document.save refuses it",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Template, p)
|
||||
),
|
||||
|
||||
@@ -764,7 +764,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) {
|
||||
|
||||
/// Export settings kept in the document or a preset, as the request being served may see them: a
|
||||
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
|
||||
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
@@ -1089,6 +1089,29 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does the file of `item` that row `r` writes carry the native document, and with it the
|
||||
/// JavaScript files the document links ([`super::access::names_linked_scripts`])? A PDF holds the
|
||||
/// artboards it is written with: those of `single` (Export PDFs As › Single file), every artboard
|
||||
/// (Full Document), else the item's artboard of its document.
|
||||
fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
|
||||
if r.format.id != "pdf" {
|
||||
return super::access::names_linked_scripts(C, r.format.id, &r.options, item.doc.artboards.len());
|
||||
}
|
||||
let (doc, options) = match (single, &item.every_artboard) {
|
||||
(Some(boards), _) => {
|
||||
let mut options = r.options.clone();
|
||||
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
|
||||
(&item.doc, options)
|
||||
}
|
||||
(None, Some(all)) => (all, r.options.clone()),
|
||||
(None, None) => match r.options_for(item.region, item.artboard) {
|
||||
Ok(options) => (&item.doc, options),
|
||||
Err(_) => return true,
|
||||
},
|
||||
};
|
||||
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
|
||||
}
|
||||
|
||||
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
@@ -1105,10 +1128,6 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
o.one_source()?;
|
||||
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
|
||||
let st = s.doc()?;
|
||||
// Before the folder is made or any row is written.
|
||||
for r in &rows {
|
||||
super::check_linked_scripts(C, r.format.id, st)?;
|
||||
}
|
||||
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
|
||||
let selection = o.selection_mode()?;
|
||||
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
|
||||
@@ -1125,6 +1144,10 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// Before the folder is made or any row is written, with the artboards each file holds.
|
||||
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
|
||||
let st = s.doc()?;
|
||||
super::check_scripts_of(C, &st.doc, st.path.as_deref(), || rows.iter().any(|r| items.iter().any(|i| names_scripts(i, r, single.as_deref()))))?;
|
||||
// The file each item writes for each SVG row, before the folder is made or any row is written.
|
||||
let base = crate::cmd::links::LinkBase::of(s.doc()?);
|
||||
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
|
||||
|
||||
@@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
|
||||
})
|
||||
}
|
||||
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
vectorcraft_format::save(&kept, false)
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
/// link to and the writer's warnings.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
|
||||
let (opts, boards, chosen) = plan(doc, p)?;
|
||||
// Preserve editing embeds the native document (once, shared by every file).
|
||||
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
|
||||
let native = opts.preserve_editing.then(|| native_attachment(doc));
|
||||
// Draw linked files as vectors when available, or their previews with a warning. Keep
|
||||
// that preparation out of the native attachment so missing links remain relinkable.
|
||||
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -501,8 +501,85 @@ fn damaged_slices_never_panic() {
|
||||
let mut f = base.clone();
|
||||
f[at] = v;
|
||||
let mut s = Session::new();
|
||||
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
|
||||
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
|
||||
// The engine's guard reports a panic as an internal error.
|
||||
for r in [
|
||||
s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})),
|
||||
s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})),
|
||||
] {
|
||||
assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "byte {at} set to {v}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The PSD file `document.export` writes from `s`, with its layers or flat.
|
||||
fn export(s: &mut Session, layers: bool) -> Vec<u8> {
|
||||
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_files_slices_survive_a_psd_export() {
|
||||
let link =
|
||||
S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) };
|
||||
let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) };
|
||||
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) };
|
||||
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
|
||||
let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[]));
|
||||
let (mut s, _) = open(&f, json!({}));
|
||||
let opened = slices(&s);
|
||||
assert_eq!(opened.len(), 3);
|
||||
for layers in [true, false] {
|
||||
let out = export(&mut s, layers);
|
||||
let (again, r) = open(&out, json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
// The same rectangles and options; the auto slices are laid out again around them.
|
||||
let mut got = slices(&again);
|
||||
let mut want = opened.clone();
|
||||
let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0)));
|
||||
order(&mut got);
|
||||
order(&mut want);
|
||||
assert_eq!(got, want);
|
||||
let layout = again.doc().unwrap().doc.slice_layout();
|
||||
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
|
||||
assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
let rect = r["id"].as_u64().unwrap();
|
||||
s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "<i>x</i>", "background": "#00ff00"})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.slice.make", &json!({"ids": [t]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap();
|
||||
let (again, _) = open(&export(&mut s, false), json!({}));
|
||||
let got = slices(&again);
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap();
|
||||
let boxed = got.iter().find(|g| g.1.name == "box").unwrap();
|
||||
// Within a pixel of the object's bounds.
|
||||
for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] {
|
||||
assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0);
|
||||
}
|
||||
assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "<i>x</i>", "#00ff00"));
|
||||
let text = got.iter().find(|g| g.1.name.is_empty()).unwrap();
|
||||
assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A & B"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() {
|
||||
let columns: Vec<S> = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect();
|
||||
let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({}));
|
||||
assert_eq!(slices(&s).len(), 20);
|
||||
let (again, r) = open(&export(&mut s, true), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
assert_eq!(slices(&again), slices(&s));
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::roots_of;
|
||||
use super::menucmds::{MAX_PIXELS, isolated_doc, unique_key};
|
||||
use super::pathops::{node_path, outline_strokes, outline_strokes_under, separate, shape_node};
|
||||
use super::pathops::{leaves, node_path, outline_strokes, separate, shape_node};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, targets, unique_name};
|
||||
|
||||
mod analysis;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
@@ -14,6 +16,8 @@ pub(super) struct Plan {
|
||||
pub(super) flat: Vec<Flat>,
|
||||
/// Objects without transparency (they stay, but for the outline options).
|
||||
pub(super) kept: Vec<NodeId>,
|
||||
/// What the outline and overprint options do to each of `kept`, in its order.
|
||||
pub(super) work: Vec<Kept>,
|
||||
/// The objects with transparency of their own.
|
||||
pub(super) transparent: Vec<NodeId>,
|
||||
}
|
||||
@@ -112,7 +116,12 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
|
||||
let reaches: Vec<Option<Rect>> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect();
|
||||
let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect();
|
||||
let cmyk = src.color_mode == ColorMode::Cmyk;
|
||||
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
|
||||
let mut out = Plan {
|
||||
flat: vec![],
|
||||
kept: vec![],
|
||||
work: vec![],
|
||||
transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect(),
|
||||
};
|
||||
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?;
|
||||
@@ -193,9 +202,101 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
|
||||
};
|
||||
out.flat.push(Flat { roots: ids, regions, area, raster, lines });
|
||||
}
|
||||
out.work = out.kept.iter().map(|id| Kept::of(src, *id, o)).collect();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What the outline and overprint options do to one object without transparency, found in one
|
||||
/// walk of it.
|
||||
pub(super) struct Kept {
|
||||
pub(super) id: NodeId,
|
||||
/// Whether the options change it.
|
||||
pub(super) changes: bool,
|
||||
/// The type the text option outlines and the stroked paths the stroke option outlines, those
|
||||
/// that show and are not pieces of a compound path: what the Flattener Preview highlights.
|
||||
pub(super) shown_text: Vec<NodeId>,
|
||||
pub(super) shown_strokes: Vec<NodeId>,
|
||||
/// In paint order: the type the text option outlines and the leaf shapes ([`leaves`]) other
|
||||
/// than type that the stroke option outlines.
|
||||
steps: Vec<Step>,
|
||||
/// The objects with overprints, each with the type or leaf shape that holds it (itself
|
||||
/// included) when a step replaces that.
|
||||
overprinted: Vec<(NodeId, Option<NodeId>)>,
|
||||
}
|
||||
|
||||
/// One object [`apply`] outlines.
|
||||
enum Step {
|
||||
/// Type; `leaf`: only groups and layers hold it, so its outlines are leaf shapes for the
|
||||
/// stroke option.
|
||||
Text { id: NodeId, leaf: bool },
|
||||
/// A leaf shape other than type.
|
||||
Leaf(NodeId),
|
||||
}
|
||||
|
||||
/// Where [`Kept::visit`] is in the object it walks.
|
||||
#[derive(Clone, Copy)]
|
||||
struct At {
|
||||
/// Neither the node nor what holds it is hidden, and it is not a piece of a compound path.
|
||||
shown: bool,
|
||||
/// Only groups and layers hold the node.
|
||||
leaf: bool,
|
||||
/// The type or leaf shape holding the node that a step replaces.
|
||||
holder: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl Kept {
|
||||
/// What the options `o` do to `root` of `d`: nothing when `d` doesn't hold it.
|
||||
fn of(d: &Document, root: NodeId, o: &FlattenOptions) -> Kept {
|
||||
let mut k = Kept { id: root, changes: false, shown_text: vec![], shown_strokes: vec![], steps: vec![], overprinted: vec![] };
|
||||
if let Some(n) = d.node(root) {
|
||||
k.visit(n, o, At { shown: true, leaf: true, holder: None });
|
||||
}
|
||||
k
|
||||
}
|
||||
|
||||
/// Note what the options `o` do to `n` and to everything under it.
|
||||
fn visit(&mut self, n: &Node, o: &FlattenOptions, at: At) {
|
||||
kept_seen(n);
|
||||
let shown = at.shown && n.visible;
|
||||
let mut holder = at.holder;
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
if o.text_to_outlines {
|
||||
self.changes = true;
|
||||
if shown {
|
||||
self.shown_text.push(n.id);
|
||||
}
|
||||
self.steps.push(Step::Text { id: n.id, leaf: at.leaf });
|
||||
holder = Some(n.id);
|
||||
}
|
||||
} else {
|
||||
if o.strokes_to_outlines && stroked(n) {
|
||||
self.changes = true;
|
||||
if shown {
|
||||
self.shown_strokes.push(n.id);
|
||||
}
|
||||
}
|
||||
if o.strokes_to_outlines && at.leaf && matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
|
||||
{
|
||||
self.steps.push(Step::Leaf(n.id));
|
||||
holder = Some(n.id);
|
||||
}
|
||||
}
|
||||
if !o.preserve_overprints && overprints(n) {
|
||||
self.changes = true;
|
||||
self.overprinted.push((n.id, holder));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
let inside = At {
|
||||
shown: shown && !matches!(n.kind, NodeKind::Compound { .. }),
|
||||
leaf: at.leaf && matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }),
|
||||
holder,
|
||||
};
|
||||
for c in children {
|
||||
self.visit(c, o, inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the
|
||||
/// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object.
|
||||
/// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is
|
||||
@@ -668,7 +769,7 @@ pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Opt
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(doc, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) {
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
@@ -753,19 +854,8 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
|
||||
d.insert(Some(layer), usize::MAX, guide)?;
|
||||
}
|
||||
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
|
||||
for mut id in plan.kept {
|
||||
if o.text_to_outlines {
|
||||
id = outline_texts_under(d, id)?;
|
||||
}
|
||||
if o.strokes_to_outlines {
|
||||
id = outline_strokes_under(d, &brushes, id)?.0;
|
||||
}
|
||||
if !o.preserve_overprints
|
||||
&& let Some(n) = d.node_mut(id)
|
||||
{
|
||||
drop_overprints(n);
|
||||
}
|
||||
ids.push(id);
|
||||
for k in plan.work {
|
||||
ids.push(outline_kept(d, &brushes, k, o)?);
|
||||
}
|
||||
ids.sort_by_key(|id| d.index_path(*id));
|
||||
sel.set(ids.iter().copied());
|
||||
@@ -838,6 +928,21 @@ fn guide_seen(n: &Node) {
|
||||
#[cfg(not(test))]
|
||||
fn guide_seen(_: &Node) {}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The nodes that [`Kept::of`] has looked at on this thread, in order.
|
||||
static KEPT_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// Note that [`Kept::of`] looked at `n`.
|
||||
#[cfg(test)]
|
||||
fn kept_seen(n: &Node) {
|
||||
KEPT_SEEN.with(|s| s.borrow_mut().push(n.id));
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn kept_seen(_: &Node) {}
|
||||
|
||||
/// An image of `r` (in a clip group when it is clipped).
|
||||
fn raster_node(d: &mut Document, r: Raster) -> Node {
|
||||
let key = unique_key(d, "flattened");
|
||||
@@ -858,38 +963,65 @@ fn raster_node(d: &mut Document, r: Raster) -> Node {
|
||||
crate::cmd::rasterfx::clip_group(d, path, FillRule::NonZero, image)
|
||||
}
|
||||
|
||||
/// Replace the type under `root` by its outlines: → the id now standing for `root`.
|
||||
fn outline_texts_under(d: &mut Document, root: NodeId) -> Result<NodeId> {
|
||||
let mut texts = vec![];
|
||||
if let Some(n) = d.node(root) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) {
|
||||
texts.push(c.clone());
|
||||
/// Do what [`Kept`] `k` found to its object of `d` (`brushes`: the document's brushes, for the
|
||||
/// stroke option): its type outlined, then the strokes of its leaf shapes, the outlines of its
|
||||
/// type included, then its overprints dropped. → the id now standing for the object.
|
||||
fn outline_kept(d: &mut Document, brushes: &[vectorcraft_brush::Brush], k: Kept, o: &FlattenOptions) -> Result<NodeId> {
|
||||
let mut root = k.id;
|
||||
let mut replaced = HashSet::new();
|
||||
let dropping = !o.preserve_overprints;
|
||||
// Each replacement loses its overprints before it goes in: no new object is looked up.
|
||||
let mut put = |d: &mut Document, old: NodeId, mut new: Node, root: &mut NodeId| -> Result<()> {
|
||||
if dropping {
|
||||
drop_overprints(&mut new);
|
||||
}
|
||||
let nid = new.id;
|
||||
*d.node_mut(old).ok_or(EngineError::NoNode(old))? = new;
|
||||
replaced.insert(old);
|
||||
if old == *root {
|
||||
*root = nid;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
// The leaf shapes of each outlined type that only groups and layers hold, by step.
|
||||
let mut outlined: Vec<Vec<Node>> = Vec::with_capacity(k.steps.len());
|
||||
for step in &k.steps {
|
||||
let mut lv = vec![];
|
||||
if let Step::Text { id, leaf } = *step
|
||||
&& let Some(out) = d.node(id).and_then(outlined_text)
|
||||
{
|
||||
let out = d.reid(&out);
|
||||
if leaf && o.strokes_to_outlines {
|
||||
leaves(&out, &mut lv);
|
||||
}
|
||||
});
|
||||
put(d, id, out, &mut root)?;
|
||||
}
|
||||
outlined.push(lv);
|
||||
}
|
||||
let mut out = root;
|
||||
for t in texts {
|
||||
let Some(o) = outlined_text(&t) else { continue };
|
||||
let o = d.reid(&o);
|
||||
let nid = o.id;
|
||||
*d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o;
|
||||
if t.id == root {
|
||||
out = nid;
|
||||
if o.strokes_to_outlines {
|
||||
for (step, lv) in k.steps.iter().zip(outlined) {
|
||||
let shapes = match *step {
|
||||
Step::Leaf(id) => d.node(id).cloned().into_iter().collect(),
|
||||
Step::Text { .. } => lv,
|
||||
};
|
||||
for l in shapes.iter().filter(|l| !matches!(l.kind, NodeKind::Text(_))) {
|
||||
if let Some(new) = outline_strokes(d, brushes, l) {
|
||||
put(d, l.id, new, &mut root)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether the outline and overprint options change `n`, an object without transparency.
|
||||
pub(super) fn kept_work(n: &Node, o: &FlattenOptions) -> bool {
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| {
|
||||
any |= (o.text_to_outlines && matches!(c.kind, NodeKind::Text(_)))
|
||||
|| (o.strokes_to_outlines && stroked(c))
|
||||
|| (!o.preserve_overprints && overprints(c));
|
||||
});
|
||||
any
|
||||
if dropping {
|
||||
for (id, holder) in k.overprinted {
|
||||
if holder.is_some_and(|h| replaced.contains(&h)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
drop_own_overprints(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
/// Whether `n` is a path with a visible stroke (outlining turns it into a fill).
|
||||
@@ -898,12 +1030,8 @@ pub(super) fn stroked(n: &Node) -> bool {
|
||||
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0))
|
||||
}
|
||||
|
||||
fn overprints(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(AppearanceItem::overprint)
|
||||
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
}
|
||||
|
||||
fn drop_overprints(n: &mut Node) {
|
||||
/// Drop the overprints of `n` itself.
|
||||
fn drop_own_overprints(n: &mut Node) {
|
||||
if overprints(n) {
|
||||
for i in &mut n.appearance.items {
|
||||
*i.overprint_mut() = false;
|
||||
@@ -914,6 +1042,16 @@ fn drop_overprints(n: &mut Node) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overprints(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(AppearanceItem::overprint)
|
||||
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
}
|
||||
|
||||
/// Drop the overprints of `n` and of everything under it.
|
||||
fn drop_overprints(n: &mut Node) {
|
||||
drop_own_overprints(n);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
drop_overprints(Arc::make_mut(c));
|
||||
@@ -994,6 +1132,208 @@ mod tests {
|
||||
assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]);
|
||||
}
|
||||
|
||||
/// The objects [`kept_session`] makes.
|
||||
struct KeptArt {
|
||||
/// Each group with its stroked rectangle (its fill overprints) and its stroked type.
|
||||
groups: Vec<(NodeId, NodeId, NodeId)>,
|
||||
/// A stroked rectangle and stroked type with an overprint, on their own.
|
||||
rect: NodeId,
|
||||
text: NodeId,
|
||||
/// A stroked compound path and its pieces.
|
||||
compound: NodeId,
|
||||
pieces: Vec<NodeId>,
|
||||
/// A group holding an unstroked rectangle and a hidden stroked rectangle.
|
||||
hidden_group: NodeId,
|
||||
hidden: NodeId,
|
||||
/// An unstroked rectangle.
|
||||
plain: NodeId,
|
||||
}
|
||||
|
||||
/// A document without transparency: `n` groups, then the other objects of [`KeptArt`].
|
||||
fn kept_session(n: usize) -> (Session, KeptArt) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let rect = |s: &mut Session, x: f64| id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
|
||||
let text = |s: &mut Session, x: f64| {
|
||||
let t = id(s.execute("text.create", &json!({"x": x, "y": 80, "text": "Hi", "size": 24})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [t.0]})).unwrap();
|
||||
t
|
||||
};
|
||||
let select = |s: &mut Session, ids: &[NodeId]| {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
};
|
||||
let overprint = |s: &mut Session, on: NodeId| {
|
||||
s.execute("attributes.set", &json!({"ids": [on.0], "overprintFill": true})).unwrap();
|
||||
};
|
||||
let unstroked = |s: &mut Session, on: NodeId| {
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": [on.0]})).unwrap();
|
||||
};
|
||||
let mut groups = vec![];
|
||||
for i in 0..n {
|
||||
let x = (i % 10) as f64 * 30.0;
|
||||
let (r, t) = (rect(&mut s, x), text(&mut s, x));
|
||||
overprint(&mut s, r);
|
||||
select(&mut s, &[r, t]);
|
||||
groups.push((id(s.execute("object.group", &json!({})).unwrap()), r, t));
|
||||
}
|
||||
let (r, t) = (rect(&mut s, 0.0), text(&mut s, 100.0));
|
||||
overprint(&mut s, t);
|
||||
let (a, b) = (rect(&mut s, 200.0), rect(&mut s, 210.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = id(s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [compound.0]})).unwrap();
|
||||
let pieces = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|c| c.id).collect();
|
||||
let (shown, hidden) = (rect(&mut s, 300.0), rect(&mut s, 310.0));
|
||||
unstroked(&mut s, shown);
|
||||
select(&mut s, &[shown, hidden]);
|
||||
let hidden_group = id(s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
let plain = rect(&mut s, 350.0);
|
||||
unstroked(&mut s, plain);
|
||||
(s, KeptArt { groups, rect: r, text: t, compound, pieces, hidden_group, hidden, plain })
|
||||
}
|
||||
|
||||
/// Every option on: type and strokes outlined, overprints dropped.
|
||||
fn outlining() -> FlattenOptions {
|
||||
FlattenOptions { text_to_outlines: true, strokes_to_outlines: true, preserve_overprints: false, ..FlattenOptions::default() }
|
||||
}
|
||||
|
||||
/// The top-level objects of `d`'s first layer, in paint order.
|
||||
fn top_level(d: &Document) -> Vec<NodeId> {
|
||||
d.layers[0].children().unwrap().iter().map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
fn sorted(mut ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
/// The nodes [`Kept::of`] looked at while `f` ran, sorted.
|
||||
fn kept_seen_by(f: impl FnOnce()) -> Vec<NodeId> {
|
||||
KEPT_SEEN.with(|v| v.borrow_mut().clear());
|
||||
f();
|
||||
sorted(KEPT_SEEN.with(|v| v.take()))
|
||||
}
|
||||
|
||||
/// The Flattener Preview, `object.flattenTransparency` and flattening a whole document each look
|
||||
/// at every node of the objects without transparency once, with type and strokes outlined and
|
||||
/// overprints dropped, an object they leave as it is included.
|
||||
#[test]
|
||||
fn kept_objects_are_looked_at_once() {
|
||||
let (mut s, _) = kept_session(100);
|
||||
let o = outlining();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let roots = top_level(&doc);
|
||||
let mut nodes = vec![];
|
||||
for r in &roots {
|
||||
doc.node(*r).unwrap().walk(&mut |c| nodes.push(c.id));
|
||||
}
|
||||
nodes.sort();
|
||||
assert_eq!(nodes.len(), 309);
|
||||
let preview = kept_seen_by(|| drop(super::super::report::report(&doc, &roots, &o).unwrap()));
|
||||
assert!(preview == nodes, "the preview looked at {} nodes of {}", preview.len(), nodes.len());
|
||||
let whole = kept_seen_by(|| drop(flatten_document(&doc, &o).unwrap().unwrap()));
|
||||
assert!(whole == nodes, "flattening the document looked at {} nodes of {}", whole.len(), nodes.len());
|
||||
let ids: Vec<u64> = roots.iter().map(|r| r.0).collect();
|
||||
let command = kept_seen_by(|| {
|
||||
s.execute(
|
||||
"object.flattenTransparency",
|
||||
&json!({"ids": ids, "textToOutlines": true, "strokesToOutlines": true, "preserveOverprints": false}),
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
assert!(command == nodes, "object.flattenTransparency looked at {} nodes of {}", command.len(), nodes.len());
|
||||
}
|
||||
|
||||
/// [`apply`]'s outlining of `kept` (objects of `d` without transparency) with `o`, done as a
|
||||
/// walk of each object for each option: → the ids standing for them, in paint order.
|
||||
fn outlined_walk_by_walk(d: &mut Document, kept: &[NodeId], o: &FlattenOptions) -> Vec<NodeId> {
|
||||
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
|
||||
let mut ids = vec![];
|
||||
for &root in kept {
|
||||
let mut id = root;
|
||||
if o.text_to_outlines {
|
||||
let mut texts = vec![];
|
||||
d.node(id).unwrap().walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) {
|
||||
texts.push(c.clone());
|
||||
}
|
||||
});
|
||||
for t in texts {
|
||||
let Some(out) = outlined_text(&t) else { continue };
|
||||
let out = d.reid(&out);
|
||||
if t.id == root {
|
||||
id = out.id;
|
||||
}
|
||||
*d.node_mut(t.id).unwrap() = out;
|
||||
}
|
||||
}
|
||||
if o.strokes_to_outlines {
|
||||
id = crate::cmd::pathops::outline_strokes_under(d, &brushes, id).unwrap().0;
|
||||
}
|
||||
if !o.preserve_overprints {
|
||||
drop_overprints(d.node_mut(id).unwrap());
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
ids.sort_by_key(|id| d.index_path(*id));
|
||||
ids
|
||||
}
|
||||
|
||||
/// With each mix of the text, stroke and overprint options, the objects without transparency
|
||||
/// end as a walk of each of them for each option leaves them: the same art, ids and selection.
|
||||
#[test]
|
||||
fn kept_objects_change_as_a_walk_per_option_changes_them() {
|
||||
let (s, _) = kept_session(3);
|
||||
let doc = Document::clone(&s.doc().unwrap().doc);
|
||||
let roots = top_level(&doc);
|
||||
for bits in 0..8u8 {
|
||||
let o = FlattenOptions {
|
||||
text_to_outlines: bits & 1 != 0,
|
||||
strokes_to_outlines: bits & 2 != 0,
|
||||
preserve_overprints: bits & 4 != 0,
|
||||
..FlattenOptions::default()
|
||||
};
|
||||
let p = plan(&doc, &roots, &o, true).unwrap();
|
||||
assert!(p.flat.is_empty(), "{o:?}");
|
||||
// In the order the plan's groups come in.
|
||||
let kept = p.kept.clone();
|
||||
assert_eq!(sorted(kept.clone()), sorted(roots.clone()), "{o:?}");
|
||||
let mut once = doc.clone();
|
||||
let mut sel = vectorcraft_doc::Selection::default();
|
||||
let (ids, ..) = apply(&mut once, &mut sel, p, &o).unwrap();
|
||||
let mut walked = doc.clone();
|
||||
let want = outlined_walk_by_walk(&mut walked, &kept, &o);
|
||||
assert_eq!(ids, want, "{o:?}");
|
||||
assert!(once == walked, "{o:?}");
|
||||
assert_eq!(once == doc, bits == 4, "{o:?}: only with every option off does nothing change");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Flattener Preview lists the kept objects the options change, and of those the type and
|
||||
/// the stroked paths that show and are not pieces of a compound path.
|
||||
#[test]
|
||||
fn the_preview_lists_what_the_options_change_in_kept_objects() {
|
||||
let (s, a) = kept_session(2);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let roots = top_level(doc);
|
||||
let r = super::super::report::report(doc, &roots, &outlining()).unwrap();
|
||||
let (g, rects, texts): (Vec<_>, Vec<_>, Vec<_>) =
|
||||
(a.groups.iter().map(|g| g.0).collect(), a.groups.iter().map(|g| g.1).collect(), a.groups.iter().map(|g| g.2).collect());
|
||||
assert_eq!(r.affected, [g.clone(), vec![a.rect, a.text, a.compound, a.hidden_group]].concat());
|
||||
// Both lists come in the order the plan's groups do.
|
||||
assert_eq!(sorted(r.text.clone()), sorted([texts, vec![a.text]].concat()));
|
||||
assert_eq!(sorted(r.strokes.clone()), sorted([rects, vec![a.rect, a.compound]].concat()));
|
||||
assert!(!r.strokes.contains(&a.hidden) && !r.strokes.iter().any(|id| a.pieces.contains(id)) && !r.affected.contains(&a.plain));
|
||||
// Dropping overprints alone changes the objects that overprint.
|
||||
let o = FlattenOptions { preserve_overprints: false, ..FlattenOptions::default() };
|
||||
let r = super::super::report::report(doc, &roots, &o).unwrap();
|
||||
assert_eq!((r.affected, r.text, r.strokes), ([g, vec![a.text]].concat(), vec![], vec![]));
|
||||
// With every option off, nothing.
|
||||
assert!(super::super::report::report(doc, &roots, &FlattenOptions::default()).unwrap().affected.is_empty());
|
||||
}
|
||||
|
||||
/// In a file without transparency with Clip Complex Regions on, art under a group's opaque
|
||||
/// image within one of its pixels joins the group, also where a long image is made at a lower
|
||||
/// resolution and its pixels are wider than at the preset's.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::analysis::draws_image;
|
||||
use super::apply::{apply, kept_work, plan};
|
||||
use super::apply::{apply, plan};
|
||||
use super::presets::{FlattenerPreset, saved_preset};
|
||||
use super::report::target_roots;
|
||||
use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param};
|
||||
@@ -194,7 +194,7 @@ pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plan = plan(&src, &roots, &o, true)?;
|
||||
let warning = crate::cmd::rasterfx::undecoded_warning(failed);
|
||||
let options = serde_json::to_value(&o).unwrap_or_default();
|
||||
if plan.flat.is_empty() && !plan.kept.iter().any(|id| src.node(*id).is_some_and(|n| kept_work(n, &o))) {
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
return Ok(json!({ "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>(), "rasterized": 0, "vector": 0, "options": options }));
|
||||
}
|
||||
let (ids, vector, rasterized) = s.edit("Flatten Transparency", |d, sel| {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::apply::{kept_work, opaque, plan, stroked};
|
||||
use super::apply::{opaque, plan, stroked};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Appearance, Color, Deserialize, Document, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Serialize, Session, Value, bad, isolated_doc,
|
||||
@@ -263,15 +263,10 @@ pub fn report(doc: &Document, roots: &[NodeId], o: &FlattenOptions) -> Result<Fl
|
||||
r.rasterized.push(a.outline());
|
||||
}
|
||||
}
|
||||
for root in plan.kept.iter().filter_map(|id| doc.node(*id)).filter(|n| kept_work(n, o)) {
|
||||
r.affected.push(root.id);
|
||||
visit(root, &mut |n| {
|
||||
if o.text_to_outlines && matches!(n.kind, NodeKind::Text(_)) {
|
||||
r.text.push(n.id);
|
||||
} else if o.strokes_to_outlines && stroked(n) {
|
||||
r.strokes.push(n.id);
|
||||
}
|
||||
});
|
||||
for k in plan.work.iter().filter(|k| k.changes) {
|
||||
r.affected.push(k.id);
|
||||
r.text.extend(&k.shown_text);
|
||||
r.strokes.extend(&k.shown_strokes);
|
||||
}
|
||||
r.affected.sort_by_key(|id| doc.index_path(*id));
|
||||
Ok(r)
|
||||
|
||||
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
font_list
|
||||
),
|
||||
cmd!(
|
||||
query "text.similarFonts",
|
||||
"Show Similar Fonts",
|
||||
[],
|
||||
None,
|
||||
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
|
||||
always,
|
||||
similar_fonts
|
||||
),
|
||||
cmd!(
|
||||
query "text.glyphCategories",
|
||||
"Glyph Categories",
|
||||
@@ -1146,6 +1155,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most families `text.similarFonts` takes as its `limit`.
|
||||
const MAX_SIMILAR: u64 = 100_000;
|
||||
|
||||
fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.similarFonts";
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let family = match p.get("family") {
|
||||
Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(),
|
||||
Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")),
|
||||
Some(_) => return Err(bad(C, "`family` must be a string")),
|
||||
};
|
||||
let limit = match p.get("limit") {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
v.as_u64()
|
||||
.filter(|n| (1..=MAX_SIMILAR).contains(n))
|
||||
.ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?,
|
||||
),
|
||||
};
|
||||
// Any of the family's names, spelled as the font menus list it; a family they don't list is not available.
|
||||
let menu = db.menu_family_list();
|
||||
let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned());
|
||||
let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) };
|
||||
let mut families = db.similar_families(&family, &menu);
|
||||
if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) {
|
||||
families.truncate(n);
|
||||
}
|
||||
Ok(json!({ "family": family, "families": families }))
|
||||
}
|
||||
|
||||
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
|
||||
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
|
||||
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Type…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones",
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as bands `lineWidth` wide filled with the series colour), lineWidth?: pt (Line Width of Draw Filled Lines: 0.01–1000; 3), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; options that leave the graph as it is record no step of history; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones",
|
||||
has_selection,
|
||||
set_type
|
||||
),
|
||||
|
||||
@@ -230,6 +230,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value
|
||||
"prefix": one_line(&spec.prefix), "suffix": one_line(&spec.suffix), "rightPrefix": one_line(&spec.right_prefix),
|
||||
"rightSuffix": one_line(&spec.right_suffix), "dropShadow": spec.drop_shadow, "legendAcrossTop": spec.legend_across_top,
|
||||
"firstRowInFront": spec.first_row_in_front, "firstColumnInFront": spec.first_column_in_front, "filledLines": spec.filled_lines,
|
||||
"lineWidth": spec.filled_line_width(),
|
||||
});
|
||||
// Only the options this graph's types use: overlap order for columns and bars, filled lines for lines.
|
||||
let kinds: Vec<GraphKind> = (0..count.max(1)).map(|i| spec.series_kind(i)).collect();
|
||||
@@ -241,6 +242,7 @@ fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value
|
||||
}
|
||||
if !has(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]) {
|
||||
o.remove("filledLines");
|
||||
o.remove("lineWidth");
|
||||
}
|
||||
}
|
||||
// Pie graphs: Legend, Position and Sort (their Legend stands for the legend checkbox).
|
||||
@@ -266,6 +268,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graph.setType";
|
||||
let id = target(s, p, C)?;
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let stored = spec.clone();
|
||||
// The series to retype: `seriesIndexes`, else, with no `id`, a selection made only of this graph's series (Group
|
||||
// Selection). Anything else selected, the graph itself for one, is the whole graph.
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
@@ -311,6 +314,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"firstRowInFront",
|
||||
"firstColumnInFront",
|
||||
"filledLines",
|
||||
"lineWidth",
|
||||
"pieLegend",
|
||||
"piePosition",
|
||||
"pieSort",
|
||||
@@ -404,6 +408,15 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?;
|
||||
spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?;
|
||||
spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?;
|
||||
if let Some(w) = p.get("lineWidth").filter(|v| !v.is_null()) {
|
||||
let w = w.as_f64().ok_or_else(|| bad(C, format!("`lineWidth` must be a number, not {w}")))?;
|
||||
let (min, max) = (vectorcraft_doc::MIN_FILLED_LINE_WIDTH, vectorcraft_doc::MAX_FILLED_LINE_WIDTH);
|
||||
if !(min..=max).contains(&w) {
|
||||
return Err(bad(C, format!("`lineWidth` must be from {min} to {max} pt, not {w}")));
|
||||
}
|
||||
// The default width is stored as no width.
|
||||
spec.line_width = (w != vectorcraft_doc::DEFAULT_FILLED_LINE_WIDTH).then_some(w);
|
||||
}
|
||||
spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?;
|
||||
// After `legend`, which the Graph Type dialog sends too.
|
||||
if let Some(v) = text_param(p, "pieLegend", C)? {
|
||||
@@ -418,6 +431,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?;
|
||||
spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?;
|
||||
spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks);
|
||||
// Options that leave the graph as it is record no step of history.
|
||||
if spec == stored {
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
let label = format!("{} Graph", spec.kind.label());
|
||||
s.edit("Graph Type", |d, sel| {
|
||||
regenerate(d, id, spec)?;
|
||||
|
||||
@@ -393,6 +393,16 @@ impl<'a> Plot<'a> {
|
||||
series_marks(self.g, i, series_fill, stroke, width)
|
||||
}
|
||||
|
||||
/// The stroke paint and width series `s`'s filled marks and its legend swatch get when the series keeps no stroke
|
||||
/// of its own: a white line between stacked segments, area bands and pie wedges, none on other marks.
|
||||
fn mark_stroke(&self, s: usize) -> (Paint, f64) {
|
||||
match self.kind(s) {
|
||||
GraphKind::StackedColumn | GraphKind::StackedBar | GraphKind::Area => (Paint::solid(Color::WHITE), 0.25),
|
||||
GraphKind::Pie => (Paint::solid(Color::WHITE), 0.5),
|
||||
_ => (Paint::None, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn series_label(&self, i: usize) -> String {
|
||||
self.g.series.get(i).cloned().unwrap_or_default()
|
||||
}
|
||||
@@ -471,7 +481,8 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
let sweep = v / total * std::f64::consts::TAU;
|
||||
let bp = wedge_path(ring, a0, sweep);
|
||||
let (fill, stroke, sw) = self.mark(s, true, Paint::solid(Color::WHITE), 0.5);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let (fill, stroke, sw) = self.mark(s, true, stroke, width);
|
||||
let dark = is_dark(&fill);
|
||||
let n = self.b.path(PathData::from_bezpath(&bp), fill, stroke, sw);
|
||||
self.push_shadowed(s, n);
|
||||
@@ -532,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);
|
||||
@@ -887,7 +898,8 @@ impl<'a> Plot<'a> {
|
||||
let Some(base) = (if v >= 0.0 { pos.get_mut(ax) } else { neg.get_mut(ax) }) else { continue };
|
||||
let (v0, v1) = (geo.vpos(ax, *base), geo.vpos(ax, *base + v));
|
||||
*base += v;
|
||||
let paint = self.mark(s, true, Paint::solid(Color::WHITE), 0.25);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let paint = self.mark(s, true, stroke, width);
|
||||
let rect = bar_rect(geo.horizontal, a, w, v0, v1);
|
||||
// A segment of 0 has no area to shade.
|
||||
let n = self.bar_node(Bar { s, rect, value: v, down: v1 < v0, per_unit: geo.per_unit(ax) }, paint, v != 0.0);
|
||||
@@ -907,7 +919,8 @@ impl<'a> Plot<'a> {
|
||||
let at = |c: usize, v: &[f64]| Point::new(geo.cat_mid(c), geo.vpos(a, v.get(c).copied().unwrap_or(0.0)));
|
||||
let mut pts: Vec<Point> = (0..ncat).map(|c| at(c, &above)).collect();
|
||||
pts.extend((0..ncat).rev().map(|c| at(c, below)));
|
||||
let (fill, stroke, w) = self.mark(s, true, Paint::solid(Color::WHITE), 0.25);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let (fill, stroke, w) = self.mark(s, true, stroke, width);
|
||||
let n = self.b.path(polyline(&pts, true), fill, stroke, w);
|
||||
self.push_series(s, n);
|
||||
*below = above;
|
||||
@@ -951,10 +964,11 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
|
||||
/// The swatch of series `s` at `(x, y)`: series drawn with markers show their marker design in the legend, and
|
||||
/// series drawn with a column design that design.
|
||||
/// series drawn with a column design that design. A default swatch has the stroke of its series' marks.
|
||||
fn legend_swatch(&mut self, s: usize, (x, y): (f64, f64)) {
|
||||
let marked = matches!(self.g.kind, GraphKind::Scatter | GraphKind::Radar) || self.kind(s) == GraphKind::Line;
|
||||
let paint = self.mark(s, true, Paint::None, 0.0);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let paint = self.mark(s, true, stroke, width);
|
||||
let column = nth(self.column_looks, s).filter(|_| self.columnar(s));
|
||||
let swatch = self.b.swatch(column, nth(&self.designs, s).filter(|_| marked), Rect::new(x, y, x + 8.0, y + 8.0), paint);
|
||||
self.push_series(s, swatch);
|
||||
|
||||
@@ -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);
|
||||
@@ -177,10 +230,11 @@ impl Gen<'_> {
|
||||
Arc::new(g)
|
||||
}
|
||||
/// A series' line joining its data points (Connect Data Points): a 1 pt stroke in the series colour, or with Draw
|
||||
/// Filled Lines a band FILLED_LINE_WIDTH wide filled with it and outlined in black.
|
||||
/// Filled Lines a band as wide as the graph's Line Width ([`GraphSpec::filled_line_width`]) filled with it and outlined
|
||||
/// in black.
|
||||
pub(super) fn data_line(&mut self, g: &GraphSpec, s: usize, pd: PathData, filled: bool) -> Arc<Node> {
|
||||
let band = if filled {
|
||||
vectorcraft_pathops::outline_stroke(&pd, FILLED_LINE_WIDTH, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0)
|
||||
vectorcraft_pathops::outline_stroke(&pd, g.filled_line_width(), vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Miter, 4.0)
|
||||
} else {
|
||||
PathData::default()
|
||||
};
|
||||
@@ -234,9 +288,6 @@ const SHADOW_OFFSET: f64 = 2.0;
|
||||
|
||||
pub(super) const SHADOW_OPACITY: f32 = 0.35;
|
||||
|
||||
/// Draw Filled Lines: how wide a filled line is.
|
||||
const FILLED_LINE_WIDTH: f64 = 3.0;
|
||||
|
||||
const FILLED_LINE_BUDGET: usize = 20_000;
|
||||
|
||||
/// Does graph `g`, with `series` series, draw Filled Lines (up to FILLED_LINE_BUDGET data points)?
|
||||
|
||||
@@ -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,382 @@ 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());
|
||||
let was_unpainted = stroke_unpainted(&rows);
|
||||
merge_row_edits(&mut rows, &old, &new);
|
||||
if old.paint.stroke != new.paint.stroke {
|
||||
keep_painted_stroke_weight(&mut rows, was_unpainted, &new.paint);
|
||||
}
|
||||
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 was_unpainted = stroke_unpainted(&rows);
|
||||
let k = &mut rows.paint;
|
||||
if on_fill.paint {
|
||||
k.fill = shown.fill.clone();
|
||||
}
|
||||
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.clone();
|
||||
}
|
||||
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;
|
||||
}
|
||||
if on_stroke.paint {
|
||||
keep_painted_stroke_weight(&mut rows, was_unpainted, &shown);
|
||||
}
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Give kept line rows whose stroke an edit painted the painted line's stroke weight (`shown`) when the kind kept no
|
||||
/// stroke paint before the edit (`was_unpainted`) and keeps the zero weight a stroke set to None left. A non-zero kept
|
||||
/// weight stays, and so do a zero weight kept with a painted stroke and a zero weight the painted line shows.
|
||||
fn keep_painted_stroke_weight(rows: &mut vectorcraft_doc::LabelRows, was_unpainted: bool, shown: &vectorcraft_doc::SeriesPaint) {
|
||||
if was_unpainted
|
||||
&& !stroke_unpainted(rows)
|
||||
&& rows.paint.stroke_width.is_some_and(|w| w <= 0.0)
|
||||
&& let Some(w) = shown.stroke_width.filter(|w| *w > 0.0)
|
||||
{
|
||||
rows.paint.stroke_width = Some(w);
|
||||
}
|
||||
}
|
||||
|
||||
/// Do kept line rows keep no stroke paint?
|
||||
fn stroke_unpainted(rows: &vectorcraft_doc::LabelRows) -> bool {
|
||||
rows.paint.stroke.as_ref().is_none_or(Paint::is_none)
|
||||
}
|
||||
|
||||
/// 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 +1699,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 +1835,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 +1878,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 +1910,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
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Crop Image",
|
||||
["Object"],
|
||||
None,
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
has_image,
|
||||
crop_image
|
||||
),
|
||||
@@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData {
|
||||
PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true))
|
||||
}
|
||||
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and
|
||||
/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or
|
||||
/// `r` not on the pixel grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> {
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when
|
||||
/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel
|
||||
/// grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> {
|
||||
let blob = doc.images.get(&im.key)?;
|
||||
let [a, b, c, d, _, _] = im.xf.as_coeffs();
|
||||
if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 {
|
||||
@@ -996,9 +996,85 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op
|
||||
return None;
|
||||
}
|
||||
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
|
||||
Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as
|
||||
/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive
|
||||
/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as
|
||||
/// Rasterize's.
|
||||
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<(f64, bool)>> {
|
||||
const C: &str = "object.cropImage";
|
||||
let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?;
|
||||
if !(1.0..=2400.0).contains(&ppi) {
|
||||
return Err(bad(C, "ppi must be between 1 and 2400"));
|
||||
}
|
||||
let (_, max) = vectorcraft_tools::cropimage::image_ppi(im);
|
||||
if ppi > max + 1e-6 {
|
||||
let max = (max * 100.0 + 1e-6).floor() / 100.0;
|
||||
return Err(bad(C, format!("ppi can't be more than {max} for this image")));
|
||||
}
|
||||
// An image whose pixels are not square is resampled on both sides, even at its denser side's resolution.
|
||||
Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6))))
|
||||
}
|
||||
|
||||
/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and
|
||||
/// no side past the renderer's).
|
||||
fn check_crop_size(w: f64, h: f64) -> Result<()> {
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
if w * h > MAX_PIXELS || w > side || h > side {
|
||||
let (w, h) = (w as u64, h as u64);
|
||||
return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully
|
||||
/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in
|
||||
/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when
|
||||
/// the working copies would not fit ([`check_resample_size`]).
|
||||
fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result<image::RgbaImage> {
|
||||
check_resample_size(img.width(), img.height(), w, h)?;
|
||||
let mut pre = image::ImageBuffer::<image::Rgba<u16>, Vec<u16>>::new(img.width(), img.height());
|
||||
for (d, s) in pre.pixels_mut().zip(img.pixels()) {
|
||||
let a = u32::from(s[3]);
|
||||
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
|
||||
// c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted.
|
||||
*dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16;
|
||||
}
|
||||
d.0[3] = (a * 257) as u16;
|
||||
}
|
||||
let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3);
|
||||
let mut res = image::RgbaImage::new(out.width(), out.height());
|
||||
for (d, s) in res.pixels_mut().zip(out.pixels()) {
|
||||
let a = u64::from(s[3]);
|
||||
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
|
||||
// c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a.
|
||||
*dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8;
|
||||
}
|
||||
d.0[3] = ((a + 128) / 257).min(255) as u8;
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and
|
||||
/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes
|
||||
/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`).
|
||||
pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> {
|
||||
let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h));
|
||||
let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12));
|
||||
if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC {
|
||||
return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` as PNG bytes.
|
||||
fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> {
|
||||
let mut png = Vec::new();
|
||||
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1014,9 +1090,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if switch_or(p, "trim", false, C)? {
|
||||
if p.get("ppi").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
|
||||
}
|
||||
return trim_image(s, id, (**im).clone());
|
||||
}
|
||||
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
|
||||
let asked = crop_resolution(p, im)?;
|
||||
// The resolution the image's pixels are resampled to when they are cut straight.
|
||||
let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t));
|
||||
let rect = match p.get("rect").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) if a.len() == 4 => {
|
||||
let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
|
||||
@@ -1038,16 +1120,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Err(bad(C, "crop rectangle doesn't overlap the image"));
|
||||
}
|
||||
if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 {
|
||||
// A box over the whole image still resamples it to a new resolution.
|
||||
let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6;
|
||||
// A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image.
|
||||
let [_, xb, xc, _, _, _] = im.xf.as_coeffs();
|
||||
let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9;
|
||||
if whole && target.is_none() && (asked.is_none() || !turned) {
|
||||
return Err(bad(C, "nothing to crop"));
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled.
|
||||
if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
put_pixels(s, id, png, cw, ch, xf)?;
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a
|
||||
// resolution is asked for.
|
||||
if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
let (cut, xf) = match target {
|
||||
Some(t) => {
|
||||
let (cw, ch) = cut.dimensions();
|
||||
let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&cut, w, h)?;
|
||||
(resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h)))
|
||||
}
|
||||
None => (cut, xf),
|
||||
};
|
||||
let (cw, ch) = cut.dimensions();
|
||||
put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?;
|
||||
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
|
||||
}
|
||||
// Keep the image's pixel density.
|
||||
let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
// A drawn crop is made at a resolution asked for even when it is the image's own: the box of a
|
||||
// turned or skewed image holds fewer of its pixels a point than the image does.
|
||||
let target = asked.map(|(t, _)| t);
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more
|
||||
// than the image's own, measured on its pixel grid however it is turned, nor past the size a
|
||||
// drawing may have), and resampled to it.
|
||||
let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
let scale = target.map_or(native, |t| {
|
||||
let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0);
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9));
|
||||
(2.0 * t).min(own).min(budget).max(t.min(own))
|
||||
});
|
||||
let mut bare = node.clone();
|
||||
bare.opacity = 1.0;
|
||||
bare.blend = Default::default();
|
||||
@@ -1058,23 +1173,41 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(e) = bare.extras_if_any() {
|
||||
e.color_mask = None;
|
||||
}
|
||||
let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0));
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale);
|
||||
// At a resolution asked for, the drawing is fitted to the box below: the image is stretched
|
||||
// about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn.
|
||||
if target.is_some()
|
||||
&& let NodeKind::Image(bi) = &mut bare.kind
|
||||
{
|
||||
let o = r.origin().to_vec2();
|
||||
bi.xf = Affine::translate(o)
|
||||
* Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height())
|
||||
* Affine::translate(-o)
|
||||
* bi.xf;
|
||||
}
|
||||
let tmp = isolated_doc(&st.doc, vec![bare]);
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
|
||||
let (png, w, h, warning) =
|
||||
render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?;
|
||||
// At a resolution asked for, the drawing is resampled to the box's size at that resolution and
|
||||
// fitted to the box, so the image keeps its size.
|
||||
let (png, w, h, xf) = match target {
|
||||
Some(t) => {
|
||||
let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8();
|
||||
// Only the decoded pixels are held while they are resampled.
|
||||
drop(png);
|
||||
let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&drawn, tw, th)?;
|
||||
let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th));
|
||||
(encode_png(&resized)?, tw, th, xf)
|
||||
}
|
||||
None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)),
|
||||
};
|
||||
s.edit("Crop Image", |d, _| {
|
||||
let key = unique_key(d, "crop");
|
||||
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: w,
|
||||
height: h,
|
||||
xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
}));
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Align",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
|
||||
has_selection_or_guides,
|
||||
align
|
||||
),
|
||||
|
||||
@@ -166,15 +166,18 @@ const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
|
||||
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
|
||||
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
|
||||
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
|
||||
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
|
||||
/// A document without pixel-aligned symbols is not walked.
|
||||
/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by
|
||||
/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked.
|
||||
fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was = before.pixel_aligned_symbols();
|
||||
// The symbol whose editing mode this edit ended, if any.
|
||||
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned);
|
||||
let mut every = false;
|
||||
for name in &aligned {
|
||||
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
@@ -184,22 +187,29 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
_ => true,
|
||||
};
|
||||
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
|
||||
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
|
||||
if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed {
|
||||
snap_symbol_art(doc, name);
|
||||
every = true;
|
||||
}
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
// The symbol editing layer holds another symbol's art.
|
||||
let editing = doc.symbol_edit.as_ref().map(|e| e.layer);
|
||||
if every {
|
||||
for layer in doc.layers.iter_mut() {
|
||||
if holds_instance(layer, &natural) {
|
||||
if Some(layer.id) != editing && holds_instance(layer, &natural) {
|
||||
snap_instances_in(Arc::make_mut(layer), &natural);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
if let Some(layer) = editing {
|
||||
let outside = |layers: &[Arc<Node>]| layers.iter().filter(|l| l.id != layer).cloned().collect::<Vec<_>>();
|
||||
changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked);
|
||||
} else {
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
}
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
snap_instance(n, &natural);
|
||||
@@ -358,9 +368,10 @@ fn snap_mask(n: &mut Node) -> bool {
|
||||
|
||||
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
|
||||
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
|
||||
/// rotated (a half turn included) or sheared instance stays where it is.
|
||||
/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any
|
||||
/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it.
|
||||
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return };
|
||||
let Some(nat) = natural.get(symbol.as_str()) else { return };
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let [na, _, _, nd, _, _] = nat.as_coeffs();
|
||||
@@ -373,7 +384,12 @@ fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
return;
|
||||
}
|
||||
let (x, y) = (e.round(), f.round());
|
||||
if x != e || y != f {
|
||||
if x == e && y == f {
|
||||
return;
|
||||
}
|
||||
n.transform(Affine::translate((x - e, y - f)), Scaling::default());
|
||||
// Whole points exactly, which adding the offset to the old position need not give.
|
||||
if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind {
|
||||
*xf = Affine::new([a, b, c, d, x, y]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -113,6 +113,30 @@ thread_local! {
|
||||
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
|
||||
}
|
||||
let data =
|
||||
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
|
||||
vectorcraft_format::load(&data?).ok()
|
||||
}
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
|
||||
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
|
||||
/// relative path taken from the file's folder): the copy would name it.
|
||||
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
@@ -291,6 +315,7 @@ impl<'a> Collector<'a> {
|
||||
// read from its editing data links are copied beside it.
|
||||
let pages = placed.get(&file.path);
|
||||
let placed_file = pages.is_some();
|
||||
check_carried_scripts(&file.name, &bytes, found_path)?;
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
@@ -471,6 +496,8 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let given_name = text_param(p, "name", C)?;
|
||||
let folder = text_param(p, "folder", C)?;
|
||||
let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?;
|
||||
// Before anything is collected or written, here where the request's read roots are in force.
|
||||
super::fileio::check_linked_scripts(C, "vectorcraft", s.doc()?, &Value::Null)?;
|
||||
let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
|
||||
let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string);
|
||||
if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
|
||||
|
||||
@@ -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 what the swap changes on 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)? };
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -318,7 +318,7 @@ pub(crate) fn style_of(n: &Node) -> Style {
|
||||
|
||||
/// Leaf shapes (paths, compound paths, text) of a subtree in paint order; guides and clipping
|
||||
/// paths are skipped.
|
||||
fn leaves(n: &Node, out: &mut Vec<Node>) {
|
||||
pub(crate) fn leaves(n: &Node, out: &mut Vec<Node>) {
|
||||
each_leaf(n, &mut |l| out.push(l.clone()));
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.commonTangents",
|
||||
"addon.pathtools.corner",
|
||||
"addon.pathtools.cornerRemove",
|
||||
"addon.pathtools.cornerSet",
|
||||
@@ -63,6 +64,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",
|
||||
@@ -703,8 +705,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, run
|
||||
/// plug-ins again, or read a file and report where it is on disk.
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
|
||||
/// report where it is on disk.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
@@ -717,5 +720,6 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"object.pathfinder.options",
|
||||
"stroke.arrowheads.edit",
|
||||
"stroke.arrowheads.list",
|
||||
"text.similarFonts",
|
||||
"type.compositeFonts.set",
|
||||
];
|
||||
|
||||
@@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 {
|
||||
(doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0)
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or
|
||||
/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints
|
||||
/// nothing, when the area it covers overflows `f64` or the scale is not positive.
|
||||
fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> {
|
||||
// What it paints (its members' effects included), and how far its fills' and strokes' raster
|
||||
// effects reach beyond that.
|
||||
let b = vectorcraft_render::painted_bounds(out, whole)?;
|
||||
let look = out.raster_effects.clone();
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let b = vectorcraft_render::painted_bounds(d, whole)?;
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around;
|
||||
let b = b.inflate(reach, reach);
|
||||
// An area too large for f64 gives a zero scale and an image transform that is not finite.
|
||||
let area = b.width() * b.height();
|
||||
@@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N
|
||||
return None;
|
||||
}
|
||||
let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale);
|
||||
Some((region, scale))
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
let (region, scale) = effect_region(out, whole, scale)?;
|
||||
let look = out.raster_effects.clone();
|
||||
// Anti-alias off: hard edges (the effects themselves stay smooth).
|
||||
let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None };
|
||||
let mut img = render(out, vec![whole.clone()], region, scale, anti_alias);
|
||||
@@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
if !below && let Some(image) = rasterize_effect_image(d, n) {
|
||||
return Some(image);
|
||||
}
|
||||
let whole = effect_art(n, below, members);
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
effect_image(d, &whole, bare.as_ref(), image_scale(d, n))
|
||||
}
|
||||
|
||||
/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`:
|
||||
/// `n` without its transparency, a group's or layer's members without their raster effects when
|
||||
/// both are set.
|
||||
fn effect_art(n: &Node, below: bool, members: bool) -> Node {
|
||||
let mut whole = n.clone();
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
@@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
strip_raster(Arc::make_mut(c), true);
|
||||
}
|
||||
}
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
// A Rasterize effect at a finer resolution than the document's is rendered at its own.
|
||||
let scale = raster_fx(n)
|
||||
.iter()
|
||||
.filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None })
|
||||
.fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0));
|
||||
effect_image(d, &whole, bare.as_ref(), scale)
|
||||
whole
|
||||
}
|
||||
|
||||
/// Pixels per point of the image of the raster effects of `n`: the document's raster effects
|
||||
/// resolution, or a Rasterize effect's finer one, which is rendered at its own.
|
||||
fn image_scale(d: &Document, n: &Node) -> f64 {
|
||||
raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0))
|
||||
}
|
||||
|
||||
/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below`
|
||||
/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the
|
||||
/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]);
|
||||
/// 0 when it paints nothing.
|
||||
pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 {
|
||||
if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) {
|
||||
// Measured as Object › Rasterize measures it.
|
||||
let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0;
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| {
|
||||
let b = b.inflate(r.add_around, r.add_around);
|
||||
((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0))
|
||||
});
|
||||
// Past Object › Rasterize's limits that image is not made, and the effect's image is.
|
||||
if let Some((w, h)) = size
|
||||
&& w * h <= super::menucmds::MAX_PIXELS
|
||||
&& w <= side
|
||||
&& h <= side
|
||||
{
|
||||
return (w * h) as u64;
|
||||
}
|
||||
}
|
||||
effect_region(d, &effect_art(n, below, members), image_scale(d, n))
|
||||
.map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64)
|
||||
}
|
||||
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
@@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
"clippingMask": r.clipping_mask,
|
||||
"addAround": r.add_around,
|
||||
});
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some((_, map)) = staged {
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
/// image takes its place with its id, name and transparency (a layer keeps the image as its only
|
||||
/// member).
|
||||
|
||||
@@ -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 unless `added`], 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), added?: false (an empty row's new color is a color added to `group`)}] | {\"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 | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded 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
|
||||
),
|
||||
@@ -1384,6 +1384,9 @@ struct Row {
|
||||
tint: f32,
|
||||
/// The row's own `model`, which takes the place of the command's for its colors.
|
||||
model: Option<ModelRule>,
|
||||
/// `added`: with no current colors, the new color is a color added to the group, which it
|
||||
/// joins after the colors of the rows with current colors.
|
||||
added: bool,
|
||||
}
|
||||
|
||||
/// The color model a row's colors take (`model`): each color's own, the new color's, or the
|
||||
@@ -1437,9 +1440,10 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
|
||||
};
|
||||
let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}")));
|
||||
match p.get("map") {
|
||||
Some(Value::Object(m)) => {
|
||||
m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None })).collect()
|
||||
}
|
||||
Some(Value::Object(m)) => m
|
||||
.iter()
|
||||
.map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false }))
|
||||
.collect(),
|
||||
Some(Value::Array(rows)) => rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
@@ -1450,7 +1454,8 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
|
||||
};
|
||||
let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let model = ModelRule::param(r, cmd)?;
|
||||
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model })
|
||||
let added = switch_or(r, "added", false, cmd)?;
|
||||
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added })
|
||||
})
|
||||
.collect(),
|
||||
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
|
||||
@@ -1487,6 +1492,10 @@ struct ColorMap {
|
||||
group: Vec<GroupSwatch>,
|
||||
keys: HashMap<ColorKey, usize>,
|
||||
hexes: HashMap<String, usize>,
|
||||
/// The current colors of the rows whose new color was removed (`to: null`, not excluded),
|
||||
/// which keep their colors.
|
||||
removed_keys: std::collections::HashSet<ColorKey>,
|
||||
removed_hexes: std::collections::HashSet<String>,
|
||||
/// Set when a colour took a new colour of another model in its own model.
|
||||
converted: std::cell::Cell<bool>,
|
||||
/// The Global Adjust every mapped colour takes after its row's new colour.
|
||||
@@ -1505,11 +1514,23 @@ impl ColorMap {
|
||||
group,
|
||||
keys: HashMap::new(),
|
||||
hexes: HashMap::new(),
|
||||
removed_keys: Default::default(),
|
||||
removed_hexes: Default::default(),
|
||||
converted: Default::default(),
|
||||
adjust,
|
||||
};
|
||||
for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) {
|
||||
let Some(to) = r.new_color() else { continue };
|
||||
let Some(to) = r.new_color() else {
|
||||
if !r.exclude {
|
||||
for m in &r.from {
|
||||
match m {
|
||||
Match::Key(k) => out.removed_keys.insert(*k),
|
||||
Match::Hex(h) => out.removed_hexes.insert(h.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let i = out.rows.len();
|
||||
let colors: Vec<Color> = r.from.iter().map(Match::color).collect();
|
||||
let link = links.get(n).cloned().flatten();
|
||||
@@ -1550,9 +1571,18 @@ impl ColorMap {
|
||||
/// the row gives it the new color in that color's model and the Global Adjust gives it the
|
||||
/// swatch's new color at that tint;
|
||||
/// other rows map the colour, which loses its link when it changes or when the group's rewrite
|
||||
/// would change it. True when anything changed.
|
||||
/// would change it; a color of a row whose new color was removed keeps its color and loses its
|
||||
/// link to a swatch of the group whose rewrite would change it. True when anything changed.
|
||||
fn map_link(&self, c: &mut Color, link: &mut Option<String>, tint: &mut f32) -> bool {
|
||||
let Some(i) = self.row_of(*c) else { return false };
|
||||
let Some(i) = self.row_of(*c) else {
|
||||
let removed = self.removed_keys.contains(&ColorKey::of(c)) || self.removed_hexes.contains(&c.to_hex());
|
||||
let rewritten = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)).is_some_and(|g| g.shown.tinted(*tint) != *c);
|
||||
if removed && rewritten {
|
||||
*link = None;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
let (Some(row), Some(l)) = (self.rows.get(i), self.links.get(i)) else { return false };
|
||||
if l.is_none()
|
||||
&& let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n))
|
||||
@@ -1650,18 +1680,27 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
let new: Vec<Color> = match group_colors {
|
||||
// A null in groupColors removes the group's swatch at its place.
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| {
|
||||
color_value(v)
|
||||
.map(|v| match v {
|
||||
Value::Null => Ok(None),
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))
|
||||
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors")))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))),
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
// A row with no current colors gives the group no color.
|
||||
None => rows.iter().filter(|r| !r.from.is_empty()).filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
|
||||
// A row with no current colors gives the group no color, unless it is a color added to
|
||||
// the group: those follow the colors of the rows with current colors.
|
||||
None => rows
|
||||
.iter()
|
||||
.filter(|r| !r.from.is_empty())
|
||||
.chain(rows.iter().filter(|r| r.from.is_empty() && r.added))
|
||||
.filter_map(Row::new_color)
|
||||
.map(|c| Some(mapped_adjust.apply(c)))
|
||||
.collect(),
|
||||
};
|
||||
let rename = text_param(p, "rename", C)?;
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
@@ -1696,7 +1735,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.zip(&new)
|
||||
.filter(|(w, _)| w.global && !w.is_reserved())
|
||||
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: *c, shown: d.linked_color(*c, w.spot) })
|
||||
.filter_map(|(w, c)| Some((w, (*c)?)))
|
||||
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: c, shown: d.linked_color(c, w.spot) })
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
@@ -1779,6 +1819,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(m) = model {
|
||||
row["model"] = json!(m.id());
|
||||
}
|
||||
if r.added {
|
||||
row["added"] = json!(true);
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -82,19 +82,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cancel Key Object",
|
||||
[],
|
||||
None,
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)",
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; a click without modifiers on an already-selected anchor point makes it the key anchor)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)",
|
||||
has_doc,
|
||||
key
|
||||
),
|
||||
cmd!(
|
||||
"select.anchors",
|
||||
"Select Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)",
|
||||
has_doc,
|
||||
anchors
|
||||
),
|
||||
cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors),
|
||||
cmd!(
|
||||
"select.segments",
|
||||
"Select Segments",
|
||||
@@ -734,17 +726,32 @@ fn key_anchor(s: &mut Session, id: Option<NodeId>, guide: Option<usize>, v: &Val
|
||||
let st = s.doc()?;
|
||||
let sel = &st.selection;
|
||||
let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len()));
|
||||
if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) {
|
||||
let is_selected_anchor = on_path
|
||||
&& !sel.segments.contains_key(&id)
|
||||
&& (sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) || (!sel.anchors.contains_key(&id) && sel.contains(id)));
|
||||
if !is_selected_anchor {
|
||||
return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1)));
|
||||
}
|
||||
// Check the new key on a copy first, so a request that fails leaves the key as it was.
|
||||
let mut trial = sel.clone();
|
||||
if !trial.anchors.contains_key(&id)
|
||||
&& let Some(p) = st.doc.node(id).and_then(|n| n.path_data())
|
||||
{
|
||||
trial.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect());
|
||||
}
|
||||
trial.key_anchor = Some((id, r));
|
||||
trial.prune(&st.doc);
|
||||
if trial.key_anchor.is_none() {
|
||||
return Err(bad(C, "select another anchor point to align to the key anchor"));
|
||||
}
|
||||
s.select(|_, sel| sel.key_anchor = Some((id, r)))?;
|
||||
s.select(|d, sel| {
|
||||
if !sel.anchors.contains_key(&id)
|
||||
&& let Some(p) = d.node(id).and_then(|n| n.path_data())
|
||||
{
|
||||
sel.anchors.insert(id, p.anchors().map(|(s, a, _)| (s, a)).collect());
|
||||
}
|
||||
sel.key_anchor = Some((id, r));
|
||||
})?;
|
||||
key_result(s)
|
||||
}
|
||||
|
||||
@@ -891,23 +898,15 @@ fn anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) {
|
||||
e.extend(path.anchors().map(|(s, i, _)| (s, i)));
|
||||
}
|
||||
// One point that add or toggle selects becomes the key anchor (a Shift-click with Direct
|
||||
// Selection); `prune` drops it unless another point is selected too.
|
||||
let single = refs.len() == 1;
|
||||
let mut newest = None;
|
||||
for r in refs {
|
||||
if mode == "toggle" && e.contains(&r) {
|
||||
e.remove(&r);
|
||||
} else if e.insert(r) && single {
|
||||
newest = Some(r);
|
||||
} else {
|
||||
e.insert(r);
|
||||
}
|
||||
}
|
||||
if e.is_empty() {
|
||||
sel.remove(id);
|
||||
} else if mode != "set"
|
||||
&& let Some(r) = newest
|
||||
{
|
||||
sel.key_anchor = Some((id, r));
|
||||
}
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -7,17 +7,20 @@
|
||||
//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All
|
||||
//! (`text.spelling.ignoreAll`) skips a word in the active document only.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_proof::{IssueKind, Options, ProofLang};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::menucmds::whole_or;
|
||||
use super::textedit::text_mut;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::typemenu::{all_texts, text_ids};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
|
||||
/// Most unknown words one check lists; past it the result says `more`.
|
||||
pub const MAX_WORDS: usize = 10_000;
|
||||
@@ -36,10 +39,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Spelling",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one",
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
cmd!(
|
||||
"text.spelling.change",
|
||||
"Change All",
|
||||
[],
|
||||
None,
|
||||
"{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}",
|
||||
has_doc,
|
||||
change_words
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.suggest",
|
||||
"Spelling Suggestions",
|
||||
@@ -107,22 +119,42 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked
|
||||
/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them.
|
||||
/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at
|
||||
/// `from` when it is given.
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.check";
|
||||
// Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than
|
||||
// a check of the whole document.
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
let mut ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)),
|
||||
None => all_texts(&s.doc()?.doc),
|
||||
};
|
||||
let max = whole_or(p, "max", MAX_WORDS as u64, C)?;
|
||||
let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?;
|
||||
let st = s.doc()?;
|
||||
// Where the last check stopped: the objects before it are skipped, and the bytes of its object
|
||||
// before `byte`.
|
||||
let mut from_byte = 0;
|
||||
if let Some(from) = p.get("from").filter(|v| !v.is_null()) {
|
||||
let (id, byte) = from_param(from, C)?;
|
||||
let Some(pos) = ids.iter().position(|i| i.0 == id) else {
|
||||
return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked")));
|
||||
};
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else {
|
||||
return Err(bad(C, format!("`from.id` {id} is not a type object")));
|
||||
};
|
||||
let len = t.plain_text().len();
|
||||
from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?;
|
||||
ids.drain(..pos);
|
||||
}
|
||||
let mut words = vec![];
|
||||
let mut more = false;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = t.plain_text();
|
||||
let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len());
|
||||
// Only the first object listed starts part way.
|
||||
let from = std::mem::take(&mut from_byte);
|
||||
let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len());
|
||||
for m in found {
|
||||
let Some(word) = text.get(m.range.clone()) else { continue };
|
||||
words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() }));
|
||||
@@ -135,6 +167,87 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "words": words, "more": more }))
|
||||
}
|
||||
|
||||
/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers.
|
||||
fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> {
|
||||
let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) };
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) {
|
||||
return Err(bad(command, format!("`from` takes id and byte, not `{k}`")));
|
||||
}
|
||||
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?;
|
||||
let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?;
|
||||
Ok((id, byte))
|
||||
}
|
||||
|
||||
/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words
|
||||
/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out
|
||||
/// once at the end rather than once for each word.
|
||||
fn change_words(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.change";
|
||||
let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string();
|
||||
let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?;
|
||||
let mut by_id: BTreeMap<NodeId, Vec<(usize, usize)>> = BTreeMap::new();
|
||||
for w in list {
|
||||
let (id, start, end) = word_param_range(w, C)?;
|
||||
by_id.entry(NodeId(id)).or_default().push((start, end));
|
||||
}
|
||||
// Every word checked against its object before anything changes.
|
||||
let st = s.doc()?;
|
||||
for (id, ranges) in &mut by_id {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else {
|
||||
return Err(bad(C, format!("{} is not a type object", id.0)));
|
||||
};
|
||||
let text = t.plain_text();
|
||||
ranges.sort_unstable();
|
||||
let mut last_end = 0;
|
||||
for &(a, b) in ranges.iter() {
|
||||
if a >= b || text.get(a..b).is_none() {
|
||||
return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0)));
|
||||
}
|
||||
if a < last_end {
|
||||
return Err(bad(C, format!("words of {} overlap at byte {a}", id.0)));
|
||||
}
|
||||
last_end = b;
|
||||
}
|
||||
// A word that already reads as `to` is left alone, so a list of only those makes no edit.
|
||||
ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str()));
|
||||
}
|
||||
by_id.retain(|_, ranges| !ranges.is_empty());
|
||||
let changed: usize = by_id.values().map(Vec::len).sum();
|
||||
if changed == 0 {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
s.edit("Change All", |d, _| {
|
||||
for (id, ranges) in &by_id {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
for &(a, b) in ranges.iter().rev() {
|
||||
// Paragraph styles and ruby follow each edit, as in `text.editRange`.
|
||||
t.splice_paras(a, b, &to);
|
||||
edit::replace_range(&mut t.runs, a, b, &to);
|
||||
t.ruby_after_replace(a, b, to.len());
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers.
|
||||
fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> {
|
||||
let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) };
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) {
|
||||
return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`")));
|
||||
}
|
||||
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?;
|
||||
let byte = |k: &str| {
|
||||
o.get(k)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|b| usize::try_from(b).ok())
|
||||
.ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number")))
|
||||
};
|
||||
Ok((id, byte("start")?, byte("end")?))
|
||||
}
|
||||
|
||||
/// One word of a type object its dictionaries don't know ([`misspellings`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Misspelling {
|
||||
@@ -149,6 +262,13 @@ pub struct Misspelling {
|
||||
/// All words). At most `max` of them; the flag says the list was cut short there. What
|
||||
/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines.
|
||||
pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
misspellings_from(t, ignored, 0, max)
|
||||
}
|
||||
|
||||
/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at
|
||||
/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since
|
||||
/// craft-proof reads a paragraph's language from all of it.
|
||||
pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
let text = t.plain_text();
|
||||
// Each run in its own language, at its bytes of the plain text.
|
||||
let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len());
|
||||
@@ -166,6 +286,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
|
||||
let mut para_start = 0;
|
||||
for para in text.split('\n') {
|
||||
let para_end = para_start + para.len();
|
||||
// No word of a paragraph that ends at `from` starts there or later.
|
||||
if para_end <= from {
|
||||
para_start = para_end + 1;
|
||||
continue;
|
||||
}
|
||||
let para_spans: Vec<(Range<usize>, ProofLang)> = spans
|
||||
.iter()
|
||||
.filter_map(|(r, lang)| {
|
||||
@@ -178,6 +303,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (para_start + issue.start, para_start + issue.end);
|
||||
if start < from {
|
||||
continue;
|
||||
}
|
||||
let Some(word) = text.get(start..end) else { continue };
|
||||
if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) {
|
||||
continue;
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1255,43 +1255,54 @@ impl GroupEdit {
|
||||
}
|
||||
|
||||
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
|
||||
/// names, kinds and global or spot flags), extra colours are added as new swatches and swatches
|
||||
/// past the end are removed. Paints linked to its global swatches follow (a removed swatch's are
|
||||
/// unlinked); `rename` renames the group. A built-in swatch (None, Registration) it would change or
|
||||
/// remove is refused.
|
||||
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
|
||||
/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors
|
||||
/// are added as new swatches and swatches past the end are removed. Paints linked to its global
|
||||
/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch
|
||||
/// (None, Registration) it would change or remove is refused.
|
||||
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
|
||||
let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?;
|
||||
let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) {
|
||||
Some(n) => d.free_swatch_name(n),
|
||||
None => group.to_string(),
|
||||
};
|
||||
let old = &d.swatch_groups[gi].swatches;
|
||||
if let Some(w) = old.iter().enumerate().find(|(i, w)| w.is_reserved() && colors.get(*i).is_none_or(|c| w.paint.color() != Some(*c))).map(|x| x.1)
|
||||
if let Some(w) = old
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c)))
|
||||
.map(|x| x.1)
|
||||
{
|
||||
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
|
||||
}
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let mut relinks = vec![];
|
||||
let mut swatches = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
for gone in swatches.split_off(colors.len().min(swatches.len())) {
|
||||
if gone.global {
|
||||
relinks.push(Relink { from: gone.name.clone(), to: gone.name, color: None, keep: false });
|
||||
let old = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
let old_len = old.len();
|
||||
// The swatches that stay, each with its new color.
|
||||
let mut kept: Vec<(Swatch, Color)> = vec![];
|
||||
for (i, w) in old.into_iter().enumerate() {
|
||||
match colors.get(i).copied().flatten() {
|
||||
Some(c) => kept.push((w, c)),
|
||||
None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
for (w, c) in swatches.iter_mut().zip(colors) {
|
||||
if w.paint.color() != Some(*c) {
|
||||
let mut swatches = Vec::with_capacity(kept.len());
|
||||
for (mut w, c) in kept {
|
||||
if w.paint.color() != Some(c) {
|
||||
// A tint swatch becomes a colour of its own.
|
||||
w.paint = Paint::solid(*c);
|
||||
w.paint = Paint::solid(c);
|
||||
if w.global {
|
||||
// Art linked to a Lab spot shows it as the Spot Colors options say.
|
||||
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(*c, w.spot)), keep: true });
|
||||
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(c, w.spot)), keep: true });
|
||||
}
|
||||
}
|
||||
swatches.push(w);
|
||||
}
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
swatches.iter().for_each(|w| free.insert(&w.name));
|
||||
for c in colors.iter().skip(swatches.len()) {
|
||||
for c in colors.iter().skip(old_len).flatten() {
|
||||
let nm = free.take(&color_name(*c));
|
||||
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
|
||||
}
|
||||
@@ -1320,6 +1331,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let colors: Vec<Color> =
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let rename = str_param(p, "rename");
|
||||
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
|
||||
@@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
|
||||
let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) {
|
||||
None => return Ok(()),
|
||||
Some(b) => match art_of(before) {
|
||||
Some(old) if same(&old) => return Ok(()),
|
||||
// Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped.
|
||||
Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()),
|
||||
old => (old.unwrap_or_default(), b.group),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1830,6 +1830,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
para: super::create::new_type_para(),
|
||||
paras: Vec::new(),
|
||||
first_para_continues: false,
|
||||
first_para_lead: None,
|
||||
area: Default::default(),
|
||||
path_effect: Default::default(),
|
||||
path_align: Default::default(),
|
||||
@@ -2136,6 +2137,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
para: Default::default(),
|
||||
paras: Vec::new(),
|
||||
first_para_continues: false,
|
||||
first_para_lead: None,
|
||||
area: Default::default(),
|
||||
path_effect: Default::default(),
|
||||
path_align: Default::default(),
|
||||
|
||||
@@ -255,6 +255,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> {
|
||||
("kinsoku", json!(v.kinsoku)),
|
||||
("kinsoku_type", json!(v.kinsoku_type)),
|
||||
("bunri_kinshi", json!(v.bunri_kinshi)),
|
||||
("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)),
|
||||
("roman_hanging", json!(v.roman_hanging)),
|
||||
("kashida", json!(v.kashida)),
|
||||
("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)),
|
||||
@@ -515,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>> {
|
||||
|
||||
@@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
.collect();
|
||||
let refs: Vec<&TextObject> = frames.iter().collect();
|
||||
let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s);
|
||||
for (id, part) in live.iter().zip(parts) {
|
||||
let texts: Vec<String> = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect();
|
||||
let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::<Vec<_>>());
|
||||
for ((id, part), lead) in live.iter().zip(parts).zip(leads) {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) {
|
||||
let mut next = (**t).clone();
|
||||
next.runs = part.runs;
|
||||
@@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
|| part.list_count != t.list_count
|
||||
|| part.list_level_counts != t.list_level_counts
|
||||
|| continues != t.first_para_continues
|
||||
|| lead != t.first_para_lead
|
||||
{
|
||||
t.runs = next.runs;
|
||||
t.para = next.para;
|
||||
@@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
t.list_count = part.list_count;
|
||||
t.list_level_counts = part.list_level_counts;
|
||||
t.first_para_continues = continues;
|
||||
t.first_para_lead = lead;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
@@ -384,17 +388,42 @@ pub(crate) fn mark_continued(doc: &mut Document) {
|
||||
let live: Vec<NodeId> = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect();
|
||||
let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect();
|
||||
let marks = vectorcraft_text::thread::continued(&frames);
|
||||
for (id, on) in live.iter().zip(marks) {
|
||||
let texts: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
|
||||
let leads = first_para_leads(&texts, &marks);
|
||||
for ((id, on), lead) in live.iter().zip(marks).zip(leads) {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues != on
|
||||
&& (t.first_para_continues != on || t.first_para_lead != lead)
|
||||
{
|
||||
t.first_para_continues = on;
|
||||
t.first_para_lead = lead;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and
|
||||
/// whether each one's first paragraph `continues` from the frame before: the last character of
|
||||
/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over
|
||||
/// the frames: each frame's lead is carried forward to the next.
|
||||
fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec<Option<char>> {
|
||||
// The lead the next frame takes when its first paragraph continues from this one.
|
||||
let mut carry = None;
|
||||
texts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, text)| {
|
||||
#[cfg(test)]
|
||||
LEAD_SCANS.with(|c| c.set(c.get() + 1));
|
||||
let lead = carry.filter(|_| continues.get(k) == Some(&true));
|
||||
let tail = text.rsplit('\n').next().unwrap_or(text);
|
||||
// A paragraph break in this frame ends the paragraph the lead came from.
|
||||
carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len()));
|
||||
lead
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's
|
||||
@@ -402,6 +431,8 @@ thread_local! {
|
||||
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`story_in`] went through a thread's frames on this thread.
|
||||
static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many frame texts [`first_para_leads`] went through on this thread.
|
||||
static LEAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's
|
||||
@@ -417,6 +448,12 @@ pub(crate) fn story_builds() -> usize {
|
||||
STORY_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn lead_scans() -> usize {
|
||||
LEAD_SCANS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a
|
||||
/// path; empty when `id` is in no thread or the thread has fewer than two such frames.
|
||||
pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
|
||||
@@ -2226,3 +2226,57 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing()
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0);
|
||||
}
|
||||
|
||||
/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of
|
||||
/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that
|
||||
/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph
|
||||
/// carries none. Flowing the story and opening a file both set it.
|
||||
#[test]
|
||||
fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() {
|
||||
let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::<Vec<_>>(), continues);
|
||||
assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]);
|
||||
assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]);
|
||||
assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]);
|
||||
assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]);
|
||||
assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]);
|
||||
assert_eq!(leads(&[], &[]), Vec::<Option<char>>::new());
|
||||
// Opening a file marks the frames as they were saved.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let mut ids = Vec::new();
|
||||
for (x, text) in [(10, "日時"), (200, "々す")] {
|
||||
let id =
|
||||
s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
ids.push(NodeId(id));
|
||||
}
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
d.text_threads = vec![ids.clone()];
|
||||
mark_continued(&mut d);
|
||||
let tb = text_of(&d, ids[1]).unwrap();
|
||||
assert!(tb.first_para_continues);
|
||||
assert_eq!(tb.first_para_lead, Some('時'));
|
||||
// Flowing the story through the frames sets it from the text each frame now holds.
|
||||
reflow(&d.clone(), &mut d);
|
||||
let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap());
|
||||
assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す");
|
||||
assert!(tb.first_para_continues);
|
||||
assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text()));
|
||||
}
|
||||
|
||||
/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one
|
||||
/// pass over the frames, each frame's text gone through once, not once for every frame after it.
|
||||
#[test]
|
||||
fn continued_frame_leads_go_through_each_frame_once() {
|
||||
let n = 2000;
|
||||
let mut texts = vec!["時".to_string()];
|
||||
texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1));
|
||||
let continues: Vec<bool> = (0..n).map(|k| k > 0).collect();
|
||||
let before = lead_scans();
|
||||
let leads = first_para_leads(&texts, &continues);
|
||||
assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before);
|
||||
assert_eq!(leads.first(), Some(&None));
|
||||
assert!(leads.iter().skip(1).all(|l| *l == Some('時')));
|
||||
// A paragraph break stops the carry, and a frame that starts a paragraph carries nothing.
|
||||
let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]);
|
||||
assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user