Compare commits

..
Author SHA1 Message Date
Timon 5a16e18b2a Add time since pointerdown to input event handling (#4443)
Add event time to the editor pointer states

The brush trace's hot core is position plus per-sample time, and the
frame clock is too coarse for high-rate tablets: several samples share
one timestamp and speed dynamics see dt = 0. The desktop stamps
editor-routed pointer input with a monotonic arrival time since winit
does not surface hardware timestamps; the web path can thread the
PointerEvent timeStamp through later.
2026-08-27 13:09:55 +00:00
Timon 3c5e1b8a38 Desktop: Support input from drawing tablets (#4354)
* Rename the editor mouse state types to Pointer* and the input_ modules

* Add optional pen attributes to the editor pointer state types

* Desktop: Send tablet pointer clicks to CEF as mouse clicks

* Desktop: End pointer lock and pending window drags on any left-equivalent release

* Desktop: Route pointer input carrying pen attributes directly to the editor

* Desktop: Route wheel and pinch input inside the viewport directly to the editor

* Desktop: Track double clicks on the direct editor route

* Desktop: Move the pointer lock position into InputState

* Restore the input state pointer position when pointer lock ends (review)

* Fix pen input being swallowed by Windows resize helper

* Update winit to 0.31.0-beta.2 from crates.io
2026-08-27 13:09:55 +00:00
Keavon Chambers 404d9f3047 Fix corrupted font resource loading in older documents 2026-08-25 14:10:22 -07:00
Keavon Chambers c8667edacc Make Data panel scalars selectable inline, denoise float display, and standardize breadcrumb string truncation (#4470)
* Make Data panel scalars selectable inline, denoise float display, and move breadcrumb truncation to Rust

* Code review fixes

* Remove denoising from f32
2026-08-22 01:28:23 -07:00
Keavon Chambers 2fa6b743fe Reintroduce improved logic for mesh interior region fill determination (#4464)
* Decide branching mesh fill insideness by winding, normalizing drawn direction at the Path node

* Fix dead connector click targets by explicitly closing the kurbo ellipse port paths

* Fix hole subtraction when a hole vertex is snapped exactly onto its covering contour

* Classify embedded negative space by its single surrounding face so fully enclosed mesh cells still fill
2026-08-19 00:59:40 -07:00
Keavon Chambers daa8b6a5a4 Delete the vestigial region domain, reverting to naive logic for mesh region fill determination (#4463)
Delete the vestigial region domain, reverting the face fill decision to the bare branching test
2026-08-18 23:50:16 -07:00
Keavon Chambers 39425ca7ea Delete the dead StrokeId and FillId attributes from the Vector segment and region domains (#4461) 2026-08-18 17:51:29 -07:00
Keavon Chambers 48e776c1af Auto-recover stuck npm installs blocked on files locked by zombie processes (#4460) 2026-08-18 16:45:35 -07:00
Keavon Chambers c19f79977b Dedupe code for BezPath emission, epsilon constants, and Polynomial internals (#4459)
* Collapse duplicated BezPath emission, constants, and Polynomial surface across the vector algorithms

* Fix the quadratic segment length lower bound using a control leg instead of the chord
2026-08-18 16:24:12 -07:00
Keavon Chambers 5c580f9dac Clean up the Vector struct implementations by privatizing and deleting unused APIs (#4458)
Trim the Vector API surface by privatizing and deleting caller-less items
2026-08-18 15:54:55 -07:00
Keavon Chambers e3b968f7e2 Port all remaining Subpath producers to BezPath and delete the legacy subpath module (#4457)
* Port all remaining Subpath producers to BezPath and delete the legacy subpath module

* Reset contour state at each MoveTo so an open contour's segments don't leak into the next region

* Give the polygon and star constructors a true center and radius instead of compensated arguments
2026-08-18 15:28:58 -07:00
Keavon Chambers 8f1b2bed5f Collapse ClickTargetType to a single multi-contour BezPath variant (#4456)
* Collapse ClickTargetType to a single multi-contour BezPath variant

* Restrict no-stroke point hits to a path's closed contours
2026-08-18 14:31:52 -07:00
Keavon Chambers c111308c67 Replace the legacy Bezier struct with kurbo::PathSeg throughout (#4455) 2026-08-18 13:08:28 -07:00
Keavon Chambers 20af96c1d9 Remove remnant dead code across the Subpath, Vector, and editor geometry API surfaces (#4454) 2026-08-18 12:34:34 -07:00
Keavon Chambers 2df0bd25c3 Add the "Type Assertion" node catalog category (#4452) 2026-08-17 23:39:02 -07:00
Keavon Chambers 656daa26bc Render a paint from its Graphic directly instead of a single-element List wrapper (#4450)
* Render a paint from its Graphic directly instead of a single-element List wrapper

* Fix a stale doc comment reference to the moved paint render implementation
2026-08-17 21:26:13 -07:00
Keavon Chambers e9e7ef54f6 Fix color and gradient list paints not rendering as stacks (#4439)
Stack every item of a color or gradient paint instead of painting only the first
2026-08-17 20:52:55 -07:00
Keavon Chambers 51662a5fe8 Fix the blend mode formulas for the Overlay, whole-color, and alpha-only modes (#4449)
* Fix the Overlay, whole-color, and alpha-only blend mode formulas

* Add unit tests covering the blend mode formula fixes
2026-08-17 20:28:17 -07:00
Keavon Chambers 35a98a2975 Move the color blending helpers down beside Color and BlendMode in no-std-types (#4448) 2026-08-17 19:33:28 -07:00
Keavon Chambers ef6d430f97 Replace the IntoPaint trait with direct Graphic-typed node inputs (#4442)
* Let the Fill and Stroke paint inputs take Item<Graphic>, replacing the IntoPaint trait

* Rename the FIll node's "fill" input to "paint"

* Let the graphic-consuming nodes take List<Graphic> directly, relying on the embedding adapters

* Remove outdated todo comments

* Re-save the demo art
2026-08-17 03:10:02 -07:00
Keavon Chambers d63362718f Split 'To Graphic' and 'Wrap Graphic' into the 'As Graphic' type assertion and 'Into Group' reducer nodes (#4441)
* Split 'To Graphic' and 'Wrap Graphic' into the 'As Graphic' type assertion and 'Into Group' reducer nodes

* Make 'Into Group' reduce List<DVec2> not Item<DVec2>

* Reset the Merge definition for every legacy alias of its coercion nodes

* Improve test
2026-08-17 02:19:59 -07:00
Keavon Chambers 104b8b71e6 Support embedding whole items into Graphic variants so their attributes survive the conversion (#4440)
Add embedding conversion adapters that move a whole ranked value inside a Graphic variant
2026-08-16 19:51:58 -07:00
Keavon Chambers f635c56eab Fix color and gradient paints not rendering with their opacity attributes (#4438)
Fade color and gradient paints by their own opacity attributes
2026-08-16 15:52:27 -07:00
Keavon Chambers c507b35645 Add rank-0 Item leaf variants to the Graphic enum alongside its List variants (#4437)
* Add the rank-0 Item leaf variants to the Graphic enum, rendering leaves and list rows through shared per-row logic

* Traverse the rank-0 Graphic leaf variants in the vector node helpers and flattening

* Reach rank-0 vector graphics from the styling and gradient-fitting helpers

* Two code review fixes

* Fix comment
2026-08-16 02:24:15 -07:00
Keavon Chambers ba7cbd83bc Store an appearance's paint as a bare Graphic rather than a single-element List<Graphic> (#4435)
Rank the coverage's paint attribute down from List<Graphic> to Graphic
2026-08-14 22:13:00 -07:00
Keavon Chambers 69585b25e3 Rename the Graphic enum wrapper variants with a "List" suffix (#4434)
* Make the Artboard and Gradient newtype fields public to match the other list newtypes

* Rename the Graphic enum's self-named Graphic::Graphic variant to Graphic::GraphicList

* Rename the Graphic::Vector variant to Graphic::VectorList

* Rename the Graphic::RasterCPU variant to Graphic::RasterCPUList

* Rename the Graphic::RasterGPU variant to Graphic::RasterGPUList

* Rename the Graphic::Color variant to Graphic::ColorList

* Rename the Graphic::Gradient variant to Graphic::GradientList

* Rename the Graphic::Text variant to Graphic::TextList

* Restore the SVG group tag comment that the variant rename sweep clobbered
2026-08-14 18:55:07 -07:00
Keavon Chambers d117c3eace Adopt the cascading "appearance" attribute in place of Vector::stroke and the "fill"/"paint" attributes (#4433)
* Add the appearance model types and attribute constants

* Dual-write the appearance attribute alongside the fill/stroke pair in all paint-writing nodes

* Read paint from the appearance attribute in the renderer, analysis, metadata, and editor, cascading from ancestors

* Retire the fill/stroke attribute pair and the Vector stroke field in favor of the appearance attribute

* Replace the Stroke node's paint order input with the relative chain order of the Fill and Stroke nodes

* Code review fixes

* Re-save demo art

* Stamp coverages in place and fuse the renderer's per-item appearance reads into single walks

* Treat an empty appearance as the undeclared state so padded rows inherit instead of blocking the cascade

* Update demo art

* Treat padded appearance rows as undeclared in the boolean flatten's group recursion
2026-08-14 13:25:23 -07:00
Keavon Chambers a034923695 Let vector modifier nodes operate on graphic content by recursing into groups (#4431)
* Make the 'Solidify Stroke' node preserve graphic structure instead of flattening its input

* Add a shared trait letting element-wise vector modifiers recurse into graphic groups

* Make 20 element-wise vector modifier nodes accept graphic input

* Make 'Separate Subpaths' and 'Points to Polyline' accept graphic input

* Make the 'Map Points' node accept graphic input

* Add TODO comments to the measure nodes deferred until the Graphic lowering refactor
2026-08-11 17:14:04 -07:00
Keavon Chambers 3994312440 Make the 'Boolean Operation' node ignore raster, color, and gradient content (#4430)
Stop the Boolean Operation flattener fabricating operands from non-path content
2026-08-11 14:22:24 -07:00
Keavon Chambers 9a129ecf5c Fix clipping masks, click targets, and bounds when rendering Vector[] and flattened graphic wrappers (#4429)
* Honor clipping masks when rendering Vector[] lists, not just Graphic[] groups

* Keep per-layer click targets when a Vector[] round-trips through a Graphic[] wrapper

* Skip the rebuild and the merged-layers snapshot when flattening a lone anonymous graphic wrapper

* Fix a group's bounds excluding its raster children and stretching to the origin

* Fix SVG clipping masks landing in the wrong space when sibling layers differ in transform
2026-08-11 13:31:48 -07:00
Keavon Chambers 8e23d3509b Fix style controls corrupting stack nodes like Transform that can't host blending or paint nodes (#4428)
* Stop chain node insertion from stranding a node on layers without a chain

* Gate the Layers panel blending controls on whether the layer can host them

* Gate the fill and stroke setters on whether the layer can host paint nodes

* Make the tool options fill and stroke controls treat layers that cannot take paint as unselected

* Remove the unused first_selected_stroke_weight helper
2026-08-11 12:48:57 -07:00
Keavon Chambers b593b26ad7 Make the 'Index Points' node index within each vector element instead of across the whole list (#4427) 2026-08-10 21:04:33 -07:00
Keavon Chambers 759519782b New node: 'Gradient to Colors' for unwrapping a gradient ramp into its colors (#4425)
* New node: 'Gradient to Colors' for unwrapping a gradient ramp into its colors

* Update 'Gradient Midpoints' wording
2026-08-08 04:37:44 -07:00
Keavon Chambers ceb2de51fb New nodes: 'Gradient Reverse', 'Gradient Shift', and 'Gradient Stretch' nodes for rearranging a ramp's stops (#4424)
* New nodes: 'Gradient Reverse', 'Gradient Shift', and 'Gradient Stretch' nodes for rearranging a ramp's stops

* Clip a lone out-of-range stop into the bake, and correct the docs that still promised edge-held stops
2026-08-08 03:09:06 -07:00
Keavon Chambers c75c6c9695 Fix read-only widget appearance and focus, and keep ColorInput picks surviving a layout diff (#4423) 2026-08-08 01:45:53 -07:00
Keavon Chambers b22158b022 Rename the 'Sample Gradient' node to 'Evaluate Gradient' (#4422)
* Rename the 'Sample Gradient' node to 'Evaluate Gradient'

* Let the Evaluate Gradient node's position reach the out-of-range values its spread modes handle
2026-08-08 01:20:55 -07:00
Keavon Chambers e68735f98e Drop CSS vendor prefixes and compat workarounds now obsolete in modern browsers (#4421) 2026-08-07 19:40:29 -07:00
Keavon Chambers c6e17a789b Clean up CSS color opacity application to theme colors (#4420) 2026-08-07 19:21:17 -07:00
Keavon Chambers 6b1e9912ef Fix Vello rendering incompatibility with its gradients using premultiplied alpha instead of SVG's straight (#4419)
* Upgrade Vello to a git main revision that honors the brush's interpolation alpha space

* Interpolate Vello gradients with straight alpha, matching the SVG renderer

* Draw the gradient picker strip and fill swatches as SVG so transparency previews with straight alpha

* Keep gradient stop handles opaque so a transparent stop's RGB stays visible

* Paint a stopless gradient's picker strip and swatch black rather than transparent
2026-08-07 18:45:12 -07:00
Keavon Chambers 681b4033f5 Add a gradient interpolation attribute with Stepped, Linear (existing), and Smooth modes (#4418)
* Delete dead code function

* Add a Gradient Interpolation axis with Stepped, Linear, and Smooth paths through the stops

* Keep the gradient interpolation attached when dragging stops in the picker

* Give the gradient popover's dropdowns the same tooltips as their row labels

* Order the gradient popover with Intrp. above Space

* Hold gradient stops in place when the cyclic flag is toggled

* Fix wrong Smooth gradient colors around stops sitting on the ramp boundaries

* Consolidate gradient settings plumbing and fix bugs

* Bundle whole-ramp gradient settings into GradientSettings across the editor plumbing

* Name the Smooth gradient interpolation's spline type in its tooltip

* Linearize the gamma hex stop colors recovered from imported Graphite SVGs

* Code review

* Aim the Smooth bake's seam subdivision at the copied boundary color

* Add GradientEvaluator to build gradient sampling state once per loop instead of per sample

* Correct the gradient evaluator's documented setup cost to O(n log n)
2026-08-07 16:43:36 -07:00
Keavon Chambers 4b01abe36d Add a "Cyclic" gradient option that closes the ramp into a seamless loop (#4416)
* Add a Cyclic gradient attribute that wraps the stop list through the 1|0 boundary back to the first stop

* Show the wrap segment's midpoint diamond in the color picker spectrum strip when cyclic

* Keep the wrap midpoint diamond tracking the pointer by a wrapped strip width when dragged past the ends

* Give the Gradient tool's viewport overlay the same cyclic wrap midpoint diamond and drag behavior

* Correct the docs claiming the final stop's midpoint is always ignored now that cyclic uses it

* Move the gradient cyclic toggle onto the Ends row as a Link icon checkbox

* Update labels

* Register GradientHueDirection with the Data panel so its attribute column renders

* Reword wrap segment to wrapped interval and stray segment usages to interval

* Clean up comments

* Fix the color picker write-back losing default position elision and the blend path guessing the cyclic flag
2026-08-06 18:52:00 -07:00
Keavon Chambers 461ddbc872 Add the "Perceptual" and "Classic" families of gradient spaces with OkLab as the new default (#4415)
* Add an OkLab gradient interpolation space and make it the new default

* Fix the Properties panel fill row resetting the gradient interpolation space to the default

* Add OkLch, Lab, LCh, and HSL gradient interpolation spaces

* Add a hue direction attribute and picker choice for polar gradient interpolation spaces

* Add an HSV gradient interpolation space

* Rename the sRGB Linear and sRGB Gamma gradient spaces to RGB Linear and RGB Gamma

* Divide the gradient interpolation dropdown between absolute and relative color spaces

* Rename the OkLch gradient interpolation space to OkLCh for channel-notation capitalization

* Shorten the color picker popover's hue direction row label to Arc

* Call the Gradient Interpolation node's parameter Space and extend the picker tooltip title to match

* Rename the gradient interpolation attribute and type family to gradient space

* Rename the gradient tool's gradient space transform to gradient to viewport transform

* Add serde aliases and a node replacement covering the gradient space renames

* Give the gradient space choices artist-facing labels and reorder the dropdown sections

* Add a Gradient Hue Direction node and its attribute read node

* Say interpolate instead of blend for gradient stop color traversal in docs and tooltips

* Label the polar perceptual gradient spaces as Perceptual Hue and group the dropdown sections by geometry

* Add a migration alias covering the gradient space attribute reader rename

* Carry the gradient hue direction attribute through boolean operations

* Register GradientHueDirection wire types in the node registry
2026-08-06 02:40:25 -07:00
Keavon Chambers 3f082c881f Make gradient evaluation follow the ramp's interpolation space attribute (#4414) 2026-08-05 19:32:51 -07:00
Keavon Chambers faed7f81bf Give whole-expanse gradient layers a transform cage based on the gradient line (#4413) 2026-08-05 17:47:54 -07:00
Keavon Chambers fd01d66070 Add a gradient interpolation space attribute with sRGB Gamma (existing) and sRGB Linear (new) (#4412)
* Build dropdown menu entries from choice type metadata

* Add a gradient interpolation color space attribute, blending stops in linear light by default

* Add a Space interpolation dropdown to the color picker popover

* Stamp legacy gradient ramps with their implicit gamma interpolation during deserialization

* Resolve color-interpolation from SVG style blocks and fix cascade order among repeated declarations
2026-08-05 15:58:25 -07:00
Keavon Chambers 0b922f1452 Fix node shaking causing an offset from the pointer for the rest of the drag (#4411) 2026-08-05 01:26:41 -07:00
Keavon Chambers 7762ab2e4c Add a Clear gradient spread that cuts off to transparency beyond the ends (#4410) 2026-08-05 00:27:18 -07:00
Keavon Chambers 1bd4ddf377 Bind the Gradient tool's spread to the gradient value's ramp instead of a Gradient Spread node (#4409) 2026-08-04 23:39:40 -07:00
Keavon Chambers 7c8b189c71 Build radio widget entries from choice type metadata so variants display their icons (#4408)
* Build radio widget entries from choice type metadata so variants display their icons

* Route the node properties enum radio through the shared choice type entry builder
2026-08-04 21:16:14 -07:00
Keavon Chambers 9b3d07dc51 Let the Fill and Gradient tools paint blank layers with whole-expanse colors and gradients (#4407)
* Let the Gradient and Fill tools paint blank layers with whole-expanse gradients and colors

* Make it work on layers with un-fed Transform nodes

* Show the Fill tool's hover pattern over the whole expanse of layers painted by a color chain

* Let the Fill and Gradient tools replace one another's whole-expanse paint on a selected layer

* Keep a shared paint node alive when a tool takes over a layer, and share the paint value lookup

* Stop a chain node from being shifted twice when a node is inserted in front of it
2026-08-04 18:32:15 -07:00
Keavon Chambers 788fe227c6 Rename gradient type to gradient form (#4405)
* Rename gradient type to gradient form

* Update the demo art for the gradient form rename

* Say form not type in the Gradient Form node's doc comment
2026-08-04 05:51:10 -07:00
Keavon Chambers ca44dbaf55 Rename spread method to gradient spread so it matches the other gradient attribute names (#4404)
* Rename spread method to gradient spread so it matches the other gradient attribute names

* Keep the legacy gradient struct's spread method field name matching its on-disk key
2026-08-04 05:15:21 -07:00
Keavon Chambers e907a4d574 Move the gradient-focused nodes from the Color category to a new Gradient category (#4403) 2026-08-04 04:27:37 -07:00
Keavon Chambers b2265be88f Move the gradient spread method into GradientRamp and the color picker popover (#4402)
* Add a spread method field to GradientRamp, carried at runtime as the gradient item's attribute

* Retire the Fill node's spread method input, folding its value into the gradient ramps on document upgrade

* Add an Ends spread method radio to the color picker popover, replacing the Gradient tool's control bar radio

* Update the demo art
2026-08-04 04:08:21 -07:00
Keavon Chambers 049b9dbc4d Ban the null literal via ESLint and replace existing usages with undefined or truthiness checks (#4401) 2026-08-03 23:47:29 -07:00
Keavon Chambers 79136c95be Wrap serialized gradient stops in a new GradientRamp struct and unify FillChoice (#4400)
* Introduce the GradientRamp exchange struct as the serialized TaggedValue::Gradient payload

* Unify FillChoice and FillChoiceUI into one enum generic over color format, carrying GradientRamp stops

* Rename the TaggedValue::Gradient variant to GradientRamp to match its payload

* Move the Color variant into the tagged_value macro list since its stored and wire forms match
2026-08-03 23:23:41 -07:00
Keavon Chambers 808662e3d2 Add a drill-in button beside Data panel gradient preview widgets (#4398) 2026-08-03 04:31:48 -07:00
Keavon Chambers 2f24459344 Rework Gradient into a newtype of List<Color> with optional position and midpoint attributes (#4397)
* Rework Gradient into a newtype of List<Color> with optional position and midpoint attributes

* Fix Vello stopless-gradient fallback coverage, empty legacy gradient tables, the node docs gradient swatch, NaN position elision, and wired setter input overwrites
2026-08-03 04:05:02 -07:00
Keavon Chambers e52a442504 Remove custom (de)serializers from the DashPattern and BoxCorners TaggedValue variants (#4394)
Replace the DashPattern and BoxCorners custom serde impls with storage-shaped Vec<f64> TaggedValue payloads
2026-08-02 01:00:46 -07:00
Keavon Chambers 5927eff059 Replace raw node input indices with compile-time parameter symbols (#4387)
* Remove the dead InputAccessor traits and the uncallable test helper built on them

* Replace raw node input indices with macro-generated parameter symbols across the editor

* Audit dynamic input index usage, converting to parameter symbols and named input position constants

* Abstract the remaining input index plumbing behind ParameterRef APIs and accessors

* Build SetInputValue messages as struct literals to keep message enums impl-free

* Delete the typed parameter markers in favor of explicit-output test introspection

* Wire the interpolation control path input per chain node type

* Return no input when a parameter symbol is read against the wrong node's parameter view
2026-07-28 11:17:30 -07:00
Keavon Chambers 949022cee0 Fix the math parser's implicit multiplication precedence and other regressions from the rewrite (#4383)
* Fix parsing regressions, make parsing 2.5x faster than the old pest parser, and clean up the math-parser rewrite

* Fix review findings: whitespace-juxtaposed numbers, mixed real/complex logic, correctly rounded literals, unified NaN truthiness, and gcd/lcm range checks
2026-07-26 16:41:51 -07:00
urisinger 0952933ede Move the math expression parser from Pest to Chumsky and add more features (#2685)
Rewrite the math-parser library using a chumsky-based lexer and parser, adding functions, comparisons, logic, and conditionals
2026-07-26 14:14:39 -07:00
Keavon Chambers b2e5b6645c Add a Connect Cells option to the 'Grid' node (#4374)
Add a Connect Cells option to the Grid node
2026-07-26 12:15:14 -07:00
Keavon Chambers 9332c7f775 Box big enum variants to satisfy Clippy's lint warnings (#4292)
* Box the `value` field of `NodeGraphMessage::SetInputValue`

* Box the `ExecutionResponse` variant of `NodeGraphUpdate`

* Box the `Layer` variant of `NodeTypeClickTargets`

* Box the `Scope` variant of `ParsedValueSource`
2026-07-26 11:50:23 -07:00
Keavon Chambers 0bce26c54e Deduplicate the network interface query helpers and collapse TransientMetadata into TransientCache (#4382)
* Route the remaining view queries through the logging query helper

* Name the cache readers by their loading contract and stop cloning the owned nodes per collision check

* Deduplicate the port center, output count, and upstream connector helpers and drop dead accessors

* Collapse the TransientMetadata enum into the Option inside TransientCache

* Extract the shared history snapshot install from undo and redo
2026-07-26 02:24:33 -07:00
Keavon Chambers 343cdb31a8 Fix wrong-input disconnects, ghost wire caches, and partial import removal in the network interface (#4381)
* Remove commented-out code and fix stale names and doc comments

* Validate that the pinned node order only references existing nodes

* Abort remove_import before any mutation when the import's wires cannot be resolved

* Purge the deleted nodes' cached wire paths in delete_nodes

* Disconnect a deleted node's inputs by position so hidden inputs cannot mask a later exposed wire

* Gather the delete_nodes layer sweep only when deleting children needs it
2026-07-26 01:33:05 -07:00
Keavon Chambers dcabaf1ae4 Move session state out of the network interface caches and replace the selection hijacks with explicit parameters (#4379)
* Move drag offsets out of the stack dependents cache into dedicated drag session state

* Replace the move_layer_to_stack selection hijack with a seeded stack dependents load

* Move text measurement into a neutral utility module out of the overlays layer

* Deduplicate the document bounds queries and name the artboard clip input index

* Replace the remove_references_from_network selection hijack with an explicit shift set

* Extract shared import and export wire disconnection used by the expose handlers

* Extract the shared epilogue of the import and export removal operations

* Move the post node lookup into the network interface to fix the layering inversion

* Clear drag offsets when the stack dependents cache unloads so programmatic shifts cannot replay them

* Use the thread-local text context for text measurement instead of a process-global mutex

* Resolve the post node lookup within the network being edited instead of the document root
2026-07-26 01:09:14 -07:00
Keavon Chambers 20f9780f55 Make the network interface's queries take &self instead of &mut self (#4378)
* Back the outward wires cache with an interior-mutability cell readable through &self

* Convert the remaining network-level caches to interior-mutability TransientCache cells

* Move the owned nodes cache out of persistent layer metadata into a transient cell

* Flatten the transient node type enum into a layer width cell with &self loading

* Back the per-node click targets cache with a TransientCache cell

* Unify the per-input and per-export wire caches into one connector-keyed map

* Flip the click target, position, and stack dependent load chains to &self

* Flip the bounding box, import export position, and port load chains to &self

* Flip the wire geometry and resolved type query families to &self

* Flip the hit testing and frontend click target surface to &self

* Flip the frontend assembly, clipboard copy, and chain validation queries to &self

* Load stack dependents before filtering layer-owned nodes out of a selected-nodes shift
2026-07-26 00:09:03 -07:00
Keavon Chambers eabaf82a26 Replace NodeTemplate's parallel node and metadata trees with a single flat recursive shape (#4377)
* Unify NodeTemplate into a single flat recursive shape with from_parts/into_parts as the storage split points

* Unify the three sole-dependent traversals onto one is_sole_dependent kernel

* Scan network exports for resource values when collecting used resources
2026-07-25 20:37:36 -07:00
Keavon Chambers 85d6eda68e Introduce the NetworkView read cursor with typed errors and convert the network queries onto it (#4376)
* Introduce a NetworkView cursor with typed errors and convert the primitive queries to it

* Convert the composite name, selection, and eligibility queries onto NetworkView
2026-07-25 19:15:15 -07:00
Keavon Chambers 7af4fe4bad Make double-clicking a text layer begin editing in shallow select mode, not just deep select mode (#4373) 2026-07-24 14:02:40 -07:00
Keavon Chambers 9bbb203da1 Break apart the enormous network_interface.rs into submodules (#4371)
Split the network interface monolith into submodules with no behavior change
2026-07-23 22:43:19 -07:00
Keavon Chambers e00dab0dc4 Add additional tests to the network interface (#4370)
* Add a network interface invariant validator and characterization tests as a refactor safety net

* Characterize stack, chain, layer move, signature edit, and preview behaviors in tests

* Sweep network interface invariants after every message in editor tests
2026-07-23 22:20:55 -07:00
Keavon Chambers 5c3982fff2 Fix assorted node graph correctness bugs and replace network interface panics with logged errors (#4364)
* Deselect deleted layer children by pruning the expanded deletion set from the selection

* Rebuild the document structure on redo to match undo

* Check for cycles in set_input before applying layout side effects rather than reverting after

* Correct the swapped old/new exposure binding names in set_input

* Reload the document structure when an import or export is appended into the first two slots

* Treat toggling preview on a disconnected export as a preview with nothing to restore

* Replace panics on malformed networks with logged errors in the network interface

* Make is_artboard an identity check independent of scene connectivity

* Stop serializing the selection undo and redo history into saved documents

* Run the set_input cycle check before the node-to-node disconnect so a rejected wire swap leaves the graph unchanged
2026-07-23 18:35:18 -07:00
Keavon Chambers 3d7e85c054 Improve number fields/labels in the UI to filter out floating point noise and truncate at correct precision (#4363)
* Improve the displayed precision of float number labels

* Show actual tiny values in high-precision number fields
2026-07-23 00:22:13 -07:00
Keavon Chambers 95f2b3bbad Make the 'Angle Between' node report the signed angle and fix its zero-vector output (#4362) 2026-07-22 22:39:36 -07:00
Keavon Chambers 515a5265fe New nodes: 'Sign', 'Distance', 'Cross Product', and 'Lerp' (#4361) 2026-07-22 22:03:50 -07:00
Keavon Chambers 2f65a3aee2 Add Vec2 support to the scalar math operator nodes (#4360)
* Add Vec2 support to the scalar math operator nodes

* Support the scalar-with-Vec2 operand order in the Exponent, Root, Logarithm, Min, Max, and Clamp nodes

* Detect an f32 base of e in the Logarithm node despite inexact widening to f64
2026-07-22 19:42:02 -07:00
Keavon Chambers 1964fdb99e Fix the 'Divide' node dividing partially-zero Vec2 denominators and the 'Logarithm' node misdetecting base e (#4359) 2026-07-22 18:41:28 -07:00
Timon 117da97dd5 Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-18 19:38:51 +00:00
Timon f88896a887 Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-07-18 10:04:07 +00:00
Keavon Chambers 0eab6aa93c Rename the nodes 'Length' -> 'Magnitude', 'Flatten Path' -> 'Combine Paths', 'Vec2 Value' -> 'Combine Vec2', and add a new 'Vec2 Value' node (#4349)
* Rename the node 'Length' -> 'Magnitude'

* Rename the node 'Flatten Path' -> 'Combine Paths'

* Replace the node 'Vec2 Value' with 'Combine Vec2' and add a new 'Vec2 Value' that's actually a vec2

* Update demo artwork
2026-07-17 09:43:04 -07:00
Keavon Chambers 581bb05f5d New nodes: 'Voronoi Cells', 'Tesselate', and 'Relax Points' (#4345) 2026-07-17 01:40:39 -07:00
Keavon Chambers 048c458789 New nodes: Sort, Filter, Reverse, Shift, Shuffle, Number Sequence, List Indices, List Slice, Read Number (#4347) 2026-07-17 01:15:10 -07:00
Keavon Chambers d241cdcb2e Consolidate the rank promotion and cache chain registrations behind one value-type list (#4346) 2026-07-16 04:05:02 -07:00
Keavon Chambers a770448bc9 New nodes: Sum, Average, Minimum, Maximum, Any, All (#4344) 2026-07-15 23:41:46 -07:00
Keavon Chambers 2090e9979a 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
2026-07-15 19:03:01 -07:00
342 changed files with 18819 additions and 49386 deletions

No files matched your search

+1 -9
View File
@@ -1,14 +1,6 @@
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native and the wasm target.
[target.'cfg(not(target_family = "wasm"))']
# Frame pointers keep the native build profileable: the record model puts ~1KB frames on the stack and
# recurses past a hundred of them, so a sampling profiler copying a fixed slice of stack unwinds a frame
# or two and reports every sample as its own root. This must live here rather than under `[build]`, which
# Cargo ignores whenever any `target.*` section matches.
# A build id is what a profiler matches a recorded module against when it goes looking for symbols;
# the linker here does not emit one on its own, and without it an imported profile is all addresses.
# It has to be the `uuid` style: perf stores a 20 byte id, and the other styles here produce 32 bytes,
# which perf truncates and the profiler then reads as a mismatch against the file it was told to use.
rustflags = ["--cfg=web_sys_unstable_apis", "-C", "force-frame-pointers=yes", "-C", "link-arg=-Wl,--build-id=uuid"]
rustflags = ["--cfg=web_sys_unstable_apis"]
[target.'cfg(target_family = "wasm")']
rustflags = [
+4 -20
View File
@@ -2,25 +2,11 @@
"image": "mcr.microsoft.com/devcontainers/base:debian",
"features": {
"ghcr.io/devcontainers/features/rust:1": {
"profile": "default",
"targets": "wasm32-unknown-unknown"
"profile": "default"
},
"ghcr.io/devcontainers/features/node:1": {
// NOTICE: keep in sync with `.nvmrc`
"version": "24"
}
},
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
"containerEnv": {
"WASM_BINDGEN_CLI_VERSION": "0.2.121",
"CARGO_ABOUT_VERSION": "0.9.2",
"BINARYEN_VERSION": "130",
"CARGO_BINSTALL_VERSION": "1.23.0"
},
"onCreateCommand": {
"Install cargo-about and wasm-bindgen-cli": "curl -sSfL https://github.com/cargo-bins/cargo-binstall/releases/download/v$CARGO_BINSTALL_VERSION/cargo-binstall-$(uname -m)-unknown-linux-musl.tgz | tar xz -C $CARGO_HOME/bin && BINSTALL_DISABLE_TELEMETRY=true cargo binstall --no-confirm cargo-about@$CARGO_ABOUT_VERSION wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION",
"Install Binaryen wasm-opt": "curl -sSfL https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-$(uname -m)-linux.tar.gz | tar xz -C $CARGO_HOME/bin --strip-components=2 binaryen-version_$BINARYEN_VERSION/bin/wasm-opt"
"ghcr.io/devcontainers/features/node:1": {}
},
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
@@ -30,16 +16,14 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
"wayou.vscode-todo-highlight",
"streetsidesoftware.code-spell-checker",
// Git
// Helpful
"mhutchie.git-graph",
"qezhu.gitlink",
// Helpful
"wmaurer.change-case"
]
}
-34
View File
@@ -1,34 +0,0 @@
# Keavon Chambers (@Keavon [email protected])
# Dennis Kobert (@TrueDoctor [email protected])
/document/format/ @TrueDoctor
/node-graph/graph-craft/ @TrueDoctor
/node-graph/preprocessor/ @TrueDoctor
/node-graph/node-macro/ @TrueDoctor
/node-graph/interpreted-executor/ @TrueDoctor
/node-graph/graphene-cli/ @TrueDoctor
# Timon Schelling (@timon-schelling [email protected])
/.nix/ @timon-schelling
/flake.nix @timon-schelling
/flake.lock @timon-schelling
/desktop/ @timon-schelling
/editor/src/messages/future/ @timon-schelling
/editor/src/messages/resource_storage/ @timon-schelling
/editor/src/messages/network/ @timon-schelling
/editor/src/messages/app_window/ @timon-schelling
/editor/src/messages/clipboard/ @timon-schelling
/editor/src/messages/viewport/ @timon-schelling
/libraries/wgpu-sync/ @timon-schelling
/node-graph/libraries/canvas-utils/ @timon-schelling
/tools/cargo-run/ @timon-schelling
/tools/third-party-licenses/ @timon-schelling
+10 -24
View File
@@ -58,7 +58,6 @@ jobs:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
@@ -303,11 +302,9 @@ jobs:
pull-requests: write
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -344,9 +341,7 @@ jobs:
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/cargo-binstall@v1.23.0
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
uses: cargo-bins/cargo-binstall@main
- name: 🚧 Install native dependencies
shell: pwsh
@@ -502,11 +497,9 @@ jobs:
pull-requests: write
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -542,11 +535,6 @@ jobs:
package-lock.json
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/[email protected]
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
- name: 🚧 Install native dependencies
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -556,7 +544,8 @@ jobs:
brew install \
pkg-config \
openssl@3 \
llvm
llvm \
cargo-binstall
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
@@ -661,20 +650,17 @@ jobs:
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
find "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries" -name "*.dylib" -exec codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" {} \;
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
SUBMISSION_ID=$(xcrun notarytool submit "$ZIP_PATH" --wait --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | tee /dev/stderr | jq -r '.id')
STATUS=$(xcrun notarytool info "$SUBMISSION_ID" --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | jq -r '.status')
if [ "$STATUS" != "Accepted" ]; then
echo "Notarization failed with status: $STATUS"
xcrun notarytool log "$SUBMISSION_ID" --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
exit 1
fi
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
-1
View File
@@ -13,4 +13,3 @@ flamegraph.svg
.direnv
.DS_Store
.nvim.lua
/.devcontainer/devcontainer-lock.json
+12 -14
View File
@@ -1,10 +1,10 @@
{ pkgs, ... }:
let
version = "151.3.24+g2384915+chromium-151.0.7922.174";
version = "149.0.5+g6770623+chromium-149.0.7827.197";
hashes = {
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
};
selectSystem =
@@ -12,19 +12,17 @@ let
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
src = pkgs.fetchurl {
inherit url;
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
hash = selectSystem hashes;
};
in
pkgs.cef-binary.overrideAttrs {
pkgs.cef-binary.overrideAttrs (finalAttrs: {
version = builtins.head (builtins.split "\\+" version);
inherit src;
postInstall = ''
@@ -40,9 +38,9 @@ pkgs.cef-binary.overrideAttrs {
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf url;
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
}
})
-1
View File
@@ -6,7 +6,6 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
Generated
+29 -55
View File
@@ -370,31 +370,15 @@ dependencies = [
name = "brush-nodes"
version = "0.1.0"
dependencies = [
"brush-types",
"bytemuck",
"core-types",
"dyn-any",
"glam",
"graphene-hash",
"graphic-types",
"half",
"node-macro",
"raster-nodes",
"raster-types",
"serde",
"tokio",
"wgpu",
"wgpu-executor",
]
[[package]]
name = "brush-types"
version = "0.1.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-hash",
"serde",
]
[[package]]
@@ -610,8 +594,8 @@ dependencies = [
[[package]]
name = "cef"
version = "151.8.0+151.3.24"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-151#35712dc3948628245cf9810eadd045d9435442e8"
version = "149.2.0+149.0.5"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
dependencies = [
"anyhow",
"cargo_metadata 0.23.1",
@@ -629,8 +613,8 @@ dependencies = [
[[package]]
name = "cef-dll-sys"
version = "151.8.0+151.3.24"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-151#35712dc3948628245cf9810eadd045d9435442e8"
version = "149.2.0+149.0.5"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
dependencies = [
"anyhow",
"cmake",
@@ -1262,7 +1246,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1372,7 +1356,7 @@ checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
[[package]]
name = "download-cef"
version = "2.3.2"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-151#35712dc3948628245cf9810eadd045d9435442e8"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
dependencies = [
"bzip2",
"clap",
@@ -1541,7 +1525,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -1688,9 +1672,9 @@ dependencies = [
[[package]]
name = "font-types"
version = "0.12.3"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75382bc7392ef10aad10935f92fc3db36d2d4dad0e5d96d8d65e04f89a07ec39"
checksum = "0a7299a780854a6d391be2ae1c8521c9368471b559dbfd6a8dbd9f407eaff100"
dependencies = [
"bytemuck",
]
@@ -2056,7 +2040,6 @@ dependencies = [
"graphene-hash",
"graphic-types",
"gungraun",
"interpreted-executor",
"js-sys",
"log",
"mmap-io",
@@ -2143,17 +2126,12 @@ dependencies = [
"dyn-any",
"glam",
"graphene-hash",
"graphic-nodes",
"graphic-types",
"log",
"math-nodes",
"node-macro",
"rand",
"raster-types",
"repeat-nodes",
"serde",
"tsify",
"vector-types",
"wasm-bindgen",
]
@@ -2230,13 +2208,12 @@ dependencies = [
name = "graphic-nodes"
version = "0.1.0"
dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"node-macro",
"rand",
"raster-types",
"serde",
"vector-types",
@@ -2246,7 +2223,6 @@ dependencies = [
name = "graphic-types"
version = "0.1.0"
dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
@@ -2389,7 +2365,6 @@ dependencies = [
"base64",
"bitflags 2.11.0",
"color",
"core-types",
"derivative",
"document-container",
"document-format",
@@ -2408,7 +2383,6 @@ dependencies = [
"kurbo",
"log",
"math-parser",
"node-macro",
"num_enum",
"once_cell",
"preprocessor",
@@ -2453,6 +2427,7 @@ dependencies = [
"graphite-proc-macros",
"js-sys",
"log",
"node-macro",
"serde",
"serde-wasm-bindgen",
"serde_bytes",
@@ -2996,7 +2971,6 @@ dependencies = [
"graph-craft",
"graphene-core",
"graphene-std",
"graphic-types",
"gungraun",
"log",
"once_cell",
@@ -4088,7 +4062,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.45.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4616,7 +4590,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.59.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -4810,7 +4784,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types 0.12.3",
"font-types 0.12.2",
"once_cell",
]
@@ -4897,7 +4871,6 @@ name = "rendering"
version = "0.1.0"
dependencies = [
"base64",
"brush-types",
"core-types",
"dyn-any",
"glam",
@@ -4924,11 +4897,15 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"kurbo",
"log",
"node-macro",
"raster-types",
"serde",
"tokio",
"vector-nodes",
"vector-types",
]
@@ -5129,7 +5106,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.59.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -5197,7 +5174,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5940,7 +5917,7 @@ dependencies = [
"getrandom 0.3.3",
"once_cell",
"rustix",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6676,9 +6653,8 @@ dependencies = [
[[package]]
name = "vello"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af76ceb17b2869be23598baef40a9c8db4de86b87c60510c3bc245559275a617"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
dependencies = [
"bytemuck",
"futures-intrusive",
@@ -6695,9 +6671,8 @@ dependencies = [
[[package]]
name = "vello_encoding"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e31cd622201690d8dfe9fd8fea8d1ae59db1bfeea414856a617d1d03438418c"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
dependencies = [
"bytemuck",
"guillotiere",
@@ -6708,9 +6683,8 @@ dependencies = [
[[package]]
name = "vello_shaders"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abf943bd2920bfd22928a9c1bad39866f7ffcc1109b6ed924ab52773e3868a83"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
dependencies = [
"bytemuck",
"log",
@@ -7228,7 +7202,7 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.60.2",
]
[[package]]
+9 -9
View File
@@ -56,7 +56,7 @@ edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
repository = "https://github.com/GraphiteEditor/Graphite"
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
version = "0.0.0"
readme = "README.md"
publish = false
@@ -80,7 +80,6 @@ no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
brush-nodes = { path = "node-graph/nodes/brush" }
blending-nodes = { path = "node-graph/nodes/blending" }
@@ -140,7 +139,7 @@ wgpu = { version = "29.0", features = [
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.98"
web-sys = { version = "=0.3.98", features = [
@@ -167,8 +166,9 @@ url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.10"
vello_encoding = "0.10"
# TODO: Return to crates.io versions once a release after 0.9 ships the ramp bake's `interpolation_alpha_space` support
vello = { git = "https://github.com/linebender/vello.git", rev = "7073a85d61ee099d1d3595651ddf92302b074348" }
vello_encoding = { git = "https://github.com/linebender/vello.git", rev = "7073a85d61ee099d1d3595651ddf92302b074348" }
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
@@ -220,8 +220,8 @@ gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "151"
cef-dll-sys = "151"
cef = "149"
cef-dll-sys = "149"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
@@ -261,5 +261,5 @@ debug = true
[patch.crates-io]
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
-146
View File
@@ -1,146 +0,0 @@
# Index-level narrowing: investigation state
Branch `brick-wave-investigation`. Why `~/Downloads/brick-waves.graphite` gets no caching around its
palette lookup, what we changed, and where it still breaks.
## The original problem
`read_index` takes its *Loop Level* as a runtime input, so its signature can only declare
`ExtractIndices` → `ContextFeature::ExtractIndex(u8::MAX)` → `IndexLevels::all()`.
A saturated mask is absorbing in both places it is consumed:
- `nullify_index_levels` (`core-types/src/context.rs:283`) early-returns on `is_all()`, so nothing is
nullified
- `IndexLevels::lifted` (`context.rs:253`) has `u32::MAX => self`, so propagation never narrows it
- `ContextModification::contains` therefore always succeeds, so `we_introduce_new_deps` is false and
**no cache boundary is ever inserted anywhere in the cone**
In `brick-waves` the whole palette chain (`StringValue → split → item_at_index → join → split →
item_at_index → join → hex_to_color`) sits under this, and re-derives per lane: 36864 evaluations
where 96 would do.
## What we built (all in the preprocessor, none of it node-specific in the compiler)
`node-graph/preprocessor/src/lib.rs`:
1. `restore_declared_context_features` — re-declares `extract`/`inject`/`index_levels` from the
registry. A document serializes `extract`/`inject` (so it can carry a declaration from an older
build) and `index_levels` is `#[serde(skip)]`, so the field was only ever trustworthy by accident.
2. `determine_index_reads` — when `loop_level` is a literal, narrows `index_levels` to
`{loop_level + 1}` (the kernel reads `nth(loop_level + 1)`).
3. `expand_network` — carries the wrapper's declaration onto the substituted proto node. Needed
because a substitution replaces `implementation` with a template network, and the declaration
would otherwise stay on the wrapper that `flatten` dissolves.
**Verified neutral**: with narrowing disabled (`LEVEL_MODE=off`) the render is byte-identical to
baseline (`md5 87fd5f79b006`). So 1 and 3 are sound on their own.
## What narrowing achieves, and how it breaks
Masks stop being saturated: precise `{1,2,3,4,6,7}` appear, boundaries go 82 → 109.
`read_index` itself is **correct** under narrowing — verified at runtime, not inferred:
| mode | chain seen | value | distinct chains |
|---|---|---|---|
| `LEVEL_MODE=only0` | `[0, 0, N, 0]` depth 4 | `nth(2) = N` | 36864 |
| narrowed | `[0, 0, N]` depth 3 | `nth(2) = N` | **96** |
Both return the full range 0..95. Nullification strips only the trailing zeroed level and the read
still lands on `N`. That is the 384× win we were after.
But `hex_to_color` receives **1 distinct hex string instead of 63**, and the render collapses from 65
colors to 3. So the correct values are lost *downstream* of `read_index`, in the string chain.
## Ruled out
- **Off-by-one in the declared level.** Declaring 2, 3, or 4 for the `loop_level=1` reader gives
byte-identical broken output. The mask *value* is irrelevant; only its non-saturation matters.
- **Keeping level 0 as well.** No change.
- **`InjectIndex` falsely discharging the requirement.** `ContextFeature::InjectIndex → INDEX` exists
(`context.rs:534`) but the macro never emits it (`parsing.rs:1041`), so `inject` never contains
`INDEX`. `new_deps &= !inject` never clears it and `we_supply_existing_deps` never fires for it.
The feature is never falsely discharged — only the *level* arithmetic discharges.
- **A node overstating `pushed_levels`.** `PROBE_LEVELS` dumps every lift. The only requirement
deaths are legitimate lane-drives (`ItemAtIndex` on `list`, `Fill` on its color inputs, …). The two
`Repeat`s consume exactly the two levels `read_index` declares: `{0,1,2} → {0,1} → {0}`. The
boundary mask follows correctly from the declarations.
- **The split/item/join level arithmetic alone.** See the repro below — it does not collapse.
Narrowing only the `loop_level=0` reader (`LEVEL_MODE=only0`) is byte-identical to baseline and adds
4 boundaries, but measures the same as `off` (10s vs 10s over 8 repeats, debug). No partial win to
bank; the payoff needs the outer-loop reader.
## Minimal reproduction (does NOT yet reproduce)
`proto::test::nested_index_lookup_boundary_levels` in `graph-craft/src/proto.rs`, with helpers
`nested_index_lookup_network` and `index_level_boundaries`.
Builds `split → item_at_index → join` twice against two resolved-level `read_index` nodes, plus two
more level-consuming hops standing in for the `Repeat`s. Masks come out `0, 2, 1, 0, 1, 0` — every
boundary keeps a level its subtree reads. **No collapse.**
It is committed as a *characterization* test, not a correctness assertion: an earlier assertion
("a boundary requiring INDEX must retain some level") passed for the wrong reason, because the real
failure is mask `{0}` above content that varies over deeper levels, not an empty mask. That invariant
can't be written until the intended semantics are settled.
## Leading hypothesis
The missing ingredient is the real `Repeat`. `string_join` only *consumes* a level; `Repeat` also
**injects an index at runtime**. That asymmetry is where the model's two jobs diverge:
`ContextModification` computes a cache key *and* rewrites the chain the subtree receives. "A `Repeat`
supplies this level, so the requirement vanishes above it" is sound for the **key** — nothing above
the `Repeat` varies over it — but the subtree below still evaluates against whatever chain survives.
`repeat-nodes` is not a `graph-craft` dependency, so a repro including it belongs in
`interpreted-executor`, asserting on evaluated values rather than masks.
## Env gates (all inert when unset)
| var | where | effect |
|---|---|---|
| `LEVEL_MODE=off` | preprocessor | disable narrowing → byte-identical to baseline |
| `LEVEL_MODE=only0` / `only1` | preprocessor | narrow only that `loop_level` |
| `LEVEL_BUMP=N` | preprocessor | add N to declared level for `loop_level >= 1` |
| `PROBE_LEVELS` | `proto.rs` | dump every `lifted` call that changes a mask |
| `PROBE_READ_INDEX` | `gcore/src/context.rs` | dump each newly seen chain + value |
| `PROBE_HEX` | `math/src/lib.rs` | dump distinct `hex_to_color` inputs |
**Narrowing is ON by default, so the tree renders wrong.** Use `LEVEL_MODE=only0` for a correct run.
Remove the probes and the `LEVEL_MODE`/`LEVEL_BUMP` block before this is fit to merge.
## Artwork
Committed under `test-artwork/`:
- `brick-waves-v3.graphite` — the migrated working copy. **Every measurement in this document used
this file**; it is the one known to reproduce.
- `brick-waves.graphite` — the original as saved from the editor. Kept so nothing is lost, but it
**does not load on this branch**:
```
GraphError { identifier: "graphic_nodes::graphic::ToGraphicNode", error: "No implementations found" }
```
It predates the rebase, so it needs a migration that does not exist here yet. Use the v3 copy.
## Repro commands
```sh
cargo build -p graphene-cli
ART=test-artwork/brick-waves-v3.graphite
# correct vs broken
LEVEL_MODE=only0 ./target/debug/graphene-cli export $ART -o ok.svg # 65 colors
./target/debug/graphene-cli export $ART -o bad.svg # 3 colors
grep -o 'fill="#[0-9a-f]*"' bad.svg | sort -u | wc -l
# where distinctness is lost
PROBE_READ_INDEX=1 ./target/debug/graphene-cli export $ART -o p.svg # read_index: correct, 96 values
PROBE_HEX=1 ./target/debug/graphene-cli export $ART -o h.svg # hex_to_color: 1 input, should be 63
# compile-time masks (note: -o /dev/null short-circuits evaluation, use a real file)
./target/debug/graphene-cli compile -p $ART | grep -o "index_levels: IndexLevels([0-9]*)" | sort | uniq -c
```
-19
View File
@@ -1,19 +0,0 @@
Copyright (c) Graphite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
View File
File renamed without changes.
+1 -3
View File
@@ -80,6 +80,4 @@ Graphite is 100% community built and funded. Please become a part of keeping the
Are you a graphics programmer or Rust developer? Graphite aims to be one of the most approachable projects for putting your engineering skills to use in the world of open source. See [instructions here](https://graphite.art/volunteer/guide/) for setting up the project and getting started.
## License
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
*By submitting code for inclusion in the project, you are agreeing to license your changes under the Apache 2.0 license, and that you have the authority to do so. Some directories may have other licenses, like dual-licensed MIT/Apache 2.0, and code submissions to those directories mean you agree to the applicable license(s).*
+2
View File
@@ -22,6 +22,8 @@ accepted = [
workarounds = ["ring"]
ignore-build-dependencies = true
ignore-dev-dependencies = true
# Clearly Defined's API would occasionally (every few months) return errors for at least a full day (maybe some weird rate limiting?), but we can just disable to perform local checking (see #1653)
no-clearly-defined = true
# https://raw.githubusercontent.com/briansmith/webpki/main/LICENSE
# is the ISC license but test code within the repo is BSD-3-Clause, but is not compiled into the crate when we use it
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[9.4105020317595,0.0,0.0,9.4105020317595,-5.928761491996683,27Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_noLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"F64":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":7,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementaLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::AsU32Node"}},"visible":true,"skip_deduplication":false}],[11731553664207576737,{"inputs":[{"Node":{"node_id":14514477720912258595,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"namLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"PrLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argumenLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop"
version = "0.1.0"
description = "Graphite Desktop"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop-bundle"
version = "0.0.0"
description = "Graphite Desktop Bundle"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop-embedded-resources"
version = "0.1.0"
description = "Graphite Desktop Embedded Resources"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop-platform-linux"
version = "0.0.0"
description = "Graphite Desktop Platform Linux"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop-platform-mac"
version = "0.0.0"
description = "Graphite Desktop Platform Mac"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop-platform-win"
version = "0.0.0"
description = "Graphite Desktop Platform Windows"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+14 -18
View File
@@ -17,11 +17,11 @@ use winit::window::WindowId;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::input::InputState;
use crate::input::{InputAction, InputState};
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::ui::{UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
@@ -98,11 +98,6 @@ impl App {
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let completion_render_sender = start_render_sender.clone();
DesktopWrapper::set_completion_notifier(move || {
let _ = completion_render_sender.try_send(());
});
Self {
render_state: None,
wgpu_context,
@@ -285,9 +280,6 @@ impl App {
render_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
}
}
DesktopFrontendMessage::WindowUpdateDirectInput { enabled } => {
self.input_state.set_direct_input(enabled);
}
DesktopFrontendMessage::UpdateUIScale { scale } => {
self.ui_scale = scale;
self.resize();
@@ -555,16 +547,20 @@ impl ApplicationHandler for App {
if let Some(window) = &self.window {
window.end_pointer_lock();
}
self.ui.send(UiCommand::Input(
InputEvent::pointer().position(pointer_lock_position).moved().modifiers(self.input_state.modifiers()).build(),
));
self.ui.send(UiCommand::Input(WindowEvent::PointerMoved {
device_id: None,
position: pointer_lock_position,
primary: true,
source: winit::event::PointerSource::Mouse,
}));
}
self.input_state.process(
&event,
|message| self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Input(message))),
|input| self.ui.send(UiCommand::Input(input)),
);
for action in self.input_state.process(&event) {
match action {
InputAction::Ui(event) => self.ui.send(UiCommand::Input(event)),
InputAction::Editor(message) => self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
}
}
match event {
WindowEvent::CloseRequested => {
+118 -326
View File
@@ -1,33 +1,30 @@
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
use winit::keyboard::ModifiersState;
use crate::ui::{InputEvent, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use crate::wrapper::messages::{EditorPointerState, InputMessage, ModifierKeys, MouseKeys, ScrollDelta};
// Marks input event as observe-only, meaning it should not result in any input messages being send by the frontend.
// And should instead be ignored by frontend input processing and only be used to update the UI state (hover, cursor).
// TODO(Timon): Remove and find a less hacky solution
trait ObserveOnlyExt {
fn observe_only(self) -> Self;
}
impl ObserveOnlyExt for crate::ui::InputEventBuilder {
fn observe_only(self) -> Self {
self.num_lock(true)
}
}
use crate::ui::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use crate::wrapper::messages::{DesktopWrapperMessage, InputMessage, ModifierKeys, MouseKeys, PointerState, ScrollDelta};
pub(crate) struct InputState {
start: Instant,
viewport_info: Option<ViewportInfo>,
direct_input: bool,
modifiers: ModifiersState,
pointer_lock_position: Option<PhysicalPosition<f64>>,
modifier_keys: ModifierKeys,
pointer_position: PhysicalPosition<f64>,
pointer_state: PointerState,
click_tracker: ClickTracker,
shake_tracker: ShakeTracker,
pointer_keys: MouseKeys,
ui_capture: bool,
multiclick: Option<Multiclick>,
}
pub(crate) enum InputAction {
Ui(WindowEvent),
Editor(DesktopWrapperMessage),
}
impl InputAction {
fn editor(message: InputMessage) -> Self {
Self::Editor(DesktopWrapperMessage::Input(message))
}
}
impl InputState {
@@ -35,12 +32,12 @@ impl InputState {
Self {
start: Instant::now(),
viewport_info: None,
direct_input: false,
modifiers: ModifiersState::default(),
pointer_lock_position: None,
modifier_keys: ModifierKeys::empty(),
pointer_position: PhysicalPosition::default(),
pointer_state: PointerState::Hover { route: Route::Ui },
click_tracker: ClickTracker::default(),
shake_tracker: ShakeTracker::default(),
pointer_keys: MouseKeys::empty(),
ui_capture: true,
multiclick: None,
}
}
@@ -48,97 +45,58 @@ impl InputState {
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
}
pub(crate) fn set_direct_input(&mut self, enabled: bool) {
self.direct_input = enabled;
}
pub(crate) fn lock_pointer(&mut self) {
self.pointer_state = match self.pointer_state {
PointerState::Hover { route } => PointerState::Locked {
route,
keys: MouseKeys::empty(),
position: self.pointer_position,
},
PointerState::Stroke { route, keys } | PointerState::Locked { route, keys, .. } => PointerState::Locked {
route,
keys,
position: self.pointer_position,
},
};
self.pointer_lock_position = Some(self.pointer_position);
}
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
let PointerState::Locked {
route: resume,
keys,
position: restore,
} = self.pointer_state
else {
return None;
};
self.pointer_position = restore;
self.pointer_state = match keys.is_empty() {
true => PointerState::Hover { route: Route::Ui },
false => PointerState::Stroke { route: resume, keys },
};
Some(restore)
let position = self.pointer_lock_position.take();
if let Some(position) = position {
self.pointer_position = position;
}
position
}
pub(crate) fn pointer_locked(&self) -> bool {
matches!(self.pointer_state, PointerState::Locked { .. })
self.pointer_lock_position.is_some()
}
pub(crate) fn modifiers(&self) -> ModifiersState {
self.modifiers
}
pub(crate) fn process(&mut self, event: &WindowEvent, mut editor_callback: impl FnMut(InputMessage), mut ui_callback: impl FnMut(InputEvent)) {
pub(crate) fn process(&mut self, event: &WindowEvent) -> Vec<InputAction> {
match event {
WindowEvent::PointerMoved { position, source, .. } => {
self.pointer_position = *position;
let route = match self.pointer_state {
PointerState::Hover { .. } => {
let next = self.route(*position);
self.pointer_state = PointerState::Hover { route: next };
next
}
PointerState::Stroke { route, .. } => route,
PointerState::Locked { keys, route: resume, .. } => match keys.is_empty() {
true => Route::Ui,
false => resume,
},
let PointerSource::TabletTool { kind, data } = source else {
return vec![InputAction::Ui(event.clone())];
};
match route {
Route::Ui => ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).build()),
Route::Editor => {
if !self.pointer_locked() {
ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).observe_only().build());
}
let editor_mouse_state = match source {
PointerSource::TabletTool { kind, data } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys();
if self.shake_tracker.detect(*position, self.start.elapsed()) {
editor_callback(InputMessage::PointerShake { editor_mouse_state, modifier_keys });
}
editor_callback(InputMessage::PointerMove { editor_mouse_state, modifier_keys });
}
let ui_capture = if self.pointer_keys.is_empty() {
self.pointer_locked() || !self.in_viewport(*position)
} else {
self.ui_capture
};
if ui_capture {
return vec![InputAction::Ui(event.clone())];
}
vec![InputAction::editor(InputMessage::PointerMove {
editor_mouse_state: self.tablet_pointer_state(kind, data),
modifier_keys: self.modifier_keys,
})]
}
WindowEvent::PointerEntered { position, .. } => {
WindowEvent::PointerEntered { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } => {
self.pointer_position = *position;
ui_callback(InputEvent::pointer().position(*position).entered().modifiers(self.modifiers).build())
vec![InputAction::Ui(event.clone())]
}
WindowEvent::PointerLeft { position: Some(position), .. } => {
self.pointer_position = *position;
ui_callback(InputEvent::pointer().position(*position).exited().modifiers(self.modifiers).build())
}
WindowEvent::PointerLeft { position: None, .. } => ui_callback(InputEvent::pointer().exited().modifiers(self.modifiers).build()),
WindowEvent::PointerButton { state, button, position, .. } => {
self.pointer_position = *position;
let tablet = matches!(button, ButtonSource::TabletTool { .. });
// Stroke keeps capture decided from first button press until all buttons are released.
if state.is_pressed() && self.pointer_keys.is_empty() {
self.ui_capture = self.pointer_locked() || !tablet || !self.in_viewport(*position);
}
let mouse_button = button.clone().mouse_button();
let keys = match mouse_button {
Some(MouseButton::Left) => MouseKeys::LEFT,
@@ -148,82 +106,43 @@ impl InputState {
Some(MouseButton::Forward) => MouseKeys::FORWARD,
_ => MouseKeys::NONE,
};
let (pointer, route) = match self.pointer_state {
PointerState::Hover { route } => match (state.is_pressed(), keys.is_empty()) {
(true, false) => {
let route = self.route(*position);
(PointerState::Stroke { route, keys }, route)
}
(true, true) => (PointerState::Hover { route }, self.route(*position)),
(false, _) => (PointerState::Hover { route }, route),
},
PointerState::Stroke { route, keys: mut held } => {
match state.is_pressed() {
true => held.insert(keys),
false => held.remove(keys),
}
match held.is_empty() {
true => (PointerState::Hover { route }, route),
false => (PointerState::Stroke { route, keys: held }, route),
}
}
PointerState::Locked { route, keys: mut held, position } => {
let resume = if state.is_pressed() && held.is_empty() { Route::Ui } else { route };
match state.is_pressed() {
true => held.insert(keys),
false => held.remove(keys),
}
(PointerState::Locked { route: resume, keys: held, position }, Route::Ui)
}
};
self.pointer_state = pointer;
let count = mouse_button.map_or(1, |button| self.click_tracker.input(*position, button, *state));
match state {
ElementState::Pressed => self.pointer_keys.insert(keys),
ElementState::Released => self.pointer_keys.remove(keys),
}
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
let pointer = InputEvent::pointer().position(*position);
let input = match state {
ElementState::Pressed => pointer.pressed(button.clone(), count),
ElementState::Released => pointer.released(button.clone(), count),
}
.modifiers(self.modifiers);
if self.pointer_locked() || keys.is_empty() || !(back_or_forward || route == Route::Editor) {
ui_callback(input.build());
return;
}
if route == Route::Editor {
ui_callback(input.observe_only().build());
if self.pointer_locked() || !(back_or_forward || (tablet && !self.ui_capture)) {
return vec![InputAction::Ui(event.clone())];
}
let editor_mouse_state = match button {
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys();
let modifier_keys = self.modifier_keys;
match state {
ElementState::Pressed => editor_callback(InputMessage::PointerDown { editor_mouse_state, modifier_keys }),
ElementState::Released if count % 2 == 0 => {
editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys });
editor_callback(InputMessage::DoubleClick {
editor_mouse_state: EditorPointerState {
mouse_keys: keys,
..editor_mouse_state
},
modifier_keys,
});
ElementState::Pressed => vec![InputAction::editor(InputMessage::PointerDown { editor_mouse_state, modifier_keys })],
ElementState::Released => {
let mut actions = vec![InputAction::editor(InputMessage::PointerUp { editor_mouse_state, modifier_keys })];
if let Some(mouse_button) = mouse_button
&& self.track_multiclick(mouse_button, *position)
{
actions.push(InputAction::editor(InputMessage::DoubleClick {
editor_mouse_state: PointerState {
mouse_keys: keys,
..editor_mouse_state
},
modifier_keys,
}));
}
actions
}
ElementState::Released => editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys }),
}
}
WindowEvent::MouseWheel { delta, .. } => {
if self.pointer_locked() || self.ui_captures(self.pointer_position) {
let input = match delta {
MouseScrollDelta::LineDelta(x, y) => InputEvent::pointer().scrolled_lines(f64::from(*x), f64::from(*y)),
MouseScrollDelta::PixelDelta(position) => InputEvent::pointer().scrolled_pixels(position.x, position.y),
};
ui_callback(input.modifiers(self.modifiers).build());
return;
if self.pointer_locked() || !self.in_viewport(self.pointer_position) {
return vec![InputAction::Ui(event.clone())];
}
let (x, y) = match delta {
@@ -233,29 +152,34 @@ impl InputState {
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys(),
});
vec![InputAction::editor(InputMessage::WheelScroll {
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys,
})]
}
WindowEvent::PinchGesture { delta, .. } => {
if self.pointer_locked() || self.ui_captures(self.pointer_position) || !delta.is_normal() {
ui_callback(InputEvent::pointer().zoomed(*delta).modifiers(self.modifiers).build());
return;
if self.pointer_locked() || !self.in_viewport(self.pointer_position) || !delta.is_normal() {
return vec![InputAction::Ui(event.clone())];
}
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys() | ModifierKeys::CONTROL,
});
vec![InputAction::editor(InputMessage::WheelScroll {
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys | ModifierKeys::CONTROL,
})]
}
WindowEvent::ModifiersChanged(modifiers) => {
self.modifiers = modifiers.state();
let modifiers = modifiers.state();
self.modifier_keys = ModifierKeys::empty();
self.modifier_keys.set(ModifierKeys::SHIFT, modifiers.shift_key());
self.modifier_keys.set(ModifierKeys::CONTROL, modifiers.control_key());
self.modifier_keys.set(ModifierKeys::ALT, modifiers.alt_key());
self.modifier_keys.set(ModifierKeys::META_OR_COMMAND, modifiers.meta_key());
vec![InputAction::Ui(event.clone())]
}
WindowEvent::KeyboardInput { event, .. } => ui_callback(InputEvent::key(event).modifiers(self.modifiers).build()),
_ => {}
_ => vec![InputAction::Ui(event.clone())],
}
}
@@ -263,32 +187,21 @@ impl InputState {
self.viewport_info.as_ref().map_or(1., |info| info.scale)
}
fn ui_captures(&self, position: PhysicalPosition<f64>) -> bool {
!self.direct_input || !self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
fn in_viewport(&self, position: PhysicalPosition<f64>) -> bool {
self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
}
fn route(&self, position: PhysicalPosition<f64>) -> Route {
if self.ui_captures(position) { Route::Ui } else { Route::Editor }
}
fn pointer_keys(&self) -> MouseKeys {
match self.pointer_state {
PointerState::Hover { .. } => MouseKeys::empty(),
PointerState::Stroke { keys, .. } | PointerState::Locked { keys, .. } => keys,
}
}
fn pointer_state(&self) -> EditorPointerState {
EditorPointerState {
fn pointer_state(&self) -> PointerState {
PointerState {
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
mouse_keys: self.pointer_keys(),
mouse_keys: self.pointer_keys,
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
..Default::default()
}
}
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> EditorPointerState {
EditorPointerState {
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> PointerState {
PointerState {
pressure: data.force.map(|force| force.normalized(None)),
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
twist: data.twist.map(f64::from),
@@ -298,29 +211,19 @@ impl InputState {
}
}
fn modifier_keys(&self) -> ModifierKeys {
let mut keys = ModifierKeys::empty();
keys.set(ModifierKeys::SHIFT, self.modifiers.shift_key());
keys.set(ModifierKeys::CONTROL, self.modifiers.control_key());
keys.set(ModifierKeys::ALT, self.modifiers.alt_key());
keys.set(ModifierKeys::META_OR_COMMAND, self.modifiers.meta_key());
keys
fn track_multiclick(&mut self, button: MouseButton, position: PhysicalPosition<f64>) -> bool {
let now = Instant::now();
let travel = MULTICLICK_ALLOWED_TRAVEL as f64;
let double = self.multiclick.take().is_some_and(|click| {
click.button == button && now.duration_since(click.time) <= MULTICLICK_TIMEOUT && (position.x - click.position.x).abs() <= travel && (position.y - click.position.y).abs() <= travel
});
if !double {
self.multiclick = Some(Multiclick { button, time: now, position });
}
double
}
}
#[derive(Clone, Copy)]
enum PointerState {
Hover { route: Route },
Stroke { route: Route, keys: MouseKeys },
Locked { route: Route, keys: MouseKeys, position: PhysicalPosition<f64> },
}
#[derive(Clone, Copy, PartialEq)]
enum Route {
Ui,
Editor,
}
struct ViewportInfo {
x: f64,
y: f64,
@@ -335,119 +238,8 @@ impl ViewportInfo {
}
}
#[derive(Default)]
struct ClickTracker {
left: ClickChains,
right: ClickChains,
middle: ClickChains,
back: ClickChains,
forward: ClickChains,
}
impl ClickTracker {
fn input(&mut self, position: PhysicalPosition<f64>, button: MouseButton, state: ElementState) -> u32 {
let position = (position.x as i32, position.y as i32);
let clicks = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
MouseButton::Back => &mut self.back,
MouseButton::Forward => &mut self.forward,
_ => return 1,
};
let chain = match state {
ElementState::Pressed => &mut clicks.down,
ElementState::Released => &mut clicks.up,
};
let now = Instant::now();
let count = match chain {
Some(previous) => {
let within_time = now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT;
let dx = position.0.abs_diff(previous.position.0) as usize;
let dy = position.1.abs_diff(previous.position.1) as usize;
let within_distance = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
if within_time && within_distance { previous.count.saturating_add(1) } else { 1 }
}
None => 1,
};
*chain = Some(Click { time: now, position, count });
count
}
}
#[derive(Default)]
struct ClickChains {
down: Option<Click>,
up: Option<Click>,
}
struct Click {
struct Multiclick {
button: MouseButton,
time: Instant,
position: (i32, i32),
count: u32,
}
#[derive(Default)]
struct ShakeTracker {
samples: VecDeque<(PhysicalPosition<f64>, Duration)>,
last: Option<Duration>,
}
// Keep heuristic and constants in sync with `detectShake` in `frontend/src/utility-functions/input.ts`.
impl ShakeTracker {
const SENSITIVITY_DIRECTION_CHANGES: usize = 3;
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO: f64 = 0.1;
const DETECTION_WINDOW: Duration = Duration::from_millis(500);
const DEBOUNCE: Duration = Duration::from_millis(1000);
fn detect(&mut self, position: PhysicalPosition<f64>, now: Duration) -> bool {
self.samples.push_back((position, now));
while self.samples.front().is_some_and(|&(_, time)| now.saturating_sub(time) > Self::DETECTION_WINDOW) {
self.samples.pop_front();
}
if self.samples.len() <= 3 || self.last.is_some_and(|time| now.saturating_sub(time) <= Self::DEBOUNCE) {
return false;
}
let mut total_distance_squared = 0.;
for i in 1..self.samples.len() {
let (p1, _) = self.samples[i - 1];
let (p2, _) = self.samples[i];
total_distance_squared += (p2.x - p1.x).powi(2) + (p2.y - p1.y).powi(2);
}
let mut direction_changes = 0;
let mut average = PhysicalPosition::new(0., 0.);
let interior_count = self.samples.len() - 2;
for i in 0..interior_count {
let (p1, _) = self.samples[i];
let (p2, _) = self.samples[i + 1];
let (p3, _) = self.samples[i + 2];
let vector1 = (p2.x - p1.x, p2.y - p1.y);
let vector2 = (p3.x - p2.x, p3.y - p2.y);
if vector1.0 * vector2.0 + vector1.1 * vector2.1 < 0. {
direction_changes += 1;
}
average.x += p2.x;
average.y += p2.y;
}
average.x /= interior_count as f64;
average.y /= interior_count as f64;
let (last, _) = self.samples[self.samples.len() - 1];
let displacement_squared = (last.x - average.x).powi(2) + (last.y - average.y).powi(2);
if Self::SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * total_distance_squared >= displacement_squared && direction_changes >= Self::SENSITIVITY_DIRECTION_CHANGES {
self.last = Some(now);
self.samples.clear();
return true;
}
false
}
position: PhysicalPosition<f64>,
}
+5 -4
View File
@@ -52,12 +52,13 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return srgb_to_linear(immediates.background_color);
}
let ui_sample = textureSample(t_ui, s_diffuse, ui_coordinate);
if (ui_sample.a >= 0.999) {
return srgb_to_linear(ui_sample);
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
if (ui_linear.a >= 0.999) {
return ui_linear;
}
let ui_srgb = unpremultiply(ui_sample);
// UI texture is premultiplied, we need to unpremultiply before blending
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
+9 -9
View File
@@ -1,7 +1,7 @@
use wgpu::PresentMode;
use crate::window::Window;
use crate::wrapper::{Texture, WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
use crate::wrapper::{WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
#[derive(derivative::Derivative)]
#[derivative(Debug)]
@@ -10,14 +10,14 @@ pub(crate) struct RenderState {
executor: WgpuExecutor,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
transparent_texture: Texture,
transparent_texture: std::sync::Arc<wgpu::Texture>,
sampler: wgpu::Sampler,
desired_width: u32,
desired_height: u32,
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<Texture>,
overlays_texture: Option<Texture>,
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
@@ -46,8 +46,8 @@ impl RenderState {
surface.configure(&context.device, &config);
let transparent_texture = Texture::from(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("transparent_fallback"),
let transparent_texture = std::sync::Arc::new(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("Transparent Texture"),
size: wgpu::Extent3d {
width: 1,
height: 1,
@@ -193,7 +193,7 @@ impl RenderState {
self.surface_outdated = true;
}
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: Texture) {
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: std::sync::Arc<wgpu::Texture>) {
self.viewport_texture = Some(viewport_texture);
self.update_bindgroup();
}
@@ -228,10 +228,10 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
match result {
Ok(texture) => {
self.overlays_texture = Some(texture);
self.overlays_texture = Some(texture.into());
}
Err(e) => {
self.overlays_texture = None;
+6 -4
View File
@@ -223,7 +223,6 @@ fn create_browser(delegate: BrowserDelegate, frames: FrameStreamer, view_info_se
.map(|browser| BrowserContext {
delegate,
browser,
input: input::InputState::default(),
view_info_sender,
_instance_dir: instance_dir,
})
@@ -253,8 +252,12 @@ pub(crate) enum InitError {
pub(crate) struct CefContextHandle;
impl CefContextHandle {
pub(crate) fn process_input(&self, event: InputEvent) {
with_context(move |context| input::process(&mut context.input, &context.browser, &event));
pub(crate) fn apply_input(&self, events: Vec<InputEvent>) {
with_context(move |context| {
for event in &events {
input::apply(&context.browser, event);
}
});
}
pub(crate) fn update_view_info(&self, update: ViewInfoUpdate) {
@@ -273,7 +276,6 @@ impl CefContextHandle {
struct BrowserContext {
delegate: BrowserDelegate,
browser: Browser,
input: input::InputState,
view_info_sender: Sender<ViewInfoUpdate>,
_instance_dir: TempDir,
}
+209 -191
View File
@@ -1,235 +1,253 @@
pub(crate) mod event;
pub(crate) use event::InputEvent;
use cef::sys::{cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
mod keymap;
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
use cef::sys::{cef_event_flags_t, cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::dpi::PhysicalPosition;
use winit::keyboard::{Key, KeyLocation, NamedKey};
mod state;
pub(crate) use state::{CefModifiers, InputState};
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use event::{InputEventKind, KeyAction, Modifiers, MouseButton, PointerAction};
#[derive(Default)]
pub(crate) struct InputState {
position: PhysicalPosition<f64>,
buttons: ButtonStates,
/// A window input translated into the plain data CEF consumes — no winit types, so it can
/// be applied to a browser living in another process.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum InputEvent {
MouseMove { data: MouseData, leave: bool },
MouseClick { data: MouseData, button: MouseButtonKind, up: bool, click_count: i32 },
MouseWheel { data: MouseData, delta_x: i32, delta_y: i32 },
Key(KeyData),
}
impl InputState {
fn pointer_move(&mut self, position: PhysicalPosition<f64>) -> bool {
let moved = (position.x as i32, position.y as i32) != (self.position.x as i32, self.position.y as i32);
self.position = position;
moved
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct MouseData {
pub(crate) x: i32,
pub(crate) y: i32,
pub(crate) modifiers: u32,
}
pub(crate) fn process(state: &mut InputState, browser: &Browser, event: &InputEvent) {
let Some(host) = browser.host() else { return };
match &event.kind {
InputEventKind::Pointer { position, action } => {
let position = position.unwrap_or(state.position);
match *action {
PointerAction::Move => {
if !state.pointer_move(position) {
return;
}
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
}
PointerAction::Enter => {
state.pointer_move(position);
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
}
PointerAction::Exit => {
state.pointer_move(position);
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 1);
}
PointerAction::Press { button, count } | PointerAction::Release { button, count } => {
state.pointer_move(position);
let cef_button = match button {
MouseButton::Left => cef_mouse_button_type_t::MBT_LEFT,
MouseButton::Right => cef_mouse_button_type_t::MBT_RIGHT,
MouseButton::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
MouseButton::Unknown => return,
};
let up = matches!(action, PointerAction::Release { .. });
state.buttons.update(button, !up);
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum MouseButtonKind {
Left,
Right,
Middle,
}
// CEF only understands single, double and triple clicks; further clicks alternate between double and triple.
let count = match count {
0 | 1 => 1,
count if count % 2 == 0 => 2,
_ => 3,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum KeyEventKind {
RawKeyDown,
KeyUp,
Char,
}
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_click_event(Some(&mouse_event(position, flags)), cef::MouseButtonType::from(cef_button), up as i32, count);
}
PointerAction::ScrollLines { x, y } => {
let flags = event_flags(&event.modifiers, &state.buttons);
let delta_x = (x * SCROLL_LINE_WIDTH * SCROLL_SPEED_X) as i32;
let delta_y = (y * SCROLL_LINE_HEIGHT * SCROLL_SPEED_Y) as i32;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), delta_x, delta_y);
}
PointerAction::ScrollPixels { x, y } => {
let flags = event_flags(&event.modifiers, &state.buttons) | PRECISION_SCROLLING_DELTA;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), (x * SCROLL_SPEED_X) as i32, (y * SCROLL_SPEED_Y) as i32);
}
PointerAction::Zoom(delta) => {
if !delta.is_normal() {
return;
}
let flags = CONTROL_DOWN | PRECISION_SCROLLING_DELTA;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), 0, (delta * PINCH_ZOOM_SPEED).round() as i32);
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct KeyData {
pub(crate) kind: KeyEventKind,
pub(crate) modifiers: u32,
pub(crate) windows_key_code: i32,
pub(crate) native_key_code: i32,
pub(crate) character: u16,
pub(crate) unmodified_character: u16,
}
/// Turns a winit event into zero or more [`InputEvent`]s, updating the tracked input state
/// (cursor position, click counting, modifiers) along the way.
pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Vec<InputEvent> {
match event {
WindowEvent::PointerMoved { position, .. } => {
if !input_state.cursor_move(position) {
return Vec::new();
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
InputEventKind::Key {
key,
key_without_modifiers,
physical_key,
location,
text,
action,
} => {
let mut flags = event_flags(&event.modifiers, &state.buttons);
WindowEvent::PointerEntered { position, .. } => {
let _ = input_state.cursor_move(position);
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
WindowEvent::PointerLeft { position, .. } => {
if let Some(position) = position {
let _ = input_state.cursor_move(position);
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: true,
}]
}
WindowEvent::PointerButton { state, button, position, .. } => {
let mouse_button = match button {
ButtonSource::Mouse(mouse_button) => Some(*mouse_button),
ButtonSource::TabletTool { button, .. } => (*button).into(),
_ => None, // TODO: Handle touch input
};
let Some(mouse_button) = mouse_button else {
return Vec::new();
};
let own_flag = match key {
Key::Named(NamedKey::Shift) => SHIFT_DOWN,
Key::Named(NamedKey::Control) => CONTROL_DOWN,
Key::Named(NamedKey::Alt) => ALT_DOWN,
Key::Named(NamedKey::AltGraph) => ALTGR_DOWN,
Key::Named(NamedKey::Meta) => COMMAND_DOWN,
let _ = input_state.cursor_move(position);
let click_count = input_state.mouse_input(&mouse_button, state).into();
let up = matches!(state, ElementState::Released);
let button = match mouse_button {
MouseButton::Left => MouseButtonKind::Left,
MouseButton::Right => MouseButtonKind::Right,
MouseButton::Middle => MouseButtonKind::Middle,
_ => return Vec::new(),
};
vec![InputEvent::MouseClick {
data: input_state.mouse_data(),
button,
up,
click_count,
}]
}
WindowEvent::MouseWheel { delta, phase: _, device_id: _, .. } => {
let (mut delta_x, mut delta_y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
};
delta_x *= SCROLL_SPEED_X as f32;
delta_y *= SCROLL_SPEED_Y as f32;
vec![InputEvent::MouseWheel {
data: input_state.mouse_data(),
delta_x: delta_x as i32,
delta_y: delta_y as i32,
}]
}
WindowEvent::ModifiersChanged(modifiers) => {
input_state.modifiers_changed(&modifiers.state());
Vec::new()
}
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
let mut kind = match (event.state, &event.logical_key) {
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => KeyEventKind::Char,
(ElementState::Pressed, _) => KeyEventKind::RawKeyDown,
(ElementState::Released, _) => KeyEventKind::KeyUp,
};
let modifiers = input_state.cef_modifiers(&event.location, event.repeat).into();
let windows_key_code = match &event.logical_key {
winit::keyboard::Key::Named(named) => named.to_vk_bits(),
winit::keyboard::Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
_ => 0,
};
match action {
KeyAction::Press | KeyAction::Repeat => flags |= own_flag,
KeyAction::Release => flags &= !own_flag,
}
flags |= match location {
KeyLocation::Left => IS_LEFT,
KeyLocation::Right => IS_RIGHT,
KeyLocation::Numpad => IS_KEY_PAD,
KeyLocation::Standard => 0,
};
if *action == KeyAction::Repeat {
flags |= IS_REPEAT;
}
let native_key_code = event.physical_key.to_native_keycode();
let windows_key_code = match key {
Key::Named(named) => named.to_vk_bits(),
Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
_ => 0,
};
let native_key_code = physical_key.to_native_keycode();
let char_representation = key.to_char_representation();
let char_representation = event.logical_key.to_char_representation();
#[allow(unused_mut)]
let mut character = char_representation as u16;
let unmodified_character = key_without_modifiers.to_char_representation() as u16;
if event.state == ElementState::Pressed && character != 0 {
kind = KeyEventKind::Char;
}
let unmodified_character = event.key_without_modifiers.to_char_representation() as u16;
#[cfg(target_os = "macos")] // See https://www.magpcss.org/ceforum/viewtopic.php?start=10&t=11650
if character == 0 && unmodified_character == 0 && text.is_some() {
if character == 0 && unmodified_character == 0 && event.text_with_all_modifiers.is_some() {
character = 1;
}
#[cfg(not(target_os = "macos"))]
let _ = text;
let key_event = |kind: cef_key_event_type_t, windows_key_code: i32| KeyEvent {
type_: kind.into(),
modifiers: flags,
let key = KeyData {
kind,
modifiers,
windows_key_code,
native_key_code,
character,
unmodified_character,
..Default::default()
};
match action {
KeyAction::Press | KeyAction::Repeat if char_representation != '\0' => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_CHAR, char_representation as i32)));
}
KeyAction::Press | KeyAction::Repeat => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
}
KeyAction::Release => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_KEYUP, windows_key_code)));
}
if kind == KeyEventKind::Char {
// CEF expects a raw key-down before the character event it produces.
vec![
InputEvent::Key(KeyData {
kind: KeyEventKind::RawKeyDown,
..key
}),
InputEvent::Key(KeyData {
windows_key_code: char_representation as i32,
..key
}),
]
} else {
vec![InputEvent::Key(key)]
}
}
WindowEvent::PinchGesture { delta, .. } => {
if !delta.is_normal() {
return Vec::new();
}
let data = MouseData {
modifiers: CefModifiers::PINCH_MODIFIERS.into(),
..input_state.mouse_data()
};
vec![InputEvent::MouseWheel {
data,
delta_x: 0,
delta_y: (delta * PINCH_ZOOM_SPEED).round() as i32,
}]
}
_ => Vec::new(),
}
}
#[derive(Default)]
struct ButtonStates {
left: bool,
right: bool,
middle: bool,
}
impl ButtonStates {
fn update(&mut self, button: MouseButton, held: bool) {
match button {
MouseButton::Left => self.left = held,
MouseButton::Right => self.right = held,
MouseButton::Middle => self.middle = held,
MouseButton::Unknown => {}
/// Sends a translated [`InputEvent`] to the browser. Must run on the thread owning the browser.
pub(crate) fn apply(browser: &Browser, event: &InputEvent) {
let Some(host) = browser.host() else { return };
match event {
InputEvent::MouseMove { data, leave } => {
host.send_mouse_move_event(Some(&data.into()), *leave as i32);
}
InputEvent::MouseClick { data, button, up, click_count } => {
let cef_button = cef::MouseButtonType::from(match button {
MouseButtonKind::Left => cef_mouse_button_type_t::MBT_LEFT,
MouseButtonKind::Right => cef_mouse_button_type_t::MBT_RIGHT,
MouseButtonKind::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
});
host.send_mouse_click_event(Some(&data.into()), cef_button, *up as i32, *click_count);
}
InputEvent::MouseWheel { data, delta_x, delta_y } => {
host.send_mouse_wheel_event(Some(&data.into()), *delta_x, *delta_y);
}
InputEvent::Key(key) => {
let key_event = KeyEvent {
type_: match key.kind {
KeyEventKind::RawKeyDown => cef_key_event_type_t::KEYEVENT_RAWKEYDOWN,
KeyEventKind::KeyUp => cef_key_event_type_t::KEYEVENT_KEYUP,
KeyEventKind::Char => cef_key_event_type_t::KEYEVENT_CHAR,
}
.into(),
modifiers: key.modifiers,
windows_key_code: key.windows_key_code,
native_key_code: key.native_key_code,
character: key.character,
unmodified_character: key.unmodified_character,
..Default::default()
};
host.send_key_event(Some(&key_event));
}
}
}
fn mouse_event(position: PhysicalPosition<f64>, flags: u32) -> MouseEvent {
MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: flags,
impl From<&MouseData> for MouseEvent {
fn from(data: &MouseData) -> Self {
MouseEvent {
x: data.x,
y: data.y,
modifiers: data.modifiers,
}
}
}
fn event_flags(modifiers: &Modifiers, buttons: &ButtonStates) -> u32 {
let bit = |condition: bool, flag: u32| if condition { flag } else { 0 };
bit(modifiers.shift, SHIFT_DOWN)
| bit(modifiers.control, CONTROL_DOWN)
| bit(modifiers.alt, ALT_DOWN)
| bit(modifiers.alt_graph, ALTGR_DOWN)
| bit(modifiers.meta, COMMAND_DOWN)
| bit(modifiers.caps_lock, CAPS_LOCK_ON)
| bit(modifiers.num_lock, NUM_LOCK_ON)
| bit(buttons.left, LEFT_MOUSE_BUTTON)
| bit(buttons.right, RIGHT_MOUSE_BUTTON)
| bit(buttons.middle, MIDDLE_MOUSE_BUTTON)
}
const fn flag(flag: cef_event_flags_t) -> u32 {
#[cfg(not(target_os = "windows"))]
{
flag.0
}
#[cfg(target_os = "windows")]
{
flag.0 as u32
}
}
const SHIFT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_SHIFT_DOWN);
const CONTROL_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_CONTROL_DOWN);
const ALT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALT_DOWN);
const ALTGR_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALTGR_DOWN);
const COMMAND_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_COMMAND_DOWN);
const CAPS_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_CAPS_LOCK_ON);
const NUM_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_NUM_LOCK_ON);
const LEFT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON);
const MIDDLE_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON);
const RIGHT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON);
const IS_LEFT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_LEFT);
const IS_RIGHT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_RIGHT);
const IS_KEY_PAD: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_KEY_PAD);
const IS_REPEAT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_REPEAT);
const PRECISION_SCROLLING_DELTA: u32 = flag(cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA);
-245
View File
@@ -1,245 +0,0 @@
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, KeyEvent};
use winit::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey, SmolStr};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct InputEvent {
pub(crate) kind: InputEventKind,
pub(crate) modifiers: Modifiers,
}
impl InputEvent {
pub fn pointer() -> PointerInputEventBuilder {
PointerInputEventBuilder { position: UnknownPosition }
}
pub fn key(event: &KeyEvent) -> InputEventBuilder {
let action = match (event.state, event.repeat) {
(ElementState::Pressed, false) => KeyAction::Press,
(ElementState::Pressed, true) => KeyAction::Repeat,
(ElementState::Released, _) => KeyAction::Release,
};
InputEventBuilder::new(InputEventKind::Key {
key: event.logical_key.clone(),
key_without_modifiers: event.key_without_modifiers.clone(),
physical_key: event.physical_key,
location: event.location,
text: event.text_with_all_modifiers.clone(),
action,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MouseButton {
Left,
Right,
Middle,
Unknown,
}
impl From<winit::event::MouseButton> for MouseButton {
fn from(button: winit::event::MouseButton) -> Self {
match button {
winit::event::MouseButton::Left => Self::Left,
winit::event::MouseButton::Right => Self::Right,
winit::event::MouseButton::Middle => Self::Middle,
_ => Self::Unknown,
}
}
}
impl From<winit::event::ButtonSource> for MouseButton {
fn from(button: winit::event::ButtonSource) -> Self {
button.mouse_button().map_or(Self::Unknown, Self::from)
}
}
#[must_use]
#[derive(Clone, Debug)]
pub struct PointerInputEventBuilder<P = UnknownPosition> {
position: P,
}
impl PointerInputEventBuilder<UnknownPosition> {
pub fn position(self, position: PhysicalPosition<f64>) -> PointerInputEventBuilder<PhysicalPosition<f64>> {
PointerInputEventBuilder { position }
}
}
impl PointerInputEventBuilder<PhysicalPosition<f64>> {
pub fn moved(self) -> InputEventBuilder {
self.finish(PointerAction::Move)
}
pub fn entered(self) -> InputEventBuilder {
self.finish(PointerAction::Enter)
}
}
impl<P: PointerPosition> PointerInputEventBuilder<P> {
pub fn exited(self) -> InputEventBuilder {
self.finish(PointerAction::Exit)
}
pub fn pressed(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
self.finish(PointerAction::Press { button: button.into(), count })
}
pub fn released(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
self.finish(PointerAction::Release { button: button.into(), count })
}
pub fn scrolled_lines(self, x: f64, y: f64) -> InputEventBuilder {
self.finish(PointerAction::ScrollLines { x, y })
}
pub fn scrolled_pixels(self, x: f64, y: f64) -> InputEventBuilder {
self.finish(PointerAction::ScrollPixels { x, y })
}
pub fn zoomed(self, delta: f64) -> InputEventBuilder {
self.finish(PointerAction::Zoom(delta))
}
fn finish(self, action: PointerAction) -> InputEventBuilder {
InputEventBuilder::new(InputEventKind::Pointer {
position: self.position.position(),
action,
})
}
}
#[must_use]
#[derive(Clone, Debug)]
pub struct InputEventBuilder {
kind: InputEventKind,
modifiers: Modifiers,
}
impl InputEventBuilder {
fn new(kind: InputEventKind) -> Self {
Self {
kind,
modifiers: Modifiers::default(),
}
}
pub fn shift(mut self, on: bool) -> Self {
self.modifiers.shift = on;
self
}
pub fn control(mut self, on: bool) -> Self {
self.modifiers.control = on;
self
}
pub fn alt(mut self, on: bool) -> Self {
self.modifiers.alt = on;
self
}
pub fn alt_graph(mut self, on: bool) -> Self {
self.modifiers.alt_graph = on;
self
}
pub fn meta(mut self, on: bool) -> Self {
self.modifiers.meta = on;
self
}
pub fn caps_lock(mut self, on: bool) -> Self {
self.modifiers.caps_lock = on;
self
}
pub fn num_lock(mut self, on: bool) -> Self {
self.modifiers.num_lock = on;
self
}
pub fn modifiers(mut self, modifiers: ModifiersState) -> Self {
self.modifiers.shift = modifiers.shift_key();
self.modifiers.control = modifiers.control_key();
self.modifiers.alt = modifiers.alt_key();
self.modifiers.meta = modifiers.meta_key();
self
}
pub fn build(self) -> InputEvent {
InputEvent {
kind: self.kind,
modifiers: self.modifiers,
}
}
}
#[expect(private_bounds)]
pub trait PointerPosition: OptionalPosition {}
impl PointerPosition for UnknownPosition {}
impl PointerPosition for PhysicalPosition<f64> {}
#[derive(Clone, Copy, Debug)]
pub struct UnknownPosition;
trait OptionalPosition {
fn position(self) -> Option<PhysicalPosition<f64>>;
}
impl OptionalPosition for UnknownPosition {
fn position(self) -> Option<PhysicalPosition<f64>> {
None
}
}
impl OptionalPosition for PhysicalPosition<f64> {
fn position(self) -> Option<PhysicalPosition<f64>> {
Some(self)
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum InputEventKind {
Pointer {
position: Option<PhysicalPosition<f64>>,
action: PointerAction,
},
Key {
key: Key,
key_without_modifiers: Key,
physical_key: PhysicalKey,
location: KeyLocation,
text: Option<SmolStr>,
action: KeyAction,
},
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum PointerAction {
Move,
Enter,
Exit,
Press { button: MouseButton, count: u32 },
Release { button: MouseButton, count: u32 },
ScrollLines { x: f64, y: f64 },
ScrollPixels { x: f64, y: f64 },
Zoom(f64),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum KeyAction {
Press,
Repeat,
Release,
}
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub(crate) struct Modifiers {
pub(crate) shift: bool,
pub(crate) control: bool,
pub(crate) alt: bool,
pub(crate) alt_graph: bool,
pub(crate) meta: bool,
pub(crate) caps_lock: bool,
pub(crate) num_lock: bool,
}
+256
View File
@@ -0,0 +1,256 @@
use cef::sys::cef_event_flags_t;
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, MouseButton};
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
use super::MouseData;
use crate::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
#[derive(Default)]
pub(crate) struct InputState {
modifiers: ModifiersState,
mouse_position: MousePosition,
mouse_state: MouseState,
mouse_click_tracker: ClickTracker,
}
impl InputState {
pub(crate) fn modifiers_changed(&mut self, modifiers: &ModifiersState) {
self.modifiers = *modifiers;
}
pub(crate) fn modifiers_apply_key_event(&mut self, key: &Key, state: &ElementState) {
let bits = match key {
Key::Named(NamedKey::Shift) => ModifiersState::SHIFT,
Key::Named(NamedKey::Control) => ModifiersState::CONTROL,
Key::Named(NamedKey::Alt) => ModifiersState::ALT,
Key::Named(NamedKey::Meta) => ModifiersState::META,
_ => return,
};
let is_pressed = matches!(state, ElementState::Pressed);
self.modifiers.set(bits, is_pressed);
}
pub(crate) fn cursor_move(&mut self, position: &PhysicalPosition<f64>) -> bool {
let new = position.into();
if self.mouse_position == new {
return false;
}
self.mouse_position = new;
true
}
pub(crate) fn mouse_input(&mut self, button: &MouseButton, state: &ElementState) -> ClickCount {
self.mouse_state.update(button, state);
self.mouse_click_tracker.input(button, state, self.mouse_position)
}
pub(crate) fn cef_modifiers(&self, location: &KeyLocation, is_repeat: bool) -> CefModifiers {
CefModifiers::new(self, location, is_repeat)
}
pub(crate) fn cef_mouse_modifiers(&self) -> CefModifiers {
self.cef_modifiers(&KeyLocation::Standard, false)
}
pub(crate) fn mouse_data(&self) -> MouseData {
MouseData {
x: self.mouse_position.x,
y: self.mouse_position.y,
modifiers: self.cef_mouse_modifiers().into(),
}
}
}
#[derive(Default, Clone, Copy, Eq, PartialEq)]
pub(crate) struct MousePosition {
x: i32,
y: i32,
}
impl From<&PhysicalPosition<f64>> for MousePosition {
fn from(position: &PhysicalPosition<f64>) -> Self {
Self {
x: position.x as i32,
y: position.y as i32,
}
}
}
#[derive(Default, Clone)]
pub(crate) struct MouseState {
left: bool,
right: bool,
middle: bool,
}
impl MouseState {
pub(crate) fn update(&mut self, button: &MouseButton, state: &ElementState) {
match state {
ElementState::Pressed => match button {
MouseButton::Left => self.left = true,
MouseButton::Right => self.right = true,
MouseButton::Middle => self.middle = true,
_ => {}
},
ElementState::Released => match button {
MouseButton::Left => self.left = false,
MouseButton::Right => self.right = false,
MouseButton::Middle => self.middle = false,
_ => {}
},
}
}
}
#[derive(Default)]
struct ClickTracker {
left: Option<ClickRecord>,
middle: Option<ClickRecord>,
right: Option<ClickRecord>,
}
impl ClickTracker {
fn input(&mut self, button: &MouseButton, state: &ElementState, position: MousePosition) -> ClickCount {
let record = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
_ => return ClickCount::Single,
};
let Some(record) = record else {
*record = Some(ClickRecord {
down_position: position,
up_position: position,
..Default::default()
});
return ClickCount::Single;
};
let now = Instant::now();
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
let (prev_count, prev_position) = match state {
ElementState::Pressed => (record.down_count, record.down_position),
ElementState::Released => (record.up_count, record.up_position),
};
let dx = position.x.abs_diff(prev_position.x) as usize;
let dy = position.y.abs_diff(prev_position.y) as usize;
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let count = match (prev_count, within_time, within_dist) {
(ClickCount::Single, true, true) => ClickCount::Double,
(ClickCount::Double, true, true) => ClickCount::Triple,
(ClickCount::Triple, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
record.time = now;
match state {
ElementState::Pressed => {
record.down_position = position;
record.down_count = count;
}
ElementState::Released => {
record.up_position = position;
record.up_count = count;
}
}
count
}
}
#[derive(Clone, Copy, PartialEq, Default)]
pub(crate) enum ClickCount {
#[default]
Single,
Double,
Triple,
}
impl From<ClickCount> for i32 {
fn from(count: ClickCount) -> i32 {
match count {
ClickCount::Single => 1,
ClickCount::Double => 2,
ClickCount::Triple => 3,
}
}
}
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
down_position: MousePosition,
up_position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
down_position: Default::default(),
up_position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
}
}
pub(crate) struct CefModifiers(cef_event_flags_t);
impl CefModifiers {
fn new(input_state: &InputState, location: &KeyLocation, is_repeat: bool) -> Self {
let mut inner = cef_event_flags_t::EVENTFLAG_NONE;
if input_state.modifiers.shift_key() {
inner |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;
}
if input_state.modifiers.control_key() {
inner |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;
}
if input_state.modifiers.alt_key() {
inner |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;
}
if input_state.modifiers.meta_key() {
inner |= cef_event_flags_t::EVENTFLAG_COMMAND_DOWN;
}
if input_state.mouse_state.left {
inner |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON;
}
if input_state.mouse_state.right {
inner |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON;
}
if input_state.mouse_state.middle {
inner |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON;
}
if is_repeat {
inner |= cef_event_flags_t::EVENTFLAG_IS_REPEAT;
}
inner |= match location {
KeyLocation::Left => cef_event_flags_t::EVENTFLAG_IS_LEFT,
KeyLocation::Right => cef_event_flags_t::EVENTFLAG_IS_RIGHT,
KeyLocation::Numpad => cef_event_flags_t::EVENTFLAG_IS_KEY_PAD,
KeyLocation::Standard => cef_event_flags_t::EVENTFLAG_NONE,
};
Self(inner)
}
pub(super) const PINCH_MODIFIERS: Self = Self(cef_event_flags_t(
cef_event_flags_t::EVENTFLAG_CONTROL_DOWN.0 | cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA.0,
));
}
impl From<CefModifiers> for u32 {
fn from(val: CefModifiers) -> Self {
#[cfg(not(target_os = "windows"))]
return val.0.0;
#[cfg(target_os = "windows")]
return val.0.0 as u32;
}
}
+15 -3
View File
@@ -23,7 +23,6 @@ mod utility;
mod view;
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
pub use input::event::{InputEvent, InputEventBuilder, MouseButton, PointerInputEventBuilder, PointerPosition, UnknownPosition};
pub struct UiContext<S: Stage = Started> {
inner: S::ContextData,
@@ -70,6 +69,7 @@ impl UiContext<Started> {
Ok(UiInstance {
inner: Arc::new(UiInstanceInner {
host: self.inner.clone(),
input: Mutex::new(input::InputState::default()),
events: Mutex::new(events),
queue,
shutdown_complete: Mutex::new(shutdown_complete),
@@ -143,6 +143,7 @@ pub struct UiInstance {
pub(crate) struct UiInstanceInner {
host: Arc<HostHandle>,
input: Mutex<input::InputState>,
events: Mutex<Receiver<UiEvent>>,
queue: events::EventQueue,
shutdown_complete: Mutex<Receiver<()>>,
@@ -153,7 +154,18 @@ impl UiInstance {
pub fn send(&self, command: UiCommand) {
let shared = &self.inner;
match command {
UiCommand::Input(event) => shared.host.send(HostControlMessage::Input(event)),
UiCommand::Input(event) => {
let events = {
let Ok(mut input) = shared.input.lock() else {
tracing::error!("Failed to lock the input state");
return;
};
input::translate(&mut input, &event)
};
if !events.is_empty() {
shared.host.send(HostControlMessage::Input(events));
}
}
UiCommand::Resized { width, height } => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
UiCommand::ScaleChanged(scale) => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
UiCommand::Refresh => shared.host.send(HostControlMessage::RefreshViewInfo),
@@ -210,7 +222,7 @@ impl Drop for UiInstanceInner {
#[derive(Debug)]
pub enum UiCommand {
Input(InputEvent),
Input(winit::event::WindowEvent),
Resized { width: u32, height: u32 },
ScaleChanged(f64),
Refresh,
+1 -1
View File
@@ -99,7 +99,7 @@ enum ControlOutcome {
fn control_loop(receiver: &IpcReceiver<HostControlMessage>, context: &CefContextHandle, sequence: &SequenceState) -> ControlOutcome {
loop {
match receiver.recv() {
Ok(HostControlMessage::Input(event)) => context.process_input(event),
Ok(HostControlMessage::Input(events)) => context.apply_input(events),
Ok(HostControlMessage::UpdateViewInfo(update)) => context.update_view_info(update),
Ok(HostControlMessage::RefreshViewInfo) => context.refresh_view_info(),
Ok(HostControlMessage::SendWebMessage(message)) => context.send_web_message(message),
+1 -1
View File
@@ -8,7 +8,7 @@ use crate::view::ViewInfoUpdate;
#[derive(Serialize, Deserialize)]
pub(crate) enum HostControlMessage {
Input(InputEvent),
Input(Vec<InputEvent>),
UpdateViewInfo(ViewInfoUpdate),
RefreshViewInfo,
SendWebMessage(Vec<u8>),
+1 -1
View File
@@ -3,7 +3,7 @@ name = "graphite-desktop-wrapper"
version = "0.1.0"
description = "Graphite Desktop Wrapper"
authors = ["Graphite Authors <[email protected]>"]
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
@@ -3,25 +3,25 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
use graphite_editor::messages::prelude::FrontendMessage;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
FrontendMessage::RenderOverlays { context } => {
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
}
FrontendMessage::TriggerOpen { filters } => {
FrontendMessage::TriggerOpen => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Open Document".to_string(),
filters,
filters: vec![],
multiple: true,
context: OpenFileDialogContext::Open,
});
}
FrontendMessage::TriggerImport { filters } => {
FrontendMessage::TriggerImport => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters,
filters: vec![],
multiple: false,
context: OpenFileDialogContext::Import,
});
@@ -31,29 +31,32 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
name,
path,
folder,
filters,
content,
} => {
let content = content.into_vec();
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
} else {
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: folder,
filters,
filters: vec![FileFilter {
name: "Graphite Document".to_string(),
extensions: vec![extension],
}],
context: SaveFileDialogContext::Document { document_id, content },
});
}
}
FrontendMessage::TriggerSaveFile { name, folder, filters, content } => {
FrontendMessage::TriggerSaveFile { name, folder, content } => {
let content = content.into_vec();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save File".to_string(),
default_filename: name,
default_folder: folder,
filters,
filters: Vec::new(),
context: SaveFileDialogContext::File { content },
});
}
@@ -122,9 +125,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
FrontendMessage::WindowUpdateDirectInput { enabled } => {
dispatcher.respond(DesktopFrontendMessage::WindowUpdateDirectInput { enabled });
}
FrontendMessage::WindowClose => {
dispatcher.respond(DesktopFrontendMessage::WindowClose);
}
+2 -7
View File
@@ -10,7 +10,6 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
@@ -53,21 +52,17 @@ impl DesktopWrapper {
executor.execute()
}
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
}
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
}
pub enum NodeGraphExecutionResult {
HasRun(Option<Texture>),
HasRun(Option<std::sync::Arc<wgpu::Texture>>),
NotRun,
}
+7 -5
View File
@@ -3,9 +3,9 @@ use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileFilter, PersistedState};
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ScrollDelta};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState as PointerState, EditorPosition as Position, MouseKeys, ScrollDelta};
pub use graphite_editor::messages::prelude::DocumentId;
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
@@ -40,9 +40,6 @@ pub enum DesktopFrontendMessage {
UpdateUIScale {
scale: f64,
},
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
@@ -103,6 +100,11 @@ pub enum DesktopWrapperMessage {
LoadThirdPartyLicenses { text: String },
}
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
#[derive(Clone, Copy)]
pub enum OpenFileDialogContext {
Open,
@@ -1,5 +1,6 @@
pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument";
pub const CONTEXT_FEATURES: &str = "context_features";
pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata";
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use core_types::Context;
use core_types::context::ContextDependencies;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
@@ -389,6 +390,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
attributes
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?;
@@ -14,9 +14,7 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
let compiler = Compiler {};
compiler
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
.map_err(|e| format!("Compilation failed: {:?}", e))?;
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
}
@@ -248,6 +246,11 @@ fn test_nested_network_flattening() {
#[test]
fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata
let context_features = ContextDependencies {
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default()
};
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
@@ -257,6 +260,7 @@ fn test_metadata_preservation() {
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
call_argument: concrete!(String),
context_features,
visible: false, // Non-default value
skip_deduplication: true, // Non-default value
..Default::default()
@@ -290,12 +294,8 @@ fn test_metadata_preservation() {
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
// Verify context_features is not stored
assert_eq!(
conv_node_0.context_features,
ContextDependencies::default(),
"context_features should resolve at compile, not round-trip"
);
// Verify context_features is preserved
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
// Verify visible is preserved
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
+1 -1
View File
@@ -310,8 +310,8 @@ fn convert_node(
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
visible: node.attributes.get_or(node::VISIBLE, true),
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
// Regenerated during compilation; not stored.
context_features: Default::default(),
original_location: Default::default(),
})
}
+1 -3
View File
@@ -8,7 +8,7 @@ edition = "2024"
readme = "../README.md"
homepage = "https://graphite.art"
repository = "https://github.com/GraphiteEditor/Graphite"
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
[features]
default = ["gpu"]
@@ -72,5 +72,3 @@ wasm-bindgen-futures = { workspace = true }
# Workspace dependencies
env_logger = { workspace = true }
futures = { workspace = true }
node-macro = { workspace = true }
core-types = { workspace = true }
+1 -1
View File
@@ -1,7 +1,7 @@
use std::env;
use std::process::Command;
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 5";
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 4";
fn main() {
// Instruct Cargo to rerun this build script if any of these environment variables change.
+1 -3
View File
@@ -135,9 +135,7 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
// BRUSH TOOL
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
pub const BRUSH_SIZE_DEFAULT: f64 = 40.;
pub const BRUSH_HARDNESS_DEFAULT: f64 = 0.;
pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
// EYEDROPPER TOOL
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
+10 -7
View File
@@ -36,7 +36,7 @@ pub struct DispatcherMessageHandlers {
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
preferences_message_handler: PreferencesMessageHandler,
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
pub(crate) tool_message_handler: ToolMessageHandler,
tool_message_handler: ToolMessageHandler,
viewport_message_handler: ViewportMessageHandler,
}
@@ -96,9 +96,8 @@ impl Dispatcher {
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
let mut s = Self::default();
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
@@ -493,11 +492,15 @@ mod test {
if let FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::DialogColumn1,
diff,
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
} = response
{
print_problem_to_terminal_on_failure(value);
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
}
}
}
}
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
pub enum AppWindowMessage {
PointerLock,
PointerLockMove { x: f64, y: f64 },
DirectInput { enabled: bool },
Restart,
Close,
Minimize,
@@ -17,12 +17,6 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
AppWindowMessage::PointerLockMove { x, y } => {
responses.add(FrontendMessage::WindowPointerLockMove { position: (x, y) });
}
AppWindowMessage::DirectInput { enabled } => {
#[cfg(not(target_family = "wasm"))]
responses.add(FrontendMessage::WindowUpdateDirectInput { enabled });
#[cfg(target_family = "wasm")]
let _ = enabled;
}
AppWindowMessage::Close => {
#[cfg(not(target_family = "wasm"))]
responses.add(FrontendMessage::WindowClose);
@@ -8,5 +8,7 @@ pub enum EventMessage {
CanvasTransformed,
ToolAbort,
SelectionChanged,
/// The document graph's nodes or wires changed, so state derived from the selection's chains may be stale
GraphChanged,
WorkingColorChanged,
}
@@ -247,9 +247,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.normalize_stored_types();
}
layers.push(entry);
}
ClipboardItem::Nodes(mut nodes) => {
for (_, template) in &mut nodes {
template.normalize_stored_types();
}
node_groups.push(nodes);
}
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
@@ -275,7 +275,11 @@ impl PreferencesDialogMessageHandler {
let checkbox_id = CheckboxId::new();
let brush_tool_description = "
Enable the Brush tool to support basic layer painting.\n\
Enable the Brush tool to support basic raster-based layer painting.\n\
\n\
This legacy experimental tool has performance and quality limitations and is slated for replacement in future versions of Graphite that will have a renewed focus on raster graphics editing.\n\
\n\
Content created with the Brush tool may not be compatible with future versions of Graphite.\n\
\n\
*Default: Off.*
"
@@ -46,15 +46,11 @@ impl LayoutHolder for LicensesDialog {
let year = &self.localized_commit_year;
let description = format!(
"
Graphite source code is copyright © {year} Graphite contrib-\n\
utors and is available under both the MIT and Apache 2.0\n\
licenses. See \"Source Code License\" for details.\n\
Graphite source code is copyright © {year} Graphite contrib-\nutors and is available under the Apache License 2.0. See\n\"Source Code License\" for details.\n\
\n\
The Graphite logo, icons, and visual identity are copyright ©\n\
{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
The Graphite logo, icons, and visual identity are copyright ©\n{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
\n\
Graphite is distributed with third-party open source code\n\
dependencies. See \"Dependency Licenses\" for details.
Graphite is distributed with third-party open source code\ndependencies. See \"Dependency Licenses\" for details.
"
);
let description = description.trim();
@@ -1,7 +1,7 @@
use super::IconName;
use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileFilter, RasterizedImage};
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
@@ -87,24 +87,16 @@ pub enum FrontendMessage {
commit_date: String,
},
TriggerDisplayThirdPartyLicensesDialog,
TriggerOpen {
filters: Vec<FileFilter>,
},
TriggerImport {
filters: Vec<FileFilter>,
},
TriggerSaveDocument {
document_id: DocumentId,
name: String,
path: Option<PathBuf>,
folder: Option<PathBuf>,
filters: Vec<FileFilter>,
content: serde_bytes::ByteBuf,
},
TriggerSaveFile {
name: String,
folder: Option<PathBuf>,
filters: Vec<FileFilter>,
content: serde_bytes::ByteBuf,
},
TriggerExportImage {
@@ -136,6 +128,8 @@ pub enum FrontendMessage {
},
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpen,
TriggerImport,
TriggerSavePreferences {
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
preferences: PreferencesMessageHandler,
@@ -350,10 +344,6 @@ pub enum FrontendMessage {
position: (f64, f64),
},
#[cfg(not(target_family = "wasm"))]
WindowUpdateDirectInput {
enabled: bool,
},
#[cfg(not(target_family = "wasm"))]
WindowClose,
#[cfg(not(target_family = "wasm"))]
WindowMinimize,
@@ -64,26 +64,6 @@ impl FileType {
FileType::Svg => "image/svg+xml",
}
}
pub fn extension(self) -> &'static str {
match self {
FileType::Png => "png",
FileType::Jpg => "jpg",
FileType::Svg => "svg",
}
}
pub fn file_filter(self) -> FileFilter {
let name = match self {
FileType::Png => "PNG Image",
FileType::Jpg => "JPEG Image",
FileType::Svg => "SVG Image",
};
FileFilter {
name: name.into(),
extensions: vec![self.extension().into()],
}
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -111,10 +91,3 @@ pub struct RasterizedImage {
pub height: u32,
pub pixels: serde_bytes::ByteBuf,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
];
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
for sublist in list {
@@ -12,8 +12,9 @@ use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
use graphene_std::list::{Item, List};
use graphene_std::list::{Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::memo::IORecord;
use graphene_std::raster::{
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
};
@@ -22,13 +23,14 @@ 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,
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
SpiralType,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin,
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
use graphene_std::{Artboard, Color, Graphic};
use graphene_std::{Appearance, Artboard, Color, Context, Cover, Coverage, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -186,8 +188,8 @@ macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None }
$(
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
Some(element.layout_with_breadcrumb($data))
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() {
Some(io.output.layout_with_breadcrumb($data))
}
)*
else { None }
@@ -195,15 +197,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(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
}
// The path's plain value form, produced by `path_of_subgraph` on leveled wires.
if let Some(path) = introspected_data.downcast_ref::<Vec<NodeId>>() {
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
return Some(table_node_id_path_layout_with_breadcrumb(&list, 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>,
@@ -234,7 +231,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<StrokeJoin>,
List<StrokeAlign>,
List<StrokeCap>,
List<PaintOrder>,
List<MergeByDistanceAlgorithm>,
List<ExtrudeJoiningAlgorithm>,
List<PointSpacingType>,
@@ -262,60 +258,61 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<QRCodeErrorCorrectionLevel>,
List<InterpolationDistribution>,
List<RowsOrColumns>,
Artboard,
Graphic,
Vector,
Raster<CPU>,
Raster<GPU>,
Color,
Gradient,
String,
f64,
f32,
u32,
u64,
i32,
i64,
bool,
DVec2,
DAffine2,
BlendMode,
GradientForm,
GradientSpace,
GradientSpread,
DashPattern,
BoxCorners,
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,
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<GradientForm>,
Item<GradientSpread>,
Item<GradientSpace>,
Item<GradientHueDirection>,
Item<GradientInterpolation>,
Item<DashPattern>,
Item<BoxCorners>,
Item<StrokeJoin>,
Item<StrokeAlign>,
Item<StrokeCap>,
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>,
])
}
@@ -481,7 +478,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
}
}
impl TableItemLayout for Artboard<'_> {
impl TableItemLayout for Artboard {
fn type_name() -> &'static str {
"Artboard"
}
@@ -517,6 +514,45 @@ impl TableItemLayout for DashPattern {
}
}
impl TableItemLayout for Appearance {
fn type_name() -> &'static str {
"Appearance"
}
fn identifier(&self) -> String {
"Appearance".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_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for Coverage {
fn type_name() -> &'static str {
"Coverage"
}
fn identifier(&self) -> String {
"Coverage".to_string()
}
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(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"
@@ -537,23 +573,40 @@ impl TableItemLayout for BoxCorners {
}
}
impl TableItemLayout for Graphic<'_> {
impl TableItemLayout for graphene_std::core_types::none::None {
fn type_name() -> &'static str {
"None"
}
fn identifier(&self) -> String {
"None".to_string()
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
label("None")
}
}
impl TableItemLayout for Graphic {
fn type_name() -> &'static str {
"Graphic"
}
fn identifier(&self) -> String {
match self {
Self::None => "None".to_string(),
Self::Stroke(_) => "Brush Stroke".to_string(),
Self::None(item) => item.identifier(),
Self::Graphic(item) => item.identifier(),
Self::Vector(item) => item.identifier(),
Self::RasterCPU(item) => item.identifier(),
Self::RasterGPU(item) => item.identifier(),
Self::Color(item) => item.identifier(),
Self::Gradient(item) => item.identifier(),
Self::Text(item) => item.identifier(),
Self::NoneList(list) => list.identifier(),
Self::GraphicList(list) => list.identifier(),
Self::Vector(list) => list.identifier(),
Self::RasterCPU(list) => list.identifier(),
Self::RasterGPU(list) => list.identifier(),
Self::Color(list) => list.identifier(),
Self::Gradient(list) => list.identifier(),
Self::Text(list) => list.identifier(),
Self::Group(_) => "Group".to_string(),
Self::Segmented(_) => "Stack".to_string(),
Self::VectorList(list) => list.identifier(),
Self::RasterCPUList(list) => list.identifier(),
Self::RasterGPUList(list) => list.identifier(),
Self::ColorList(list) => list.identifier(),
Self::GradientList(list) => list.identifier(),
Self::TextList(list) => list.identifier(),
}
}
// Don't put a breadcrumb for Graphic
@@ -562,17 +615,22 @@ impl TableItemLayout for Graphic<'_> {
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
match self {
Self::None => label("None"),
Self::Stroke(_) => label("Brush Stroke"),
Self::None(item) => item.layout_with_breadcrumb(data),
Self::Graphic(item) => item.layout_with_breadcrumb(data),
Self::Vector(item) => item.layout_with_breadcrumb(data),
Self::RasterCPU(item) => item.layout_with_breadcrumb(data),
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
Self::Color(item) => item.layout_with_breadcrumb(data),
Self::Gradient(item) => item.layout_with_breadcrumb(data),
Self::Text(item) => item.layout_with_breadcrumb(data),
Self::NoneList(list) => list.layout_with_breadcrumb(data),
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
Self::Vector(list) => list.layout_with_breadcrumb(data),
Self::RasterCPU(list) => list.layout_with_breadcrumb(data),
Self::RasterGPU(list) => list.layout_with_breadcrumb(data),
Self::Color(list) => list.layout_with_breadcrumb(data),
Self::Gradient(list) => list.layout_with_breadcrumb(data),
Self::Text(list) => list.layout_with_breadcrumb(data),
Self::Group(_) => Vec::new(),
Self::Segmented(_) => Vec::new(),
Self::VectorList(list) => list.layout_with_breadcrumb(data),
Self::RasterCPUList(list) => list.layout_with_breadcrumb(data),
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
Self::ColorList(list) => list.layout_with_breadcrumb(data),
Self::GradientList(list) => list.layout_with_breadcrumb(data),
Self::TextList(list) => list.layout_with_breadcrumb(data),
}
}
}
@@ -603,27 +661,6 @@ impl TableItemLayout for Vector {
let mut table_rows = Vec::new();
match data.vector_table_tab {
VectorTableTab::Points => {
table_rows.push(column_headings(&["", "position"]));
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
let position = DVec2::new(round_away_float_noise(position.x), round_away_float_noise(position.y));
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{position}")).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Segments => {
table_rows.push(column_headings(&["", "start_index", "end_index", "handles"]));
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{start}")).narrow(true).widget_instance(),
TextLabel::new(format!("{end}")).narrow(true).widget_instance(),
TextLabel::new(format!("{handles:?}")).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Handles => {
table_rows.push(column_headings(&["", "colinear_manipulators[0]", "colinear_manipulators[1]"]));
table_rows.extend(self.colinear_manipulators.iter().enumerate().map(|(index, [a, b])| {
@@ -634,6 +671,31 @@ impl TableItemLayout for Vector {
]
}));
}
VectorTableTab::Points => {
table_rows.push(column_headings(&["", "position"]));
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format_dvec2(position)).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Segments => {
table_rows.push(column_headings(&["", "start_point", "end_point", "handles"]));
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
let handles = match handles {
BezierHandles::Linear => "Linear".to_string(),
BezierHandles::Quadratic { handle } => format!("Quadratic — {}", format_dvec2(handle)),
BezierHandles::Cubic { handle_start, handle_end } => format!("Cubic — start: {}, end: {}", format_dvec2(handle_start), format_dvec2(handle_end)),
};
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("Point {start}")).narrow(true).widget_instance(),
TextLabel::new(format!("Point {end}")).narrow(true).widget_instance(),
TextLabel::new(handles).narrow(true).widget_instance(),
]
}));
}
}
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
@@ -953,6 +1015,7 @@ macro_rules! impl_table_item_layout_for_choice_enum {
}
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
GradientForm,
GradientSpread,
GradientSpace,
@@ -961,7 +1024,6 @@ impl_table_item_layout_for_choice_enum!(
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
@@ -1165,6 +1227,9 @@ macro_rules! known_item_types {
Raster<GPU>,
Graphic,
Artboard,
Appearance,
Coverage,
Cover,
DashPattern,
BoxCorners,
BlendMode,
@@ -1176,7 +1241,6 @@ macro_rules! known_item_types {
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
@@ -1224,6 +1288,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_widgets(any: &dyn Any, target: PathStep, data: &LayoutData) -> Option<Vec<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_widgets(target, data));
}
macro_rules! check {
( $($ty:ty),* $(,)? ) => {
$(
@@ -1277,18 +1345,13 @@ fn table_node_id_path_layout_with_breadcrumb(path: &List<NodeId>, data: &mut Lay
}
/// Type-dispatched recursion into an attribute value for the Data panel breadcrumb navigation.
/// Mirrors [`dispatch_value_widgets`] but routes to [`TableItemLayout::layout_with_breadcrumb`].
/// 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));
}
// The path's plain value form, the layer-path marker's owned shape.
if let Some(path) = any.downcast_ref::<Vec<NodeId>>() {
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
return Some(table_node_id_path_layout_with_breadcrumb(&list, 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),* $(,)? ) => {
@@ -10,7 +10,6 @@ use crate::consts::{
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
VIEWPORT_ROTATE_SNAP_INTERVAL,
};
use crate::messages::frontend::utility_types::FileFilter;
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
@@ -35,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::Cover;
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
@@ -917,14 +916,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
responses.add(SelectToolMessage::Abort);
responses.add(DocumentMessage::DocumentHistoryForward);
// The Pen tool advances its in-progress drawing to match the re-applied document once the graph has re-evaluated
if *current_tool == ToolType::Pen {
responses.add(DeferMessage::AfterGraphRun {
messages: vec![PenToolMessage::Redo.into()],
});
}
responses.add(ToolMessage::Redo);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
@@ -1074,10 +1066,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
(true, Some(storage)) => storage
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportOptions {
include_history: false,
..Default::default()
},
document_format::ExportOptions::default(),
export_load_handle.as_ref(),
Some(&legacy_document),
)
@@ -1097,10 +1086,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
name,
path,
folder,
filters: vec![FileFilter {
name: "Graphite Document".into(),
extensions: vec![extension.into()],
}],
content: content.into(),
})
});
@@ -1536,19 +1521,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
// The Pen tool keeps drawing across an undo, so instead of aborting beforehand it rewinds to match the reverted document once the graph has re-evaluated
if *current_tool == ToolType::Pen {
responses.add(DocumentMessage::DocumentHistoryBackward);
responses.add(DeferMessage::AfterGraphRun {
messages: vec![PenToolMessage::Undo.into()],
});
} else {
responses.add(EventMessage::ToolAbort);
responses.add(DocumentMessage::DocumentHistoryBackward);
}
responses.add(ToolMessage::PreUndo);
responses.add(DocumentMessage::DocumentHistoryBackward);
responses.add(OverlaysMessage::Draw);
responses.add(ToolMessage::Undo);
responses.add(EventMessage::SelectionChanged);
}
DocumentMessage::UngroupSelectedLayers => {
@@ -1901,8 +1877,8 @@ impl DocumentMessageHandler {
layer_click_targets.is_some_and(|targets| {
targets.iter().all(|target| match target.target_type() {
ClickTargetType::Path(_) | ClickTargetType::Instance { .. } => {
let mut path = target.path_in_layer().map(|path| path.into_owned()).unwrap_or_default();
ClickTargetType::Path(path) => {
let mut path = path.clone();
path.apply_affine(Affine::new(layer_transform.to_cols_array()));
bezpath_is_inside_bezpath(&path, &viewport_polygon, None, None)
}
@@ -2764,7 +2740,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 item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::list::item_at_index::IDENTIFIER).expect("Item at Index 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();
@@ -2780,7 +2756,7 @@ impl DocumentMessageHandler {
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
let has_stroke = appearance.is_some_and(|appearance| {
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke())
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_fully_transparent())
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_guaranteed_fully_transparent())
});
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
@@ -3800,7 +3776,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
}
@@ -3832,8 +3808,8 @@ fn quad_to_kurbo(quad: Quad) -> BezPath {
fn click_targets_to_kurbo<'a>(click_targets: impl Iterator<Item = &'a ClickTarget>, transform: DAffine2) -> BezPath {
let segments = click_targets
.filter_map(|target| target.path_in_layer().map(|path| path.into_owned()))
.flat_map(|path| path.segments().collect::<Vec<_>>())
.filter_map(|target| if let ClickTargetType::Path(path) = target.target_type() { Some(path.segments()) } else { None })
.flatten()
.map(|bezier| Affine::new(transform.to_cols_array()) * bezier);
BezPath::from_path_segments(segments)
}
@@ -4105,11 +4081,10 @@ mod document_message_handler_tests {
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
let document = editor.active_document();
for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
&& (bbox[0].x - min_x).abs() < 1.
&& (bbox[0].y - min_y).abs() < 1.
{
return Some(layer);
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
return Some(layer);
}
}
}
None
@@ -4164,8 +4139,9 @@ mod document_message_handler_tests {
.await;
// The operation completed without crashing
// Verifying application still functions by performing another operation, which panics if the folder move left the editor broken
// Verifying application still functions by performing another operation
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
assert!(true, "Application didn't crash after folder move operation");
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
@@ -4335,23 +4311,22 @@ mod document_message_handler_tests {
let instrumented = editor.eval_graph().await.unwrap();
// An empty stack base is never served: `Extend` maps no lane onto it, so the monitor records nothing rather than an empty list.
// A base that wrongly carried a phantom element would therefore show up as a recorded row, which this catches.
// The `news` guard below is what keeps both assertions honest, since a wrong `Output` type empties every record.
// The emptiness guards keep these assertions honest: a wrong `Output` type on `grab_all_input` yields no records at all, which would otherwise pass without checking anything
let base_lengths: Vec<usize> = instrumented
.grab_all_input::<graphene_std::list::extend::BaseInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.grab_all_input::<graphene_std::graphic::extend::BaseInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.map(|base| base.len())
.collect();
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
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::list::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.collect();
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
let phantom_count = news
.iter()
.flat_map(|new| new.iter_element_values())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None))
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
.count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
}
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::text::{Font, TypesettingConfig};
@@ -91,7 +92,7 @@ pub enum GraphOperationMessage {
color: Option<Color>,
stroke: Stroke,
},
StrokePaintOrderSet {
StrokeOrderSet {
layer: LayerNodeIdentifier,
paint_order: PaintOrder,
},
@@ -111,23 +112,9 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
modification_type: VectorModificationType,
},
NewBrushGroupLayer {
id: NodeId,
strokes_node_id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
color: Color,
diameter: f64,
hardness: f64,
flow: f64,
},
NewBrushStrokesNode {
Brush {
layer: LayerNodeIdentifier,
strokes_node_id: NodeId,
color: Color,
diameter: f64,
hardness: f64,
flow: f64,
strokes: Vec<BrushStroke>,
},
SetUpstreamToChain {
layer: LayerNodeIdentifier,
@@ -1,18 +1,16 @@
use super::transform_utils;
use super::utility_types::ModifyInputsContext;
use super::utility_types::{ModifyInputsContext, set_stroke_paint_order};
use crate::consts::{LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, DefinitionIdentifier};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
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::value::TaggedValue;
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::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
@@ -133,12 +131,15 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.stroke_set(color, stroke);
}
}
GraphOperationMessage::StrokePaintOrderSet { layer, paint_order } => {
if let Some(stroke_node_id) = crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_id(layer, network_interface)
&& super::utility_types::set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order)
{
GraphOperationMessage::StrokeOrderSet { layer, paint_order } => {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let Some(stroke_node_id) = ModifyInputsContext::locate_node_in_layer_chain(&stroke_reference, layer, network_interface) else {
return;
};
if set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order) {
responses.add(PropertiesPanelMessage::Refresh);
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
}
GraphOperationMessage::TransformChange {
@@ -171,35 +172,10 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.vector_modify(modification_type);
}
}
GraphOperationMessage::NewBrushGroupLayer {
id,
strokes_node_id,
parent,
insert_index,
color,
diameter,
hardness,
flow,
} => {
let layer = ModifyInputsContext::new(network_interface, responses).create_layer(id);
insert_brush_strokes_chain(network_interface, layer, strokes_node_id, color, diameter, hardness, flow);
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
responses.add(GraphOperationMessage::SetUpstreamToChain { layer });
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewBrushStrokesNode {
layer,
strokes_node_id,
color,
diameter,
hardness,
flow,
} => {
insert_brush_strokes_chain(network_interface, layer, strokes_node_id, color, diameter, hardness, flow);
responses.add(GraphOperationMessage::SetUpstreamToChain { layer });
responses.add(NodeGraphMessage::RunDocumentGraph);
GraphOperationMessage::Brush { layer, strokes } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.brush_modify(strokes);
}
}
GraphOperationMessage::SetUpstreamToChain { layer } => {
let Some(OutputConnector::Node { node_id: first_chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(layer.to_node()), &[]) else {
@@ -250,7 +226,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::primary_input(artboard_layer.to_node()), 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.
@@ -258,7 +234,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.set_input(&InputConnector::layer_secondary_input(artboard_layer.to_node()), 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::primary_input(artboard_layer.to_node()), bottom_input, &[]);
}
}
@@ -871,22 +847,6 @@ fn import_usvg_node_inner(
}
}
fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, layer: LayerNodeIdentifier, strokes_node_id: NodeId, color: Color, diameter: f64, hardness: f64, flow: f64) {
let Some(strokes_node_type) = resolve_proto_node_type(graphene_std::brush::brush_strokes::IDENTIFIER) else {
log::error!("Brush strokes node does not exist");
return;
};
let strokes_node = strokes_node_type.node_template_input_override([
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
Some(NodeInput::value(TaggedValue::Color(color), false)),
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
Some(NodeInput::value(TaggedValue::F64(flow), false)),
]);
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
}
/// 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, gradient_info: &SvgGradientInfo) {
let bezpath = convert_usvg_path(path);
@@ -1069,6 +1029,81 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
mod tests {
use super::*;
#[tokio::test]
async fn stroke_order_set_reorders_the_fill_and_stroke_nodes() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_paint_order;
use crate::test_utils::test_prelude::*;
use graphene_std::vector::style::PaintOrder;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let document = editor.active_document();
let layer = document.metadata().all_layers().next().unwrap();
let paint_order = get_stroke_paint_order(layer, &document.network_interface);
assert_eq!(paint_order, PaintOrder::StrokeAbove, "a fresh shape should stroke above its fill");
editor
.handle_message(GraphOperationMessage::StrokeOrderSet {
layer,
paint_order: PaintOrder::StrokeBelow,
})
.await;
let paint_order = get_stroke_paint_order(layer, &editor.active_document().network_interface);
assert_eq!(paint_order, PaintOrder::StrokeBelow, "the rewrite should move the stroke downstream of the fill");
editor
.handle_message(GraphOperationMessage::StrokeOrderSet {
layer,
paint_order: PaintOrder::StrokeAbove,
})
.await;
let paint_order = get_stroke_paint_order(layer, &editor.active_document().network_interface);
assert_eq!(paint_order, PaintOrder::StrokeAbove, "the rewrite should move the stroke back upstream of the fill");
}
#[tokio::test]
async fn a_node_inserted_between_the_fill_and_stroke_makes_the_order_swap_inapplicable() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::tool::common_functionality::graph_modification_utils::stroke_paint_order_applicable;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
assert!(
stroke_paint_order_applicable(layer, &editor.active_document().network_interface),
"a fresh shape's adjacent Fill and Stroke pair should be swappable"
);
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let stroke_node_id = ModifyInputsContext::locate_node_in_layer_chain(&stroke_reference, layer, &editor.active_document().network_interface).unwrap();
let node_template = Box::new(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).unwrap().default_node_template());
let passthrough_node_id = NodeId::new();
editor
.handle_message(NodeGraphMessage::InsertNode {
node_id: passthrough_node_id,
node_template,
})
.await;
editor
.handle_message(NodeGraphMessage::InsertNodeBetween {
node_id: passthrough_node_id,
input_connector: InputConnector::node_at_index(stroke_node_id, 0),
insert_node_input_index: 0,
})
.await;
assert!(
!stroke_paint_order_applicable(layer, &editor.active_document().network_interface),
"a node between the pair should gray the order radio out"
);
}
#[test]
fn color_interpolation_resolves_per_gradient_with_inheritance_and_style_priority() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" color-interpolation="linearRGB">
@@ -12,8 +12,8 @@ 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 graphene_std::list::List;
use graph_craft::{ProtoNodeIdentifier, list};
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::text::{Font, TypesettingConfig};
@@ -71,8 +71,8 @@ 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(background), false)),
@@ -86,7 +86,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)),
]);
@@ -98,7 +98,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, &[]);
@@ -110,7 +110,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, &[]);
@@ -414,7 +414,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::layer_secondary_input(output_layer.to_node()), &[]);
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
log::error!("Combine Paths does not exist in ModifyInputsContext::existing_node_id");
return None;
@@ -431,7 +431,8 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn fill_color_set(&mut self, color: Option<Color>) {
let Some(fill_node_id) = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
return;
};
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::PaintInput);
@@ -443,10 +444,15 @@ impl<'a> ModifyInputsContext<'a> {
}
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);
if existing_fill_node_id.is_none() {
self.restore_default_stroke_order();
}
}
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: DAffine2) {
let Some(fill_node_id) = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
return;
};
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput);
@@ -487,6 +493,21 @@ impl<'a> ModifyInputsContext<'a> {
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
false,
);
if existing_fill_node_id.is_none() {
self.restore_default_stroke_order();
}
}
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
fn restore_default_stroke_order(&mut self) {
let Some(output_layer) = self.get_output_layer() else { return };
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let Some(stroke_node_id) = Self::locate_node_in_layer_chain(&stroke_reference, output_layer, self.network_interface) else {
return;
};
set_stroke_paint_order(self.network_interface, &[], stroke_node_id, PaintOrder::StrokeAbove);
}
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
@@ -644,7 +665,7 @@ impl<'a> ModifyInputsContext<'a> {
.nodes
.get(&node_id)
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput));
if current_input.is_none_or(|input| input.as_value().is_none()) {
if !current_input.is_some_and(|input| input.as_value().is_some()) {
return;
}
@@ -668,7 +689,7 @@ impl<'a> ModifyInputsContext<'a> {
.nodes
.get(&node_id)
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput));
if current_input.is_none_or(|input| input.as_value().is_none()) {
if !current_input.is_some_and(|input| input.as_value().is_some()) {
return;
}
@@ -956,6 +977,17 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
let Some(brush_node_id) = self.existing_proto_node_id(graphene_std::brush::brush::brush::IDENTIFIER, true) else {
return;
};
self.set_input_with_refresh(
InputConnector::node(brush_node_id, graphene_std::brush::brush::brush::TraceInput),
NodeInput::value(TaggedValue::BrushStrokes(strokes), false),
false,
);
}
pub fn resize_artboard(&mut self, location: DVec2, dimensions: DVec2) {
let Some(artboard_node_id) = self.existing_network_node_id("Artboard", true) else {
return;
@@ -1002,40 +1034,37 @@ fn primary_output_consumers(network_interface: &mut NodeNetworkInterface, networ
.unwrap_or_default()
}
/// The fill wired directly to the stroke on either side, and whether the stroke currently paints above it.
/// The downstream node of the pair appends its cover last, so it paints on top.
pub fn adjacent_fill_of_stroke(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId) -> Option<(NodeId, bool)> {
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let is_fill = |network_interface: &NodeNetworkInterface, node_id: &NodeId| network_interface.reference(node_id, network_path) == Some(fill_reference.clone());
let stroke_primary_source = match network_interface.input_from_connector(&InputConnector::node_at_index(stroke_node_id, 0), network_path) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
};
if let Some(source) = stroke_primary_source.filter(|source| is_fill(network_interface, source)) {
return Some((source, true));
}
let consumers = primary_output_consumers(network_interface, network_path, stroke_node_id);
let fill_consumer = consumers.iter().find_map(|connector| match connector {
InputConnector::Node { node_id, input_index: 0 } if is_fill(network_interface, node_id) => Some(*node_id),
_ => None,
});
fill_consumer.map(|fill_node_id| (fill_node_id, false))
}
/// Swaps a chain's directly adjacent Stroke and Fill nodes when their order disagrees with the requested
/// paint order: both nodes append their cover, so the downstream one of the pair paints on top, following
/// the painter's algorithm. Without a fill wired directly to the stroke, nothing changes.
/// Returns whether the graph changed.
pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId, paint_order: PaintOrder) -> bool {
let Some((fill_node_id, currently_above)) = adjacent_fill_of_stroke(network_interface, network_path, stroke_node_id) else {
return false;
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let is_fill = |network_interface: &NodeNetworkInterface, node_id: &NodeId| network_interface.reference(node_id, network_path).as_ref() == Some(&fill_reference);
// Find the fill wired directly to the stroke on either side; the downstream one of the pair paints on top
let stroke_primary_source = match network_interface.input_from_connector(&InputConnector::node_at_index(stroke_node_id, 0), network_path) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
};
let (fill_node_id, currently_above) = if let Some(source) = stroke_primary_source.filter(|source| is_fill(network_interface, source)) {
(source, true)
} else {
let consumers = primary_output_consumers(network_interface, network_path, stroke_node_id);
let fill_consumer = consumers.iter().find_map(|connector| match connector {
InputConnector::Node { node_id, input_index: 0 } if is_fill(network_interface, node_id) => Some(*node_id),
_ => None,
});
let Some(fill_node_id) = fill_consumer else { return false };
(fill_node_id, false)
};
if (paint_order == PaintOrder::StrokeAbove) == currently_above {
return false;
}
// Swap the pair in place: the downstream node takes the upstream one's source, consumers of the
// downstream node move over to the upstream one, and the wire linking the pair reverses direction
let (upstream, downstream) = if currently_above { (fill_node_id, stroke_node_id) } else { (stroke_node_id, fill_node_id) };
let Some(upstream_source) = network_interface.input_from_connector(&InputConnector::node_at_index(upstream, 0), network_path).cloned() else {
return false;
@@ -2,7 +2,7 @@ mod document_node_derive;
use super::node_properties::choice::enum_choice;
use super::node_properties::{self, ParameterWidgetsInfo};
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
use super::utility_types::FrontendNodeType;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
@@ -13,9 +13,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)]
@@ -159,8 +158,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -2)),
..Default::default()
},
// Collection of the content into the layer's group; the group keeps
// the content level's element type for the legacy boundary.
// Secondary (left) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
@@ -177,8 +175,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
inputs: vec![
NodeInput::node(NodeId(1), 0),
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(2), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
..Default::default()
},
@@ -193,7 +195,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeTemplate {
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(4), 0)],
implementation: NodeTemplateImplementation::ProtoNode(list::extend::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
..Default::default()
},
@@ -204,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)],
input_metadata: vec![("Base", "TODO").into(), ("Content", "TODO").into()],
output_names: vec!["Out".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
@@ -224,11 +226,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![
NodeInput::node(NodeId(6), 0),
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),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default()
@@ -243,14 +245,18 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(1), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
..Default::default()
},
// The monitor node is used to display a thumbnail in the UI.
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(7), 0)],
inputs: vec![NodeInput::node(NodeId(2), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T),
skip_deduplication: true,
@@ -259,37 +265,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
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: NodeTemplateImplementation::ProtoNode(list::extend::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default()
},
// Content coercion into a graphic level, evaluated within the artboard's footprint
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-35, -3)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::import(concrete!(TaggedValue), 2)],
implementation: NodeTemplateImplementation::ProtoNode(artboard::translate_footprint::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-28, -3)),
..Default::default()
},
// Lifts the artboard element onto a one-lane level so it concatenates with the base stack
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(2), 0),
NodeInput::value(TaggedValue::U32(1), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-10, -3)),
..Default::default()
},
]
.into_iter()
.enumerate()
@@ -298,8 +280,8 @@ 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(Color::WHITE), false),
@@ -371,7 +353,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 3: Floor (integer count per subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(concrete!(f64), 1)],
inputs: vec![NodeInput::import(item!(f64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
@@ -459,8 +441,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(concrete!(Vector), 4),
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default()
@@ -494,11 +476,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),
],
input_metadata: vec![
("Content", "TODO").into(),
@@ -558,7 +540,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
// 5: Map
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(list::map::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
..Default::default()
@@ -584,7 +566,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)],
input_metadata: vec![("Vector", "TODO").into()],
output_names: vec!["Vector".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
@@ -601,12 +583,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::import(concrete!(String), 1),
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
@@ -654,14 +631,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::import(generic!(T), 0),
NodeInput::import(concrete!(Footprint), 1),
NodeInput::node(NodeId(1), 0),
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
],
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
@@ -674,7 +644,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.)),
@@ -706,7 +676,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
nodes: [
NodeTemplate {
inputs: vec![
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -716,7 +686,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -726,7 +696,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -736,7 +706,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -751,7 +721,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)],
input_metadata: vec![("Image", "TODO").into()],
output_names: vec!["".to_string(), "Red".to_string(), "Green".to_string(), "Blue".to_string(), "Alpha".to_string()],
..Default::default()
@@ -767,14 +737,14 @@ 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: [
NodeTemplate {
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: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
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: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
@@ -804,7 +774,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
category: "",
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Extract,
inputs: vec![NodeInput::type_default(descriptor!(DocumentNode), true)],
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
input_metadata: vec![("Node", "TODO").into()],
output_names: vec!["Document Node".to_string()],
..Default::default()
@@ -827,11 +797,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
NodeTemplate {
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: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
@@ -840,14 +810,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 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)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(list::item_at_index::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// 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
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(list::remove_at_index::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
},
@@ -918,7 +888,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),
],
input_metadata: vec![("Content", "TODO").into(), ("Modification", "TODO").into()],
@@ -1515,127 +1485,26 @@ pub fn resolve_document_node_type(identifier: &DefinitionIdentifier) -> Option<&
DOCUMENT_NODE_TYPES.get(identifier)
}
impl InputTypeConstraint {
#[must_use]
fn type_name(ty: &Type) -> String {
ty.nested_type().to_string()
}
/// Find types that satisfy both constraints
#[must_use]
fn intersection(self, other: Self) -> Self {
match (self, other) {
(Self::Limited(a), Self::Limited(b)) => Self::Limited(a.intersection(&b).cloned().collect()),
(Self::Limited(a), Self::All) | (Self::All, Self::Limited(a)) => Self::Limited(a),
(Self::All, Self::All) => Self::All,
}
}
/// Construct a constraint that no types satisfy
#[must_use]
fn empty() -> Self {
Self::Limited(Default::default())
}
/// Check if type satisfies the constraint
#[must_use]
fn satisfies(&self, ty: &Type) -> bool {
match self {
Self::Limited(types) => types.contains(&Self::type_name(ty)),
Self::All => true,
}
}
/// Add a new type that the constraint satisfied. Returns true if the type is not previously added.
fn insert(&mut self, ty: &Type) -> bool {
match self {
Self::Limited(types) => types.insert(Self::type_name(ty)),
Self::All => false,
}
}
/// Compute the type constraint for one input. Note that this cannot use the infrastructure in the node network interface as the node is not placed in a network.
#[must_use]
fn compute_constraint_for_input(template_document_node: &NodeTemplate, name: &str, input_index: usize) -> Self {
// Add input type from node implementation
match &template_document_node.implementation {
// TODO: This does not consider the constrains by nodes not directly connected to the import
NodeTemplateImplementation::Network(nested_network) => {
// Find all inputs connected to the relevant import
fn valid_types_from_node(child_node: &NodeTemplate, name: &str, input_index: usize) -> impl Iterator<Item = InputTypeConstraint> {
let all_inputs = child_node.inputs.iter().enumerate();
let input_for_import = all_inputs.filter(move |(_, child_input)| matches!(child_input, NodeInput::Import { import_index, .. } if *import_index == input_index));
input_for_import.map(move |(index, _)| InputTypeConstraint::compute_constraint_for_input(child_node, name, index))
}
let all_type_constraints = nested_network.nodes.values().flat_map(|node| valid_types_from_node(node, name, input_index));
// The type fed to the network must satisfy all protonodes it is connected to
let intersection_of_constraints = all_type_constraints.reduce(|a, b| a.intersection(b));
// If no constraints, then all types are accepted
intersection_of_constraints.unwrap_or(Self::All)
}
NodeTemplateImplementation::ProtoNode(proto_node_identifier) => {
// The passthrough node has no implementations but accepts all types (it is filtered from the compiled network)
if proto_node_identifier == &graphene_std::ops::passthrough::IDENTIFIER {
return Self::All;
}
let Some(implementations) = interpreted_executor::node_registry::NODE_REGISTRY.get(proto_node_identifier) else {
warn!("No implementations found for protonode {proto_node_identifier} in {name}");
return Self::All;
};
// Find the union of all the possible types from the dynamic executor implementations
let mut result_accepted = Self::empty();
for node_io in implementations.iter().map(|entry| &entry.io) {
if let Some(input_type) = node_io.inputs.get(input_index) {
result_accepted.insert(input_type);
}
}
result_accepted
}
NodeTemplateImplementation::Extract => {
warn!("Input types for extract node {name} not supported");
Self::All
}
}
}
/// Compute the type constraints for each input, validating that the current input satisfies the value.
#[must_use]
fn constraints_for_all_inputs(template_document_node: &NodeTemplate, name: &str) -> Vec<Self> {
let input_indices = 0..template_document_node.inputs.len();
let all_input_constraints: Vec<_> = input_indices.map(|input_index| Self::compute_constraint_for_input(template_document_node, name, input_index)).collect();
// Validate that the current inputs are valid
for (index, (constraint, input)) in all_input_constraints.iter().zip(&template_document_node.inputs).enumerate() {
if let Some(value) = input.as_value() {
let input_ty = value.ty();
// Empty types are used when the input must come from the graph so they can be skipped.
if input_ty.nested_type() != &concrete!(()) && !constraint.satisfies(&input_ty) {
warn!("The default value for input index {index} node {name} is {input_ty}, but does not satisfy {constraint:?}");
}
}
}
all_input_constraints
}
}
pub fn collect_node_types() -> Vec<FrontendNodeType> {
DOCUMENT_NODE_TYPES
.iter()
.filter(|(_, definition)| !definition.category.is_empty())
.map(|(identifier, definition)| {
let input_types = definition
.node_template
.inputs
.iter()
.map(|node_input| node_input.as_value().map(|node_value| node_value.ty().nested_type().to_string()).unwrap_or_default())
.collect::<Vec<String>>();
let mut name = definition.node_template.display_name.clone();
if name.is_empty() {
name = identifier.implementation_name_from_identifier()
}
FrontendNodeType {
identifier: identifier.serialized(),
input_types: InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, &name),
name,
category: definition.category.to_string(),
input_types,
}
})
.collect()
@@ -1709,80 +1578,3 @@ mod test {
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
}
}
#[cfg(test)]
mod test_type_constraints {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::InputTypeConstraint;
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation};
use crate::test_utils::test_prelude::*;
use core_types::Ctx;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::{Type, concrete, generic};
use node_macro;
#[track_caller]
fn all_satisifed(constraint: &InputTypeConstraint, values: impl IntoIterator<Item = Type>) {
for ty in values {
assert!(constraint.satisfies(&ty), "{ty} not satisfied by {:#?}", constraint);
}
}
#[test]
fn passthrough() {
let node_type = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).expect("passthrough node");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
assert_eq!(constraint, vec![InputTypeConstraint::All]);
}
#[node_macro::node(category(""))]
fn test_node_accept_f32_f64_dvec2<T: std::any::Any>(_: impl Ctx, #[implementations(f32, f64, DVec2)] a: T, _b: bool) -> T {
a
}
#[test]
fn single_protonode() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
assert!(!constraint[0].satisfies(&concrete!(String)));
all_satisifed(&constraint[1], [concrete!(bool)]);
}
#[node_macro::node(category(""))]
fn test_node_accept_f32_f64_string<T: std::any::Any>(_: impl Ctx, #[implementations(f32, f64, String)] a: T, _b: bool) -> T {
a
}
#[test]
fn single_protonode2() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
all_satisifed(&constraint[1], [concrete!(bool)]);
}
#[test]
fn network() {
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let inner_network = NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: [(NodeId(10), atan_node), (NodeId(11), min_node)].into_iter().collect(),
..Default::default()
};
let node = NodeTemplate {
inputs: vec![NodeInput::import(generic!(X), 0)],
implementation: NodeTemplateImplementation::Network(inner_network),
..Default::default()
};
let constraint = InputTypeConstraint::compute_constraint_for_input(&node, "name", 0);
all_satisifed(&constraint, [concrete!(f32), concrete!(f64)]);
assert!(!constraint.satisfies(&concrete!(String)));
assert!(!constraint.satisfies(&concrete!(glam::DVec2)));
}
}
@@ -28,7 +28,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
let node_registry = NODE_REGISTRY.lock().unwrap();
let empty_implementations: Vec<RegistryEntry> = Vec::new();
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new();
let context_type = concrete!(Context);
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
@@ -41,17 +41,18 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
fields,
description,
properties,
context_features,
..
} = metadata;
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
implementations.iter().map(|entry| &entry.io.call_argument).collect()
implementations.iter().map(|(_, io)| &io.call_argument).collect()
} else if let Some(impls) = extended_node_registry.get(id) {
impls.iter().map(|entry| &entry.io.call_argument).collect()
impls.keys().map(|io| &io.call_argument).collect()
} else {
Vec::new()
};
@@ -73,7 +74,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
context_features: ContextDependencies::default(),
context_features: ContextDependencies::from(context_features.as_slice()),
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
@@ -157,7 +157,6 @@ pub enum NodeGraphMessage {
SetInputValue {
node_id: NodeId,
input_index: usize,
// Boxed to keep the whole editor message tree small; `TaggedValue` alone is 568 bytes
value: Box<TaggedValue>,
},
SetInput {
@@ -1734,6 +1734,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::UpdateLayerPanel);
responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(PropertiesPanelMessage::Refresh);
responses.add(EventMessage::GraphChanged);
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
@@ -1757,7 +1758,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
let value = *value;
let reference = network_interface.reference(&node_id, selection_network_path);
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
@@ -1769,7 +1769,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
});
let input = NodeInput::value(value, false);
let input = NodeInput::value(*value, false);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node_at_index(node_id, input_index),
input,
@@ -17,9 +17,9 @@ use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete};
use graphene_std::animation::RealTimeMode;
use graphene_std::brush::brush_stroke::BrushTrace;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{
BlendMode, CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
SelectiveColorChoice,
@@ -33,8 +33,8 @@ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
};
use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintOrder, StrokeAlign, StrokeCap,
StrokeJoin, build_transform_with_y_preservation,
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{NodeParameter, ParameterRef};
@@ -57,7 +57,7 @@ fn optionally_update_value_at_index<T>(value: impl Fn(&T) -> Option<TaggedValue>
Some(value) => NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: Box::new(value),
value: value.into(),
}
.into(),
None => Message::NoOp,
@@ -228,6 +228,24 @@ pub(crate) fn property_from_type(
let default_info = ParameterWidgetsInfo::at_index(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) => {
@@ -259,22 +277,16 @@ pub(crate) fn property_from_type(
// ===============
// 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<Gradient>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
// Leveled wires type by their element; each element keeps its list form's widget.
Some(x) if x == TypeId::of::<Color>() => color_widget(default_info, ColorInput::default().allow_none(true)),
Some(x) if x == TypeId::of::<Gradient>() => color_widget(default_info, ColorInput::default().allow_none(false)),
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
// ============
@@ -310,7 +322,6 @@ pub(crate) fn property_from_type(
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(),
@@ -326,30 +337,19 @@ pub(crate) fn property_from_type(
// =====
// 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),
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
};
extra_widgets.push(widgets);
@@ -460,6 +460,33 @@ pub fn vector_modification_widget(parameter_widgets_info: ParameterWidgetsInfo)
widgets
}
pub fn brush_strokes_widget(parameter_widgets_info: ParameterWidgetsInfo) -> 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 widgets };
let Some(input) = document_node.inputs.get(index) else { return widgets };
if let Some(TaggedValue::BrushStrokes(strokes)) = input.as_non_exposed_value() {
let stroke_count = strokes.len();
let sample_count: usize = strokes.iter().map(|s| s.trace.len()).sum();
let label = if stroke_count == 0 {
"Empty".to_string()
} else {
format!(
"{stroke_count} {} / {sample_count} {}",
if stroke_count == 1 { "Stroke" } else { "Strokes" },
if sample_count == 1 { "Sample" } else { "Samples" }
)
};
widgets.extend_from_slice(&[Separator::new(SeparatorStyle::Unrelated).widget_instance(), TextLabel::new(label).widget_instance()]);
}
widgets
}
pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetInstance> {
let ParameterWidgetsInfo { document_node, node_id: _, index, .. } = parameter_widgets_info;
@@ -840,7 +867,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: Box::new(TaggedValue::Resource(resource_id)),
value: TaggedValue::Resource(resource_id).into(),
}
.into(),
]),
@@ -1396,7 +1423,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: Box::new(TaggedValue::F32(percent.clamp(0., 100.) as f32)),
value: TaggedValue::F32(percent.clamp(0., 100.) as f32).into(),
}
.into()
}
@@ -1552,7 +1579,7 @@ fn spectrum_slider_row(
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: Box::new(TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32)),
value: TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32).into(),
}
.into()
})
@@ -2084,13 +2111,13 @@ pub(crate) fn string_capitalization_properties(node_id: NodeId, context: &mut No
NodeGraphMessage::SetInputValue {
node_id,
input_index: UseJoinerInput::INDEX,
value: Box::new(TaggedValue::Bool(true)),
value: TaggedValue::Bool(true).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: JoinerInput::INDEX,
value: Box::new(TaggedValue::String(value.clone())),
value: TaggedValue::String(value.clone()).into(),
}
.into(),
]),
@@ -2145,13 +2172,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
NodeGraphMessage::SetInputValue {
node_id,
input_index: IndividualCornerRadiiInput::INDEX,
value: Box::new(TaggedValue::Bool(false)),
value: TaggedValue::Bool(false).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: Box::new(TaggedValue::BoxCorners(vec![uniform_val])),
value: TaggedValue::BoxCorners(vec![uniform_val]).into(),
}
.into(),
]),
@@ -2164,13 +2191,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
NodeGraphMessage::SetInputValue {
node_id,
input_index: IndividualCornerRadiiInput::INDEX,
value: Box::new(TaggedValue::Bool(true)),
value: TaggedValue::Bool(true).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: Box::new(TaggedValue::BoxCorners(corner_values.to_vec())),
value: TaggedValue::BoxCorners(corner_values.to_vec()).into(),
}
.into(),
]),
@@ -2294,7 +2321,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>();
input_types.sort_by_key(|ty| ty.type_name());
let input_type = input_types.first().cloned();
@@ -2482,7 +2509,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: Box::new(TaggedValue::Color(color)),
value: TaggedValue::Color(color).into(),
}
.into(),
);
@@ -2495,13 +2522,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: PaintInput::INDEX,
value: Box::new(TaggedValue::GradientRamp(ramp.clone())),
value: TaggedValue::GradientRamp(ramp.clone()).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupGradientInput::INDEX,
value: Box::new(TaggedValue::GradientRamp(ramp)),
value: TaggedValue::GradientRamp(ramp).into(),
}
.into(),
]),
@@ -2577,13 +2604,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: HasTransformInput::INDEX,
value: Box::new(TaggedValue::Bool(true)),
value: TaggedValue::Bool(true).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: TransformInput::INDEX,
value: Box::new(TaggedValue::DAffine2(new_transform)),
value: TaggedValue::DAffine2(new_transform).into(),
}
.into(),
]),
@@ -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::GradientRamp(_) => 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 == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => Self::Graphic,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => Self::Artboard,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => Self::Raster,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => Self::Vector,
n if n == graphene_std::core_types::normalize_type_name(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,
}
}
@@ -105,13 +102,6 @@ pub struct FrontendNode {
pub locked: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum InputTypeConstraint {
Limited(std::collections::BTreeSet<String>),
All,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendNodeType {
@@ -119,7 +109,7 @@ pub struct FrontendNodeType {
pub name: String,
pub category: String,
#[serde(rename = "inputTypes")]
pub input_types: Vec<InputTypeConstraint>,
pub input_types: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -1,10 +1,9 @@
use super::utility_types::{DrawHandles, OverlayContext};
use crate::consts::{HIDE_HANDLE_DISTANCE, SNAP_POINT_TOLERANCE};
use crate::consts::HIDE_HANDLE_DISTANCE;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
pub use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
use crate::messages::tool::common_functionality::utility_functions::closest_open_path_endpoint;
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, point_to_dvec2, segment_to_handles};
@@ -133,7 +132,7 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
let display_handles = overlay_context.visibility_settings.handles();
let display_anchors = overlay_context.visibility_settings.anchors();
for layer in document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface) {
for layer in document.network_interface.selected_nodes().selected_layers(document.metadata()) {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
if display_path {
@@ -202,41 +201,25 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
}
}
/// Draws an anchor overlay at each endpoint of every open path on the selected visible layers, in the selected style for endpoints that are part of the path editing selection.
/// Given a pointer position, the endpoint a press there would continue from is drawn in the hover style instead.
pub fn open_path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &ShapeState, pointer: Option<DVec2>, overlay_context: &mut OverlayContext) {
pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext) {
if !overlay_context.visibility_settings.anchors() {
return;
}
let selected_nodes = document.network_interface.selected_nodes();
let is_selected = |layer: LayerNodeIdentifier, id: PointId| {
shape_editor
.selected_shape_state
.get(&layer)
.is_some_and(|state| state.is_point_selected(ManipulatorPointId::Anchor(id)))
};
let hovered = pointer.and_then(|pointer| closest_open_path_endpoint(document, pointer, SNAP_POINT_TOLERANCE, selected_nodes.selected_visible_layers(&document.network_interface)));
for layer in selected_nodes.selected_visible_layers(&document.network_interface) {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
for layer in document.network_interface.selected_nodes().selected_layers(document.metadata()) {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else {
continue;
};
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
let selected = shape_editor.selected_shape_state.get(&layer);
let is_selected = |selected: Option<&SelectedLayerState>, point: ManipulatorPointId| selected.is_some_and(|selected| selected.is_point_selected(point));
for id in vector.anchor_endpoints() {
if hovered.is_some_and(|(hovered_layer, hovered_id, _)| hovered_layer == layer && hovered_id == id) {
continue;
}
let Some(position) = vector.point_domain.position_from_id(id) else { continue };
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(layer, id), None);
for point in vector.anchor_endpoints() {
let Some(position) = vector.point_domain.position_from_id(point) else { continue };
let position = transform.transform_point2(position);
overlay_context.manipulator_anchor(position, is_selected(selected, ManipulatorPointId::Anchor(point)), None);
}
}
// Drawn last so its halo sits above any other endpoint at the same spot
if let Some((layer, id, position)) = hovered {
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
overlay_context.hover_manipulator_anchor(transform.transform_point2(position), is_selected(layer, id));
}
}
pub fn hex_to_rgba_u8(hex: &str) -> [u8; 4] {
@@ -1012,11 +1012,6 @@ impl OverlayContextInternal {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
combined.extend(placed.elements().iter().copied());
}
}
}
@@ -972,11 +972,6 @@ impl OverlayContext {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
combined.extend(placed.elements().iter().copied());
}
});
if !combined.is_empty() {
@@ -3,7 +3,7 @@ use crate::messages::portfolio::{document::resource::utility_types::EmbeddedReso
use crate::messages::prelude::*;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graph_craft::application_io::resource::{DataSource, LoadResource, Resource, ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
use graph_craft::application_io::resource::{DataSource, LoadResource, Resource, ResourceHash, ResourceId, ResourceRegistry};
use graphene_std::text::Font;
use std::sync::Arc;
use url::Url;
@@ -49,8 +49,15 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
responses.add(ResourceMessage::Resolve { resource_id });
}
ResourceMessage::ResolveAll => {
let storage = resource_storage.resources_mut();
let ids: Vec<ResourceId> = self.registry.ids().filter(|id| !self.registry.hash(id).is_some_and(|hash| storage.contains(&hash))).collect();
// A resource keeps its hash when storage evicts its data, so only a fetchable source can repair it
let refetchable = self
.registry
.resolved()
.filter(|info| info.hash.is_some_and(|hash| !resource_storage.contains(hash)))
.filter(|info| info.sources.iter().any(|source| matches!(source, DataSource::Url(_) | DataSource::Font { .. })))
.map(|info| info.id);
let ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).chain(refetchable).collect();
for id in ids {
if self.pending_resolves.contains(&id) {
continue;
@@ -67,7 +74,9 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
log::error!("Resolve for {resource_id}: no registry entry");
return;
};
if info.hash.is_some_and(|hash| resource_storage.resources_mut().contains(hash)) {
// This hash names the very data that is missing, so it cannot stand in for fetching that data
let data_missing = info.hash.is_some_and(|hash| !resource_storage.contains(hash));
if info.hash.is_some() && !data_missing {
log::warn!("Resource {resource_id} already resolved");
return;
}
@@ -80,7 +89,7 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
.sources
.iter()
.map(|source| match source {
DataSource::Font { family, style } => {
DataSource::Font { family, style } if !data_missing => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
@@ -216,16 +225,20 @@ impl ResourceMessageHandler {
.resolved()
.filter(|info| info.sources.contains(&DataSource::Embedded))
.filter_map(|info| {
if let Some(hash) = info.hash {
let resource = resources_load_handle.load(*hash);
Some(async move { resource.await.map(|resource| (*hash, resource)) })
} else {
None
}
let (id, hash) = (info.id, *info.hash?);
let resource = resources_load_handle.load(hash);
Some(async move { (id, hash, resource.await) })
})
.collect::<Vec<_>>();
self.embedded = EmbeddedResources::from_iter(futures::future::join_all(embedded).await.into_iter().flatten());
let loaded = futures::future::join_all(embedded).await;
// Saving without these bytes writes a document whose registry claims to carry them
for (id, hash, _) in loaded.iter().filter(|(_, _, resource)| resource.is_none()) {
log::error!("Resource {id} ({hash}) is marked as embedded but its data is missing from storage, so the saved document will not contain it");
}
self.embedded = EmbeddedResources::from_iter(loaded.into_iter().filter_map(|(_, hash, resource)| resource.map(|resource| (hash, resource))));
}
pub fn collect_garbage(&mut self, used: &[ResourceId]) {
@@ -305,28 +318,45 @@ mod tests {
use super::*;
use graph_craft::application_io::resource::ResourceStorage;
/// Storage can lose a resource's data while the document keeps the hash naming it, which leaves the graph
/// pointing at bytes that are gone. Only sources that can be fetched again are worth re-resolving.
#[test]
fn resolve_all_refetches_resources_whose_bytes_are_missing() {
fn resolve_all_refetches_resources_whose_data_is_missing() {
let mut handler = ResourceMessageHandler::default();
let storage = ResourceStorageMessageHandler::default();
let fonts = FontsMessageHandler::default();
let font = |style: &str| DataSource::Font {
family: "Lato".into(),
style: Some(style.into()),
};
// Present: its bytes are in storage, so it is already usable
let present = ResourceId::new();
let present_hash = storage.resources_mut().store(b"stored font bytes");
handler.registry.resolve(&present, present_hash);
handler.registry.push_source_back(&present, DataSource::Embedded);
handler.registry.push_source_back(
&present,
DataSource::Font {
family: "Lato".into(),
style: Some("Regular (400)".into()),
},
);
let cached = ResourceId::from(1);
let cached_hash = storage.resources_mut().store(b"stored font bytes");
handler.registry.resolve(&cached, cached_hash);
handler.registry.push_source_back(&cached, font("Regular (400)"));
// Recoverable: its bytes are gone, but the font it came from can be downloaded again
let recoverable = ResourceId::new();
handler.registry.resolve(&recoverable, ResourceHash::from(b"evicted font bytes".as_slice()));
handler.registry.push_source_back(&recoverable, DataSource::Embedded);
handler.registry.push_source_back(
&recoverable,
DataSource::Font {
family: "Lato".into(),
style: Some("Black (900)".into()),
},
);
let evicted = ResourceId::from(2);
let evicted_hash = ResourceHash::from(b"evicted font bytes".as_slice());
handler.registry.resolve(&evicted, evicted_hash);
handler.registry.push_source_back(&evicted, font("Black (900)"));
// Unrecoverable: its bytes are gone and nothing records where to fetch them from
let unrecoverable = ResourceId::new();
handler.registry.resolve(&unrecoverable, ResourceHash::from(b"evicted image bytes".as_slice()));
handler.registry.push_source_back(&unrecoverable, DataSource::Embedded);
let mut responses = VecDeque::new();
let fonts = FontsMessageHandler::default();
handler.process_message(
ResourceMessage::ResolveAll,
&mut responses,
@@ -338,8 +368,9 @@ mod tests {
);
let resolve_requested = |id: ResourceId| responses.contains(&Message::from(ResourceMessage::Resolve { resource_id: id }));
assert!(resolve_requested(evicted), "a resource whose bytes are gone should be resolved again");
assert!(!resolve_requested(cached), "a resource whose bytes are in storage should be left alone");
assert_eq!(handler.registry.hash(&evicted), Some(evicted_hash), "the hash keeps naming the content");
assert!(resolve_requested(recoverable), "a missing resource with a font source should be fetched again");
assert!(!resolve_requested(present), "a resource whose data is in storage should be left alone");
assert!(!resolve_requested(unrecoverable), "a missing resource with no fetchable source has nowhere to fetch from");
}
}
@@ -741,7 +741,7 @@ async fn none_fill_survives_document_reopen() {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: fill_node_id,
input_index: graphene_std::vector::fill::PaintInput::INDEX,
value: Box::new(graph_craft::document::value::TaggedValue::no_paint()),
value: graph_craft::document::value::TaggedValue::no_paint().into(),
})
.await;
assert!(fill_paint_value(editor.active_document()).is_no_paint(), "the None pick should store as no_paint");
@@ -20,30 +20,6 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
}
/// Dev tool: writes each demo's migrated re-save into the directory named by `DEMO_OUT`, leaving the checked-in originals untouched.
#[test]
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
fn migrate_demo_artwork_into_demo_out() {
use crate::messages::portfolio::document_migration::{
document_migration_reset_layer_definitions, document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades,
};
let out_dir = std::env::var("DEMO_OUT").expect("set DEMO_OUT to the output directory");
for entry in std::fs::read_dir("../demo-artwork").unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|extension| extension.to_str()) != Some("graphite") {
continue;
}
let content = std::fs::read_to_string(&path).unwrap();
let content = document_migration_string_preprocessing(content);
let reset = document_migration_reset_node_definition(&content);
let reset_layers = document_migration_reset_layer_definitions(&content);
let mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
document_migration_upgrades(&mut document, reset, reset_layers);
let out = format!("{out_dir}/{}", path.file_name().unwrap().to_string_lossy());
std::fs::write(out, document.serialize_document()).unwrap();
}
}
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
/// iterate every node addressable from the metadata side.
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
@@ -40,8 +40,7 @@ pub struct DocumentMetadata {
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
/// Per-layer resolved appearance snapshot, exposed so message handlers can
/// read the paint and stroke parameters that live on the coverage rows.
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
@@ -189,8 +188,8 @@ impl DocumentMetadata {
self.visual_targets(layer)?
.iter()
.filter_map(|click_target| match click_target.target_type() {
ClickTargetType::Path(_) | ClickTargetType::Instance { .. } => {
let mut transformed = click_target.path_in_layer().map(|path| path.into_owned()).unwrap_or_default();
ClickTargetType::Path(path) => {
let mut transformed = path.clone();
transformed.apply_affine(Affine::new(transform.to_cols_array()));
let control_box = transformed.control_box();
@@ -254,8 +253,11 @@ impl DocumentMetadata {
self.all_layers().filter_map(|layer| self.bounding_box_viewport(layer)).reduce(Quad::combine_bounds)
}
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = std::borrow::Cow<'_, BezPath>> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| target.path_in_layer())
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &BezPath> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| match target.target_type() {
ClickTargetType::Path(path) => Some(path),
ClickTargetType::FreePoint(_) => None,
})
}
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
@@ -40,6 +40,8 @@ use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::Appearance;
use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
@@ -228,7 +228,7 @@ impl NodeNetworkInterface {
})
.collect::<Vec<(NodeId, i32)>>();
node_ids_with_position.sort_unstable_by_key(|entry| entry.1);
node_ids_with_position.sort_unstable_by(|a, b| a.1.cmp(&b.1));
Some(node_ids_with_position.into_iter().map(|(node_id, _)| node_id).collect::<Vec<_>>())
}
@@ -650,6 +650,18 @@ impl NodeNetworkInterface {
node.call_argument = call_argument;
}
pub fn set_context_features(&mut self, node_id: &NodeId, network_path: &[NodeId], context_features: ContextDependencies) {
let Some(network) = self.network_mut(network_path) else {
log::error!("Could not get nested network in set_context_features");
return;
};
let Some(node) = network.nodes.get_mut(node_id) else {
log::error!("Could not get node in set_context_features");
return;
};
node.context_features = context_features;
}
/// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
@@ -841,13 +841,6 @@ impl NodeNetworkInterface {
self.query(network_path, "is_visible", |view| view.is_visible(node_id)).unwrap_or_default()
}
/// Whether a layer in the document network is visible, which also requires every ancestor to be visible.
pub fn is_layer_visible(&self, layer: LayerNodeIdentifier) -> bool {
layer
.ancestors(self.document_metadata())
.all(|ancestor| ancestor == LayerNodeIdentifier::ROOT_PARENT || self.is_visible(&ancestor.to_node(), &[]))
}
pub fn is_layer(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "is_layer", |view| view.is_layer(node_id)).unwrap_or_default()
}
@@ -57,26 +57,20 @@ impl TypeSource {
}
}
/// Whether the compiled type is a packed `Record` lane, as opposed to a bare rank-0 value.
/// 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 {
// `nested_type` peels `Record`, so the rank has to be read off the unpeeled type
fn is_record(ty: &Type) -> bool {
match ty {
Type::Fn(_, output) | Type::Future(output) => is_record(output),
Type::Record(_) => true,
_ => false,
}
}
match self {
TypeSource::Compiled(compiled_type) => is_record(compiled_type),
TypeSource::TaggedValue(value_type) => is_record(value_type),
_ => false,
}
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some())
}
/// The element type's identifier name, so semantic type checks can be rank-agnostic.
/// The element type with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic.
pub fn compiled_element_type(&self) -> Option<&Type> {
Some(element_of(self.compiled_nested_type()?))
}
/// The identifier name of [`Self::compiled_element_type`].
pub fn compiled_element_name(&self) -> Option<String> {
Some(self.compiled_nested_type()?.identifier_name())
Some(self.compiled_element_type()?.identifier_name())
}
pub fn compiled_nested_type(&self) -> Option<&Type> {
@@ -115,6 +109,14 @@ impl TypeSource {
}
}
/// Peels any `Fn`/`Future` wrapper, then any rank-0 `Item` or rank-1 `List` wrapper, down to the element type.
fn element_of(ty: &Type) -> &Type {
match ty.nested_type() {
Type::Item(element) | Type::List(element) => element.as_ref(),
other => other,
}
}
impl NodeNetworkInterface {
fn input_has_error(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
match input_connector {
@@ -183,13 +185,13 @@ impl NodeNetworkInterface {
}
let chain_type = self.input_type(&secondary_input, network_path);
match chain_type.compiled_nested_type() {
match chain_type.compiled_element_type() {
Some(element) => {
let Some(implementations) = NODE_REGISTRY.get(node) else {
log::error!("Proto node {node:?} not found in the node registry, in layer_chain_hosts_node");
return false;
};
implementations.iter().any(|entry| entry.io.inputs.first().is_some_and(|content| content.nested_type() == element))
implementations.keys().any(|node_io| node_io.inputs.first().is_some_and(|content| element_of(content) == element))
}
None => !matches!(chain_type, TypeSource::Invalid),
}
@@ -241,7 +243,18 @@ impl NodeNetworkInterface {
}
};
// `TaggedValue::from_type` recurses through `Record` to the element, so a record default already drops to rank 0
// 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)
}
@@ -287,9 +300,8 @@ impl NodeNetworkInterface {
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations
.iter()
.filter_map(|entry| {
let node_io = &entry.io;
.keys()
.filter_map(|node_io| {
// Check if this NodeIOTypes implementation is valid for the other inputs
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, iterator_index), network_path);
@@ -328,9 +340,8 @@ impl NodeNetworkInterface {
let valid_output_types = self.valid_output_types(&OutputConnector::primary_output(*node_id), network_path);
implementations
.iter()
.filter_map(|entry| {
let node_io = &entry.io;
.keys()
.filter_map(|node_io| {
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None;
}
@@ -359,7 +370,7 @@ impl NodeNetworkInterface {
log::error!("Protonode {render_node:?} not found in registry");
return Vec::new();
};
implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
implementations.keys().map(|types| types.inputs[1].clone()).collect()
}
}
}
@@ -186,8 +186,8 @@ impl NodeNetworkInterface {
self.document_metadata.layer_vector_data = new_layer_vector_data;
}
/// Update the per-layer resolved appearance snapshot.
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<graphene_std::Appearance>>) {
/// Update the per-layer `ATTR_APPEARANCE` snapshot.
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
}
}
@@ -2,7 +2,6 @@ use super::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graphene_std::Context;
use graphene_std::ContextDependencies;
// PartialEq required by message handlers
/// All persistent editor and Graphene data for a node, unified into a single flat shape.
@@ -218,6 +217,13 @@ impl NodeTemplate {
}
}
}
/// Normalizes the stored types at every nesting level via [`DocumentNode::normalize_stored_types`], round-tripping through the split halves to reuse its logic.
pub fn normalize_stored_types(&mut self) {
let (mut document_node, persistent_node_metadata) = std::mem::take(self).into_parts();
document_node.normalize_stored_types();
*self = NodeTemplate::from_parts(document_node, persistent_node_metadata);
}
}
impl NodeTemplateImplementation {
@@ -52,7 +52,13 @@ pub struct SelectedNodes(pub Vec<NodeId>);
impl SelectedNodes {
pub fn layer_visible(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
network_interface.is_layer_visible(layer)
layer.ancestors(network_interface.document_metadata()).all(|layer| {
if layer != LayerNodeIdentifier::ROOT_PARENT {
network_interface.is_visible(&layer.to_node(), &[])
} else {
true
}
})
}
pub fn selected_visible_layers<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
@@ -8,9 +8,9 @@ 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, list};
use graphene_std::Color;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
@@ -76,6 +76,25 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::raster::OpacityNode", "graphene_core::blending_nodes::OpacityNode"],
},
// ================================
// brush
// ================================
NodeReplacement {
node: graphene_std::brush::brush::blit::IDENTIFIER,
aliases: &["graphene_brush::BlitNode", "graphene_std::brush::BlitNode", "graphene_brush::brush::BlitNode"],
},
NodeReplacement {
node: graphene_std::brush::brush::brush::IDENTIFIER,
aliases: &["graphene_brush::BrushNode", "graphene_std::brush::BrushNode", "graphene_brush::brush::BrushNode"],
},
NodeReplacement {
node: graphene_std::brush::brush::brush_stamp_generator::IDENTIFIER,
aliases: &[
"graphene_brush::BrushStampGeneratorNode",
"graphene_std::brush::BrushStampGeneratorNode",
"graphene_brush::brush::BrushStampGeneratorNode",
],
},
// ================================
// gcore
// ================================
NodeReplacement {
@@ -132,12 +151,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::list::extend::IDENTIFIER,
aliases: &[
"graphene_core::graphic::graphic::ExtendNode",
"graphene_core::graphic::ExtendNode",
"graphic_nodes::graphic::ExtendNode",
],
node: graphene_std::graphic::extend::IDENTIFIER,
aliases: &["graphene_core::graphic::graphic::ExtendNode", "graphene_core::graphic::ExtendNode"],
},
NodeReplacement {
node: graphene_std::graphic::flatten_graphic::IDENTIFIER,
@@ -152,35 +167,29 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
},
NodeReplacement {
node: graphene_std::list::item_at_index::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",
"graphic_nodes::graphic::ItemAtIndexNode",
],
},
NodeReplacement {
node: graphene_std::graphic::read_gradient_spread_attribute::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode", "graphic_nodes::graphic::ReadSpreadMethodAttributeNode"],
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
},
NodeReplacement {
node: graphene_std::graphic::read_gradient_space_attribute::IDENTIFIER,
aliases: &[
"graphic_nodes::graphic::ReadAttributeGradientInterpolationNode",
"graphic_nodes::graphic::ReadGradientInterpolationAttributeNode",
],
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
},
NodeReplacement {
node: graphene_std::list::remove_at_index::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode", "graphic_nodes::graphic::RemoveAtIndexNode"],
node: graphene_std::graphic::remove_at_index::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode"],
},
// The legacy layer extend no longer exists as a node; the aliases still land on its identifier so the
// subgraph rebuild below recognizes and replaces the networks that carried it.
NodeReplacement {
node: ProtoNodeIdentifier::new("graphic_nodes::graphic::LegacyLayerExtendNode"),
node: graphene_std::graphic::legacy_layer_extend::IDENTIFIER,
aliases: &[
"graphene_core::graphic_element::LayerNode",
"graphene_core::graphic_types::LayerNode",
@@ -865,10 +874,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::context::read_index::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceIndexNode", "core_types::vector::InstanceIndexNode"],
},
// The string map folded into the general Map, and its reader into the vararg readers.
NodeReplacement {
node: graphene_std::list::map::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceMapNode", "text_nodes::MapStringNode", "graphic_nodes::graphic::MapNode"],
node: graphene_std::graphic::map::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceMapNode"],
},
NodeReplacement {
node: graphene_std::context::read_position::IDENTIFIER,
@@ -878,10 +886,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::context::read_vector::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceVectorNode"],
},
NodeReplacement {
node: graphene_std::context::read_string::IDENTIFIER,
aliases: &["text_nodes::ReadStringNode"],
},
NodeReplacement {
node: graphene_std::repeat::repeat::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceRepeatNode", "core_types::vector::InstanceRepeatNode"],
@@ -1073,24 +1077,15 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
return true;
}
// Every Merge layer network is built from the two nodes that became "As Graphic" and "Into Group", so their definitions
// are reset to pick up the current plumbing instead of the alias migration meant for standalone copies of those nodes.
if into_group_aliases().any(|alias| document_serialized_content.contains(alias)) {
return true;
}
false
}
/// Whether the layer networks built from the coercion nodes that became "As Graphic" and "Into Group" need their definitions reset.
///
/// A document still naming either node by an alias stores the pre-split plumbing, which the alias migration alone would mangle:
/// it maps both names onto the reducer, leaving a reducer where the layer wants the assertion. Resetting those two layer
/// definitions installs the current plumbing instead. This stays narrower than a full
/// [`document_migration_reset_node_definition`], whose one-shot input reorderings would re-apply to documents already carrying them.
pub fn document_migration_reset_layer_definitions(document_serialized_content: &str) -> bool {
into_group_aliases().any(|alias| document_serialized_content.contains(alias))
}
/// The layer networks whose definitions [`document_migration_reset_layer_definitions`] resets.
fn is_coercion_layer_definition(reference: &DefinitionIdentifier) -> bool {
matches!(reference, DefinitionIdentifier::Network(name) if name == "Merge" || name == "Artboard")
}
pub fn document_migration_replace_resources_referenced_by_hash(document_serialized_content: String) -> (String, HashMap<ResourceHash, ResourceId>) {
fn collect_resources_referenced_by_hash(s: &str) -> HashMap<ResourceHash, Vec<Range<usize>>> {
let mut out: HashMap<ResourceHash, Vec<Range<usize>>> = HashMap::new();
@@ -1162,8 +1157,9 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
(out, hash_to_id)
}
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool, reset_layer_definitions: bool) {
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();
@@ -1193,8 +1189,32 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Brush" wrapper network was replaced with the `brush` proto node directly. Convert old `Network("Brush")` instances to the proto node, forwarding all 3 inputs (Background, Trace, Cache) one-to-one.
// This must run as a pre-pass before the recursive iteration below: replacing the outer Brush's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
let brush_layers: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Brush".into()))).then_some((*node_id, path)))
.collect();
for (node_id, network_path) in &brush_layers {
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves the original upstream→node wire from cache
// rather than triggering a fresh rebuild from the (already-mutated) post-`replace_inputs` state, which would orphan wires.
let _ = document.network_interface.outward_wires(network_path);
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER);
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
for (index, input) in old_inputs.iter().take(3).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
}
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
// This must run as a pre-pass before the recursive iteration below: replacing the outer Transform's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
.network_interface
.document_network()
@@ -1261,7 +1281,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
// The "Image" wrapper network was replaced with the `image` proto node directly. Convert old `Network("Image")` instances to the proto node, forwarding the embedded image data so the `image` pass in `migrate_node` below turns it into a resource.
// Pre-pass for the same reason as the Transform migration above: replacing the outer Image's network impl orphans its child paths.
// Pre-pass for the same reason as the Brush and Transform migrations above: replacing the outer Image's network impl orphans its child paths.
let image_layers: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
@@ -1305,7 +1325,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.map(|(node_id, node, path)| (*node_id, node.clone(), path))
.collect::<Vec<(NodeId, graph_craft::document::DocumentNode, Vec<NodeId>)>>();
for (node_id, node, network_path) in &nodes {
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open, reset_layer_definitions);
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[]`) -> converter pair, which reuses the same proto
@@ -1423,51 +1443,14 @@ fn fold_gradient_spread_into_ramp_input(input: &NodeInput, gradient_spread: Grad
}
}
fn migrate_node(
node_id: &NodeId,
node: &DocumentNode,
network_path: &[NodeId],
document: &mut DocumentMessageHandler,
reset_node_definitions_on_open: bool,
reset_layer_definitions: bool,
) -> Option<()> {
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.
migrate_removed_catalog_definitions(node_id, node, network_path, document);
if let Some(reference) = document.network_interface.reference(node_id, network_path)
&& (reset_node_definitions_on_open || (reset_layer_definitions && is_coercion_layer_definition(&reference)))
{
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
let node_definition = resolve_document_node_type(&reference)?;
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
// The leveled-records flip moved the Copy to Points content wire ahead of the points wire.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::copy_to_points::IDENTIFIER) {
let mut node_template = node_definition.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[0].clone(), network_path);
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// The leveled-records flip moved the Repeat on Points content wire ahead of the points wire.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::repeat::repeat_on_points::IDENTIFIER) {
let mut node_template = node_definition.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[0].clone(), network_path);
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// The leveled-records flip gave Mandelbrot a unit primary input.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
let mut node_template = node_definition.default_node_template();
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
}
}
// Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally
@@ -1482,18 +1465,6 @@ fn migrate_node(
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Rebuild stale Rasterize subgraphs from before the async-source conversion gave the inner proto node a unit primary input (5 inputs, now 6).
if let DocumentNodeImplementation::Network(inner) = &node.implementation
&& inner
.nodes
.values()
.any(|n| n.inputs.len() == 5 && matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("rasterize")))
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Rasterize".into()))
&& let Some(node_definition) = resolve_document_node_type(&DefinitionIdentifier::Network("Rasterize".into()))
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
@@ -1849,7 +1820,7 @@ fn migrate_node(
inputs_count = 7;
}
// Upgrade Stroke node to reorder parameters and add "Align" (#2644), landing on the shape without the retired "Paint Order" input
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
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)?;
@@ -1885,8 +1856,6 @@ fn migrate_node(
for (index, input) in old_inputs.iter().enumerate().take(7) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
// A document old enough to still carry "Paint Order" also predates `DashPattern`, and the standalone dash
// conversion below reads the pre-migration node, where index 7 is still the paint order
let dash_input = migrate_dash_input(&old_inputs[8]).unwrap_or_else(|| old_inputs[8].clone());
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), old_inputs[9].clone(), network_path);
@@ -1895,22 +1864,6 @@ fn migrate_node(
set_stroke_paint_order(&mut document.network_interface, network_path, *node_id, paint_order);
}
// The String Split node gained a unit primary so its level stands on its own rather than inheriting its
// subject's rank, which shifts its three original inputs one slot later
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::string_split::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.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)?;
for (index, input) in old_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index + 1), input.clone(), network_path);
}
inputs_count = 4;
}
// TODO: Eventually remove this 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
{
@@ -1953,6 +1906,28 @@ fn migrate_node(
.set_input(&InputConnector::node(*node_id, graphene_std::vector::stroke::DashPatternInput), migrated, network_path);
}
// The stored no-paint sentinel was the `List<Graphic>` type default before the paint connectors ranked down to `Item<Graphic>`.
// This must run before the stale-List-default cleanup below, which would otherwise adopt the definition's default paint.
{
let legacy_no_paint = TaggedValue::TypeDefault(list!(graphene_std::Graphic));
let paint_parameters: &[ParameterRef] = &[graphene_std::vector::fill::PaintInput.into(), graphene_std::vector::stroke::PaintInput.into()];
for parameter in paint_parameters {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
continue;
}
let Some(NodeInput::Value { tagged_value, exposed }) = node.inputs.get(parameter.input_index) else {
continue;
};
if **tagged_value == legacy_no_paint {
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, parameter.input_index),
NodeInput::value(TaggedValue::no_paint(), *exposed),
network_path,
);
}
}
}
// The corner radius became the `BoxCorners` value type; convert any already-shaped rectangle that still stores a legacy corner input
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
&& let Some(corner_input) = node.input(graphene_std::vector::generator_nodes::rectangle::CornerRadiusInput)
@@ -2254,6 +2229,36 @@ fn migrate_node(
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
}
// Old shape: [background, bounds, trace, cache]. Both "bounds" (input 1) and "cache" (input 3) are dropped, and "cache" is now stored as
// internal node state via `#[data]` on the brush node, so it is not a node input at all in the new shape.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::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);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[2].clone(), network_path);
}
// Old shape: [background, trace, cache]. The "cache" input is dropped because the brush node now stores its cache as internal `#[data]` state.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.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)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*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.inputs.first()?.clone();
document.network_interface.set_input(&InputConnector::node_at_index(*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);
@@ -2715,6 +2720,15 @@ fn migrate_node(
}
}
// Add context features to nodes that don't have them (fine-grained context caching migration)
if node.context_features == graphene_std::ContextDependencies::default()
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
&& let Some(node_definition) = resolve_document_node_type(&reference)
{
let context_features = node_definition.node_template.context_features;
document.network_interface.set_context_features(node_id, network_path, context_features);
}
// Add the "Scale Type" parameter to the "Decompose Scale" node
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -2753,7 +2767,7 @@ fn migrate_node(
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 0),
NodeInput::type_default(descriptor!(graphene_std::list::List<graphene_std::vector::Vector>), true),
NodeInput::type_default(item!(graphene_std::vector::Vector), true),
network_path,
);
@@ -2803,7 +2817,7 @@ fn migrate_node(
.input_from_connector(&InputConnector::node_at_index(*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 stored_type.name.contains("list::List<") && !tagged_value.is_no_paint() => {
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,
@@ -2963,15 +2977,6 @@ mod tests {
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
}
#[test]
fn a_written_attribute_no_longer_resets_the_layer_definitions() {
// The node resolves natively again, so a document carrying it keeps
// its own layer internals instead of rebuilding them.
assert!(!document_migration_reset_node_definition(
r#"{"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}}}"#
));
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
#[test]
fn every_into_group_alias_resets_the_merge_definition() {
@@ -2979,15 +2984,10 @@ mod tests {
assert!(!aliases.is_empty(), "the reset is driven by these aliases, so losing them all would disable it unnoticed");
for alias in aliases {
let document = format!(r#""implementation":{{"ProtoNode":"{alias}"}}"#);
assert!(
document_migration_reset_layer_definitions(&document),
document_migration_reset_node_definition(&format!(r#""implementation":{{"ProtoNode":"{alias}"}}"#)),
"a document referencing `{alias}` should reset its layer definitions"
);
assert!(
!document_migration_reset_node_definition(&document),
"`{alias}` alone must not reset every definition, which would re-apply the one-shot input reorderings"
);
}
}
@@ -3035,7 +3035,7 @@ mod tests {
);
document.network_interface.set_input(&InputConnector::node_at_index(consumer_id, 0), NodeInput::node(text_id, 0), &[]);
document_migration_upgrades(&mut document, false, false);
document_migration_upgrades(&mut document, false);
let network = document.network_interface.document_network();
let text_node = network.nodes.get(&text_id).expect("the upgraded text node should keep its ID");
@@ -52,7 +52,7 @@ pub enum PortfolioMessage {
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<Box<document_format::GddV1>>,
gdd: Option<document_format::GddV1>,
},
DestroyAllDocuments,
EditorPreferences,
@@ -5,7 +5,7 @@ use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, FileFilter, PersistedState};
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
@@ -305,7 +305,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Document was closed before its working copy finished mounting.
return;
};
document.set_storage(gdd.map(|gdd| *gdd));
document.set_storage(gdd);
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
@@ -501,10 +501,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(FrontendMessage::TriggerSaveFile {
name: filename,
folder: None,
filters: vec![FileFilter {
name: "Graphite Document".into(),
extensions: vec![FILE_EXTENSION.into()],
}],
content: serde_bytes::ByteBuf::from(content),
});
} else {
@@ -512,10 +508,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
Ok(zip_bytes) => responses.add(FrontendMessage::TriggerSaveFile {
name: format!("{FOLDER_NAME}.zip"),
folder: None,
filters: vec![FileFilter {
name: "Zip Archive".into(),
extensions: vec!["zip".into()],
}],
content: serde_bytes::ByteBuf::from(zip_bytes),
}),
Err(e) => {
@@ -660,28 +652,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
PortfolioMessage::Open => {
// This portfolio message wraps the frontend message so it can be listed as an action, which isn't possible for frontend messages
responses.add(FrontendMessage::TriggerOpen {
filters: vec![
FileFilter {
name: "Graphite Document".into(),
extensions: vec![FILE_EXTENSION.into(), GDD_FILE_EXTENSION.into()],
},
FileFilter {
name: "Image".into(),
extensions: vec!["svg".into(), "png".into(), "jpg".into(), "jpeg".into(), "bmp".into(), "gif".into()],
},
],
});
responses.add(FrontendMessage::TriggerOpen);
}
PortfolioMessage::Import => {
// This portfolio message wraps the frontend message so it can be listed as an action, which isn't possible for frontend messages
// TODO: Also offer the Graphite document filter once importing Graphite documents as nodes is supported
responses.add(FrontendMessage::TriggerImport {
filters: vec![FileFilter {
name: "Image".into(),
extensions: vec!["svg".into(), "png".into(), "jpg".into(), "jpeg".into(), "bmp".into(), "gif".into()],
}],
});
responses.add(FrontendMessage::TriggerImport);
}
PortfolioMessage::OpenFile { path, content } => {
let name = path.file_stem().map(|n| n.to_string_lossy().to_string());
@@ -853,8 +828,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} => {
// Upgrade the document being opened to use fresh copies of all nodes
let reset_node_definitions_on_open = reset_node_definitions_on_open || document_migration_reset_node_definition(&document_serialized_content);
// Reinstall just the layer networks whose coercion nodes were split into "As Graphic" and "Into Group"
let reset_layer_definitions = document_migration_reset_layer_definitions(&document_serialized_content);
// Upgrade the document being opened with string replacements on the original JSON
let document_serialized_content = document_migration_string_preprocessing(document_serialized_content);
// Upgrade resources from being referend by hash to beeing referened by ID
@@ -905,7 +878,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
// Upgrade the document's nodes to be compatible with the latest version
document_migration_upgrades(&mut document, reset_node_definitions_on_open, reset_layer_definitions);
document_migration_upgrades(&mut document, reset_node_definitions_on_open);
// Load the document's embedded resources into the resource storage
std::mem::take(&mut document.resources.embedded).into_iter().for_each(|(hash, resource)| {
@@ -1941,7 +1914,7 @@ impl PortfolioMessageHandler {
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
gdd: Some(Box::new(gdd)),
gdd: Some(gdd),
})
};
future.into()
@@ -93,7 +93,6 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
zoom_with_scroll: self.zoom_with_scroll,
});
responses.add(FrontendMessage::UpdateUIScale { scale: self.ui_scale });
responses.add(ToolMessage::RefreshToolShelf);
}
PreferencesMessage::ResetToDefaults => {
responses.add(PreferencesMessage::Load { preferences: Self::default() });
@@ -48,6 +48,11 @@ impl ResourceStorageMessageHandler {
inner: self.storage.clone().expect("Resource storage not initialized"),
}
}
/// Whether the resource's data is held in storage, assuming it is until storage is initialized.
pub fn contains(&self, hash: &ResourceHash) -> bool {
self.storage.as_ref().is_none_or(|storage| storage.contains(hash))
}
}
impl std::fmt::Debug for ResourceStorageMessageHandler {
@@ -125,6 +125,9 @@ pub struct DrawingToolState {
pub miter_limit: Option<f64>,
/// Paint order from the selection. `None` = mixed.
pub paint_order: Option<PaintOrder>,
/// Whether any selected layer has a lone adjacent Fill/Stroke pair for the paint order to swap.
/// Stays true with an empty selection, where the radio still sets the default for new shapes.
pub paint_order_applicable: bool,
/// Dash lengths from the selection. `None` = mixed.
pub dash_lengths: Option<Vec<f64>>,
/// Dash offset from the selection. `None` = mixed.
@@ -150,6 +153,7 @@ impl DrawingToolState {
stroke_join: Some(StrokeJoin::default()),
miter_limit: Some(4.),
paint_order: Some(PaintOrder::default()),
paint_order_applicable: true,
dash_lengths: Some(Vec::new()),
dash_offset: Some(0.),
last_synced_selection: Vec::new(),
@@ -188,12 +192,14 @@ impl DrawingToolState {
transform: glam::DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
// The paint order is the chain order of the Fill and Stroke nodes, so a below choice reorders the new pair
if self.paint_order.unwrap_or_default() == graphene_std::vector::style::PaintOrder::StrokeBelow {
responses.add(GraphOperationMessage::StrokePaintOrderSet {
layer,
paint_order: graphene_std::vector::style::PaintOrder::StrokeBelow,
});
}
/// Queues the paint order rewrite for a freshly created `layer`. The order is the relative position of the
/// Stroke and Fill nodes in the chain, so this must run after both the stroke and fill have been applied.
pub fn apply_stroke_order_to_new_layer(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
let paint_order = self.paint_order.unwrap_or_default();
if paint_order != PaintOrder::default() {
responses.add(GraphOperationMessage::StrokeOrderSet { layer, paint_order });
}
}
}
@@ -310,12 +316,23 @@ pub fn sync_drawing_state(drawing: &mut DrawingToolState, natural_fill_enabled:
/// Reads the stroke proto-node inputs (align, cap, join, miter limit, paint order, dash lengths, dash offset) across the selection and updates
/// the matching fields on `drawing`. Each field becomes `None` (mixed) when selected strokes disagree. With no selection, fields are left as-is.
fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessageHandler) -> bool {
let strokes: Vec<_> = graph_modification_utils::paintable_selected_layers(document)
let layers = graph_modification_utils::paintable_selected_layers(document);
// The order radio only swaps a layer's lone adjacent Fill/Stroke pair, so it grays out when no selected
// layer has one; with nothing selected it still sets the default order for new shapes
let paint_order_applicable = layers.is_empty() || layers.iter().any(|&layer| graph_modification_utils::stroke_paint_order_applicable(layer, &document.network_interface));
let mut applicability_changed = false;
if drawing.paint_order_applicable != paint_order_applicable {
drawing.paint_order_applicable = paint_order_applicable;
applicability_changed = true;
}
let strokes: Vec<_> = layers
.into_iter()
.filter_map(|layer| graph_modification_utils::get_stroke_options(layer, &document.network_interface))
.collect();
if strokes.is_empty() {
return false;
return applicability_changed;
}
fn unanimous<T: PartialEq + Clone>(values: impl IntoIterator<Item = T>) -> Option<T> {
@@ -332,7 +349,7 @@ fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessag
let new_dash_lengths = unanimous(strokes.iter().map(|s| &s.dash_lengths)).cloned();
let new_dash_offset = unanimous(strokes.iter().map(|s| s.dash_offset));
let mut changed = false;
let mut changed = applicability_changed;
if drawing.stroke_align != new_align {
drawing.stroke_align = new_align;
@@ -68,8 +68,6 @@ impl SpiralTurns {
self.handle_state == SpiralTurnsState::Dragging
}
// Records one snapshot of the spiral's parameters; grouping them would only move the same fields into a struct
#[allow(clippy::too_many_arguments)]
pub fn store_initial_parameters(
&mut self,
layer: LayerNodeIdentifier,
@@ -4,12 +4,12 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate, OutputConnector};
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::Color;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::raster_types::Image;
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};
@@ -682,23 +682,7 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
Some(TaggedValue::F64(value)) => *value,
_ => 4.,
};
// The paint order is the chain order of the Fill and Stroke nodes: the downstream one of an adjacent pair paints on top
let paint_order = {
let stroke_node_id = get_stroke_id(layer, network_interface);
let primary_source = |node_id: Option<NodeId>| {
node_id.and_then(|node_id| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, 0), &[]) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
})
};
if primary_source(stroke_node_id).is_some_and(|source| Some(source) == get_fill_id(layer, network_interface)) {
PaintOrder::StrokeAbove
} else if primary_source(get_fill_id(layer, network_interface)).is_some_and(|source| Some(source) == stroke_node_id) {
PaintOrder::StrokeBelow
} else {
PaintOrder::default()
}
};
let paint_order = get_stroke_paint_order(layer, network_interface);
let dash_lengths = match parameters.value(stroke::DashPatternInput) {
Some(TaggedValue::DashPattern(lengths)) => lengths.clone(),
_ => Vec::new(),
@@ -724,6 +708,67 @@ pub fn get_stroke_id(layer: LayerNodeIdentifier, network_interface: &NodeNetwork
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
}
/// Whether the paint order swap can act on the layer: exactly one Fill and one Stroke node in its chain,
/// wired directly together. Extra paint nodes make the swap unreliable, since a cover replaced in place
/// keeps the slot in the paint order that its upstream sibling established.
pub fn stroke_paint_order_applicable(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let mut strokes = Vec::new();
let mut fills = Vec::new();
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
for node_id in node_graph_layer
.horizontal_layer_flow()
.take_while(|&node_id| node_id == layer.to_node() || !network_interface.is_layer(&node_id, &[]))
{
let reference = network_interface.reference(&node_id, &[]);
if reference.as_ref() == Some(&stroke_reference) {
strokes.push(node_id);
} else if reference.as_ref() == Some(&fill_reference) {
fills.push(node_id);
}
}
let (&[stroke_node_id], &[fill_node_id]) = (strokes.as_slice(), fills.as_slice()) else {
return false;
};
let primary_source = |node_id: NodeId| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, 0), &[]) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
};
primary_source(stroke_node_id) == Some(fill_node_id) || primary_source(fill_node_id) == Some(stroke_node_id)
}
/// The paint order of a layer's stroke, read from the chain topology: both the Fill and Stroke nodes append
/// their cover, so the more downstream of the two paints on top, following the painter's algorithm.
pub fn get_stroke_paint_order(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> PaintOrder {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
// The flow iterates downstream to upstream, so the first of the pair encountered is the one painting on top
let mut stroke_position = None;
let mut fill_position = None;
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
for (position, node_id) in node_graph_layer
.horizontal_layer_flow()
.take_while(|&node_id| node_id == layer.to_node() || !network_interface.is_layer(&node_id, &[]))
.enumerate()
{
let reference = network_interface.reference(&node_id, &[]);
if reference.as_ref() == Some(&stroke_reference) {
stroke_position.get_or_insert(position);
} else if reference.as_ref() == Some(&fill_reference) {
fill_position.get_or_insert(position);
}
}
match stroke_position.zip(fill_position) {
Some((stroke_position, fill_position)) if fill_position < stroke_position => PaintOrder::StrokeBelow,
_ => PaintOrder::StrokeAbove,
}
}
/// Writes the weight back to every selected non-artboard layer's stroke. Layers with an existing stroke just have their
/// `WeightInput` updated; layers without one get a fresh stroke node added (defaulting to a black stroke with the new
/// weight) only when the new weight is nonzero, so changing back to 0 doesn't keep adding empty strokes.
@@ -1111,9 +1156,7 @@ 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::layer_secondary_input(layer.to_node()), &[]);
// A leveled wire is typed by its element; depth rides the layout.
let compiled = layer_input_type.compiled_nested_type();
compiled == Some(&concrete!(Raster<CPU>)) || compiled == Some(&concrete!(Raster<GPU>))
matches!(layer_input_type.compiled_element_name().as_deref(), Some("Raster<CPU>" | "Raster<GPU>"))
}
}
@@ -88,8 +88,11 @@ impl ShapeType {
}
pub fn tooltip_description(&self) -> String {
// TODO: Add descriptions to all the shape tools
String::new()
(match self {
// TODO: Add descriptions to all the shape tools
_ => "",
})
.into()
}
pub fn icon_name(&self) -> String {
@@ -677,6 +677,7 @@ mod tests {
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
..Default::default()
};
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
let snap_results = &mut SnapResults::default();
@@ -734,7 +734,7 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
if !snap_data.ignore_bounds(layer) {
let to_document = document.metadata().transform_to_document(layer);
for bezpath in document.metadata().layer_outline(layer) {
bezpath_anchor_snap_points(layer, &bezpath, snap_data, points, to_document);
bezpath_anchor_snap_points(layer, bezpath, snap_data, points, to_document);
}
}
@@ -64,7 +64,9 @@ where
if has_dash {
rows.push(LayoutGroup::row(dash_offset_row(drawing.dash_offset, to_message.clone())));
}
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", drawing.paint_order, false, {
// An inapplicable order (no Fill/Stroke pair to reorder) grays out and highlights no entry, since the synced value is only a fallback
let paint_order = drawing.paint_order.filter(|_| drawing.paint_order_applicable);
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", paint_order, !drawing.paint_order_applicable, {
let to_message = to_message.clone();
move |value| to_message(StrokeOptionsUpdate::PaintOrder(value))
})));
@@ -198,9 +200,11 @@ pub fn apply_miter_limit(drawing: &mut DrawingToolState, limit: f64, document: &
pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.paint_order = Some(order);
// The paint order is the chain order of the Fill and Stroke nodes, so applying it reorders the pair
for layer in document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface) {
responses.add(GraphOperationMessage::StrokePaintOrderSet { layer, paint_order: order });
// A mixed selection only grays the radio out when no layer can take the swap, so skip the ones that can't
for layer in graph_modification_utils::paintable_selected_layers(document) {
if graph_modification_utils::stroke_paint_order_applicable(layer, &document.network_interface) {
responses.add(GraphOperationMessage::StrokeOrderSet { layer, paint_order: order });
}
}
}
@@ -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::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
@@ -25,12 +23,6 @@ pub fn should_extend(document: &DocumentMessageHandler, goal: DVec2, tolerance:
closest_point(document, goal, tolerance, layers, |_| false)
}
/// Finds the endpoint of an open path closest to the goal (in viewport space) across the given layers, if one lies within the tolerance.
/// Only anchors with a single connected segment qualify, so closed paths are never matched. Returns the endpoint's position in the layer's local space.
pub fn closest_open_path_endpoint(document: &DocumentMessageHandler, goal: DVec2, tolerance: f64, layers: impl Iterator<Item = LayerNodeIdentifier>) -> Option<(LayerNodeIdentifier, PointId, DVec2)> {
closest_candidate_point(document, goal, tolerance, layers, |vector| vector.anchor_endpoints().collect())
}
/// Determine the closest point to the goal point under max_distance.
/// Additionally exclude checking closeness to the point which given to exclude() returns true.
pub fn closest_point<T>(
@@ -43,32 +35,19 @@ pub fn closest_point<T>(
where
T: Fn(PointId) -> bool,
{
closest_candidate_point(document, goal, max_distance, layers, |vector| vector.anchor_points().filter(|&id| !exclude(id)).collect())
}
/// Determines the closest of each visible layer's candidate points to the goal (in viewport space) under max_distance. Returns the point's position in the layer's local space.
fn closest_candidate_point(
document: &DocumentMessageHandler,
goal: DVec2,
max_distance: f64,
layers: impl Iterator<Item = LayerNodeIdentifier>,
candidates: impl Fn(&Vector) -> Vec<PointId>,
) -> Option<(LayerNodeIdentifier, PointId, DVec2)> {
let mut best = None;
let mut best_distance_squared = max_distance * max_distance;
for layer in layers {
if !document.network_interface.is_layer_visible(layer) {
continue;
}
let viewspace = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
let viewspace = document.metadata().transform_to_viewport(layer);
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
for id in candidates(&vector) {
for id in vector.anchor_points() {
if exclude(id) {
continue;
}
let Some(point) = vector.point_domain.position_from_id(id) else { continue };
let distance_squared = viewspace.transform_point2(point).distance_squared(goal);
if distance_squared < best_distance_squared {
best = Some((layer, id, point));
best_distance_squared = distance_squared;
@@ -545,7 +524,7 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
let node_id = NodeGraphLayer::new(first_layer, network_interface).horizontal_layer_flow().nth(1)?;
let output_type = network_interface.output_type(&OutputConnector::primary_output(node_id), &[]);
if output_type.compiled_nested_type() != Some(&concrete!(List<Vector>)) {
if output_type.compiled_element_name().as_deref() != Some("Vector") {
return None;
}
+3
View File
@@ -76,6 +76,8 @@ pub enum ToolMessage {
},
DeactivateTools,
InitTools,
PreUndo,
Redo,
RefreshToolOptions,
RefreshToolShelf,
ResetColors,
@@ -88,6 +90,7 @@ pub enum ToolMessage {
},
ToggleSelectVsPath,
SwapColors,
Undo,
UpdateCursor,
UpdateHints,
UpdateSelectionMode {
Loaded 100 of 342 files, more files were not shown because too many files have changed in this diff. Show more