mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-21 14:58:11 +08:00
Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)
* Add rank polymorphism node audit classifying all 271 nodes
* Implement StaticType for Item<T>
* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input
* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate
* Document the Item kernel implementation and staging plan
* Route Item<Vector> through TaggedValue::TypeDefault
* Add executor integration tests covering the Item and List wire variants
* Collapse element-wise Item/List wire pairs to the List form for conversion insertion
* Migrate sixteen vector modifier nodes to Item element-wise kernels
* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels
* Fix bevel_with_transform test to actually exercise the transform attribute
* Implement From<T> for Item<T>
* Register PromoteNode rank adapters wrapping bare values into Item wires
* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor
* Define a real promote node backing the PromoteNode registry identifiers
* Zip ranked Item connectors by frame slot in the mapped element-wise variant
* Register ItemToListNode singleton raise adapters
* Resolve Item wires against List connectors by inserting promotion adapters at construction
* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end
* Implement Clampable for Item and List wires with per-variant clamp bounds
* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire
* Implement ApplyTransform for Item
* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0
* Detect element-wise nodes by lazy primary connectors declaring Output = Item
* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone
* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2
* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters
* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes
* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro
* Amend the audit with the DashPattern value type resolution
* Migrate the string family to Item element-wise kernels
* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters
* Shadow owned node parameters in bodies instead of mut in signatures
* Migrate the math family and string measure nodes to Item element-wise kernels
* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows
* Flat-map expander kernels returning List under the mapped variant's frame
* Migrate the expander nodes to Item kernels flat-mapping under the frame
* Remove the unused peel_list helper
* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in
Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).
Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.
* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk
* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites
* Flip the vector shape generators to emit rank-0 Item<Vector>
The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.
Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.
* Parse ranked Item<T> parameter defaults against the bare element type
A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.
* Parse an element-wise primary's scalar default against the bare element type
An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.
* Add the DashPattern value type for stroke dash sequences
Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.
* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector
Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.
Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.
Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.
* Register rank adapters for the ranked Stroke enum parameters
The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.
* Display Item wires in the Data panel without a List's ID column
Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.
* Register MonitorNode for Item wire types so the Data panel introspects them directly
Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.
* Color and double Item/List wires and cleave layer-stack connectors in the node graph
* Route wire color and rank through hidden nodes and refresh them on type changes
* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node
* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires
* Back DashPattern with a List<f64> so the Data panel can introspect its lengths
* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>
* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions
* Rank the remaining bare and unnecessarily-List connectors across the node catalog
* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values
* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill
* Restore generator frame-from-params ranking to the roadmap as a planned stage
* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract
* Unload only the wires whose displayed style changed when types update
* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized
* Restore the whole-List Transform variant so rank-1 content wires resolve again
* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes
* Give every ranked connector a field adapter and add numeric cast variants for legacy wires
* Key a ranked param's type default off its Item wire form when no literal default exists
* Inherit the layer's content value when splicing a node into an empty chain
* Migrate stale List-form TypeDefault inputs to the definition's current default
* Generate the mapped wire variant only when the element-wise node has a frame source
* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps
* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot
* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers
* Convert the measure family to element-wise Item kernels per the audit classification
* Prefer the bare element value over the Item type default so ranked params keep their widgets
* Rename GradientStopsUI to GradientUI
* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix
* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2
* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes
* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions
* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius
* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness
* Rank the value, color, and text generator params to Item
* Rank the raster, web-request, and context-reader generator params to Item
* Fix the repeat and brush test wirings left behind by the param-ranking sweeps
* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes
* Delete the Attach Attribute node, folding its role into Write Attribute
* Add the Filter and Sort list companion nodes
* Guard the removed-definition migration swap target with a test
* Add the Box Corners value type in place of the rectangle corner radius list
* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node
* Rank the Combine Channels node's channel connectors to Item
* Make Map Points an element-wise node
* Delete the deprecated Upload Texture node
* Update the implementation roadmap to reflect the landed stages
* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path
* Prefer the rank-0 default when disconnecting a rank-capable input
* Make Path Modify an element-wise node
* Wrap node paths in a NodeIdPath newtype so they flow as a single Item
* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves
* Stop the Brush node from setting layer attributes its paint operation doesn't produce
* Present-gate Flatten Path's adopted layer path like its fill and stroke
* Gate carried layer attributes on static column presence, not runtime values
* Give the remaining graphic Item<T> types a default so unconnected primaries resolve
* Dispatch a ranked param's Properties widget from its rank-0 element type
* Make Extract Transform an element-wise node, restoring the Origins to Polyline body
* Rename Flatten Path to Combine Paths
* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath
* Drop the dead List<u8> and List<NodeId> wire rows
* Rank Flatten Graphic's Fully Flatten toggle to Item
* Update the implementation roadmap with the endgame scope
* Make Combine Paths a reducer that collapses the whole frame into one path
* Stop type-converter nodes from carrying the source's unrelated attributes
* Format the Origins to Polyline regression test
* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value
* Make Switch a framed element-wise select, bundling whole collections
* Widen and align element-type coverage across the list and graphic nodes
* Register the compiler's cache chain pair for every ranked enum and newtype wire
* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires
* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion
* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg
* Delete the vestigial Clone debug node
* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters
* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR
* Deduplicate the promotion adapter registrations into the field adapter macro
* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge
* Vertical wire styling
* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>
* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row
* Rank Path Modify's modification parameter to Item<Box<VectorModification>>
* Rename the field adapter node family to input adapter
* Drop the dead bare scalar rows from Context Modification's implementations list
* Move the dynamic executor's test module into its own file
* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode
* Materialize stored TaggedValues as ranked Item wires at the source
* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization
* Plant the input adapter for List-only inputs, composing position conversion from standard rows
* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers
* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect
* Enforce ranked node inputs in the macro, rejecting bare wire declarations
* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel
* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration
* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced
* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs
* Rewrite the element-wise accessor wire type at the primary input, not raw index 0
* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row
* Gate the remaining Raster<GPU> registry rows behind the gpu feature
* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter
* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index
* Store paint picks as plain color/gradient values, removing the FillChoice value type
* Code review restructuring
* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node
* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR
* Parse Fill and Stroke color defaults through the paint wire's Graphic element
* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing
* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration
* Migrate the legacy 4-input Fill directly to the split has-transform shape
* Upgrade the demo artwork
* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues
* Remove the rank polymorphism working documents
* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation
* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types
* Derive PartialEq for Item now that attributes participate in equality
* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types
* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
This commit is contained in:
@@ -252,9 +252,20 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let mut vectors = Vec::new();
|
||||
let mut resources = Vec::new();
|
||||
for item in items {
|
||||
// Pasted templates skip document migration, so stored types normalize here
|
||||
match item {
|
||||
ClipboardItem::Layer(entry) => layers.push(entry),
|
||||
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
|
||||
ClipboardItem::Layer(mut entry) => {
|
||||
for (_, template) in &mut entry.nodes {
|
||||
template.document_node.normalize_stored_types();
|
||||
}
|
||||
layers.push(entry);
|
||||
}
|
||||
ClipboardItem::Nodes(mut nodes) => {
|
||||
for (_, template) in &mut nodes {
|
||||
template.document_node.normalize_stored_types();
|
||||
}
|
||||
node_groups.push(nodes);
|
||||
}
|
||||
ClipboardItem::Vector(vector) => vectors.push(vector),
|
||||
ClipboardItem::Resource(resource) => resources.push(resource),
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::parse_css_color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, Gradient, GradientUI};
|
||||
|
||||
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
|
||||
const MIN_MIDPOINT: f64 = 0.01;
|
||||
@@ -28,7 +28,7 @@ pub struct ColorPickerMessageHandler {
|
||||
old_is_none: bool,
|
||||
|
||||
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
|
||||
gradient: Option<GradientStops>,
|
||||
gradient: Option<Gradient>,
|
||||
active_marker_index: Option<u32>,
|
||||
active_marker_is_midpoint: bool,
|
||||
|
||||
@@ -430,7 +430,7 @@ impl ColorPickerMessageHandler {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
|
||||
let mut row_widgets = vec![
|
||||
SpectrumInput::new(GradientStopsUI::from(gradient))
|
||||
SpectrumInput::new(GradientUI::from(gradient))
|
||||
.markers(markers)
|
||||
.active_marker_index(self.active_marker_index)
|
||||
.active_marker_is_midpoint(self.active_marker_is_midpoint)
|
||||
|
||||
@@ -6,7 +6,7 @@ use derivative::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientUI};
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -531,7 +531,7 @@ pub struct SpectrumInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
pub track: GradientStopsUI,
|
||||
pub track: GradientUI,
|
||||
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackCSS")]
|
||||
#[widget_builder(skip)]
|
||||
|
||||
@@ -6,14 +6,25 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{Item, List, NodeIdPath};
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
|
||||
use graphene_std::text::TextAlign;
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{DashPattern, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
|
||||
use graphene_std::{Artboard, Color, Context, Graphic};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -176,10 +187,10 @@ macro_rules! generate_layout_downcast {
|
||||
}
|
||||
// TODO: We simply try all these types sequentially. Find a better strategy.
|
||||
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
||||
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
||||
// `Item<NodeIdPath>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
||||
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<NodeId>>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, data));
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<NodeIdPath>>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&io.output.element().0, data));
|
||||
}
|
||||
generate_layout_downcast!(introspected_data, data, [
|
||||
List<Artboard>,
|
||||
@@ -188,27 +199,106 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<Gradient>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<u8>,
|
||||
List<f32>,
|
||||
List<u32>,
|
||||
List<u64>,
|
||||
List<i32>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientType>,
|
||||
List<GradientSpreadMethod>,
|
||||
GradientStops,
|
||||
f64,
|
||||
u32,
|
||||
u64,
|
||||
bool,
|
||||
String,
|
||||
Option<f64>,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
List<DashPattern>,
|
||||
List<BoxCorners>,
|
||||
List<StrokeJoin>,
|
||||
List<StrokeAlign>,
|
||||
List<StrokeCap>,
|
||||
List<PaintOrder>,
|
||||
List<MergeByDistanceAlgorithm>,
|
||||
List<ExtrudeJoiningAlgorithm>,
|
||||
List<PointSpacingType>,
|
||||
List<StringCapitalization>,
|
||||
List<LuminanceCalculation>,
|
||||
List<RedGreenBlue>,
|
||||
List<RedGreenBlueAlpha>,
|
||||
List<RelativeAbsolute>,
|
||||
List<SelectiveColorChoice>,
|
||||
List<XY>,
|
||||
List<ScaleType>,
|
||||
List<ReferencePoint>,
|
||||
List<CentroidType>,
|
||||
List<BooleanOperation>,
|
||||
List<NoiseType>,
|
||||
List<FractalType>,
|
||||
List<CellularDistanceFunction>,
|
||||
List<CellularReturnType>,
|
||||
List<DomainWarpType>,
|
||||
List<RealTimeMode>,
|
||||
List<GridType>,
|
||||
List<ArcType>,
|
||||
List<SpiralType>,
|
||||
List<TextAlign>,
|
||||
List<QRCodeErrorCorrectionLevel>,
|
||||
List<InterpolationDistribution>,
|
||||
List<RowsOrColumns>,
|
||||
Item<Artboard>,
|
||||
Item<Graphic>,
|
||||
Item<Vector>,
|
||||
Item<Raster<CPU>>,
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<f32>,
|
||||
Item<u32>,
|
||||
Item<u64>,
|
||||
Item<i32>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientType>,
|
||||
Item<GradientSpreadMethod>,
|
||||
Item<DashPattern>,
|
||||
Item<BoxCorners>,
|
||||
Item<StrokeJoin>,
|
||||
Item<StrokeAlign>,
|
||||
Item<StrokeCap>,
|
||||
Item<PaintOrder>,
|
||||
Item<MergeByDistanceAlgorithm>,
|
||||
Item<ExtrudeJoiningAlgorithm>,
|
||||
Item<PointSpacingType>,
|
||||
Item<StringCapitalization>,
|
||||
Item<LuminanceCalculation>,
|
||||
Item<RedGreenBlue>,
|
||||
Item<RedGreenBlueAlpha>,
|
||||
Item<RelativeAbsolute>,
|
||||
Item<SelectiveColorChoice>,
|
||||
Item<XY>,
|
||||
Item<ScaleType>,
|
||||
Item<ReferencePoint>,
|
||||
Item<CentroidType>,
|
||||
Item<BooleanOperation>,
|
||||
Item<NoiseType>,
|
||||
Item<FractalType>,
|
||||
Item<CellularDistanceFunction>,
|
||||
Item<CellularReturnType>,
|
||||
Item<DomainWarpType>,
|
||||
Item<RealTimeMode>,
|
||||
Item<GridType>,
|
||||
Item<ArcType>,
|
||||
Item<SpiralType>,
|
||||
Item<TextAlign>,
|
||||
Item<QRCodeErrorCorrectionLevel>,
|
||||
Item<InterpolationDistribution>,
|
||||
Item<RowsOrColumns>,
|
||||
])
|
||||
}
|
||||
|
||||
@@ -246,6 +336,57 @@ trait TableItemLayout {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TableItemLayout> TableItemLayout for Item<T> {
|
||||
fn type_name() -> &'static str {
|
||||
T::type_name()
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.element().identifier()
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
if let Some(step) = data.desired_path.get(data.current_depth).cloned() {
|
||||
match step {
|
||||
PathStep::Element(_) => {
|
||||
data.current_depth += 1;
|
||||
let result = self.element().layout_with_breadcrumb(data);
|
||||
data.current_depth -= 1;
|
||||
return result;
|
||||
}
|
||||
PathStep::Attribute { key, .. } => {
|
||||
if let Some(any) = self.attributes().get_any(&key) {
|
||||
data.current_depth += 1;
|
||||
if let Some(result) = drilldown_attribute_layout(any, data) {
|
||||
data.current_depth -= 1;
|
||||
return result;
|
||||
}
|
||||
data.current_depth -= 1;
|
||||
warn!("Drilldown unsupported for attribute {key:?}");
|
||||
}
|
||||
data.desired_path.truncate(data.current_depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
|
||||
|
||||
// A single element, so no leading ID column, unlike the `List` table
|
||||
let mut values = vec![self.element().value_widget(PathStep::Element(0), data)];
|
||||
for key in &attribute_keys {
|
||||
let target = PathStep::Attribute { row: 0, key: key.clone() };
|
||||
let widget = self.attributes().get_any(key).and_then(|any| dispatch_value_widget(any, target, data)).unwrap_or_else(|| {
|
||||
let text = self.attributes().display_value(key, display_value_override).unwrap_or_else(|| "-".to_string());
|
||||
TextLabel::new(text).narrow(true).widget_instance()
|
||||
});
|
||||
values.push(widget);
|
||||
}
|
||||
|
||||
let mut column_names = vec!["element"];
|
||||
column_names.extend(attribute_keys.iter().map(|s| s.as_str()));
|
||||
|
||||
vec![LayoutGroup::table(vec![column_headings(&column_names), values], false)]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TableItemLayout> TableItemLayout for List<T> {
|
||||
fn type_name() -> &'static str {
|
||||
"List"
|
||||
@@ -324,12 +465,53 @@ impl TableItemLayout for Artboard {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for DashPattern {
|
||||
fn type_name() -> &'static str {
|
||||
"DashPattern"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"DashPattern".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
|
||||
fn value_widget(&self, target: PathStep, data: &LayoutData) -> WidgetInstance {
|
||||
self.0.value_widget(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for BoxCorners {
|
||||
fn type_name() -> &'static str {
|
||||
"BoxCorners"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"BoxCorners".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
|
||||
fn value_widget(&self, target: PathStep, data: &LayoutData) -> WidgetInstance {
|
||||
self.0.value_widget(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Graphic {
|
||||
fn type_name() -> &'static str {
|
||||
"Graphic"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
match self {
|
||||
Self::None => "None".to_string(),
|
||||
Self::Graphic(list) => list.identifier(),
|
||||
Self::Vector(list) => list.identifier(),
|
||||
Self::RasterCPU(list) => list.identifier(),
|
||||
@@ -345,6 +527,7 @@ impl TableItemLayout for Graphic {
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
match self {
|
||||
Self::None => label("None"),
|
||||
Self::Graphic(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Vector(list) => list.layout_with_breadcrumb(data),
|
||||
Self::RasterCPU(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -512,7 +695,7 @@ impl TableItemLayout for Raster<GPU> {
|
||||
format!("Raster ({} x {})", self.data().width(), self.data().height())
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let widgets = vec![TextLabel::new("Raster is a texture on the GPU and cannot currently be displayed here").widget_instance()];
|
||||
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
|
||||
vec![LayoutGroup::row(widgets)]
|
||||
}
|
||||
}
|
||||
@@ -537,7 +720,7 @@ impl TableItemLayout for Color {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for GradientStops {
|
||||
impl TableItemLayout for Gradient {
|
||||
fn type_name() -> &'static str {
|
||||
"Gradient"
|
||||
}
|
||||
@@ -585,6 +768,21 @@ impl TableItemLayout for u8 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u32)"
|
||||
@@ -600,6 +798,37 @@ impl TableItemLayout for u32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
// TODO: Make this robust for large i64 values that don't fit in f64 (beyond roughly 2^53), as with u64.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u64)"
|
||||
@@ -726,45 +955,73 @@ impl TableItemLayout for Affine2 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for BlendMode {
|
||||
fn type_name() -> &'static str {
|
||||
"BlendMode"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
// Choice enums all display as their variant's label, shown inline as a plain text widget
|
||||
macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
($($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl TableItemLayout for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
stringify!($ty)
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
PaintOrder,
|
||||
MergeByDistanceAlgorithm,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
XY,
|
||||
ScaleType,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
NoiseType,
|
||||
FractalType,
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
ArcType,
|
||||
SpiralType,
|
||||
TextAlign,
|
||||
QRCodeErrorCorrectionLevel,
|
||||
InterpolationDistribution,
|
||||
RowsOrColumns,
|
||||
);
|
||||
|
||||
impl TableItemLayout for GradientType {
|
||||
// ReferencePoint is not a choice enum with display labels, so its variant name serves as the label
|
||||
impl TableItemLayout for ReferencePoint {
|
||||
fn type_name() -> &'static str {
|
||||
"GradientType"
|
||||
"ReferencePoint"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
format!("{self:?}")
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for GradientSpreadMethod {
|
||||
fn type_name() -> &'static str {
|
||||
"GradientSpreadMethod"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
TextLabel::new(self.to_string()).narrow(true).widget_instance()
|
||||
TextLabel::new(self.identifier()).narrow(true).widget_instance()
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![self.value_widget(PathStep::Element(0), _data)])]
|
||||
@@ -905,12 +1162,10 @@ macro_rules! known_item_types {
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<Gradient>,
|
||||
List<String>,
|
||||
List<NodeId>,
|
||||
List<f64>,
|
||||
List<u8>,
|
||||
GradientStops,
|
||||
Gradient,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
@@ -919,9 +1174,12 @@ macro_rules! known_item_types {
|
||||
Vec2,
|
||||
Option<f64>,
|
||||
f64,
|
||||
f32,
|
||||
u8,
|
||||
u32,
|
||||
u64,
|
||||
i32,
|
||||
i64,
|
||||
bool,
|
||||
String,
|
||||
Vector,
|
||||
@@ -929,6 +1187,42 @@ macro_rules! known_item_types {
|
||||
Raster<GPU>,
|
||||
Graphic,
|
||||
Artboard,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
BlendMode,
|
||||
GradientType,
|
||||
GradientSpreadMethod,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
PaintOrder,
|
||||
MergeByDistanceAlgorithm,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
XY,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
CentroidType,
|
||||
BooleanOperation,
|
||||
NoiseType,
|
||||
FractalType,
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
ArcType,
|
||||
SpiralType,
|
||||
TextAlign,
|
||||
QRCodeErrorCorrectionLevel,
|
||||
InterpolationDistribution,
|
||||
RowsOrColumns,
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -949,6 +1243,10 @@ fn display_value_override(any: &dyn Any) -> Option<String> {
|
||||
/// element-column rendering and attribute-column rendering. Returns `None` for unrecognized
|
||||
/// types so the caller can fall back to a debug-formatted [`TextLabel`].
|
||||
fn dispatch_value_widget(any: &dyn Any, target: PathStep, data: &LayoutData) -> Option<WidgetInstance> {
|
||||
// `NodeIdPath` (e.g. the `editor:layer_path` attribute) drills into its inner path list, matching `drilldown_attribute_layout`.
|
||||
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
|
||||
return Some(path.0.value_widget(target, data));
|
||||
}
|
||||
macro_rules! check {
|
||||
( $($ty:ty),* $(,)? ) => {
|
||||
$(
|
||||
@@ -1005,10 +1303,10 @@ fn table_node_id_path_layout_with_breadcrumb(path: &List<NodeId>, data: &mut Lay
|
||||
/// Mirrors [`dispatch_value_widget`] but routes to [`TableItemLayout::layout_with_breadcrumb`].
|
||||
/// Returns `None` for unrecognized types.
|
||||
fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
||||
// `List<NodeId>` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
|
||||
// resolves against the prefix made up of preceding items. Handled before the generic `List<T>` blanket impl.
|
||||
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(path, data));
|
||||
// `NodeIdPath` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
|
||||
// resolves against the prefix made up of preceding items. Handled before the generic blanket impl.
|
||||
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
|
||||
}
|
||||
macro_rules! check {
|
||||
( $($ty:ty),* $(,)? ) => {
|
||||
|
||||
@@ -34,9 +34,9 @@ use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graph_craft::list;
|
||||
use graphene_std::graphic::is_paint_present;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
@@ -125,7 +125,7 @@ pub struct DocumentMessageHandler {
|
||||
/// network path, the node itself, and its original relative gradient. The deferred migration removes each entry as its bake lands.
|
||||
/// Transient migration state, but persisted in the saved document so unfinished bakes retry on the next open instead of losing placement.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
|
||||
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
|
||||
// =============================================
|
||||
// Fields omitted from the saved document format
|
||||
@@ -2748,7 +2748,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// For each selected layer, splits its fill and stroke into two stacked layers connected
|
||||
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
|
||||
/// to a shared `Solidify Stroke` node via two `Item at Index` nodes (indices 0 and 1).
|
||||
/// Layers with only a stroke get just a `Solidify Stroke` added.
|
||||
/// Layers with only a fill, or neither, are left untouched.
|
||||
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
|
||||
@@ -2758,7 +2758,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
|
||||
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
|
||||
let item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Item at Index node should exist");
|
||||
|
||||
let mut resulting_layers: Vec<NodeId> = Vec::new();
|
||||
|
||||
@@ -2791,7 +2791,7 @@ impl DocumentMessageHandler {
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
|
||||
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
@@ -2813,7 +2813,7 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
@@ -3789,7 +3789,7 @@ impl DocumentMessageHandler {
|
||||
/// Create a network interface with a single export
|
||||
fn default_document_network_interface() -> NodeNetworkInterface {
|
||||
let mut network_interface = NodeNetworkInterface::default();
|
||||
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
|
||||
network_interface.add_export(TaggedValue::TypeDefault(list!(graphene_std::Artboard)), -1, "", &[]);
|
||||
network_interface
|
||||
}
|
||||
|
||||
@@ -4007,7 +4007,7 @@ mod document_message_handler_tests {
|
||||
#[test]
|
||||
fn pending_gradient_bakes_round_trip_through_serialization() {
|
||||
let document = DocumentMessageHandler {
|
||||
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::Gradient::default())],
|
||||
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::LegacyGradient::default())],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -4318,4 +4318,35 @@ mod document_message_handler_tests {
|
||||
Dist: {distance} (should be < 1)"
|
||||
);
|
||||
}
|
||||
|
||||
// Grouping choreography transiently disconnects the stack wire, and the stored default for that connector
|
||||
// must stay an empty list rather than any value which materializes as a one-element phantom in the stack
|
||||
#[tokio::test]
|
||||
async fn grouping_adds_no_phantom_element_to_the_stack() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
|
||||
let instrumented = editor.eval_graph().await.unwrap();
|
||||
|
||||
let base_lengths: Vec<usize> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::BaseInput<graphene_std::Graphic>>(&editor.runtime)
|
||||
.map(|base| base.len())
|
||||
.collect();
|
||||
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
|
||||
|
||||
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput<graphene_std::Graphic>>(&editor.runtime).collect();
|
||||
let phantom_count = news
|
||||
.iter()
|
||||
.flat_map(|new| new.iter_element_values())
|
||||
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None))
|
||||
.count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -22,7 +22,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
FillGradientSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient: GradientStops,
|
||||
gradient: Gradient,
|
||||
gradient_type: GradientType,
|
||||
spread_method: GradientSpreadMethod,
|
||||
transform: DAffine2,
|
||||
@@ -33,7 +33,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
GradientStopsSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
stops: GradientStops,
|
||||
stops: Gradient,
|
||||
},
|
||||
GradientTransformSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
|
||||
+13
-21
@@ -8,12 +8,11 @@ use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::list::List;
|
||||
use graph_craft::list;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::{Gradient, GradientSpreadMethod, GradientStop, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
@@ -180,7 +179,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
}
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::type_default(list!(Artboard), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
} else {
|
||||
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
|
||||
@@ -188,7 +187,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
|
||||
|
||||
// Set the bottom input of the artboard back to artboard
|
||||
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
|
||||
let bottom_input = NodeInput::type_default(list!(Artboard), true);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
|
||||
}
|
||||
}
|
||||
@@ -508,8 +507,8 @@ const GRAPHITE_NAMESPACE: &str = "https://graphite.art";
|
||||
/// Pre-parses the raw SVG XML to extract gradient stops that have `graphite:midpoint` attributes.
|
||||
/// Graphite exports gradients with midpoint curve data by writing interpolated approximation stops
|
||||
/// alongside the real stops. Real stops are tagged with `graphite:midpoint` attributes.
|
||||
/// Returns a map from gradient element `id` to `GradientStops` containing only the real stops.
|
||||
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, GradientStops> {
|
||||
/// Returns a map from gradient element `id` to `Gradient` containing only the real stops.
|
||||
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, Gradient> {
|
||||
let mut result = HashMap::new();
|
||||
|
||||
// Quick check: if the SVG doesn't reference `graphite:midpoint` at all, skip parsing
|
||||
@@ -555,7 +554,7 @@ fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, GradientStops>
|
||||
}
|
||||
|
||||
if has_any_midpoint && !real_stops.is_empty() {
|
||||
result.insert(gradient_id, GradientStops::new(real_stops));
|
||||
result.insert(gradient_id, Gradient::new(real_stops));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,14 +578,7 @@ fn parse_hex_stop_color(hex: &str, opacity: f32) -> Option<Color> {
|
||||
/// interact with any existing layers in the parent stack. All descendant layers use a lightweight
|
||||
/// O(n) import path that skips collision detection and instead calculates positions directly from
|
||||
/// the known tree structure.
|
||||
fn import_usvg_node(
|
||||
modify_inputs: &mut ModifyInputsContext,
|
||||
node: &usvg::Node,
|
||||
id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
graphite_gradient_stops: &HashMap<String, GradientStops>,
|
||||
) {
|
||||
fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, id: NodeId, parent: LayerNodeIdentifier, insert_index: usize, graphite_gradient_stops: &HashMap<String, Gradient>) {
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
|
||||
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
@@ -649,7 +641,7 @@ fn import_usvg_node_inner(
|
||||
id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
graphite_gradient_stops: &HashMap<String, GradientStops>,
|
||||
graphite_gradient_stops: &HashMap<String, Gradient>,
|
||||
group_extents_map: &mut HashMap<LayerNodeIdentifier, Vec<u32>>,
|
||||
) -> u32 {
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
@@ -692,7 +684,7 @@ fn import_usvg_node_inner(
|
||||
}
|
||||
|
||||
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
|
||||
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, Gradient>) {
|
||||
let subpaths = convert_usvg_path(path);
|
||||
|
||||
// Skip creating a Transform node entirely when the SVG-native transform is identity.
|
||||
@@ -807,7 +799,7 @@ fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMet
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, Gradient>) {
|
||||
match &fill.paint() {
|
||||
usvg::Paint::Color(color) => modify_inputs.fill_color_set(Some(usvg_color(*color, fill.opacity().get()))),
|
||||
usvg::Paint::LinearGradient(linear) => {
|
||||
@@ -827,7 +819,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
midpoint: 0.5,
|
||||
color: usvg_color(stop.color(), stop.opacity().get()),
|
||||
});
|
||||
GradientStops::new(stops)
|
||||
Gradient::new(stops)
|
||||
}
|
||||
};
|
||||
let spread_method = convert_spread_method(linear.spread_method());
|
||||
@@ -851,7 +843,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
midpoint: 0.5,
|
||||
color: usvg_color(stop.color(), stop.opacity().get()),
|
||||
});
|
||||
GradientStops::new(stops)
|
||||
Gradient::new(stops)
|
||||
}
|
||||
};
|
||||
let spread_method = convert_spread_method(radial.spread_method());
|
||||
|
||||
@@ -8,7 +8,7 @@ use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
@@ -16,7 +16,7 @@ use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -134,11 +134,11 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
/// Creates an artboard as the primary export for the document network.
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::type_default(list!(Artboard), true)),
|
||||
Some(NodeInput::type_default(list!(Graphic), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(Some(background)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(background), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||
]);
|
||||
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
|
||||
@@ -149,7 +149,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
|
||||
.expect("Boolean node does not exist")
|
||||
.node_template_input_override([
|
||||
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
|
||||
Some(NodeInput::type_default(list!(Graphic), true)),
|
||||
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
|
||||
]);
|
||||
|
||||
@@ -161,7 +161,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
|
||||
let blend = resolve_network_node_type("Blend")
|
||||
.expect("Blend node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
|
||||
|
||||
let blend_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
@@ -173,7 +173,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
|
||||
.expect("Morph node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
@@ -300,7 +300,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier) {
|
||||
let color_value = resolve_proto_node_type(graphene_std::math_nodes::color_value::IDENTIFIER)
|
||||
.expect("Color Value node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(Some(color)), false))]);
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(color), false))]);
|
||||
|
||||
let color_value_id = NodeId::new();
|
||||
self.network_interface.insert_node(color_value_id, color_value, &[]);
|
||||
@@ -437,7 +437,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
|
||||
if node_definition.identifier == "Path" {
|
||||
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
|
||||
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
|
||||
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
|
||||
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
|
||||
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
|
||||
return None;
|
||||
@@ -460,11 +460,15 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
|
||||
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
|
||||
|
||||
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
|
||||
// The backup remembers the last solid color, so the red-slash "none" choice leaves it untouched
|
||||
if let Some(color) = color {
|
||||
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
}
|
||||
let fill_value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(fill_value, false), false);
|
||||
}
|
||||
|
||||
pub fn fill_gradient_set(&mut self, gradient: GradientStops, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
|
||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
|
||||
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
@@ -488,9 +492,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX))
|
||||
.is_some_and(|input| input.as_value().is_some());
|
||||
if transform_is_value {
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
|
||||
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
|
||||
NodeInput::value(TaggedValue::DAffine2(transform), false),
|
||||
true,
|
||||
);
|
||||
}
|
||||
@@ -563,7 +572,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
|
||||
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
|
||||
pub fn gradient_stops_set(&mut self, stops: Gradient) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let gradient_value_id = match get_upstream_gradient_value_node_id(output_layer, self.network_interface) {
|
||||
@@ -716,7 +725,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
|
||||
@@ -729,8 +738,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<graphene_std::list::List<f64>>::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths.into()), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
}
|
||||
|
||||
@@ -14,9 +14,8 @@ use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, descriptor};
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
#[allow(unused_imports)]
|
||||
@@ -207,7 +206,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Graphic>), true), NodeInput::type_default(descriptor!(List<Graphic>), true)],
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -292,11 +291,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(TaggedValue), 1),
|
||||
NodeInput::import(concrete!(TaggedValue), 2),
|
||||
NodeInput::import(concrete!(TaggedValue), 3),
|
||||
NodeInput::import(concrete!(TaggedValue), 4),
|
||||
NodeInput::import(concrete!(TaggedValue), 5),
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -327,7 +326,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(List<Artboard>))), 0),
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
@@ -341,11 +340,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Artboard>), true),
|
||||
NodeInput::type_default(descriptor!(List<Graphic>), true),
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Some(Color::WHITE)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
..Default::default()
|
||||
@@ -453,9 +452,9 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count Elements (number of subpaths)
|
||||
// 1: List Length (number of subpaths)
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(vector::count_elements::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(vector::list_length::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -468,7 +467,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 3: Floor (integer count per subpath)
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 1)],
|
||||
inputs: vec![NodeInput::import(item!(f64), 1)],
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
@@ -544,8 +543,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(generic!(T), 4),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -575,11 +574,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Vector>), true),
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(descriptor!(List<Vector>), false),
|
||||
NodeInput::type_default(list!(Vector), false),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -604,7 +603,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count Elements
|
||||
// 1: List Length
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
@@ -826,7 +825,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Vector>), true)],
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -924,7 +923,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(concrete!(String), 1)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -999,7 +998,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(concrete!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
|
||||
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1011,7 +1010,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Vector>), true),
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(
|
||||
TaggedValue::Footprint(Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::new(1000., 1000.), 0., DVec2::new(0., 0.)),
|
||||
@@ -1081,7 +1080,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1090,7 +1089,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1099,7 +1098,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1108,7 +1107,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
|
||||
NodeInput::import(list!(Raster<CPU>), 0),
|
||||
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
|
||||
@@ -1122,7 +1121,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
|
||||
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -1183,13 +1182,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
|
||||
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
|
||||
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
..Default::default()
|
||||
@@ -1244,85 +1243,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
),
|
||||
properties: None,
|
||||
},
|
||||
#[cfg(feature = "gpu")]
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Upload Texture",
|
||||
category: "Debug",
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(List<Raster<CPU>>), 0), NodeInput::scope(platform_application_io::wgpu_executor::IDENTIFIER)],
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::memoize::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
output_names: vec!["Texture".to_string()],
|
||||
network_metadata: Some(NodeNetworkMetadata {
|
||||
persistent_metadata: NodeNetworkPersistentMetadata {
|
||||
node_metadata: [
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
description: Cow::Borrowed("TODO"),
|
||||
properties: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Extract",
|
||||
category: "",
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Extract,
|
||||
inputs: vec![NodeInput::type_default(descriptor!(DocumentNode), true)],
|
||||
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
@@ -1350,25 +1277,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(String), 0),
|
||||
NodeInput::import(concrete!(String), 1),
|
||||
NodeInput::import(concrete!(f64), 2),
|
||||
NodeInput::import(concrete!(bool), 3),
|
||||
NodeInput::import(concrete!(bool), 4),
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(f64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: extract_element at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::extract_element::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: omit_element at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::omit_element::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
@@ -1450,7 +1377,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: vec![
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(List<Vector>), 0)],
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
skip_deduplication: true,
|
||||
@@ -1474,7 +1401,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(descriptor!(List<Vector>), true),
|
||||
NodeInput::type_default(item!(Vector), true),
|
||||
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
|
||||
],
|
||||
..Default::default()
|
||||
@@ -2207,3 +2134,33 @@ impl DocumentNodeDefinition {
|
||||
self.node_template_input_override(self.node_template.document_node.inputs.clone().into_iter().map(Some))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::resolve_network_node_type;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// Guards the embedded Map body chain (Read Vector -> Extract Transform -> Decompose Translation -> As Vector) against registry drift
|
||||
#[tokio::test]
|
||||
async fn origins_to_polyline_resolves_and_evaluates() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = NodeId::new();
|
||||
let node_template = resolve_network_node_type("Origins to Polyline")
|
||||
.expect("the Origins to Polyline definition should exist")
|
||||
.default_node_template();
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(node_template),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,6 +1179,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
data_type: self.wire_in_progress_type,
|
||||
thick: false,
|
||||
dashed: false,
|
||||
is_list: false,
|
||||
center_path_string: String::new(),
|
||||
};
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: Some(wire_path) });
|
||||
}
|
||||
@@ -1431,7 +1433,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
return None;
|
||||
}
|
||||
|
||||
let (wire, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
|
||||
let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
|
||||
|
||||
let node_bbox = kurbo::Rect::new(node_bbox[0].x, node_bbox[0].y, node_bbox[1].x, node_bbox[1].y).to_path(DEFAULT_ACCURACY);
|
||||
let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None);
|
||||
@@ -1726,7 +1728,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
continue;
|
||||
};
|
||||
|
||||
if node_bbox[1].x >= document_bbox[0].x && node_bbox[0].x <= document_bbox[1].x && node_bbox[1].y >= document_bbox[0].y && node_bbox[0].y <= document_bbox[1].y {
|
||||
// Expand the cull box by a grid cell so a node stays rendered until its connectors, which reach beyond its bounding box, also leave the viewport
|
||||
let cull_margin = 24.;
|
||||
if node_bbox[1].x + cull_margin >= document_bbox[0].x
|
||||
&& node_bbox[0].x - cull_margin <= document_bbox[1].x
|
||||
&& node_bbox[1].y + cull_margin >= document_bbox[0].y
|
||||
&& node_bbox[0].y - cull_margin <= document_bbox[1].y
|
||||
{
|
||||
nodes.push(*node_id);
|
||||
}
|
||||
for error in &network_interface.resolved_types.node_graph_errors {
|
||||
@@ -2167,7 +2175,37 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::UpdateTypes { resolved_types, node_graph_errors } => {
|
||||
// Hidden passthrough nodes let a wire borrow its color and rank from an upstream node, so any type change can restyle wires whose own node is unchanged.
|
||||
// Compare each displayed wire's style (color, rank) across the update and unload only those that changed, so value-only recompiles keep their built wire paths.
|
||||
let types_changed = !resolved_types.add.is_empty() || !resolved_types.remove.is_empty();
|
||||
let wire_style = |network_interface: &mut NodeNetworkInterface, input: &InputConnector| {
|
||||
network_interface.upstream_output_connector(input, breadcrumb_network_path).map(|output| {
|
||||
let output_type = network_interface.output_type(&output, breadcrumb_network_path);
|
||||
(output_type.displayed_type(), output_type.is_list())
|
||||
})
|
||||
};
|
||||
let styles_before = types_changed.then(|| {
|
||||
network_interface
|
||||
.node_graph_input_connectors(breadcrumb_network_path)
|
||||
.into_iter()
|
||||
.map(|input| {
|
||||
let style = wire_style(network_interface, &input);
|
||||
(input, style)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
network_interface.resolved_types.update(resolved_types, node_graph_errors);
|
||||
|
||||
if let Some(styles_before) = styles_before {
|
||||
for (input, style_before) in styles_before {
|
||||
if wire_style(network_interface, &input) != style_before {
|
||||
network_interface.unload_wire(&input, breadcrumb_network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::UpdateActionButtons => {
|
||||
if selection_network_path == breadcrumb_network_path {
|
||||
|
||||
@@ -19,7 +19,7 @@ use graph_craft::{Type, concrete};
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::brush::brush_stroke::BrushTrace;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::list::List;
|
||||
@@ -32,9 +32,11 @@ use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
DashPattern, FillChoiceUI, Gradient, GradientSpreadMethod, GradientType, GradientUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
|
||||
@@ -213,6 +215,24 @@ pub(crate) fn property_from_type(
|
||||
|
||||
let default_info = ParameterWidgetsInfo::new(node_id, index, true, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
let is_exposed = default_info.is_exposed();
|
||||
|
||||
let mut widgets = start_widgets(default_info);
|
||||
if !is_exposed {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("-")
|
||||
.tooltip_label(type_label)
|
||||
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
|
||||
vec![LayoutGroup::from(widgets)]
|
||||
};
|
||||
|
||||
let mut extra_widgets = vec![];
|
||||
let widgets = match ty {
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -234,92 +254,84 @@ pub(crate) fn property_from_type(
|
||||
// For all other types, use TypeId-based matching
|
||||
_ => {
|
||||
use std::any::TypeId;
|
||||
|
||||
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
|
||||
fn id_is<T: 'static>(id: TypeId) -> bool {
|
||||
id == TypeId::of::<T>()
|
||||
}
|
||||
|
||||
match concrete_type.id {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
|
||||
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some(x) if x == TypeId::of::<bool>() => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if x == TypeId::of::<String>() => text_widget(default_info).into(),
|
||||
Some(x) if x == TypeId::of::<DVec2>() => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
Some(x) if x == TypeId::of::<DAffine2>() => transform_widget(default_info, &mut extra_widgets),
|
||||
// ==========
|
||||
// LIST TYPES
|
||||
// ==========
|
||||
Some(x) if x == TypeId::of::<List<f64>>() => array_of_number_widget(default_info, TextInput::default()).into(),
|
||||
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||
Some(x) if x == TypeId::of::<List<GradientStops>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if x == TypeId::of::<List<BrushStroke>>() => brush_strokes_widget(default_info).into(),
|
||||
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
|
||||
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<BrushTrace>(x) => brush_strokes_widget(default_info).into(),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
Some(x) if x == TypeId::of::<Font>() => font_widget(default_info),
|
||||
Some(x) if x == TypeId::of::<Footprint>() => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if x == TypeId::of::<Box<VectorModification>>() => vector_modification_widget(default_info).into(),
|
||||
Some(x) if x == TypeId::of::<Image<Color>>() => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
// ===============================
|
||||
// MANUALLY IMPLEMENTED ENUM TYPES
|
||||
// ===============================
|
||||
Some(x) if x == TypeId::of::<ReferencePoint>() => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if x == TypeId::of::<BlendMode>() => blend_mode_widget(default_info),
|
||||
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
|
||||
// =========================
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if x == TypeId::of::<GradientType>() => enum_choice::<GradientType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<GradientSpreadMethod>() => enum_choice::<GradientSpreadMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RealTimeMode>() => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RedGreenBlue>() => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RedGreenBlueAlpha>() => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<XY>() => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StringCapitalization>() => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<NoiseType>() => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<FractalType>() => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<CellularDistanceFunction>() => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<CellularReturnType>() => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<DomainWarpType>() => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<RelativeAbsolute>() => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if x == TypeId::of::<GridType>() => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StrokeCap>() => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StrokeJoin>() => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<StrokeAlign>() => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<PaintOrder>() => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<ArcType>() => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<RowsOrColumns>() => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<TextAlign>() => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<MergeByDistanceAlgorithm>() => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<ExtrudeJoiningAlgorithm>() => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<PointSpacingType>() => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<BooleanOperation>() => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<CentroidType>() => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<LuminanceCalculation>() => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<QRCodeErrorCorrectionLevel>() => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<ScaleType>() => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if x == TypeId::of::<InterpolationDistribution>() => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientType>(x) => enum_choice::<GradientType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpreadMethod>(x) => enum_choice::<GradientSpreadMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PaintOrder>(x) => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<LuminanceCalculation>(x) => enum_choice::<LuminanceCalculation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
// =====
|
||||
// OTHER
|
||||
// =====
|
||||
_ => {
|
||||
let is_exposed = default_info.is_exposed();
|
||||
|
||||
let mut widgets = start_widgets(default_info);
|
||||
|
||||
if !is_exposed {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("-")
|
||||
.tooltip_label(concrete_type.to_string())
|
||||
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
return Err(vec![widgets.into()]);
|
||||
}
|
||||
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
|
||||
Type::List(element) => match element.as_ref() {
|
||||
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
|
||||
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
|
||||
},
|
||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
@@ -854,6 +866,32 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
|
||||
widgets
|
||||
}
|
||||
|
||||
pub fn dash_pattern_widget(parameter_widgets_info: ParameterWidgetsInfo, text_input: TextInput) -> Vec<WidgetInstance> {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
|
||||
let mut widgets = start_widgets(parameter_widgets_info);
|
||||
|
||||
let Some(document_node) = document_node else { return Vec::new() };
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(TaggedValue::DashPattern(pattern)) = &input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
text_input
|
||||
.value(pattern.0.iter_element_values().map(|length| length.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(
|
||||
move |input: &TextInput| Some(TaggedValue::DashPattern(DashPattern::from(input.value.as_str()))),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.widget_instance(),
|
||||
])
|
||||
}
|
||||
widgets
|
||||
}
|
||||
|
||||
pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetInstance>, Option<Vec<WidgetInstance>>) {
|
||||
pub fn assign_font_message(node_id: NodeId, font: Font) -> Message {
|
||||
let resource_id = ResourceId::new();
|
||||
@@ -1166,30 +1204,37 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
// Add the color input
|
||||
match &**tagged_value {
|
||||
TaggedValue::Color(color) => widgets.push(
|
||||
color_button
|
||||
.value(FillChoiceUI::from(&match color {
|
||||
Some(color) => FillChoice::Solid(*color),
|
||||
None => FillChoice::None,
|
||||
}))
|
||||
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid().map(Color::from)), node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
),
|
||||
TaggedValue::Gradient(stops) => widgets.push(
|
||||
color_button
|
||||
.value(FillChoiceUI::from(&FillChoice::Gradient(stops.clone())))
|
||||
.on_update(update_value(
|
||||
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().map(GradientStops::from).unwrap_or_default()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
),
|
||||
x => warn!("Color {x:?}"),
|
||||
}
|
||||
let widget_value = match &**tagged_value {
|
||||
TaggedValue::Color(color) => FillChoiceUI::Solid(SRGBA8::from(*color)),
|
||||
TaggedValue::Gradient(stops) => FillChoiceUI::Gradient(GradientUI::from(stops)),
|
||||
value if value.is_no_paint() => FillChoiceUI::None,
|
||||
x => {
|
||||
warn!("Color {x:?}");
|
||||
return LayoutGroup::row(widgets);
|
||||
}
|
||||
};
|
||||
|
||||
// A paint input (`allow_none`) stores the pick as a plain color, gradient, or no-paint type default,
|
||||
// while a plain color or gradient input always keeps its own value type
|
||||
let on_update: fn(&ColorInput) -> TaggedValue = if color_button.allow_none {
|
||||
|input| match &input.value {
|
||||
FillChoiceUI::None => TaggedValue::no_paint(),
|
||||
FillChoiceUI::Solid(srgba) => TaggedValue::Color(Color::from(*srgba)),
|
||||
FillChoiceUI::Gradient(gradient_ui) => TaggedValue::Gradient(Gradient::from(gradient_ui)),
|
||||
}
|
||||
} else if matches!(&**tagged_value, TaggedValue::Gradient(_)) {
|
||||
|input| TaggedValue::Gradient(input.value.as_gradient().map(Gradient::from).unwrap_or_default())
|
||||
} else {
|
||||
|input| TaggedValue::Color(input.value.as_solid().map(Color::from).unwrap_or(Color::TRANSPARENT))
|
||||
};
|
||||
|
||||
widgets.push(
|
||||
color_button
|
||||
.value(widget_value)
|
||||
.on_update(update_value(on_update, node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
|
||||
LayoutGroup::row(widgets)
|
||||
}
|
||||
@@ -1258,8 +1303,8 @@ pub fn query_assign_colors_randomize(node_id: NodeId, context: &NodePropertiesCo
|
||||
}
|
||||
|
||||
/// 2-stop black-to-white gradient track for spectrum sliders that map a value to a grayscale axis.
|
||||
fn bw_track() -> GradientStops {
|
||||
GradientStops {
|
||||
fn bw_track() -> Gradient {
|
||||
Gradient {
|
||||
position: vec![0., 1.],
|
||||
midpoint: vec![0.5, 0.5],
|
||||
color: vec![Color::BLACK, Color::WHITE],
|
||||
@@ -1267,8 +1312,8 @@ fn bw_track() -> GradientStops {
|
||||
}
|
||||
|
||||
/// 3-stop black-to-color-to-white gradient track for spectrum sliders that map a value to a hue's full luminance range.
|
||||
fn color_track(color: Color) -> GradientStops {
|
||||
GradientStops {
|
||||
fn color_track(color: Color) -> Gradient {
|
||||
Gradient {
|
||||
position: vec![0., 0.5, 1.],
|
||||
midpoint: vec![0.5; 3],
|
||||
color: vec![Color::BLACK, color, Color::WHITE],
|
||||
@@ -1303,7 +1348,7 @@ pub(crate) fn brightness_contrast_properties(node_id: NodeId, context: &mut Node
|
||||
|
||||
let contrast_min = if use_classic_value { -100. } else { -50. };
|
||||
let zero_position = -contrast_min / (100. - contrast_min);
|
||||
let contrast_track = GradientStops {
|
||||
let contrast_track = Gradient {
|
||||
position: vec![0., zero_position, 1.],
|
||||
midpoint: vec![0.5; 3],
|
||||
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), Color::BLACK, Color::from_rgbf32_unchecked(0.5, 0.5, 0.5)],
|
||||
@@ -1400,7 +1445,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
|
||||
|
||||
// Build the shared spectrum widget (placed on the first non-exposed row)
|
||||
let spectrum_widget = (!spectrum_markers.is_empty()).then(|| {
|
||||
SpectrumInput::new(GradientStopsUI::from(&bw_track()))
|
||||
SpectrumInput::new(GradientUI::from(&bw_track()))
|
||||
.markers(spectrum_markers)
|
||||
.show_midpoints(false)
|
||||
.allow_insert(false)
|
||||
@@ -1493,13 +1538,13 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
let saturated_current_hue = Color::from_hsva(marker_hue, 1., 1., 1.);
|
||||
|
||||
// Hue: cyclic rainbow
|
||||
let hue_track = GradientStops {
|
||||
let hue_track = Gradient {
|
||||
position: vec![0., 1. / 6., 2. / 6., 3. / 6., 4. / 6., 5. / 6., 1.],
|
||||
midpoint: vec![0.5; 7],
|
||||
color: vec![Color::RED, Color::YELLOW, Color::GREEN, Color::CYAN, Color::BLUE, Color::MAGENTA, Color::RED],
|
||||
};
|
||||
// Saturation: gray to the fully saturated current hue
|
||||
let saturation_track = GradientStops {
|
||||
let saturation_track = Gradient {
|
||||
position: vec![0., 1.],
|
||||
midpoint: vec![0.5, 0.5],
|
||||
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), saturated_current_hue],
|
||||
@@ -1549,7 +1594,7 @@ fn spectrum_slider_row(
|
||||
node_id: NodeId,
|
||||
context: &mut NodePropertiesContext,
|
||||
input_index: usize,
|
||||
track: GradientStops,
|
||||
track: Gradient,
|
||||
handle_color: Color,
|
||||
value_min: f64,
|
||||
value_max: f64,
|
||||
@@ -1574,7 +1619,7 @@ fn spectrum_slider_row(
|
||||
|
||||
let position_to_value = move |position: f64| value_min + position * value_range;
|
||||
row.push(
|
||||
SpectrumInput::new(GradientStopsUI::from(&track))
|
||||
SpectrumInput::new(GradientUI::from(&track))
|
||||
.markers(vec![SpectrumMarker::new(position, 0.5, handle_color)])
|
||||
.show_midpoints(false)
|
||||
.allow_insert(false)
|
||||
@@ -1634,7 +1679,7 @@ pub(crate) fn threshold_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
pub(crate) fn vibrance_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::vibrance::*;
|
||||
|
||||
let track = GradientStops {
|
||||
let track = Gradient {
|
||||
position: vec![0., 1.],
|
||||
midpoint: vec![0.5, 0.5],
|
||||
color: vec![Color::from_rgbf32_unchecked(0.5, 0.5, 0.5), Color::RED],
|
||||
@@ -2167,7 +2212,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
// Corner Radius
|
||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::<f64>::INDEX, true, context));
|
||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::INDEX, true, context));
|
||||
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
||||
@@ -2187,20 +2232,15 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
};
|
||||
if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() {
|
||||
// Values
|
||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::<f64>::INDEX) else {
|
||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::INDEX) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
let uniform_val = match input.as_non_exposed_value() {
|
||||
Some(TaggedValue::F64(x)) => *x,
|
||||
Some(TaggedValue::F64Array(values)) => values.first().copied().unwrap_or(0.),
|
||||
_ => 0.,
|
||||
};
|
||||
let individual_val = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::F64(x)) => vec![x; 4],
|
||||
Some(TaggedValue::F64Array(values)) => values.clone(),
|
||||
_ => vec![0.; 4],
|
||||
let corner_values = match input.as_non_exposed_value() {
|
||||
Some(TaggedValue::BoxCorners(corners)) => corners.to_corner_values(),
|
||||
_ => [0.; 4],
|
||||
};
|
||||
let uniform_val = corner_values[0];
|
||||
|
||||
// Uniform/individual radio input widget
|
||||
let uniform = RadioEntryData::new("Uniform")
|
||||
@@ -2215,14 +2255,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
||||
value: TaggedValue::F64(uniform_val),
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::BoxCorners(BoxCorners::from(uniform_val)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value);
|
||||
let individual_val_for_switch = individual_val.clone();
|
||||
let individual = RadioEntryData::new("Individual")
|
||||
.label("Individual")
|
||||
.on_update(move |_| Message::Batched {
|
||||
@@ -2235,8 +2274,8 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
||||
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::BoxCorners(BoxCorners::from(corner_values.to_vec())),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2247,24 +2286,23 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
|
||||
// Radius value input widget
|
||||
let input_widget = if is_individual {
|
||||
let from_string = |string: &str| {
|
||||
string
|
||||
.split(&[',', ' '])
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(str::parse::<f64>)
|
||||
.collect::<Result<Vec<f64>, _>>()
|
||||
.ok()
|
||||
.map(|values| TaggedValue::F64Array(values.into_iter().take(4).collect()))
|
||||
};
|
||||
TextInput::default()
|
||||
.value(individual_val.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::<f64>::INDEX))
|
||||
.value(corner_values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(
|
||||
move |x: &TextInput| Some(TaggedValue::BoxCorners(BoxCorners::from(x.value.as_str()))),
|
||||
node_id,
|
||||
CornerRadiusInput::INDEX,
|
||||
))
|
||||
.widget_instance()
|
||||
} else {
|
||||
NumberInput::default()
|
||||
.value(Some(uniform_val))
|
||||
.unit(" px")
|
||||
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::<f64>::INDEX))
|
||||
.on_update(update_value(
|
||||
move |x: &NumberInput| TaggedValue::BoxCorners(BoxCorners::from(x.value.unwrap())),
|
||||
node_id,
|
||||
CornerRadiusInput::INDEX,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance()
|
||||
};
|
||||
@@ -2333,10 +2371,14 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
let mut unit_suffix = None;
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(proto_node_identifier)
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
number_options = NumberOptions {
|
||||
@@ -2349,12 +2391,14 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
display_decimal_places = field.number_display_decimal_places;
|
||||
unit_suffix = field.unit;
|
||||
step = field.number_step;
|
||||
if let Some(ref default) = field.default_type {
|
||||
break 'early_return default.clone();
|
||||
}
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
let Some(implementations) = &interpreted_executor::node_registry::NODE_REGISTRY.get(proto_node_identifier) else {
|
||||
if let Some(default) = default_type {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
let Some(implementations) = &interpreted_executor::node_registry::NODE_REGISTRY.get(&proto_node_identifier) else {
|
||||
log::error!("Could not get implementation for protonode {proto_node_identifier:?}");
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -2442,7 +2486,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
enum ResolvedFill {
|
||||
Solid(Option<Color>),
|
||||
Gradient {
|
||||
gradient: GradientStops,
|
||||
gradient: Gradient,
|
||||
gradient_type: GradientType,
|
||||
spread_method: GradientSpreadMethod,
|
||||
transform: DAffine2,
|
||||
@@ -2452,9 +2496,6 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
Other,
|
||||
}
|
||||
|
||||
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::INDEX);
|
||||
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
|
||||
|
||||
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
|
||||
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, context));
|
||||
|
||||
@@ -2466,51 +2507,42 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
// bounding-box default transform needs the layer, and it falls back to a unit box when there isn't one.
|
||||
let layer = root_layer_for_chain_node(node_id, context);
|
||||
|
||||
let fill = match input_type.compiled_nested_type() {
|
||||
Some(ty) if ty == &concrete!(List<Color>) => {
|
||||
if let Ok(document_node) = get_document_node(node_id, context) {
|
||||
let color = match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
|
||||
Some(&TaggedValue::Color(c)) => c,
|
||||
_ => None,
|
||||
};
|
||||
ResolvedFill::Solid(color)
|
||||
} else {
|
||||
ResolvedFill::Other
|
||||
}
|
||||
}
|
||||
Some(ty) if ty == &concrete!(List<GradientStops>) => {
|
||||
// Read this node's own inputs rather than the layer's nearest Fill, which may be a different node when Fills are chained
|
||||
if let Ok(document_node) = get_document_node(node_id, context)
|
||||
&& let Some(gradient) = graph_modification_utils::read_fill_node_gradient(document_node, || {
|
||||
let fill = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
|
||||
Some(TaggedValue::Color(color)) => ResolvedFill::Solid(Some(*color)),
|
||||
Some(value) if value.is_no_paint() => ResolvedFill::Solid(None),
|
||||
Some(TaggedValue::Gradient(_)) => {
|
||||
match graph_modification_utils::read_fill_node_gradient(document_node, || {
|
||||
layer.map_or([DVec2::ZERO, DVec2::ONE], |layer| context.network_interface.document_metadata().nonzero_bounding_box(layer))
|
||||
}) {
|
||||
ResolvedFill::Gradient {
|
||||
gradient: gradient.stops,
|
||||
gradient_type: gradient.gradient_type,
|
||||
spread_method: gradient.spread_method,
|
||||
transform: gradient.transform,
|
||||
transform_is_value: gradient.transform_is_value,
|
||||
Some(gradient) => ResolvedFill::Gradient {
|
||||
gradient: gradient.stops,
|
||||
gradient_type: gradient.gradient_type,
|
||||
spread_method: gradient.spread_method,
|
||||
transform: gradient.transform,
|
||||
transform_is_value: gradient.transform_is_value,
|
||||
},
|
||||
None => ResolvedFill::Other,
|
||||
}
|
||||
} else {
|
||||
ResolvedFill::Other
|
||||
}
|
||||
}
|
||||
_ => ResolvedFill::Other,
|
||||
_ => ResolvedFill::Other,
|
||||
},
|
||||
Err(_) => ResolvedFill::Other,
|
||||
};
|
||||
|
||||
let (backup_color, backup_gradient) = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let backup_color = match document_node.inputs[BackupColorInput::INDEX].as_value() {
|
||||
Some(&TaggedValue::Color(color)) => color,
|
||||
Some(&TaggedValue::Color(color)) => Some(color),
|
||||
_ => None,
|
||||
};
|
||||
let backup_stops = match document_node.inputs[BackupGradientInput::INDEX].as_value() {
|
||||
Some(TaggedValue::Gradient(stops)) => stops.clone(),
|
||||
_ => GradientStops::default(),
|
||||
_ => Gradient::default(),
|
||||
};
|
||||
(backup_color, backup_stops)
|
||||
}
|
||||
Err(_) => (None, GradientStops::default()),
|
||||
Err(_) => (None, Gradient::default()),
|
||||
};
|
||||
|
||||
match &fill {
|
||||
@@ -2536,28 +2568,33 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
FillChoiceUI::None
|
||||
}
|
||||
}
|
||||
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientStopsUI::from(stops)),
|
||||
ResolvedFill::Gradient { gradient: stops, .. } => FillChoiceUI::Gradient(GradientUI::from(stops)),
|
||||
ResolvedFill::Other => FillChoiceUI::None,
|
||||
};
|
||||
|
||||
let solid_set_messages = move |color: Option<Color>| Message::Batched {
|
||||
messages: Box::new([
|
||||
let solid_set_messages = move |color: Option<Color>| {
|
||||
let mut messages = vec![
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
value: color.map_or_else(TaggedValue::no_paint, TaggedValue::Color),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: BackupColorInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
];
|
||||
if let Some(color) = color {
|
||||
messages.push(
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: BackupColorInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
Message::Batched { messages: messages.into() }
|
||||
};
|
||||
|
||||
let gradient_set_messages = move |gradient: GradientStops| Message::Batched {
|
||||
let gradient_set_messages = move |gradient: Gradient| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
@@ -2585,7 +2622,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
solid_set_messages(color)
|
||||
}
|
||||
FillChoiceUI::Gradient(gradient_stops_ui) => {
|
||||
let gradient = GradientStops::from(gradient_stops_ui);
|
||||
let gradient = Gradient::from(gradient_stops_ui);
|
||||
gradient_set_messages(gradient)
|
||||
}
|
||||
})
|
||||
@@ -2602,7 +2639,11 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
let entries = vec![
|
||||
RadioEntryData::new("solid")
|
||||
.label("Solid")
|
||||
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::<List<Graphic>>::INDEX))
|
||||
.on_update(update_value(
|
||||
move |_| backup_color.map_or_else(TaggedValue::no_paint, TaggedValue::Color),
|
||||
node_id,
|
||||
FillInput::<List<Graphic>>::INDEX,
|
||||
))
|
||||
.on_commit(commit_value),
|
||||
RadioEntryData::new("gradient")
|
||||
.label("Gradient")
|
||||
@@ -2668,7 +2709,22 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
} else {
|
||||
"Swap the start and end points of the gradient line."
|
||||
})
|
||||
.on_update(update_value(move |_| TaggedValue::OptionalDAffine2(Some(new_transform)), node_id, TransformInput::INDEX))
|
||||
.on_update(move |_| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: HasTransformInput::INDEX,
|
||||
value: TaggedValue::Bool(true),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: TransformInput::INDEX,
|
||||
value: TaggedValue::DAffine2(new_transform),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.widget_instance();
|
||||
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
spread_methods_row.push(reverse_direction_button);
|
||||
@@ -2712,8 +2768,8 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
_ => &StrokeJoin::Miter,
|
||||
};
|
||||
|
||||
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::<List<f64>>::INDEX].as_value() {
|
||||
Some(TaggedValue::F64Array(values)) => values.is_empty(),
|
||||
let has_dash_lengths = match &document_node.inputs[DashPatternInput::INDEX].as_value() {
|
||||
Some(TaggedValue::DashPattern(pattern)) => pattern.0.is_empty(),
|
||||
_ => true,
|
||||
};
|
||||
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
|
||||
@@ -2739,10 +2795,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput::INDEX, true, context))
|
||||
.property_row();
|
||||
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
||||
let dash_lengths = array_of_number_widget(
|
||||
ParameterWidgetsInfo::new(node_id, DashLengthsInput::<List<f64>>::INDEX, true, context),
|
||||
TextInput::default().centered(true),
|
||||
);
|
||||
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput::INDEX, true, context), TextInput::default().centered(true));
|
||||
let number_input = disabled_number_input;
|
||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput::INDEX, true, context), number_input);
|
||||
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::Type;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use graphene_std::{Type, simplify_identifier_name};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -24,20 +19,22 @@ pub enum FrontendGraphDataType {
|
||||
|
||||
impl FrontendGraphDataType {
|
||||
pub fn from_type(input: &Type) -> Self {
|
||||
match TaggedValue::from_type_or_none(input) {
|
||||
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
|
||||
TaggedValue::Color(_) => Self::Color,
|
||||
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
|
||||
TaggedValue::String(_) => Self::Typography,
|
||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||
n if n == std::any::type_name::<List<Graphic>>() => Self::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => Self::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => Self::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => Self::Vector,
|
||||
n if n == std::any::type_name::<List<String>>() => Self::Typography,
|
||||
_ => Self::General,
|
||||
},
|
||||
// Color a wire by its element type, peeling a rank-0 `Item` or rank-1 `List` wrapper (and a whole-list `Bundle` cell) so all ranks share the element's color
|
||||
let nested_type = input.nested_type();
|
||||
let element = match nested_type.bundle_element_name() {
|
||||
Some(bundle_element) => simplify_identifier_name(bundle_element),
|
||||
None => nested_type.list_element().unwrap_or(nested_type).identifier_name(),
|
||||
};
|
||||
|
||||
match element.as_str() {
|
||||
"Vector" => Self::Vector,
|
||||
"Graphic" => Self::Graphic,
|
||||
"Artboard" => Self::Artboard,
|
||||
"Color" => Self::Color,
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -708,3 +708,103 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
// Autosaving the undone state still round-trips cleanly (no drift panic).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
|
||||
/// The document's single Fill node, as `(network_path, node_id)`.
|
||||
fn find_fill_node(document: &DocumentMessageHandler) -> (Vec<graph_craft::document::NodeId>, graph_craft::document::NodeId) {
|
||||
node_paths(&document.network_interface)
|
||||
.into_iter()
|
||||
.find(|(network_path, node_id)| {
|
||||
let Some(network) = document.network_interface.nested_network(network_path) else { return false };
|
||||
network.nodes[node_id].implementation == graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
})
|
||||
.expect("the document should contain a Fill node")
|
||||
}
|
||||
|
||||
/// The stored paint value of the document's single Fill node.
|
||||
fn fill_paint_value(document: &DocumentMessageHandler) -> graph_craft::document::value::TaggedValue {
|
||||
use graphene_std::NodeInputDecleration as _;
|
||||
|
||||
let (network_path, node_id) = find_fill_node(document);
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let input = network.nodes[&node_id]
|
||||
.inputs
|
||||
.get(graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX)
|
||||
.expect("Fill should have a paint input");
|
||||
input.as_value().expect("the paint input should hold a value").clone()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn none_fill_survives_document_reopen() {
|
||||
use graphene_std::NodeInputDecleration as _;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
|
||||
// Pick the red-slash "none" paint, stored the same way as the Fill widget's None choice
|
||||
let (_, fill_node_id) = find_fill_node(editor.active_document());
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: fill_node_id,
|
||||
input_index: graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX,
|
||||
value: graph_craft::document::value::TaggedValue::no_paint(),
|
||||
})
|
||||
.await;
|
||||
assert!(fill_paint_value(editor.active_document()).is_no_paint(), "the None pick should store as no_paint");
|
||||
|
||||
// Reopen through the editor's real open path, which runs the document migrations
|
||||
let serialized = editor.active_document().serialize_document();
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenDocumentFile {
|
||||
document_name: None,
|
||||
document_path: None,
|
||||
document_serialized_content: serialized,
|
||||
})
|
||||
.await;
|
||||
|
||||
let reopened_paint = fill_paint_value(editor.active_document());
|
||||
assert!(reopened_paint.is_no_paint(), "a none fill should survive reopening, but the stored paint became {reopened_paint:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration as _;
|
||||
|
||||
// A minimal master-era document: a 4-input Fill (content, fill: wired, backup color, backup gradient) fed by another node
|
||||
const LEGACY_DOCUMENT: &str = r#"{"network_interface":{"network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[1,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"OptionalColor":null},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::ops::SampleGradientNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]},"network_metadata":{"persistent_metadata":{"node_metadata":[[1,{"persistent_metadata":{"reference":"Fill","display_name":"","input_properties":[{"input_data":{"input_name":"Vector Data"},"widget_override":null},{"input_data":{"input_name":"Fill"},"widget_override":null},{"input_data":{"input_name":"Backup Color"},"widget_override":null},{"input_data":{"input_name":"Backup Gradient"},"widget_override":null}],"output_names":["Future<Instances<VectorData>>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[0,0]}}},"network_metadata":null}}],[2,{"persistent_metadata":{"reference":"Sample Gradient","display_name":"","input_properties":[{"input_data":{"input_name":"Primary"},"widget_override":null},{"input_data":{"input_name":"Gradient"},"widget_override":null},{"input_data":{"input_name":"Position"},"widget_override":null}],"output_names":["Future<Color>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[-20,0]}}},"network_metadata":null}}]],"previewing":"No","navigation_metadata":{"node_graph_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"node_graph_to_viewport":[1.0,0.0,0.0,1.0,0.0,0.0],"node_graph_top_right":[0.0,0.0]},"selection_undo_history":[],"selection_redo_history":[]}}},"collapsed":[],"name":"legacy_fill.graphite","commit_hash":"0000000000000000000000000000000000000000","document_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"document_mode":"DesignMode","view_mode":"Normal","overlays_visibility_settings":{"all":true,"artboard_name":true,"compass_rose":true,"quick_measurement":true,"transform_measurement":true,"transform_cage":true,"hover_outline":true,"selection_outline":true,"pivot":true,"path":true,"anchors":true,"handles":true},"rulers_visible":true,"snapping_state":{"snapping_enabled":true,"grid_snapping":false,"artboards":true,"tolerance":8.0,"bounding_box":{"center_point":true,"corner_point":true,"edge_midpoint":true,"align_with_edges":true,"distribute_evenly":true},"path":{"anchor_point":true,"line_midpoint":true,"along_path":true,"normal_to_path":true,"tangent_to_path":true,"path_intersection_point":true,"align_with_anchor_point":true,"perpendicular_from_endpoint":true},"grid":{"origin":[0.0,0.0],"grid_type":{"Rectangular":{"spacing":[1.0,1.0]}},"grid_color":{"red":0.6,"green":0.6,"blue":0.6,"alpha":1.0},"dot_display":false}},"graph_view_overlay_open":false,"graph_fade_artwork_percentage":80.0}"#;
|
||||
|
||||
// Deserializing alone must succeed, so a failure below is attributable to the migrations
|
||||
DocumentMessageHandler::deserialize_document(LEGACY_DOCUMENT).expect("the legacy document should deserialize");
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenDocumentFile {
|
||||
document_name: None,
|
||||
document_path: None,
|
||||
document_serialized_content: LEGACY_DOCUMENT.to_string(),
|
||||
})
|
||||
.await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let (network_path, node_id) = find_fill_node(document);
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let inputs = &network.nodes[&node_id].inputs;
|
||||
|
||||
assert_eq!(inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
|
||||
let paint = &inputs[graphene_std::vector::fill::FillInput::<graphene_std::list::List<graphene_std::Graphic>>::INDEX];
|
||||
assert!(
|
||||
matches!(paint, graph_craft::document::NodeInput::Node { .. }),
|
||||
"the wired legacy fill should keep its connection, but became {paint:?}"
|
||||
);
|
||||
let has_transform = inputs[graphene_std::vector::fill::HasTransformInput::INDEX].as_value();
|
||||
assert!(
|
||||
matches!(has_transform, Some(TaggedValue::Bool(_))),
|
||||
"the has-transform input should hold a bool, but became {has_transform:?}"
|
||||
);
|
||||
let transform = inputs[graphene_std::vector::fill::TransformInput::INDEX].as_value();
|
||||
assert!(
|
||||
matches!(transform, Some(TaggedValue::DAffine2(_))),
|
||||
"the transform input should hold a matrix, but became {transform:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
@@ -2499,14 +2499,20 @@ impl NodeNetworkInterface {
|
||||
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
|
||||
let path_string = vector_wire.to_svg();
|
||||
let data_type = self.input_type(&input, network_path).displayed_type();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let input_type = self.input_type(&input, network_path);
|
||||
let data_type = input_type.displayed_type();
|
||||
let is_list = input_type.is_list();
|
||||
let wire_path_update = Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed: false,
|
||||
is_list,
|
||||
center_path_string,
|
||||
});
|
||||
|
||||
Some(WirePathUpdate {
|
||||
@@ -2516,15 +2522,15 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the vector subpath and a boolean of whether the wire should be thick.
|
||||
pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> {
|
||||
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
|
||||
pub fn vector_wire_from_input(&mut self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
|
||||
let Some(input_position) = self.get_input_center(input, network_path) else {
|
||||
log::error!("Could not get dom rect for wire end: {input:?}");
|
||||
return None;
|
||||
};
|
||||
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector
|
||||
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
|
||||
return Some((BezPath::new(), false));
|
||||
return Some((BezPath::new(), BezPath::new(), false));
|
||||
};
|
||||
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
|
||||
log::error!("Could not get output port for wire start: {:?}", upstream_output);
|
||||
@@ -2533,21 +2539,29 @@ impl NodeNetworkInterface {
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
Some((build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style), thick))
|
||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
pub fn wire_path_from_input(&mut self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, network_path: &[NodeId]) -> Option<WirePath> {
|
||||
let (vector_wire, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
|
||||
let (vector_wire, center_line, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
|
||||
let path_string = vector_wire.to_svg();
|
||||
let data_type = self
|
||||
let center_path_string = center_line.to_svg();
|
||||
let (data_type, is_list) = self
|
||||
.upstream_output_connector(input, network_path)
|
||||
.map(|output| self.output_type(&output, network_path).displayed_type())
|
||||
.unwrap_or(FrontendGraphDataType::General);
|
||||
.map(|output| {
|
||||
let output_type = self.output_type(&output, network_path);
|
||||
(output_type.displayed_type(), output_type.is_list())
|
||||
})
|
||||
.unwrap_or((FrontendGraphDataType::General, false));
|
||||
Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed,
|
||||
is_list,
|
||||
center_path_string,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6105,6 +6119,19 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Chain is empty: wire the node as the first (and only) entry in the chain
|
||||
if matches!(current_input, NodeInput::Value { .. }) {
|
||||
// A node whose exposed primary defaults to no value inherits the layer's content value, so the chain keeps producing the layer's content type
|
||||
let node_primary = InputConnector::node(*node_id, 0);
|
||||
let default_is_valueless = self
|
||||
.input_from_connector(&node_primary, network_path)
|
||||
.is_some_and(|input| matches!(input, NodeInput::Value { tagged_value, exposed: true } if matches!(**tagged_value, TaggedValue::None)));
|
||||
if default_is_valueless {
|
||||
if import {
|
||||
self.set_input_for_import(&node_primary, current_input.clone(), network_path);
|
||||
} else {
|
||||
self.set_input(&node_primary, current_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Wire: [parent] -> [new node]
|
||||
if import {
|
||||
self.set_input_for_import(&parent_input, NodeInput::node(*node_id, 0), network_path);
|
||||
|
||||
+38
-22
@@ -4,11 +4,7 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::{Type, concrete};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
|
||||
@@ -56,28 +52,28 @@ impl TypeSource {
|
||||
return FrontendGraphDataType::Invalid;
|
||||
};
|
||||
match self.compiled_nested_type() {
|
||||
Some(nested_type) => match TaggedValue::from_type_or_none(nested_type) {
|
||||
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => {
|
||||
FrontendGraphDataType::Number
|
||||
}
|
||||
TaggedValue::Color(_) => FrontendGraphDataType::Color,
|
||||
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
|
||||
TaggedValue::String(_) => FrontendGraphDataType::Typography,
|
||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||
n if n == std::any::type_name::<List<Graphic>>() => FrontendGraphDataType::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => FrontendGraphDataType::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => FrontendGraphDataType::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => FrontendGraphDataType::Vector,
|
||||
n if n == std::any::type_name::<List<String>>() => FrontendGraphDataType::Typography,
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
Some(nested_type) => FrontendGraphDataType::from_type(nested_type),
|
||||
None => FrontendGraphDataType::General,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the compiled type is a rank-1 `List<T>`, as opposed to a rank-0 `Item<T>` or a bare value.
|
||||
/// A bundled cell carrying a whole list displays as the list it carries.
|
||||
pub fn is_list(&self) -> bool {
|
||||
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some())
|
||||
}
|
||||
|
||||
/// The element type's identifier name with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic.
|
||||
pub fn compiled_element_name(&self) -> Option<String> {
|
||||
let nested_type = self.compiled_nested_type()?;
|
||||
// A rank-0 `Item` or rank-1 `List` peels to its element; a bare value reports itself
|
||||
let element = match nested_type {
|
||||
Type::Item(element) | Type::List(element) => element.as_ref(),
|
||||
other => other,
|
||||
};
|
||||
Some(element.identifier_name())
|
||||
}
|
||||
|
||||
pub fn compiled_nested_type(&self) -> Option<&Type> {
|
||||
match self {
|
||||
TypeSource::Compiled(compiled_type) => Some(compiled_type.nested_type()),
|
||||
@@ -206,6 +202,19 @@ impl NodeNetworkInterface {
|
||||
concrete!(())
|
||||
}
|
||||
};
|
||||
|
||||
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0),
|
||||
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0
|
||||
if let Some(element) = guaranteed_type.nested_type().list_element()
|
||||
&& let Some(item_type) = self
|
||||
.potential_valid_input_types(input_connector, network_path)
|
||||
.into_iter()
|
||||
.find(|ty| matches!(ty.nested_type(), Type::Item(item_element) if item_element.as_ref() == element))
|
||||
&& let Some(item_default) = TaggedValue::from_type(&item_type)
|
||||
{
|
||||
return item_default;
|
||||
}
|
||||
|
||||
TaggedValue::from_type_or_none(&guaranteed_type)
|
||||
}
|
||||
|
||||
@@ -333,12 +342,19 @@ impl NodeNetworkInterface {
|
||||
pub fn output_type(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
|
||||
match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => {
|
||||
// A hidden node is replaced by a passthrough during flattening, so its output carries its primary input's type
|
||||
if *output_index == 0 && !self.is_visible(node_id, network_path) {
|
||||
return self.input_type(&InputConnector::node(*node_id, 0), network_path);
|
||||
}
|
||||
|
||||
// First try iterating upstream to the first protonode and try get its compiled type
|
||||
let Some(implementation) = self.implementation(node_id, network_path) else {
|
||||
return TypeSource::Error("Could not get implementation");
|
||||
};
|
||||
match implementation {
|
||||
DocumentNodeImplementation::Network(_) => self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat()),
|
||||
// The compiler removes passthrough nodes so they resolve no type of their own, but their output carries their primary input's type
|
||||
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => self.input_type(&InputConnector::node(*node_id, 0), network_path),
|
||||
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
|
||||
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
|
||||
None => TypeSource::Unknown,
|
||||
|
||||
@@ -12,6 +12,12 @@ pub struct WirePath {
|
||||
pub data_type: FrontendGraphDataType,
|
||||
pub thick: bool,
|
||||
pub dashed: bool,
|
||||
// A rank-1 `List<T>` wire renders as a doubled-up pair of parallel lines to distinguish it from a rank-0 `Item<T>` wire
|
||||
#[serde(rename = "isList")]
|
||||
pub is_list: bool,
|
||||
// A thick wire's center line reaches past the wire into the cleaved connector slots, so it needs its own longer path; empty otherwise
|
||||
#[serde(rename = "centerPathString")]
|
||||
pub center_path_string: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -57,6 +63,19 @@ impl GraphWireStyle {
|
||||
|
||||
pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
|
||||
let grid_spacing = 24.;
|
||||
|
||||
// A thick layer-stack wire (vertical at both ends) is skipped across a single straight grid cell where its connectors
|
||||
// already meet, and otherwise trimmed 3px inward at each end since it overshoots the connectors.
|
||||
let (output_position, input_position) = if vertical_out && vertical_in {
|
||||
if thick_wire_spans_single_cell(output_position, input_position) {
|
||||
return BezPath::new();
|
||||
}
|
||||
let trim = 3. * (input_position.y - output_position.y).signum();
|
||||
(output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim))
|
||||
} else {
|
||||
(output_position, input_position)
|
||||
};
|
||||
|
||||
match graph_wire_style {
|
||||
GraphWireStyle::Direct => {
|
||||
let horizontal_gap = (output_position.x - input_position.x).abs();
|
||||
@@ -101,6 +120,31 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
|
||||
}
|
||||
}
|
||||
|
||||
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
|
||||
let grid_spacing = 24.;
|
||||
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
||||
}
|
||||
|
||||
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
|
||||
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
||||
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
|
||||
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
|
||||
return BezPath::new();
|
||||
}
|
||||
|
||||
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let output_trim = 1.5;
|
||||
let input_trim = 1.;
|
||||
let start = output_position + DVec2::new(0., output_trim * sign);
|
||||
let end = input_position - DVec2::new(0., input_trim * sign);
|
||||
|
||||
let mut center_line = BezPath::new();
|
||||
center_line.move_to(dvec2_to_point(start));
|
||||
center_line.line_to(dvec2_to_point(end));
|
||||
center_line
|
||||
}
|
||||
|
||||
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
|
||||
let grid_spacing = 24;
|
||||
let line_width = 2;
|
||||
|
||||
@@ -7,15 +7,18 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Inp
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
use graph_craft::{Type, item};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::misc::BoxCorners;
|
||||
use graphene_std::vector::style::{DashPattern, PaintOrder, StrokeAlign};
|
||||
use std::collections::HashMap;
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -32,6 +35,9 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
|
||||
("\"OptionalF64\":", "\"F64\":"),
|
||||
("\"path_bool_nodes::BooleanOperation\"", "\"vector_types::vector::misc::BooleanOperation\""),
|
||||
("\"core_types::table::Table<", "\"core_types::list::List<"),
|
||||
// The `GradientStops` type was renamed to `Gradient`; stale stored output names are cleared so the display falls back to the live type name
|
||||
("\"output_names\":[\"GradientStops\"]", "\"output_names\":[\"\"]"),
|
||||
("vector_types::gradient::GradientStops", "vector_types::gradient::Gradient"),
|
||||
];
|
||||
|
||||
pub struct NodeReplacement<'a> {
|
||||
@@ -87,10 +93,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::animation::animation_time::IDENTIFIER,
|
||||
aliases: &["graphene_core::animation::AnimationTimeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::clone::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::CloneNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::extract_xy::extract_xy::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::ExtractXyNode"],
|
||||
@@ -106,6 +108,14 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::transform_nodes::FreezeRealTimeNode",
|
||||
"graphene_core::vector::SubpathSegmentLengthsNode",
|
||||
"core_types::vector::SubpathSegmentLengthsNode",
|
||||
// The deleted debug Option trio degrades to a passthrough of its single input (audit resolution 8)
|
||||
"graphene_core::ops::SizeOfNode",
|
||||
"graphene_core::debug::SizeOfNode",
|
||||
"graphene_core::ops::SomeNode",
|
||||
"graphene_core::debug::SomeNode",
|
||||
"graphene_core::ops::UnwrapNode",
|
||||
"graphene_core::debug::UnwrapNode",
|
||||
"graphene_core::debug::UnwrapOptionNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -120,18 +130,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::animation::real_time::IDENTIFIER,
|
||||
aliases: &["graphene_core::animation::RealTimeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::size_of::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::SizeOfNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::some::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::SomeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::debug::unwrap_option::IDENTIFIER,
|
||||
aliases: &["graphene_core::ops::UnwrapNode", "graphene_core::debug::UnwrapNode"],
|
||||
},
|
||||
// ================================
|
||||
// graphic
|
||||
// ================================
|
||||
@@ -161,13 +159,19 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::index_elements::IDENTIFIER,
|
||||
node: graphene_std::graphic::item_at_index::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::graphic_element::IndexNode",
|
||||
"graphene_core::graphic::IndexNode",
|
||||
"graphene_core::graphic::IndexElementsNode",
|
||||
"graphic_nodes::graphic::IndexElementsNode",
|
||||
"graphic_nodes::graphic::ExtractElementNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::remove_at_index::IDENTIFIER,
|
||||
aliases: &["graphic_nodes::graphic::OmitElementNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::legacy_layer_extend::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -735,8 +739,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
// vector
|
||||
// ================================
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::apply_transform::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::ApplyTransformNode", "graphene_core::vector::vector_modification::ApplyTransformNode"],
|
||||
node: graphene_std::vector::bake_transform::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::vector::ApplyTransformNode",
|
||||
"graphene_core::vector::vector_modification::ApplyTransformNode",
|
||||
"vector_nodes::vector_modification_nodes::ApplyTransformNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::area::IDENTIFIER,
|
||||
@@ -771,7 +779,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::ClosePathNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::count_elements::IDENTIFIER,
|
||||
node: graphene_std::vector::list_length::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::CountElementsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -1121,6 +1129,7 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
|
||||
|
||||
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
|
||||
document.network_interface.migrate_path_modify_node();
|
||||
document.network_interface.document_network_mut().normalize_stored_types();
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
|
||||
@@ -1285,9 +1294,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> "Text to Vector" pair, which reuses the same
|
||||
// proto identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current
|
||||
// 12-input node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and move it onto `text_to_vector`.
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
|
||||
// identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input
|
||||
// node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and splice the matching converter after it.
|
||||
let old_text_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
@@ -1321,7 +1330,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, new_index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
let separate_glyphs = old_inputs.get(12).cloned();
|
||||
// A `true` toggle at index 12 chose per-glyph geometry, which is now the dedicated "Text to Vector Glyphs" node
|
||||
let separate_glyphs = matches!(old_inputs.get(12).and_then(|input| input.as_value()), Some(TaggedValue::Bool(true)));
|
||||
|
||||
// Collect the inputs reading the old text node's output before any rewiring so the new node can be spliced onto those wires.
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
@@ -1333,44 +1343,62 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
|
||||
let text_was_in_chain = text_nodes_in_chain.contains(node_id);
|
||||
|
||||
// Insert the `text_to_vector` node that converts the `text` `String[]` output back into vector geometry.
|
||||
let Some(text_to_vector_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER)) else {
|
||||
// Insert the converter that turns the `text` `String[]` output back into vector geometry: "Text to Vector Glyphs" for the per-glyph case, otherwise "Text to Vector".
|
||||
let converter_identifier = if separate_glyphs {
|
||||
graphene_std::text::text_to_vector_glyphs::IDENTIFIER
|
||||
} else {
|
||||
graphene_std::text::text_to_vector::IDENTIFIER
|
||||
};
|
||||
let Some(converter_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(converter_identifier)) else {
|
||||
continue;
|
||||
};
|
||||
let text_to_vector_id = NodeId::new();
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(text_to_vector_id, text_to_vector_definition.default_node_template(), network_path);
|
||||
let converter_id = NodeId::new();
|
||||
document.network_interface.insert_node(converter_id, converter_definition.default_node_template(), network_path);
|
||||
|
||||
// Splice `text_to_vector` onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for
|
||||
// dropping a node on a wire), then carry the old `separate_glyphs` value onto its second input.
|
||||
// Splice the converter onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for dropping a node on a wire).
|
||||
if let Some((first_consumer, remaining_consumers)) = downstream_consumers.split_first() {
|
||||
document.network_interface.insert_node_between(&text_to_vector_id, first_consumer, 0, network_path);
|
||||
document.network_interface.insert_node_between(&converter_id, first_consumer, 0, network_path);
|
||||
for consumer in remaining_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(text_to_vector_id, 0), network_path);
|
||||
document.network_interface.set_input(consumer, NodeInput::node(converter_id, 0), network_path);
|
||||
}
|
||||
} else {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(text_to_vector_id, 0), NodeInput::node(*node_id, 0), network_path);
|
||||
}
|
||||
if let Some(separate_glyphs) = separate_glyphs {
|
||||
document.network_interface.set_input(&InputConnector::node(text_to_vector_id, 1), separate_glyphs, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(converter_id, 0), NodeInput::node(*node_id, 0), network_path);
|
||||
}
|
||||
|
||||
// If `text` was in a layer chain, re-chain `text_to_vector` and its upstream so both lay out by distance from the layer (the splice
|
||||
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place `text_to_vector` beside it instead of
|
||||
// If `text` was in a layer chain, re-chain the converter and its upstream so both lay out by distance from the layer (the splice
|
||||
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place the converter beside it instead of
|
||||
// leaving it at the origin.
|
||||
if text_was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&text_to_vector_id, network_path);
|
||||
document.network_interface.force_set_upstream_to_chain(&converter_id, network_path);
|
||||
} else if let Some(text_position) = document.network_interface.position(node_id, network_path) {
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&text_to_vector_id, text_position + IVec2::new(7, 0), network_path);
|
||||
document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let pattern = match &*tagged_value.clone().into_inner() {
|
||||
TaggedValue::F64Array(lengths) => DashPattern::from(lengths.clone()),
|
||||
TaggedValue::F64(length) => DashPattern::from(*length),
|
||||
TaggedValue::String(text) => DashPattern::from(text.as_str()),
|
||||
_ => return None,
|
||||
};
|
||||
Some(NodeInput::value(TaggedValue::DashPattern(pattern), *exposed))
|
||||
}
|
||||
|
||||
/// Converts a legacy rectangle corner radius input (a single `f64` or a `List<f64>` of up to four values) to the `BoxCorners` value type.
|
||||
fn migrate_corner_radius_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let corners = match &*tagged_value.clone().into_inner() {
|
||||
TaggedValue::F64Array(values) => BoxCorners::from(values.clone()),
|
||||
TaggedValue::F64(value) => BoxCorners::from(*value),
|
||||
_ => return None,
|
||||
};
|
||||
Some(NodeInput::value(TaggedValue::BoxCorners(corners), *exposed))
|
||||
}
|
||||
|
||||
fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) -> Option<()> {
|
||||
// Must run before the reset block below: a node referencing a removed catalog entry would otherwise abort
|
||||
// `migrate_node` via the `?` on `resolve_document_node_type`, preventing subsequent migration blocks from running.
|
||||
@@ -1572,8 +1600,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 5;
|
||||
}
|
||||
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the
|
||||
// value-model 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _transform).
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
||||
// 8-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _has_transform, _transform).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
@@ -1582,21 +1610,21 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// Content: no change
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
// Fill: a literal Fill value is decomposed, and a wired input (`List<GradientStops> / List<Color>`) is kept as-is
|
||||
// Fill: a literal Fill value is decomposed, and a wired input (`List<Gradient> / List<Color>`) is kept as-is
|
||||
match old_inputs[1].as_value() {
|
||||
Some(TaggedValue::LegacyFill(old_fill)) => {
|
||||
let exposed = old_inputs[1].is_exposed();
|
||||
let fill_value = match old_fill {
|
||||
graphic_types::migrations::legacy::Fill::None => TaggedValue::Color(None),
|
||||
graphic_types::migrations::legacy::Fill::Solid(color) => TaggedValue::Color(Some(*color)),
|
||||
graphic_types::migrations::legacy::Fill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
|
||||
graphic_types::migrations::legacy::LegacyFill::None => TaggedValue::no_paint(),
|
||||
graphic_types::migrations::legacy::LegacyFill::Solid(color) => TaggedValue::Color(*color),
|
||||
graphic_types::migrations::legacy::LegacyFill::Gradient(gradient) => TaggedValue::Gradient(gradient.stops.clone()),
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(fill_value, exposed), network_path);
|
||||
|
||||
// Gradient metadata (4, 5, 6): applies only to a literal gradient, solids/none keep the template defaults
|
||||
if let graphic_types::migrations::legacy::Fill::Gradient(gradient) = old_fill {
|
||||
// Gradient metadata (4, 5, 6, 7): applies only to a literal gradient, solids/none keep the template defaults
|
||||
if let graphic_types::migrations::legacy::LegacyFill::Gradient(gradient) = old_fill {
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 4),
|
||||
NodeInput::value(TaggedValue::GradientType(gradient.gradient_type), false),
|
||||
@@ -1608,20 +1636,23 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
network_path,
|
||||
);
|
||||
|
||||
let transform = if gradient.absolute {
|
||||
Some(gradient.transform * gradient.to_transform())
|
||||
if gradient.absolute {
|
||||
let transform = gradient.transform * gradient.to_transform();
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
} else {
|
||||
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint target's bounds
|
||||
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint
|
||||
// target's bounds, so the template's unbaked `_has_transform = false` stands until the bake lands
|
||||
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, gradient.clone()));
|
||||
None
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wired/exposed fill keeps the connection.
|
||||
// The generic paint connector accepts the existing `List<Color>`/`List<GradientStops>` paint sources directly.
|
||||
// The generic paint connector accepts the existing `List<Color>`/`List<Gradient>` paint sources directly.
|
||||
_ => {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
@@ -1640,7 +1671,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
if matches!(
|
||||
old_inputs[1].as_value(),
|
||||
Some(TaggedValue::LegacyFill(
|
||||
graphic_types::migrations::legacy::Fill::None | graphic_types::migrations::legacy::Fill::Solid(_)
|
||||
graphic_types::migrations::legacy::LegacyFill::None | graphic_types::migrations::legacy::LegacyFill::Solid(_)
|
||||
))
|
||||
) {
|
||||
document
|
||||
@@ -1652,19 +1683,54 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
network_path,
|
||||
);
|
||||
|
||||
let transform = if g.absolute {
|
||||
Some(g.transform * g.to_transform())
|
||||
if g.absolute {
|
||||
let transform = g.transform * g.to_transform();
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
} else {
|
||||
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, g.clone()));
|
||||
None
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = 7;
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.iter().enumerate().take(6) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
|
||||
match old_inputs.get(6).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::LegacyOptionalDAffine2(value)) => {
|
||||
let has_transform = value.is_some();
|
||||
let transform = value.unwrap_or(glam::DAffine2::IDENTITY);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(has_transform), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
}
|
||||
// A wired (or otherwise non-value) transform keeps its connection and is treated as present
|
||||
_ => {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
let transform_input = old_inputs.get(6).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::DAffine2(glam::DAffine2::IDENTITY), false));
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), transform_input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
|
||||
@@ -1683,10 +1749,111 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[6].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 6), old_inputs[7].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), paint_order_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[3].clone(), network_path);
|
||||
let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone());
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), dash_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 9), old_inputs[4].clone(), network_path);
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
// A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color,
|
||||
// since only paint connectors keep the no-paint choice
|
||||
{
|
||||
let migrate_color_input = |input: &NodeInput, fallback: Color| -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
if !tagged_value.is_no_paint() {
|
||||
return None;
|
||||
}
|
||||
Some(NodeInput::value(TaggedValue::Color(fallback), *exposed))
|
||||
};
|
||||
|
||||
let conversions: &[(ProtoNodeIdentifier, usize, Color)] = &[
|
||||
(graphene_std::vector::fill::IDENTIFIER, graphene_std::vector::fill::BackupColorInput::INDEX, Color::BLACK),
|
||||
(
|
||||
graphene_std::artboard::create_artboard::IDENTIFIER,
|
||||
graphene_std::artboard::create_artboard::BackgroundInput::INDEX,
|
||||
Color::WHITE,
|
||||
),
|
||||
(
|
||||
graphene_std::math_nodes::color_value::IDENTIFIER,
|
||||
graphene_std::math_nodes::color_value::ColorInput::INDEX,
|
||||
Color::TRANSPARENT,
|
||||
),
|
||||
(
|
||||
graphene_std::raster_nodes::adjustments::black_and_white::IDENTIFIER,
|
||||
graphene_std::raster_nodes::adjustments::black_and_white::TintInput::INDEX,
|
||||
Color::BLACK,
|
||||
),
|
||||
(
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput::INDEX,
|
||||
Color::BLACK,
|
||||
),
|
||||
(
|
||||
graphene_std::raster_nodes::std_nodes::empty_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::empty_image::ColorInput::INDEX,
|
||||
Color::WHITE,
|
||||
),
|
||||
];
|
||||
for &(ref identifier, index, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(identifier.clone()) {
|
||||
continue;
|
||||
}
|
||||
let Some(input) = node.inputs.get(index) else { continue };
|
||||
if let Some(migrated) = migrate_color_input(input, fallback) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), migrated, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The stroke dash sequence became the `DashPattern` value type; convert any already-shaped stroke that still stores a legacy dash input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER)
|
||||
&& let Some(dash_input) = node.inputs.get(graphene_std::vector::stroke::DashPatternInput::INDEX)
|
||||
&& let Some(migrated) = migrate_dash_input(dash_input)
|
||||
{
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, graphene_std::vector::stroke::DashPatternInput::INDEX), migrated, network_path);
|
||||
}
|
||||
|
||||
// The rectangle's corner radius became the `BoxCorners` value type and its hidden individual-radii toggle moved after the
|
||||
// user-visible inputs. A legacy rectangle stores that toggle (a plain `bool`) at index 3, where the new shape stores the corner
|
||||
// radius, so a `bool` value there identifies the old input order: [width, height, individual, corner_radius, clamped].
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
|
||||
&& let Some(toggle_input) = node.inputs.get(3)
|
||||
&& matches!(toggle_input.as_value(), Some(TaggedValue::Bool(_)))
|
||||
{
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
let corner_radius = migrate_corner_radius_input(&old_inputs[4]).unwrap_or_else(|| old_inputs[4].clone());
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 3), corner_radius, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[5].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
|
||||
// The Text to Vector node's runtime `separate_glyphs` toggle became the dedicated "Text to Vector Glyphs" node, leaving Text to Vector as a plain
|
||||
// string-to-compound-path converter. A 2-input Text to Vector is the old toggled shape: a `true` toggle routes to Text to Vector Glyphs, otherwise
|
||||
// the node stays Text to Vector; either way the toggle input is dropped and the string wire is preserved.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER) && inputs_count == 2 {
|
||||
let separate_glyphs = matches!(node.inputs.get(1).and_then(|input| input.as_value()), Some(TaggedValue::Bool(true)));
|
||||
let target = if separate_glyphs {
|
||||
graphene_std::text::text_to_vector_glyphs::IDENTIFIER
|
||||
} else {
|
||||
graphene_std::text::text_to_vector::IDENTIFIER
|
||||
};
|
||||
|
||||
let mut node_template = resolve_proto_node_type(target)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
if let Some(string_input) = node.inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), string_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 8 {
|
||||
let mut template: NodeTemplate = legacy_text_node_template()?;
|
||||
@@ -1986,6 +2153,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// A brush node saved before `Item<Raster<CPU>>` had a default stored its unconnected background as the invalid `()`,
|
||||
// which fails type resolution against the raster primary; adopt the definition's empty-raster default instead.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER) && matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::None)) {
|
||||
let default_background = resolve_document_node_type(&reference)?.node_template.document_node.inputs.first()?.clone();
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), default_background, network_path);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::RemoveHandlesNode")) {
|
||||
let mut node_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::auto_tangents::IDENTIFIER))?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
@@ -2202,7 +2376,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// Migrate from the v2 "Morph" node (2 inputs: content, progression) to the v3 "Morph" node (5 inputs: content, progression, reverse, distribution, path).
|
||||
// The old progression used integer part for pair selection (range 0..N-1 where N is the number of content objects).
|
||||
// The new progression uses fractional 0..1 for euclidean traversal through all objects.
|
||||
// We insert Count Elements → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
|
||||
// We insert List Length → Subtract 1 → Divide to remap: new_progression = old_progression / (N - 1).
|
||||
// For the common 2-object case (N=2), this divides by 1 which is a no-op, preserving identical behavior.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::morph::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2217,14 +2391,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
return None;
|
||||
};
|
||||
|
||||
// Create Count Elements node: counts content `List` items → N
|
||||
let Some(count_elements_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::count_elements::IDENTIFIER)) else {
|
||||
log::error!("Could not get count_elements node from definition when upgrading morph");
|
||||
// Create List Length node: counts content `List` items → N
|
||||
let Some(list_length_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::list_length::IDENTIFIER)) else {
|
||||
log::error!("Could not get list_length node from definition when upgrading morph");
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
return None;
|
||||
};
|
||||
let count_elements_template = count_elements_def.default_node_template();
|
||||
let count_elements_id = NodeId::new();
|
||||
let list_length_template = list_length_def.default_node_template();
|
||||
let list_length_id = NodeId::new();
|
||||
|
||||
// Create Subtract node: N → N-1
|
||||
let Some(subtract_def) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER)) else {
|
||||
@@ -2246,10 +2420,10 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let divide_id = NodeId::new();
|
||||
|
||||
// Insert and position nodes
|
||||
document.network_interface.insert_node(count_elements_id, count_elements_template, network_path);
|
||||
document.network_interface.insert_node(list_length_id, list_length_template, network_path);
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&count_elements_id, morph_position + IVec2::new(-21, 2), network_path);
|
||||
.shift_absolute_node_position(&list_length_id, morph_position + IVec2::new(-21, 2), network_path);
|
||||
|
||||
document.network_interface.insert_node(subtract_id, subtract_template, network_path);
|
||||
document.network_interface.shift_absolute_node_position(&subtract_id, morph_position + IVec2::new(-14, 2), network_path);
|
||||
@@ -2257,13 +2431,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.insert_node(divide_id, divide_template, network_path);
|
||||
document.network_interface.shift_absolute_node_position(÷_id, morph_position + IVec2::new(-7, 1), network_path);
|
||||
|
||||
// Wire: content source → Count Elements input 0
|
||||
document.network_interface.set_input(&InputConnector::node(count_elements_id, 0), old_inputs[0].clone(), network_path);
|
||||
// Wire: content source → List Length input 0
|
||||
document.network_interface.set_input(&InputConnector::node(list_length_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
// Wire: Count Elements output → Subtract input 0 (minuend)
|
||||
// Wire: List Length output → Subtract input 0 (minuend)
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(count_elements_id, 0), network_path);
|
||||
.set_input(&InputConnector::node(subtract_id, 0), NodeInput::node(list_length_id, 0), network_path);
|
||||
|
||||
// Wire: old progression → Divide input 0 (numerator)
|
||||
document.network_interface.set_input(&InputConnector::node(divide_id, 0), old_inputs[1].clone(), network_path);
|
||||
@@ -2444,11 +2618,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let modification = modification.clone();
|
||||
let was_exposed = *exposed;
|
||||
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, 0),
|
||||
NodeInput::type_default(descriptor!(graphene_std::list::List<graphene_std::vector::Vector>), true),
|
||||
network_path,
|
||||
);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 0), NodeInput::type_default(item!(graphene_std::vector::Vector), true), network_path);
|
||||
|
||||
if !was_exposed {
|
||||
document
|
||||
@@ -2480,6 +2652,34 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
|
||||
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
|
||||
if let Some(definition) = resolve_document_node_type(&reference) {
|
||||
let definition_inputs = definition.node_template.document_node.inputs.clone();
|
||||
for (index, definition_input) in definition_inputs.iter().enumerate() {
|
||||
if !matches!(definition_input, NodeInput::Value { .. }) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let stale_list_default = document
|
||||
.network_interface
|
||||
.input_from_connector(&InputConnector::node(*node_id, index), network_path)
|
||||
.is_some_and(|stored_input| match stored_input {
|
||||
NodeInput::Value { tagged_value, .. } => match &**tagged_value {
|
||||
TaggedValue::TypeDefault(stored_type) if matches!(stored_type, Type::List(_)) && !tagged_value.is_no_paint() => {
|
||||
!matches!(definition_input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, TaggedValue::TypeDefault(definition_type) if definition_type == stored_type))
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
});
|
||||
|
||||
if stale_list_default {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), definition_input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// PUT ALL MIGRATIONS ABOVE THIS LINE
|
||||
// ==================================
|
||||
@@ -2565,6 +2765,31 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
}
|
||||
}
|
||||
|
||||
// The removed Attach Attribute node (merged into Write Attribute per audit resolution 6) degrades to a passthrough of its
|
||||
// content: its eager whole-list source input cannot be mechanically rewired as Write Attribute's lazy per-item value producer.
|
||||
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
|
||||
&& identifier.as_str().ends_with("::AttachAttributeNode")
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
if let Some(content) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Upload Texture node's old wrapper-network form maps onto its proto node form, which draws the executor from scope
|
||||
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
|
||||
&& name == "Upload Texture"
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
if let Some(content) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), content.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
@@ -2572,6 +2797,13 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// The removed-definition blocks above abort silently via `?` if their swap target ever leaves the catalog
|
||||
#[test]
|
||||
fn removed_definition_swap_targets_resolve() {
|
||||
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
|
||||
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
|
||||
@@ -4,18 +4,18 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, GradientSpreadMethod, GradientType, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::{Color, Graphic};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -310,7 +310,7 @@ pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &No
|
||||
}
|
||||
|
||||
/// Get the gradient stops of a layer, if any.
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||
// Try to find the gradient stops value that is created by a Fill node first
|
||||
if let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
|
||||
return network_interface
|
||||
@@ -329,7 +329,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(stops.clone())
|
||||
}
|
||||
|
||||
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<GradientStops>`
|
||||
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<Gradient>`
|
||||
/// layer this is the layer's incoming footprint transform; for a Fill-owned gradient value it composes the layer's viewport
|
||||
/// transform with the [0,1]² → bounding-box mapping.
|
||||
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
|
||||
@@ -363,10 +363,10 @@ pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
|
||||
/// Get the current fill of a layer from the closest "Fill" node.
|
||||
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
||||
let TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
color
|
||||
Some(*color)
|
||||
}
|
||||
|
||||
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
|
||||
@@ -570,8 +570,8 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashPatternInput::INDEX) {
|
||||
Some(TaggedValue::DashPattern(value)) => value.0.iter_element_values().copied().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
|
||||
@@ -626,7 +626,7 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
|
||||
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
|
||||
pub struct FillNodeGradient {
|
||||
pub stops: GradientStops,
|
||||
pub stops: Gradient,
|
||||
pub gradient_type: GradientType,
|
||||
pub spread_method: GradientSpreadMethod,
|
||||
pub transform: DAffine2,
|
||||
@@ -649,9 +649,11 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
let has_transform = matches!(fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
|
||||
let transform = match transform_input {
|
||||
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
|
||||
let transform = match (has_transform, transform_input) {
|
||||
(true, Some(&TaggedValue::DAffine2(value))) => value,
|
||||
(false, _) => initial_gradient_transform_for_bounding_box(bounding_box()),
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -667,7 +669,11 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
||||
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
||||
match tagged {
|
||||
TaggedValue::Color(color) => Some(Some(*color)),
|
||||
value if value.is_no_paint() => Some(None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregated fill state across all selected non-artboard layers.
|
||||
@@ -687,7 +693,7 @@ pub struct SelectedStrokeState {
|
||||
}
|
||||
|
||||
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is the no-paint choice.
|
||||
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
@@ -700,8 +706,9 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
|
||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
|
||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
||||
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
|
||||
TaggedValue::Color(color) => Some(FillChoice::Solid(*color)),
|
||||
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
|
||||
value if value.is_no_paint() => Some(FillChoice::None),
|
||||
_ => None,
|
||||
}
|
||||
})()
|
||||
@@ -799,10 +806,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
|
||||
Some(TaggedValue::OptionalDAffine2(value)) => {
|
||||
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
|
||||
}
|
||||
let has_transform = matches!(read(graphene_std::vector::fill::HasTransformInput::INDEX), Some(TaggedValue::Bool(true)));
|
||||
let transform = match (has_transform, read(graphene_std::vector::fill::TransformInput::INDEX)) {
|
||||
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
||||
(false, _) => initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)),
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -826,7 +833,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
let value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(weight);
|
||||
@@ -977,6 +984,6 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
||||
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
|
||||
|
||||
layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<GPU>>))
|
||||
matches!(layer_input_type.compiled_element_name().as_deref(), Some("Raster<CPU>" | "Raster<GPU>"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,7 +421,7 @@ impl ShapeState {
|
||||
(point.as_handle().is_some() && self.ignore_handles) || (point.as_anchor().is_some() && self.ignore_anchors)
|
||||
}
|
||||
|
||||
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a «Flatten Path» node.
|
||||
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a Flatten Path node.
|
||||
fn add_dummy_modification_to_trigger_graph_reorganization(layer: LayerNodeIdentifier, start_point: PointId, _end_point: PointId, responses: &mut VecDeque<Message>) {
|
||||
// Apply a zero-delta to one of the points to trigger reorganization
|
||||
let dummy_modification = VectorModificationType::ApplyPointDelta {
|
||||
|
||||
@@ -75,8 +75,8 @@ mod test_ellipse {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
|
||||
Some(ResolvedEllipse {
|
||||
radius_x: instrumented.grab_protonode_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_protonode_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
transform: document.metadata().transform_to_document(layer),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// All non-color stroke-related options surfaced in the control bar popover.
|
||||
@@ -215,7 +214,7 @@ pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, docu
|
||||
|
||||
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_lengths = Some(lengths.clone());
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX, TaggedValue::F64Array(lengths), responses);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashPatternInput::INDEX, TaggedValue::DashPattern(lengths.into()), responses);
|
||||
}
|
||||
|
||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
|
||||
@@ -11,9 +11,7 @@ use crate::messages::tool::common_functionality::transformation_cage::SelectedEd
|
||||
use crate::messages::tool::tool_messages::path_tool::PathOverlayMode;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::subpath::{Bezier, BezierHandles};
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
|
||||
@@ -568,11 +566,11 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
|
||||
}
|
||||
for _ in selected_layers {}
|
||||
|
||||
// Must be a layer of type List<Vector>
|
||||
// Must be a vector layer, at either rank
|
||||
let node_id = NodeGraphLayer::new(first_layer, network_interface).horizontal_layer_flow().nth(1)?;
|
||||
|
||||
let output_type = network_interface.output_type(&OutputConnector::node(node_id, 0), &[]);
|
||||
if output_type.compiled_nested_type() != Some(&concrete!(List<Vector>)) {
|
||||
if output_type.compiled_element_name().as_deref() != Some("Vector") {
|
||||
return None;
|
||||
}
|
||||
|
||||
|
||||
@@ -205,17 +205,19 @@ impl Fsm for FillToolFsmState {
|
||||
#[cfg(test)]
|
||||
mod test_fill {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<Color>> {
|
||||
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
|
||||
instrumented.grab_all_input::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
|
||||
instrumented.grab_all_input_as::<fill::FillInput<List<Graphic>>, Item<Color>>(&editor.runtime).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -245,7 +247,7 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
||||
let color = fills.first().unwrap().element();
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
|
||||
}
|
||||
|
||||
@@ -258,7 +260,7 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
||||
let color = fills.first().unwrap().element();
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ use glam::DMat2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStop, GradientStops, GradientStopsUI, GradientType, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, Gradient, GradientSpreadMethod, GradientStop, GradientType, GradientUI, build_transform_with_y_preservation};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
pub struct GradientTool {
|
||||
@@ -53,7 +53,7 @@ pub enum GradientToolMessage {
|
||||
CommitTransactionForColorStop,
|
||||
CloseStopColorPicker,
|
||||
UpdateStopColor { color: Color },
|
||||
UpdateStops { stops: GradientStopsUI },
|
||||
UpdateStops { stops: GradientUI },
|
||||
UpdateOptions { options: GradientOptionsUpdate },
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
}
|
||||
}
|
||||
ToolMessage::Gradient(GradientToolMessage::UpdateStops { stops }) => {
|
||||
apply_stops_update(&mut self.data, context, responses, GradientStops::from(&stops));
|
||||
apply_stops_update(&mut self.data, context, responses, Gradient::from(&stops));
|
||||
}
|
||||
ToolMessage::Gradient(GradientToolMessage::CloseStopColorPicker) => {
|
||||
if self.data.color_picker_transaction_open {
|
||||
@@ -264,7 +264,7 @@ impl LayoutHolder for GradientTool {
|
||||
.or_else(|| self.data.default_gradient_stops.clone())
|
||||
.map(FillChoice::Gradient)
|
||||
.unwrap_or_else(|| {
|
||||
FillChoice::Gradient(GradientStops::new([
|
||||
FillChoice::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -389,7 +389,7 @@ enum GradientSource {
|
||||
}
|
||||
|
||||
/// Get the gradient with appearance information from Fill node values, or the chain connected to Fill node / layer.
|
||||
fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(GradientStops, GradientAppearance, GradientSource)> {
|
||||
fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(Gradient, GradientAppearance, GradientSource)> {
|
||||
if let Some(stops) = get_gradient_stops(layer, network_interface) {
|
||||
// A Fill node holding a direct gradient value decodes through the shared reader
|
||||
if let Some(fill_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
|
||||
@@ -521,15 +521,15 @@ struct SelectedGradient {
|
||||
dragging: GradientDragTarget,
|
||||
/// Transform from the geometry's local gradient space to viewport space.
|
||||
gradient_space_transform: DAffine2,
|
||||
gradient: GradientStops,
|
||||
gradient: Gradient,
|
||||
appearance: GradientAppearance,
|
||||
initial_gradient: GradientStops,
|
||||
initial_gradient: Gradient,
|
||||
/// Transform from unit [0, 1] line to the geometry's local gradient space, the snapshot from `GradientAppearance.transform`.
|
||||
initial_gradient_transform: DAffine2,
|
||||
is_gradient_chain: bool,
|
||||
}
|
||||
|
||||
fn calculate_insertion(start: DVec2, end: DVec2, stops: &GradientStops, mouse: DVec2) -> Option<f64> {
|
||||
fn calculate_insertion(start: DVec2, end: DVec2, stops: &Gradient, mouse: DVec2) -> Option<f64> {
|
||||
let distance = (end - start).angle_to(mouse - start).sin() * (mouse - start).length();
|
||||
let projection = ((end - start).angle_to(mouse - start)).cos() * start.distance(mouse) / start.distance(end);
|
||||
|
||||
@@ -568,7 +568,7 @@ fn calculate_insertion(start: DVec2, end: DVec2, stops: &GradientStops, mouse: D
|
||||
}
|
||||
|
||||
impl SelectedGradient {
|
||||
pub fn new(gradient: GradientStops, appearance: GradientAppearance, source: GradientSource, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
|
||||
pub fn new(gradient: Gradient, appearance: GradientAppearance, source: GradientSource, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
|
||||
let gradient_space_transform = gradient_space_transform(layer, document);
|
||||
Self {
|
||||
layer: Some(layer),
|
||||
@@ -820,7 +820,7 @@ impl SelectedGradient {
|
||||
}
|
||||
|
||||
/// Send the four per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &GradientStops, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
responses.add(GraphOperationMessage::GradientStopsSet { layer, stops: gradient.clone() });
|
||||
responses.add(GraphOperationMessage::GradientTransformSet {
|
||||
layer,
|
||||
@@ -868,11 +868,11 @@ struct GradientToolData {
|
||||
has_selected_gradient: bool,
|
||||
/// Cached stops of the currently selected layer's gradient, mirrored into the control-bar widget.
|
||||
/// Independent of any in-progress drag (which uses `selected_gradient`) so it stays current after selection changes too.
|
||||
current_gradient_stops: Option<GradientStops>,
|
||||
current_gradient_stops: Option<Gradient>,
|
||||
/// User-customized default gradient stop colors: used when nothing that has a gradient is selected.
|
||||
/// `None` means to follow the working colors.
|
||||
/// Cleared on tool deactivation so each fresh activation starts from the working colors again.
|
||||
default_gradient_stops: Option<GradientStops>,
|
||||
default_gradient_stops: Option<Gradient>,
|
||||
/// Cached viewport-space orientation (true = predominantly rightward) of the selected gradient line.
|
||||
/// Used to refresh the control bar's "Reverse Direction" icon only when the line's apparent direction flips.
|
||||
gradient_orientation_rightward: bool,
|
||||
@@ -1496,7 +1496,7 @@ impl Fsm for GradientToolFsmState {
|
||||
// Generate a new gradient running primary → secondary so the default working colors
|
||||
// (primary = black, secondary = white) produce the expected black-to-white gradient
|
||||
None => (
|
||||
GradientStops::new([
|
||||
Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -1738,7 +1738,7 @@ impl Fsm for GradientToolFsmState {
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_stop_at_point(gradient: &mut GradientStops, point: DVec2, unit_to_viewport: DAffine2) -> Option<usize> {
|
||||
fn insert_stop_at_point(gradient: &mut Gradient, point: DVec2, unit_to_viewport: DAffine2) -> Option<usize> {
|
||||
let (start, end) = gradient_handle_positions(unit_to_viewport);
|
||||
let t = ((end - start).angle_to(point - start)).cos() * start.distance(point) / start.distance(end);
|
||||
(0. ..=1.).contains(&t).then(|| gradient.insert_stop(t))
|
||||
@@ -1831,8 +1831,8 @@ fn apply_gradient_update(
|
||||
data: &mut GradientToolData,
|
||||
context: &mut ToolActionMessageContext,
|
||||
responses: &mut VecDeque<Message>,
|
||||
condition: impl Fn((&GradientStops, &GradientAppearance)) -> bool,
|
||||
update: impl Fn((&mut GradientStops, &mut GradientAppearance)),
|
||||
condition: impl Fn((&Gradient, &GradientAppearance)) -> bool,
|
||||
update: impl Fn((&mut Gradient, &mut GradientAppearance)),
|
||||
) {
|
||||
let selected_layers: Vec<_> = context
|
||||
.document
|
||||
@@ -1888,7 +1888,7 @@ fn apply_gradient_update(
|
||||
/// Set new gradient stops on every selected layer's gradient. Unlike `apply_gradient_update`, this doesn't open its own
|
||||
/// transaction so it can be called repeatedly during a color picker drag and have all the changes coalesced into a
|
||||
/// single undo entry by the surrounding 'on_commit' callback.
|
||||
fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessageContext, responses: &mut VecDeque<Message>, new_gradient: GradientStops) {
|
||||
fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessageContext, responses: &mut VecDeque<Message>, new_gradient: Gradient) {
|
||||
let selected_layers: Vec<_> = context
|
||||
.document
|
||||
.network_interface
|
||||
@@ -1933,7 +1933,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
}
|
||||
|
||||
/// Find the first selected visible layer that has a gradient and return both the layer ID and its resolved gradient.
|
||||
fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<LayerNodeIdentifier>, Option<(GradientStops, GradientAppearance)>) {
|
||||
fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<LayerNodeIdentifier>, Option<(Gradient, GradientAppearance)>) {
|
||||
for layer in document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface) {
|
||||
if let Some((gradient, appearance, _source)) = resolve_gradient(layer, &document.network_interface) {
|
||||
return (Some(layer), Some((gradient, appearance)));
|
||||
@@ -1942,7 +1942,7 @@ fn current_layer_and_gradient(document: &DocumentMessageHandler) -> (Option<Laye
|
||||
(None, None)
|
||||
}
|
||||
|
||||
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<(GradientStops, GradientAppearance, GradientSource)> {
|
||||
fn get_gradient_on_selected_layer(document: &DocumentMessageHandler) -> Option<(Gradient, GradientAppearance, GradientSource)> {
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
@@ -2015,19 +2015,19 @@ mod test_gradient {
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
||||
use graphene_std::vector::{Gradient, GradientStop, fill};
|
||||
use graphene_std::{Graphic, NodeInputDecleration};
|
||||
|
||||
use super::gradient_space_transform;
|
||||
|
||||
struct ResolvedGradient {
|
||||
stops: GradientStops,
|
||||
stops: Gradient,
|
||||
spread_method: GradientSpreadMethod,
|
||||
transform: DAffine2,
|
||||
}
|
||||
|
||||
impl ResolvedGradient {
|
||||
fn new(stops: GradientStops, appearance: super::GradientAppearance) -> Self {
|
||||
fn new(stops: Gradient, appearance: super::GradientAppearance) -> Self {
|
||||
Self {
|
||||
stops,
|
||||
spread_method: appearance.spread_method,
|
||||
@@ -2068,8 +2068,9 @@ mod test_gradient {
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
|
||||
let has_transform = matches!(fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let local_transform = match fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::OptionalDAffine2(Some(value))) => value,
|
||||
Some(&TaggedValue::DAffine2(value)) if has_transform => value,
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -2147,7 +2148,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_node_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: TaggedValue::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2184,7 +2185,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_node_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: TaggedValue::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2655,7 +2656,7 @@ mod test_gradient {
|
||||
// Create original transform for the control geometry and apply it
|
||||
let initial_start = DVec2::new(10., 50.);
|
||||
let initial_end = DVec2::new(200., 50.);
|
||||
let stops = GradientStops::new([
|
||||
let stops = Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2726,7 +2727,7 @@ mod test_gradient {
|
||||
let layer = create_gradient_list_layer(&mut editor).await;
|
||||
|
||||
// Set up a 3-stop gradient with distinct colors
|
||||
let original_stops = GradientStops::new([
|
||||
let original_stops = Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2827,7 +2828,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_value_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: TaggedValue::Gradient(Gradient::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
|
||||
@@ -82,7 +82,7 @@ struct ExecutionContext {
|
||||
/// Set when this execution is a gradient-migration measurement run, carrying the "Fill" node (addressed by its enclosing
|
||||
/// network path) and its original relative gradient. The evaluated geometry is read back from the inspect result to size the
|
||||
/// gradient; such runs never touch the visible artwork. Carrying the entry keeps a stale re-dispatched response paired with the fill it measured.
|
||||
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
|
||||
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
@@ -92,7 +92,7 @@ struct ExecutionContext {
|
||||
#[derive(Debug, Clone)]
|
||||
struct GradientMigration {
|
||||
document_id: DocumentId,
|
||||
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
|
||||
remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
resolution: UVec2,
|
||||
scale: f64,
|
||||
}
|
||||
@@ -450,7 +450,6 @@ impl NodeGraphExecutor {
|
||||
resolved_types: incomplete_delta,
|
||||
node_graph_errors,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
return Err(format!("Node graph evaluation failed:\n{e}"));
|
||||
}
|
||||
@@ -461,7 +460,6 @@ impl NodeGraphExecutor {
|
||||
resolved_types: type_delta,
|
||||
node_graph_errors,
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphUpdate::EyedropperPreview(raster) => {
|
||||
let (data, width, height) = raster.to_flat_u8();
|
||||
@@ -492,7 +490,7 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
// Snapshot the queue but leave `pending_gradient_bbox_bake` populated, so subsequent render requests keep deferring here (and hit the guard above); each entry is removed from the document as its bake lands.
|
||||
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
|
||||
let remaining: VecDeque<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)> = document.pending_gradient_bbox_bake.iter().cloned().collect();
|
||||
let Some((first_network_path, first_fill, first_gradient)) = remaining.front().cloned() else {
|
||||
return false;
|
||||
};
|
||||
@@ -519,7 +517,7 @@ impl NodeGraphExecutor {
|
||||
document_id: DocumentId,
|
||||
network_path: Vec<NodeId>,
|
||||
fill_node_id: NodeId,
|
||||
gradient: graphic_types::migrations::legacy::Gradient,
|
||||
gradient: graphic_types::migrations::legacy::LegacyGradient,
|
||||
resolution: UVec2,
|
||||
scale: f64,
|
||||
responses: &mut VecDeque<Message>,
|
||||
@@ -588,7 +586,7 @@ impl NodeGraphExecutor {
|
||||
&mut self,
|
||||
document: &mut DocumentMessageHandler,
|
||||
document_id: DocumentId,
|
||||
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient),
|
||||
bake_target: (Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient),
|
||||
inspect_result: Option<InspectResult>,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
@@ -610,10 +608,14 @@ impl NodeGraphExecutor {
|
||||
if fill_transform_unbaked(document, &network_path, fill_node_id) {
|
||||
let absolute_gradient = gradient.to_absolute(bounding_box, item_transform);
|
||||
let gradient_transform = absolute_gradient.transform * absolute_gradient.to_transform();
|
||||
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
|
||||
let has_transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX);
|
||||
let transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&input, NodeInput::value(TaggedValue::OptionalDAffine2(Some(gradient_transform)), false), &network_path);
|
||||
.set_input(&has_transform_input, NodeInput::value(TaggedValue::Bool(true), false), &network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&transform_input, NodeInput::value(TaggedValue::DAffine2(gradient_transform), false), &network_path);
|
||||
}
|
||||
|
||||
// The transform is settled, so its entry no longer needs to persist for a retry on the next open
|
||||
@@ -821,16 +823,16 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether the fill node's transform input is still the unset `OptionalDAffine2(None)` placeholder that the migration leaves
|
||||
/// behind, meaning its gradient placement has not yet been baked (or set by the user), so a measured bake may safely be written.
|
||||
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
|
||||
/// (or set by the user), so a measured bake may safely be written.
|
||||
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
|
||||
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Some(node) = network.nodes.get(&fill_node_id) else { return false };
|
||||
matches!(
|
||||
node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::OptionalDAffine2(None))
|
||||
node.inputs.get(graphene_std::vector::fill::HasTransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::Bool(false))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -917,9 +919,18 @@ mod test {
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graphene_std::Context;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::memo::IORecord;
|
||||
use test_prelude::LayerNodeIdentifier;
|
||||
|
||||
/// A ranked input whose `Item<E>` Result carries an element `E`, recovered by `grab_ranked_input`.
|
||||
pub trait RankedResult {
|
||||
type Element: Send + Sync + Clone + 'static;
|
||||
}
|
||||
impl<E: Send + Sync + Clone + 'static> RankedResult for Item<E> {
|
||||
type Element = E;
|
||||
}
|
||||
|
||||
/// Stores all of the monitor nodes that have been attached to a graph
|
||||
#[derive(Default)]
|
||||
pub struct Instrumented {
|
||||
@@ -942,11 +953,17 @@ mod test {
|
||||
let mut monitor_node_ids = Vec::with_capacity(node.inputs.len());
|
||||
for input in &mut node.inputs {
|
||||
let node_id = NodeId::new();
|
||||
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
|
||||
monitor_nodes.push((old_input, node_id));
|
||||
path.push(node_id);
|
||||
monitor_node_ids.push(path.clone());
|
||||
path.pop();
|
||||
|
||||
// A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent
|
||||
if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
|
||||
monitor_nodes.push((old_input, node_id));
|
||||
}
|
||||
if let DocumentNodeImplementation::ProtoNode(identifier) = &mut node.implementation {
|
||||
path.push(*id);
|
||||
@@ -978,15 +995,21 @@ mod test {
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
{
|
||||
// This is quite inflexible since it only allows the footprint as inputs.
|
||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() {
|
||||
Self::downcast_record::<Input::Result>(dynamic).or_else(|| {
|
||||
warn!("cannot downcast type for introspection");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
|
||||
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
|
||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Input::Result>>() {
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Input::Result>>() {
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else {
|
||||
warn!("cannot downcast type for introspection");
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1005,6 +1028,18 @@ mod test {
|
||||
.filter_map(Instrumented::downcast::<Input>) // Some might not resolve (e.g. generics that don't work properly)
|
||||
}
|
||||
|
||||
/// Like [`Self::grab_all_input`], but downcasting the recorded values to `Output` instead of the marker's `Result`.
|
||||
/// Useful when a stored value's wire form (e.g. `Item<Color>`) differs from the declared row types the marker's generic accepts.
|
||||
pub fn grab_all_input_as<'a, Input: NodeInputDecleration + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
|
||||
self.protonodes_by_name
|
||||
.get(&Input::identifier())
|
||||
.map_or([].as_slice(), |x| x.as_slice())
|
||||
.iter()
|
||||
.filter_map(|inputs| inputs.get(Input::INDEX))
|
||||
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
|
||||
.filter_map(Instrumented::downcast_record::<Output>)
|
||||
}
|
||||
|
||||
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
@@ -1016,6 +1051,17 @@ mod test {
|
||||
Self::downcast::<Input>(dynamic)
|
||||
}
|
||||
|
||||
/// Grabs a ranked (`Item<E>`) input's recorded value as its bare element `E`.
|
||||
/// A stored value materializes as an `Item<E>` wire, so the monitor records the whole cell and this unwraps its element.
|
||||
pub fn grab_ranked_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<<Input::Result as RankedResult>::Element>
|
||||
where
|
||||
Input::Result: RankedResult,
|
||||
{
|
||||
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
|
||||
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
|
||||
Self::downcast_record::<Item<<Input::Result as RankedResult>::Element>>(dynamic).map(|item| item.into_element())
|
||||
}
|
||||
|
||||
pub fn grab_input_from_layer<Input: NodeInputDecleration>(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
|
||||
@@ -10,7 +10,7 @@ use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::ops::Convert;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
@@ -378,7 +378,7 @@ impl NodeRuntime {
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
|
||||
match self.executor.input_type() {
|
||||
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()),
|
||||
Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()),
|
||||
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
|
||||
Some(t) => Err(format!("Invalid input type {t:?}")),
|
||||
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
|
||||
@@ -441,6 +441,28 @@ impl NodeRuntime {
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Rank-0 wires record single items; each arm mirrors its list counterpart through a singleton raise
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Graphic>>>() {
|
||||
if update_thumbnails {
|
||||
let singleton = List::new_from_item(io.output.clone());
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&singleton, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
|
||||
}
|
||||
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Artboard>>>() {
|
||||
if update_thumbnails {
|
||||
let singleton = List::new_from_item(io.output.clone());
|
||||
let bounds = artboard_clip_bounds(&singleton);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
|
||||
}
|
||||
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Vector>>>() {
|
||||
self.vector_modify.insert(parent_network_node_id, io.output.element().clone());
|
||||
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<String>>>() {
|
||||
if update_thumbnails {
|
||||
let singleton = List::new_from_item(io.output.clone());
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&singleton, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Other
|
||||
else {
|
||||
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
|
||||
|
||||
Reference in New Issue
Block a user