Compare commits

...
Author SHA1 Message Date
Dennis Kobert 663d670492 Name the carried source consistently in the entries emitter 2026-09-09 13:13:53 +00:00
Dennis Kobert d7e9e8fe45 Adopt master's list length name for the element count node 2026-09-09 13:08:40 +00:00
Dennis Kobert 25cc63eb8d Source a record io node's rows from its implementations secondary 2026-09-09 13:08:40 +00:00
Dennis KobertandClaude Fable 5 a46a23e516 Read a named attribute at each value type it can hold
One read node per value type, mirroring master's read family. A name
means one value type, so there is no coercion between them: master's
number read silently widened integers, and these refuse instead, which
is the same rule the write side already enforces.

Each takes any record wire through the opaque reading input and serves
the name's own default where the attribute is absent, so the value
carries the declared type either way.

The gradient enums join the value-type rows now that a family exists to
read them at.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:48:58 +00:00
Dennis KobertandClaude Fable 5 840729db04 Accept any record wire on an input read only for its attributes
An element generic declared on a reading input, absent from the output
and from every other input, has nowhere to go and nothing to be: the
node reads its declared attributes and never the element. That is an
attr-to-element map, so it accepts any upstream record wire.

The blessing is inferred rather than marked, since the signature already
says it. The two substrate pieces were both in place: the element rides
as the byte-carried token, so the registry takes one generic row instead
of a row per element type, and the reads resolve against the input's own
layout as they always have. Only the passthrough rule stood in the way,
in the three places that enforced it.

A generic the output carries, or one on an input with no reads, is
unchanged and still owes an implementations list.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:49 +00:00
Dennis KobertandClaude Fable 5 8501010ece Name the attribute read for the type it reads
The read is a number read, not a read of whatever the name holds: our
model has no coercion, so a name written at another value type is a graph
error rather than a conversion. The name says so.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:49 +00:00
Dennis KobertandClaude Fable 5 6e5ab01b76 Serve a declared name's census default on an absent read
An absent read of a name the census declares now serves that name's own
default rather than its value type's, which is the rule for a declared
name. The census stages it exactly as it fills any absent field, as the
declared default's bytes, so the read reuses the census's own mechanism
instead of a second one; the compiler takes them when the name folds and
`set_layout` installs them beside the offset.

A name the census does not declare keeps the value type's default, which
is that case's own rule. One name carries one value type, checked when
the name folds, so the row's value type and width agree with the read's.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:49 +00:00
Dennis KobertandClaude Fable 5 fffcaa6555 Resolve a named read's offset when the graph compiles
The fold already holds the name and the read input's finished layout, so
the offset falls out there rather than at construction: `RecordLayout`
carries the resolved numbers and `set_layout` copies them into the read
slots. Constructors are untouched, and census-marker reads keep their
current installation.

A read meets the value type the name was written at, so a disagreement
between a read here and a write upstream is the same graph error as two
writes disagreeing; the one-name-one-type check now spans reads and
writes together. An absent attribute stays absent and the read serves
the forced default rather than reporting it.

`read_attribute` is the catalog's get half, typed and never `Option` at
the kernel boundary, with the name declared exactly as the write side
declares it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:43 +00:00
Dennis KobertandClaude Fable 5 41fa0ba955 Keep the name placeholder out of the kernel entirely
A name input declares where a placeholder's name is wired and nothing
more. The name is spent resolving the layout when the graph compiles, so
the kernel neither declares it nor is passed it; the return type's
`Named<X, V>` is the only tie between the write slot and the folded name.

The wire is untouched: the input keeps its declared position and crosses
as constant text, so a document's input order is unchanged. The
placeholder stays a concrete token, so it adds no generic for the node
to carry and none to go unconstrained.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:46:31 +00:00
Dennis KobertandClaude Fable 5 bc7e2232e3 Carry the new layout fields through the hand-built fixtures
The record fixtures spell their metas and resolved layouts out in full,
so the name-from-input fields reach them as empty. `named_value!`'s
example moves to `ignore`: its `for T` arm implements a core-types trait
on the value type, which only core-types itself may do.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:45:48 +00:00
Dennis KobertandClaude Fable 5 81d72b159b Write an attribute under a name the graph supplies
`Named<X>` in parameter position declares where a placeholder's name is
wired, and the macro gives that input constant text; `Attr<Named<X, V>>`
in the return writes under it. The kernel is handed the bare placeholder,
since the name is spent resolving the layout and a folded offset is all
the write needs, so the hot path matches a marker node's exactly.

A name-generic write names its value type through the wired generic,
which only an implementations row resolves, so those nodes emit their
layout meta per row rather than sharing one across rows.

`write_attribute` is the catalog's set half, restoring the identifier
master's documents carry with its input positions. Its name input is a
constant, so those documents resolve without migration, and the reset
marker that stood in for the missing node retires with it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:45:42 +00:00
Dennis KobertandClaude Fable 5 db9a59aa7d Fold attribute names out of their constant inputs when the graph compiles
`compute_layouts` resolves every name-from-input write against the text
its name input carries, so a folded meta is indistinguishable from a
marker node's and the layout holds a `&'static str` from there on. That
leaves nowhere for a name to be computed, which is the whole of the
rule: a name input that is not a constant is refused right here, per
node, with the path the editor pins its diagnostic to.

One name carries one value type, checked across the census and the
names a node folds together, so no graph can declare one field at two
widths. `compute_layouts` returns those refusals rather than panicking.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:44:42 +00:00
Dennis KobertandClaude Fable 5 4f12de68a7 Carry a name-generic attribute's value type as its own row
An attribute's name and its value type separate: `AttrValue` declares
everything `Attribute` does except the name and its name-specific
default, and `Named<X, V>` pairs one with a name the graph supplies.
The value type stays concrete in the signature while the name varies
per instance, so a computed name has nowhere to come from.

`LayoutMeta` gains the name-from-input variant the fold consumes: a
`FieldWrite` template with every facet minted from the concrete type
and only the name left as a placeholder, plus the input position the
name's constant sits at. `fold_name` resolves one, preferring the
census row's descriptor where the name is declared so a known name
keeps its census default. `RecordLayout` carries the folded names so
`set_layout` can resolve offsets without a marker's `NAME`.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:44:36 +00:00
Dennis Kobert 8266a61c52 Pad master era stroke nodes with the trailing paint order input 2026-09-08 19:42:50 +00:00
Dennis Kobert 5faafa1964 Move the paint order input last so master era documents index cleanly 2026-09-08 19:40:15 +00:00
Dennis Kobert 9e6250d0d9 Accept any paint element on the graphic fill and stroke rows 2026-09-08 19:35:27 +00:00
Dennis Kobert 35a34168d7 Accept any paint element on the fill and stroke inputs 2026-09-08 18:54:21 +00:00
Dennis Kobert a593430e38 Adapt the test surface to our wire kind and no-content graphic 2026-09-08 17:41:29 +00:00
Dennis Kobert 33b20d6329 Bring the editor onto the reconciled node catalog and paint carrier 2026-09-08 16:33:52 +00:00
Dennis Kobert 3830ace926 Reach a compiling workspace on the merged tree 2026-09-08 16:11:30 +00:00
Dennis Kobert a854c25eb8 Rebuild the render walk on the new vector and gradient APIs 2026-09-08 15:23:20 +00:00
Dennis Kobert ff45cf9525 Keep the preprocessor and the type defaults on one wire kind 2026-09-08 15:18:12 +00:00
Dennis Kobert 95ce26e36c Drop the stranded ranked wrappers from the node signatures 2026-09-08 15:16:13 +00:00
Dennis Kobert c98570fd8a Read the stroke weight from the paint list in the clip path test 2026-09-08 15:14:43 +00:00
Dennis Kobert 694fd05ea0 Match the render metadata collection arity across the render seam 2026-09-08 15:13:45 +00:00
Dennis Kobert b93b395d2f Speak our record wire kind in the type defaults and artboard exports 2026-09-08 15:11:33 +00:00
Dennis Kobert 8555e6fb79 Drop the superseded rank promotion executor tests and cover brush stroke lists 2026-09-08 15:09:41 +00:00
Dennis Kobert db9b587f41 Route the render metadata attributes through fill and stroke 2026-09-08 15:06:47 +00:00
Dennis Kobert 985f85baec Adapt the merged tree to our rank model and paint attributes 2026-09-08 15:06:05 +00:00
Dennis Kobert f59ceba19f Merge origin/master into the async record refactor
Scaffolding merge for the reconcile; the final series to master is
authored fresh. Rank plumbing resolves to our axis-IR model, the node
macro and the LaneSource render walk stay ours, master's vector
restructure and gradient vocabulary are adopted, and the paint and
appearance adoption is deliberately deferred behind our fill and stroke
markers.
2026-09-08 15:03:57 +00:00
Dennis Kobert b321c094d2 Keep the new assert messages inside the format width 2026-09-08 13:29:09 +00:00
Dennis Kobert d4768d606f Justify the unsafe sites in the arena, record and graphic glue 2026-09-08 13:23:52 +00:00
Dennis Kobert 148008c695 Refuse a wasm threads build where the Send and Sync impls assume one thread 2026-09-08 13:15:18 +00:00
Dennis Kobert 2b5845464c Rederive the shared source pointer through an unwinding set_layout 2026-09-08 13:15:13 +00:00
Dennis Kobert 5e388cb38f Assert the deep element glue is registered before the executor evaluates 2026-09-08 13:15:06 +00:00
Dennis Kobert 49daf2895e Make Attribute an unsafe trait stating its re-park and glue coupling 2026-09-08 13:14:59 +00:00
Dennis Kobert 682d3dafbd Bound attribute value types Send and Sync 2026-09-08 13:14:59 +00:00
Dennis Kobert ad03b5b0bf Check a census row against the field before its writer runs 2026-09-08 13:14:33 +00:00
Dennis Kobert 324925aedb Debit the retained hint before the drop glue that may panic 2026-09-08 13:14:18 +00:00
Dennis Kobert e78a987e3e Bind a park forwarding to the destination arena generation 2026-09-08 13:14:12 +00:00
Dennis Kobert 2c8fa44eb4 Mint arena handles only over bytes the bump reserved 2026-09-08 13:14:12 +00:00
Dennis Kobert 6b22316077 Re-park a cross-arena adopt's payloads into the target arena 2026-09-08 13:11:04 +00:00
Dennis Kobert 98cabee4c6 Rebuild stale rasterize subgraphs at document migration 2026-09-08 12:53:02 +00:00
Dennis Kobert e0848abc59 Scan item attribute values for groups the ownership gates miss 2026-09-08 12:22:04 +00:00
Dennis Kobert f237a5ee50 Claim the carrier's frame before the lazy cursor snapshot 2026-09-08 12:22:04 +00:00
Dennis Kobert df99ab3a72 Guard attribute writes against an uninstalled layout offset 2026-09-07 16:12:01 +00:00
Dennis Kobert 0fc4424a09 State the disjointness a plan's copies require 2026-09-07 16:11:56 +00:00
Dennis Kobert e9a3199456 State what contains the laundered arena borrow in the flatten test 2026-09-07 16:11:32 +00:00
Dennis Kobert ef8312806d Serve the probe record the forwarding test finishes 2026-09-07 16:11:32 +00:00
Dennis Kobert 548cbfbf4e Check the claim's layout when replaying an owned record 2026-09-07 16:11:32 +00:00
Dennis Kobert 313c591f70 State from_resident's borrow-window contract at its call sites 2026-09-07 16:11:32 +00:00
Dennis Kobert f07f708ee8 Back the owned-item tests' lanes with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 5f73044b6b Back the repark test's element slot with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 11aedd8196 Refuse record layouts wider than the frame tier's alignment 2026-09-07 16:03:10 +00:00
Dennis Kobert f4f266b1ba Refuse a lift that never filled its layout's fields 2026-09-07 15:56:28 +00:00
Dennis Kobert 77e4e8c894 Bound and order the lanes a serve run records as filled 2026-09-07 15:51:08 +00:00
Dennis Kobert c231bd0eb8 Check the serve run's lane capacity arithmetic 2026-09-07 15:50:32 +00:00
Dennis Kobert 095e0bb4ff Require content glue for a group's element 2026-09-07 15:39:00 +00:00
Dennis Kobert 369f7db992 Copy records out untyped instead of through a byte slice 2026-09-07 15:38:53 +00:00
Dennis Kobert 79750fb52d Stage attribute default bytes through zeroed storage 2026-09-07 15:38:11 +00:00
Keavon Chambers e725f55043 Relicense Graphite under the dual MIT/Apache-2.0 license (#4208)
Relicense under dual MIT/Apache-2.0
2026-09-06 23:57:37 -07:00
Keavon Chambers fb35dadf1b Remove a couple of old frontend comments 2026-09-06 23:19:06 -07:00
Keavon Chambers 5612b63633 Extend open paths from endpoints with the Freehand tool and skip hidden layers in path edits (#4508)
* Let the Freehand tool continue a selected open path from its endpoint and show endpoint overlays in the Freehand and Spline tools

* Share the closest-point search with the open path endpoint lookup, tally endpoint connections in a single pass, and rename the endpoint overlay function

* Skip hidden layers and use the feeds-aware transform in path point searches, path overlays, and Freehand point placement

* Map the Spline tool's merge goal with the feeds-aware transform so it matches the endpoint candidates

* Highlight the hovered open path endpoint in the Freehand and Spline tools
2026-09-06 20:37:49 -07:00
Keavon Chambers 97430120f4 Revert #1594 and #1623 so the Freehand tool no longer extends existing paths 2026-09-06 15:47:49 -07:00
Keavon Chambers b0567122f5 Give each Pen tool segment its own history step and keep drawing across undo/redo (#4507)
* Give each Pen tool segment its own history step and keep drawing across undo/redo

* Test that undo during a Pen tool handle transform cancels it and rewinds
2026-09-06 15:47:23 -07:00
Keavon Chambers ae87be30b0 Revert #1587 and #1597 so the Pen tool no longer handles per-segment history 2026-09-06 14:03:19 -07:00
Dennis Kobert f7360688f2 Point the construction docs at the registry that exists 2026-09-06 17:08:03 +00:00
Dennis Kobert 00920823aa Rewrite the node-graph README for the record and serving model 2026-09-06 16:58:45 +00:00
Dennis Kobert 0426a01e82 Rename the DynEdge alias to DynSource 2026-09-06 16:27:32 +00:00
Dennis Kobert 02f9cf3e6b Rename generic_record_edge_type to generic_record_source_type 2026-09-06 16:27:25 +00:00
Dennis Kobert 33f7257e47 Rename record_edge_type to record_source_type 2026-09-06 16:27:11 +00:00
Dennis Kobert 2921f44e5c Rename leveled_record_value_edge to leveled_record_value_source 2026-09-06 16:27:01 +00:00
Dennis Kobert 1e91511f93 Rename record_value_edge to record_value_source 2026-09-06 16:26:49 +00:00
Dennis Kobert daf0231c0c Rename the record_edge accessor to record_source 2026-09-06 16:26:33 +00:00
Dennis Kobert 92adc524ca Rename EdgeHandle to SourceHandle 2026-09-06 16:26:03 +00:00
Dennis Kobert 9f0e0ebc96 Clear the remaining clippy warnings on the diff surface 2026-09-06 16:25:17 +00:00
Dennis Kobert a911bcc165 Justify the three clippy lints that must stand 2026-09-06 16:24:53 +00:00
Dennis Kobert 5bedfa4d11 Name the erased repark and replay function types 2026-09-06 16:24:35 +00:00
Dennis Kobert e52af0cee0 Condense the multi-line safety notes to one line 2026-09-06 16:00:05 +00:00
Dennis Kobert fbdba0e545 Drop narration and internal asides from comments 2026-09-06 15:59:41 +00:00
Dennis Kobert 6cdab6b95d Drop docs naming mechanisms that do not exist 2026-09-06 15:58:40 +00:00
Dennis Kobert e92faf763d Correct docs that misstate what the code does 2026-09-06 15:58:01 +00:00
Dennis Kobert 305c36fb25 Reattach docs to the items they describe 2026-09-06 15:57:05 +00:00
Dennis Kobert fc9e69a7a7 Spell the elided Graphic and Artboard lifetimes in return paths 2026-09-06 15:48:45 +00:00
Dennis Kobert c9525d76c4 Give the split graphic modules their abstraction-level docs 2026-09-06 15:45:57 +00:00
Dennis Kobert 451922c217 Reattach the legacy mapping doc to its function 2026-09-06 15:29:03 +00:00
Dennis Kobert 92ea594a2a Split the graphic module into type, paint, walk, glue, and legacy modules 2026-09-06 15:29:03 +00:00
Dennis Kobert 9d3abe385f Sweep the data-flow wire and edge wording to input and source 2026-09-06 15:14:55 +00:00
Dennis Kobert 96521333d6 Rename SharedEdge to SharedSource 2026-09-06 15:13:57 +00:00
Dennis Kobert d80651e85c Rename ElementEdge to ElementInput 2026-09-06 15:13:32 +00:00
Dennis Kobert a16a4c6354 Rename RecordEdgeInput to RecordInput 2026-09-06 15:13:22 +00:00
Dennis Kobert d294d75198 Rename DerivedRecordEdge to DerivedRecordInput 2026-09-06 15:12:54 +00:00
Dennis Kobert 8f7d3936f8 Rename serve_edge to serve_input 2026-09-06 15:12:46 +00:00
Dennis Kobert 6961687172 Split the record module by abstraction level 2026-09-06 14:25:09 +00:00
Timon f11e6f3bc6 Desktop: Port the pointer shake event detection for direct input routing (#4506)
Desktop: Port shake detection for direct input routing
2026-09-06 10:42:20 +00:00
Timon d2bf8f99d2 Desktop: Mirror direct viewport input to the UI (#4502)
Desktop: Mirror direct-routed input to the UI
2026-09-06 01:29:19 +00:00
Timon 63725ea623 Desktop: Make input routing aware of floating menus (#4498)
* Desktop: Make input routing aware of floating menus

* Desktop: Route mouse input like pen input

* Desktop: Model pointer input routing as a state machine
2026-09-06 01:29:18 +00:00
Timon 80746a7f55 Desktop: Restructure UI input handling (#4500) 2026-09-06 01:29:18 +00:00
Keavon Chambers 23c7a96a94 Pin cargo-binstall and cargo-about and cross-reference all tool version pins (#4505)
* Pin cargo-binstall and cargo-about and cross-reference all tool version pins

* Pin the cargo-binstall GitHub Action to its release tag

* Use a version floor for cargo-about and drop the Nix sync notices
2026-09-05 17:09:47 -07:00
Daniel Z. 4d9a626df2 Fix dev environment configurations with devcontainer, vscode, and cargo-about (#4372)
Some minor fixes to issues I ran into using devcontainer on this project
with vscode.
 
- Add `esbenp.prettier-vscode` to the recommended extensions list as
it's already used in `.vscode/settings.json`
- Install `wasm32-unknown-unknown` Rust target in devcontainer
- Add cargo-binstall and pin cargo-about version in devcontainer
- Remove `no-clearly-defined = true` from `about.toml`:
  - cargo-about 0.9.1 fails to run if `no-clearly-defined` is present
- cargo-about 0.8.0 already [removed
support](https://github.com/EmbarkStudios/cargo-about/blob/main/CHANGELOG.md#080---2025-09-05)
for clearlydefined.io, so the argument is a no-op
2026-09-05 22:55:20 +00:00
Dennis Kobert 38d479bdfa Key the paint list park sites so a group-free paint moves 2026-09-05 13:12:17 +00:00
Dennis Kobert 14660bdb64 Key the element park path and its replay to the element type 2026-09-05 13:12:17 +00:00
Dennis Kobert b362452ff2 Guard arena moves by the park's static type instead of its size 2026-09-05 13:12:17 +00:00
Dennis Kobert 30573e6eb6 Condense the narrative comments to their constraints 2026-09-05 13:12:17 +00:00
Dennis Kobert 9ac039074d Scope the paint graphics import to the test that uses it 2026-09-05 13:11:45 +00:00
Dennis Kobert fdde760259 Drop the unread kernel field from the intent IR 2026-09-05 13:11:45 +00:00
Dennis Kobert 1be90ebb4a Delete the orphaned graphic accessor, introspection helper, and fn type macro 2026-09-05 13:11:45 +00:00
Dennis Kobert 8fa250a9f9 Delete the attribute helpers the refactor orphaned 2026-09-05 13:11:45 +00:00
Dennis Kobert 0b70b18338 Delete the unused record batch buffer accessors 2026-09-05 13:11:45 +00:00
Dennis Kobert 40efbc3261 Name the generic-carry predicate for what it now covers 2026-09-05 12:23:34 +00:00
Dennis Kobert 39ce55ab61 Convert rasterize to an async record source with an owned merged-layers write 2026-09-05 12:17:06 +00:00
Dennis Kobert 3e1a9a1acf Let an async source write an owned attribute through its claim 2026-09-05 11:58:02 +00:00
Dennis Kobert ab93e1f071 Add the owned attribute crossing over the deep field glue 2026-09-05 11:52:42 +00:00
Timon 54c5aa32f0 Desktop: Fix node graph grid dot transparency (#4504) 2026-09-04 13:37:19 +00:00
Timon dd84cd7417 Add 'Scale with Viewport' option to the Brush tool (#4485)
* Add an Autoscale option to the Brush tool

* Put Autoscale option in a Diameter popover

* Rename option to "Scale with Viewport"
2026-09-02 17:44:37 +00:00
Timon 2a1d7d0721 Fix Brush tool drawing into nested layers (#4487)
* Fix Brush tool drawing into nested layers

* Remove hardcoded input indices
2026-09-02 17:44:37 +00:00
Timon 34b2312113 Desktop: Update CEF to 151 (#4490) 2026-09-02 17:44:37 +00:00
Timon de8713b686 Desktop: Improve Mac signing and notarization 2026-09-02 17:44:37 +00:00
Dennis Kobert aa50c42930 Measure the promoted paint list's retained heap 2026-09-02 08:26:26 +00:00
Dennis Kobert c73976f407 Refuse a mistyped park in the arena move 2026-09-02 08:26:26 +00:00
Dennis Kobert cac1c47b86 Cover the promoted paint field's sharing and move laws 2026-09-02 00:10:07 +00:00
Dennis Kobert 1426f6401f Route graphic-list field promotes straight into the persistent region 2026-09-02 00:10:07 +00:00
Dennis Kobert 6b951c1806 Add an opt-in promote half to the deep field glue 2026-09-02 00:09:46 +00:00
Dennis Kobert 1f860aae6a Move group-free graphic and artboard headers at the promote 2026-09-01 22:51:18 +00:00
Dennis Kobert e415714b04 Promote a leaf element by moving its header into the persistent region 2026-09-01 22:51:18 +00:00
Dennis Kobert a6016b2c03 Move a parked payload between arenas instead of cloning its heap 2026-09-01 22:51:18 +00:00
Dennis Kobert c12f8f1115 Add changing-seasons to the gungraun benchmark arguments 2026-09-01 13:18:01 +00:00
Dennis Kobert 4e7d72d4b8 Flush the persistent region on its heap budget 2026-08-31 23:52:44 +00:00
Dennis Kobert 41d42fe794 Delete the now unused frame table 2026-08-31 23:52:44 +00:00
Dennis Kobert 21dfe04bf8 Insert the boundary memo at context nullification 2026-08-31 23:52:34 +00:00
Dennis Kobert 0f26893ec1 Split the memo roles between the span memo and memoize 2026-08-31 23:52:34 +00:00
Dennis Kobert 0cd428f1b1 Share persistent graphic interiors when promoting 2026-08-31 23:52:21 +00:00
Dennis Kobert 39ed962e16 Promote memo levels by provenance 2026-08-31 23:52:21 +00:00
Dennis Kobert 6a5417ed3d Report an arena's occupancy and retained heap 2026-08-31 23:52:21 +00:00
Timon 7986cabadb Update Nix flake (#4489) 2026-08-31 11:36:39 +00:00
Timon 150cfaa550 Add the CODEOWNERS file (#4477)
Introduce `CODEOWNERS` file
2026-08-31 09:32:47 +00:00
Dennis Kobert 29052a58db Let async source kernels write attributes through their frame claim 2026-08-29 23:00:17 +00:00
Dennis Kobert 84d11b9285 Serve memo hits out of the persistent region 2026-08-29 22:07:27 +00:00
Dennis Kobert 5a6192bbd6 Give the executor a persistent arena flushed between evaluations 2026-08-29 22:07:27 +00:00
Dennis Kobert ca831c00db Promote a materialized batch into a target region 2026-08-29 22:07:27 +00:00
Dennis Kobert fe8ca88752 Name a persistent region on the evaluation scope 2026-08-29 22:07:27 +00:00
Dennis Kobert 8fd2529e27 Flag an arena whose reservation was refused 2026-08-29 22:07:27 +00:00
Dennis Kobert 641fcc88c6 Read declared attributes through one core-types helper 2026-08-29 20:16:17 +00:00
Dennis Kobert 78e35eb6ea Re-derive the shared edge pointer and type-check the paint transmute 2026-08-29 20:16:12 +00:00
Dennis Kobert 3302a3b0b8 Mint attribute reads through a layout-checked field token 2026-08-29 20:16:05 +00:00
Dennis Kobert 41d295f140 Tie a record view to the storage it points into 2026-08-29 20:14:44 +00:00
Dennis Kobert a955d6b458 Run cargo fmt 2026-08-29 18:40:02 +00:00
Dennis Kobert 97bc10e4c3 Pass frame space by argument and delete the record stack 2026-08-29 18:33:23 +00:00
Timon 5457b4faec Remove now obsolete disable-registration special case from node macro (#4484) 2026-08-29 15:58:14 +02:00
Dennis Kobert 3af6834d3c Flip the Node trait from eval onto the frame claim's serve 2026-08-29 12:26:46 +00:00
Dennis Kobert 277641d27e Delete the plain edge kind 2026-08-29 10:07:10 +00:00
Keavon Chambers 1c055bfaab Add a thanks banner to the donation page's flow 2026-08-29 02:36:24 -07:00
Keavon Chambers c64a9e5cee Revamp the website's donation page 2026-08-28 23:16:22 -07:00
Keavon Chambers ff2afbccda Update the roadmap on the website 2026-08-28 23:01:48 -07:00
Keavon Chambers 3bb6aa97b9 Bump the Graphite release series to alpha 5, intended as retroactively backdated to the start of 2026 2026-08-28 22:59:49 -07:00
Timon d5bb887b79 Improve fix for corrupted font resource loading in older documents (#4482)
* Revert "Fix corrupted font resource loading in older documents"

This reverts commit 404d9f3047.

* Fix migrations for the Read Vector, Dot Product, Query JSON, and Sample Polyline nodes

* Fix text node migrations

* Provide resource storage to the resource message handler

* Refetch resources whose stored bytes are missing

* Add test for refetching resources with missing bytes
2026-08-29 00:01:37 +00:00
Dennis Kobert f3e945c5d8 Introduce the serve surface: the frame claim's proof-bearing lift on Node 2026-08-28 19:18:54 +00:00
Dennis Kobert aef750153b Claim the node frame once and close every exit through its drop 2026-08-28 19:11:38 +00:00
Dennis Kobert f4d37524c8 Structure record stack rewinds as scope guards and make reserve unsafe 2026-08-28 18:02:50 +00:00
Dennis Kobert e5b910f840 Adopt serving lifetimes and the safe record surfaces in the node crates 2026-08-28 13:30:06 +00:00
Dennis Kobert 25f49e8750 Give the graphic types the serving lifetime 2026-08-28 13:30:06 +00:00
Dennis Kobert 1ef7c9c2c2 Support author-named serving lifetimes in the node macro 2026-08-28 13:30:06 +00:00
Dennis Kobert f34ec257e7 Normalize lifetime arguments out of registry type names 2026-08-28 13:30:05 +00:00
Dennis Kobert 1e5b2c7f62 Serve group items at the evaluation lifetime 2026-08-28 13:30:05 +00:00
Dennis Kobert c6b669fc88 Key the element glue on static type projections 2026-08-28 13:30:05 +00:00
Timon c2afc07a04 Move file filter creation from frontend to editor (#4351) 2026-08-28 09:19:44 +00:00
Dennis Kobert d814b610da Migrate test sources and assertions onto the safe record builders 2026-08-27 21:17:31 +00:00
Dennis Kobert 5181c74205 Add the frame builder and captured record reads 2026-08-27 21:17:31 +00:00
Dennis Kobert 4cb711e3f8 Stamp value types on layout fields and include type identity in layout equality 2026-08-27 21:17:31 +00:00
Dennis Kobert e8aea0728a Build native groups at the legacy conversion seams 2026-08-27 20:22:24 +00:00
Dennis Kobert 6f809fda73 Add the run builder and census-driven list adoption 2026-08-27 19:28:41 +00:00
Dennis Kobert ba84e2a968 De-table the graphic leaf variants 2026-08-27 18:55:32 +00:00
James Lindsay c8f38059f8 Frontend type constraints (#4334) 2026-08-27 18:13:12 +00:00
Dennis Kobert 72387d17ad Read the vector kernel seams natively 2026-08-27 15:57:10 +00:00
Dennis Kobert 048a4c4b70 Flatten boolean content natively 2026-08-27 15:45:36 +00:00
Dennis Kobert b262195549 Flatten vector rows natively and serve solidify per lane 2026-08-27 15:35:13 +00:00
Timon c7a64fff0c Add the 'Basic Brush' node and replace the legacy Brush tool implementation with it (#4469)
* Draw raster images with pad extension instead of repeat

* Add the GPU basic brush renderer

* Rework the brush tool around the GPU basic brush

* Remove the CPU brush implementation
2026-08-27 15:19:02 +00:00
Timon fd31f2d89b Add caching infrastructure for the GPU brush nodes (#4468)
Add the per-brush texture cache value type
2026-08-27 15:19:01 +00:00
Timon 10256dd22c Introduce the new brush stroke data types (#4467)
* Add the brush stroke format types

* Route brush strokes through the node graph

* Store brush style as per-item attributes instead of a struct
2026-08-27 15:19:01 +00:00
Timon 96cc520c4b Improve texture caching by allowing weak refs and more formats (#4447)
* Destroy GPU textures when the last reference drops

* Request pooled textures synchronously

* Pool cached textures by format

* Add the owned GPU buffer type

* Route the remaining GPU allocations through the executor

* Add weak texture parking to the texture cache

* Raise the texture cache budget to 1GB for native and 512MB for wasm
2026-08-27 15:19:00 +00:00
Timon 8c48d5acce Fix Vello-related GPU out-of-memory issues (#4446)
* Update vello

* Reuse vello image atlas slots across frames
2026-08-27 15:19:00 +00:00
Timon 681b38d3d6 Support input from drawing tablets on web (#4445)
* 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

* 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.

* Capture pen input via browser api

* Replay coalesced pointer samples for smoother pen strokes

* Handle missing or empty coalesced pen events
2026-08-27 15:18:59 +00:00
Dennis Kobert 68a2fb2be3 Render root levels natively and remove the unconstructed stack form 2026-08-27 14:44:19 +00:00
Dennis Kobert 50911a6a25 Recreate introspection data from the monitor's context snapshot 2026-08-27 13:53:25 +00:00
Dennis Kobert 79f3571b02 Store paint content in its native form 2026-08-27 12:33:44 +00:00
Dennis Kobert 34ea9c59fd Deepen graphic-list field values at the persistence seams 2026-08-27 12:05:14 +00:00
Dennis Kobert 92ec2069ad Carry group content across memo seams in an owned form 2026-08-27 11:27:26 +00:00
Dennis Kobert 20e70e7bc9 Exclude executor teardown from the measured bench regions 2026-08-27 10:09:18 +00:00
Dennis Kobert 084f14e973 Resolve paint and transform columns once per lane loop 2026-08-26 23:03:17 +00:00
Dennis Kobert 694d3d34b3 Reduce measurement overhead for run_once benchmark 2026-08-27 00:37:25 +02:00
Dennis Kobert ed457093b1 Store artboard content as a native group 2026-08-26 21:50:36 +00:00
Dennis Kobert 7d44f6ec9e Collect a group element as its typed lowering 2026-08-26 21:50:35 +00:00
Dennis Kobert 54c140e4f3 Walk groups natively with lane paint threaded down 2026-08-26 19:43:32 +00:00
Dennis Kobert 5987c449b2 Serve bounding boxes through the lane source 2026-08-26 19:43:31 +00:00
Dennis Kobert c7605d12a6 Drive every render body from the lane source 2026-08-26 17:47:50 +00:00
Dennis Kobert d9533de9ea Look up paint through the paint markers instead of string keys 2026-08-26 17:47:38 +00:00
Dennis Kobert bc33e14c35 Read gradient columns per lane and drive color rendering from the lane source 2026-08-26 15:59:24 +00:00
Dennis Kobert 2b06d27729 Distinguish an absent column from a defaulted one on the lane source 2026-08-26 15:48:01 +00:00
Dennis Kobert b685ca77f2 Serve record runs through the lane source surface 2026-08-26 15:17:06 +00:00
Dennis Kobert e5b1fad675 Read render attributes through census markers instead of string keys 2026-08-26 14:55:27 +00:00
Dennis Kobert eb11eec5bb Store paint attributes in the paint markers' owned optional form 2026-08-26 14:02:01 +00:00
Dennis Kobert 182c2a1554 Cover the batch path that rebinds a lane-varying eager input 2026-08-25 21:15:12 +00:00
Dennis Kobert 913d7093ea Restore the index declaration on single-lane leveled values 2026-08-25 21:07:52 +00:00
Dennis Kobert 938fc1783a Treat a single-lane leveled value as invariant under the addressed lane 2026-08-25 20:27:39 +00:00
Dennis Kobert d452ac0de1 Hoist a batch input only where the compiler proves it cannot vary per lane 2026-08-25 20:09:12 +00:00
Dennis Kobert 95bbeb6634 Push the flat copy number Repeat on Points declares as its level extent 2026-08-25 17:15:00 +00:00
Dennis Kobert 5176bfd331 Query per-copy extents with the same chain shape the value path builds 2026-08-25 16:36:49 +00:00
Dennis Kobert db761cf8ed Drop a duplicated wasm import 2026-08-25 11:19:22 +00:00
Dennis Kobert 34e03038df Cargo fmt 2026-08-25 11:17:17 +00:00
Dennis Kobert bb3643541d Resolve context features from the registry at compile instead of persisting them 2026-08-25 11:16:56 +00:00
Dennis Kobert ff99f3605c Drop unread index bounds from fold kernels and mark re-addressing nodes ModifyIndex 2026-08-25 11:05:38 +00:00
Dennis Kobert 9cf037e992 Treat Modify bounds as transparent and drop the redundant fold-context validation 2026-08-25 11:04:57 +00:00
Dennis Kobert 888cdf17b0 Compress nullified index chains by dropping trailing zeroed levels 2026-08-25 11:04:57 +00:00
Dennis Kobert 9aef511891 Cargo fmt 2026-08-24 23:15:10 +02:00
Dennis Kobert 0d88e8be9f Inline status cell calls 2026-08-24 23:14:06 +02:00
Dennis Kobert 56d38b3f61 Re-save the demo artwork in its migrated form 2026-08-24 21:06:51 +00:00
Dennis Kobert a6c56c8655 Resolve index levels from the registry instead of persisting them 2026-08-24 20:40:51 +00:00
Dennis Kobert 2c84bb478f Derive pushed index levels per input and pop them when lifting requirements 2026-08-24 17:06:07 +00:00
Dennis Kobert 9cdaf06ca9 Count assign colors lanes without legacy conversion and cache the offsets 2026-08-24 17:06:07 +00:00
Dennis Kobert 027218f16c Declare which index levels a node reads and nullify the rest 2026-08-24 17:06:07 +00:00
Dennis Kobert f1ccb74625 Serve the monitored lane from its own capture materialization 2026-08-24 16:42:28 +00:00
Dennis Kobert cb5fabc6ad Add an env-gated arena allocation trace 2026-08-24 14:31:21 +00:00
Dennis Kobert 2448157af8 Close the memoize frame on a valueless materialization and trace node exits 2026-08-24 14:11:46 +00:00
Dennis Kobert d718cdb225 Keep the monitor's whole-extent capture off the record stack 2026-08-24 12:23:32 +00:00
Dennis Kobert dcc9059041 Give To Graphic a unit row so an unconnected content input renders as nothing 2026-08-24 12:02:46 +00:00
Dennis Kobert d70eae205d Quiet the clippy type-complexity and closure lints on the record kernels 2026-08-24 11:07:14 +00:00
Dennis Kobert ed6922d7eb Read the layer path in its owned form and retarget the introspection tests 2026-08-24 10:26:24 +00:00
Dennis Kobert abb099a1c3 Take brush on record wires and keep its legacy core behind brush_core 2026-08-24 09:27:52 +00:00
Dennis Kobert a4d01bfd11 Route the whole record through switch and drop its fifteen typed rows 2026-08-24 08:51:12 +00:00
Dennis Kobert d38c767312 Gather a chosen subject lane through a Lane output and convert pack_strips 2026-08-24 08:22:25 +00:00
Dennis Kobert aba941e81d Collapse typed levels in To Graphic like the pre-flip list conversion 2026-08-24 01:35:32 +00:00
Dennis Kobert 8c67ad508f Restore pre-flip color parity: rng replay, typed wrap, boolean marker paints 2026-08-24 00:43:44 +00:00
Dennis Kobert 9ca897963f Prune the unused legacy Adjust and Blend list implementations 2026-08-23 20:00:24 +00:00
Dennis Kobert 2575b94e8f Swap the leveled repeat_radial and repeat_on_points in for the eager variants 2026-08-23 19:50:36 +00:00
Dennis Kobert b03e4fb215 Let record nodes take element-consuming lazy inputs and convert map_points 2026-08-23 19:28:27 +00:00
Dennis Kobert c0eb2ee4ff Remove the runtime-named attribute family and its type-erased bridges 2026-08-23 19:05:26 +00:00
Dennis Kobert faa5c9d3db Install the resolved layout in the create_context test 2026-08-23 18:18:13 +00:00
Dennis Kobert bedb0d4159 Turn the byte-list wires into plain shared slices 2026-08-23 17:46:04 +00:00
Dennis Kobert 94b9d279a2 Retarget the palette executor test at the folded record wire 2026-08-23 17:29:43 +00:00
Dennis Kobert 7c4b029d76 Convert the math color and gradient family to element and marker kernels 2026-08-23 17:22:46 +00:00
Dennis Kobert 9ba3c16e79 Convert blur, median_filter, color_overlay, and image_color_palette to record kernels 2026-08-23 17:10:00 +00:00
Dennis Kobert 511b4da9f5 Convert the raster std and adjustments families to element kernels and keep the unit primary's slot 2026-08-23 16:52:43 +00:00
Dennis Kobert 2c15dc838e Convert dehaze, empty_image, extend_image_to_bounds, and image to record kernels 2026-08-23 10:11:34 +00:00
Dennis Kobert 73b2ef1d58 Convert cut_path, separate_subpaths, and path_is_closed to fold kernels 2026-08-23 09:56:09 +00:00
Dennis Kobert 9d2031f7d0 Convert the per-lane vector geometry nodes and the level measures to record kernels 2026-08-23 09:44:25 +00:00
Dennis Kobert 7b609ea781 Parse primitive defaults through record wire types 2026-08-23 08:39:35 +00:00
Dennis Kobert 5e918af371 Restore the sample_polyline test attribute and drop dead scaffolding 2026-08-23 08:31:40 +00:00
Dennis Kobert 6e9cac3b32 Trace record stack frames under an env gate 2026-08-23 08:31:39 +00:00
Dennis Kobert 893cbfe450 Close the frame on interrupt exits and rewind extent value queries 2026-08-23 08:31:39 +00:00
Dennis Kobert e40ee486a9 Claim the node frame on every cache serve and reclaim extracted edges 2026-08-23 08:31:39 +00:00
Dennis Kobert 58182bc2d3 Keep the executor arena at 128 MiB 2026-08-23 00:57:37 +00:00
Dennis Kobert 3fb8b10f80 Cache materialized spans per context and size emitter extents from the subject query 2026-08-23 00:57:37 +00:00
Dennis Kobert 6fe533a875 Cache whole levels in memoize and gate the monitor capture to lane zero 2026-08-23 00:57:37 +00:00
Dennis Kobert feea006fc3 Skip the consuming lane in the index reader 2026-08-23 00:57:37 +00:00
Dennis Kobert 73897111d0 Stop declaring derived index injection as a context feature 2026-08-23 00:57:37 +00:00
Dennis Kobert e76dcb15aa Convert mix and gradient value to element kernels 2026-08-22 22:15:03 +00:00
Dennis Kobert 538959ea90 Convert morph to a fold emitter 2026-08-22 22:15:03 +00:00
Dennis Kobert c33f8ae75b Convert mirror to a fold emitter and bridge levels into the erased list 2026-08-22 22:15:03 +00:00
Dennis Kobert 3126a5b278 Convert copy to points, sample polyline, scatter, spline, jitter, and assign colors 2026-08-22 20:59:37 +00:00
Dennis Kobert 5f6c18893e Grow the executor arena for per-copy paint parks 2026-08-22 20:59:37 +00:00
Dennis Kobert cdc6f11d92 Add an env-gated inferred type dump 2026-08-22 20:59:37 +00:00
Dennis Kobert c4b22c03b9 Size extent-path materialization by the total flat span 2026-08-22 20:59:37 +00:00
Dennis Kobert 6ab9d0360a Convert flatten path and solidify stroke to fold kernels 2026-08-22 19:11:48 +00:00
Dennis Kobert 01da817f61 Grow the executor arena for fold snapshots 2026-08-22 19:11:48 +00:00
Dennis Kobert 040bd71f82 Add an env-gated resolved layout depth dump 2026-08-22 19:11:48 +00:00
Dennis Kobert f2b0f7c533 Defer an empty side's inner extent in extend 2026-08-22 19:11:48 +00:00
Dennis Kobert a2918887f6 Collapse the whole subject wire in materialized folds 2026-08-22 19:11:48 +00:00
Dennis Kobert 7b993c5de6 Place lane paint onto the vector interiors at the legacy boundary 2026-08-22 17:29:51 +00:00
Dennis Kobert 3da7f6cea3 Drop the legacy fill and stroke rows for single-typed paint 2026-08-22 17:29:51 +00:00
Dennis Kobert 7569bdb9cb Convert path modify to a flip kernel over one default lane 2026-08-22 17:29:51 +00:00
Dennis Kobert 4e8a44650e Push the repeat array copies onto a derived level 2026-08-22 17:29:51 +00:00
Dennis Kobert b4346fd47d Convert the generators to element producers 2026-08-22 17:29:51 +00:00
Dennis Kobert e9a18a6437 Emit boolean results as elements with parked attributes 2026-08-22 17:29:51 +00:00
Dennis Kobert 77b0be5c15 Lift shallower sources in the layout union 2026-08-22 16:22:54 +00:00
Dennis Kobert 4bceae26f2 Add the leveled fill rows and the graphic coercion entries 2026-08-22 16:13:01 +00:00
Dennis Kobert c0f50d41d7 Drop the manual extent overrides in favor of the derivation 2026-08-22 15:55:49 +00:00
Dennis Kobert 0b2aa3798a Derive extent forwarding for level-preserving passthroughs 2026-08-22 15:34:22 +00:00
Dennis Kobert 13cd718c90 Drop an unused import 2026-08-22 15:02:01 +00:00
Dennis Kobert 39c7ba39cf Lift the artboard element onto a level and migrate demos for smoke tests 2026-08-22 15:01:27 +00:00
Dennis Kobert 6635e0aeff Convert the artboard constructor to an attribute kernel behind a footprint translate 2026-08-22 14:46:29 +00:00
Dennis Kobert 98dabd7ff5 Materialize the boolean operation's content level 2026-08-22 14:36:42 +00:00
Dennis Kobert a244cc13d0 Convert the blending family to attribute kernels 2026-08-22 14:32:15 +00:00
Dennis Kobert fb71ea426d Bridge legacy seams and convert the transform family 2026-08-22 14:25:31 +00:00
Dennis Kobert 217f32eb88 Type the list-typed value defaults by their element 2026-08-22 12:59:37 +00:00
Dennis Kobert 7fb36123e9 Point the render wrapper at the leveled intermediate 2026-08-22 12:50:47 +00:00
Dennis Kobert 46220ac268 Switch the tagged list values and layer internals onto leveled wires 2026-08-22 12:47:31 +00:00
Dennis Kobert 887dbaca2c Re-home the layer-path stamp and switch the node path to its plain value form 2026-08-22 12:35:48 +00:00
Dennis Kobert 44369cb12b Swap the repeat node to its leveled form in place 2026-08-22 12:29:16 +00:00
Dennis Kobert 56c772de4c Swap the map and index family nodes to their leveled forms in place 2026-08-22 12:27:53 +00:00
Dennis Kobert 93e34d00e5 Swap the graphic structural nodes to their leveled forms in place 2026-08-22 12:24:02 +00:00
Dennis Kobert 46f048b07c Add the leveled render intermediate beside the legacy rows 2026-08-22 12:15:08 +00:00
Dennis Kobert 4b130b4319 Map element-typed wires to their list forms' defaults and widgets 2026-08-22 11:48:27 +00:00
Dennis Kobert da0f70bb5f Stage the flip's document reset markers 2026-08-22 11:48:27 +00:00
Dennis Kobert 5821816228 Add the leveled boundary helpers and the deep group element copy 2026-08-22 11:48:26 +00:00
Dennis Kobert 8eaa541c8c Add the leveled value source and the dormant leveled edge form 2026-08-22 10:52:21 +00:00
Dennis Kobert e4adf16eba Move the paint and merged-layer markers to graphic-types as optional references 2026-08-22 10:23:02 +00:00
Dennis Kobert a8d257e7d6 Move the downstream-typed attribute markers to their value types' crates 2026-08-22 09:34:24 +00:00
Dennis Kobert 49c592013c Declare the core-typed attribute markers and re-export their names 2026-08-22 09:20:17 +00:00
Dennis Kobert 80db9c13c8 Signal past-end for repeat overruns so drains cross structure nodes 2026-08-21 22:17:06 +00:00
Dennis Kobert cf87796072 Probe lower-bound inner levels to their exact span 2026-08-21 22:17:06 +00:00
Dennis Kobert 8859e6b1a0 Add the layer-path stamp carrier 2026-08-21 22:03:31 +00:00
Dennis Kobert 1f23991a72 Add the editor layer path marker 2026-08-21 22:03:31 +00:00
Dennis Kobert 2be252d7b4 Fold a color level into evenly spaced gradient stops 2026-08-21 21:48:21 +00:00
Dennis Kobert 2c1acbdc62 Render groups through the legacy conversion 2026-08-21 20:36:06 +00:00
Dennis Kobert 61e751f278 Convert groups to their legacy list form 2026-08-21 20:36:06 +00:00
Dennis Kobert cdd62ed269 Retarget the wrap and flatten pilots onto group storage 2026-08-21 20:16:19 +00:00
Dennis Kobert f12094ced6 Add in-place group adoption for arena-resident batches 2026-08-21 20:16:19 +00:00
Dennis Kobert b5c4aa4598 Add the group variant to Graphic with typed run walks 2026-08-21 19:34:03 +00:00
Dennis Kobert da8ae2be43 Tag record layouts with their element type 2026-08-21 19:34:02 +00:00
Dennis Kobert 157c011953 Pick hashed element glue in the macro emissions 2026-08-21 18:21:38 +00:00
Dennis Kobert ae6807f8e3 Add content hashing and equality glue to record layouts 2026-08-21 18:21:38 +00:00
Dennis Kobert 17ba74485a Add arena-adopted group storage for nested records 2026-08-21 16:52:23 +00:00
Dennis Kobert 1f2eef5f8f Add the wrap collector beside the production node 2026-08-21 16:52:23 +00:00
Dennis Kobert 1b6513b954 Treat a free side as one lane in the extend split 2026-08-21 16:52:23 +00:00
Dennis Kobert 74fddff589 Add leveled vararg sources beside the production read nodes 2026-08-21 14:38:26 +00:00
Dennis Kobert 7e24f810c6 Register the map family for each production content type 2026-08-21 13:14:49 +00:00
Dennis Kobert 306cf1110f Emit one registry row per ranked implementation 2026-08-21 13:14:49 +00:00
Dennis Kobert b610eede20 Carry ranked element generics as struct parameters 2026-08-21 13:14:49 +00:00
Dennis Kobert 21f671555a Derive lower-bound extents for leveled outputs and drop the map extent fns 2026-08-21 12:37:57 +00:00
Dennis Kobert 951059aa3a Drain lower-bound reducer subjects by guess-and-double 2026-08-21 12:36:41 +00:00
Dennis Kobert e68254eff3 Carry an extent hint on batch returns 2026-08-21 12:32:57 +00:00
Dennis Kobert 61cf619f4b Add the lower-bound extent and the past-end signal 2026-08-21 12:22:09 +00:00
Dennis Kobert 7914a09d4b Carry only the element in the map vararg 2026-08-21 12:19:54 +00:00
Dennis Kobert 95e2cbca15 Test extend associativity and the batched fold across the seam 2026-08-21 09:18:45 +00:00
Dennis Kobert 724bb0fc17 Reject ragged inner extents in the extend concat 2026-08-21 09:18:37 +00:00
Dennis Kobert fb171cd5ac Test the partial fold keeping its subject's outer level 2026-08-19 21:43:14 +00:00
Dennis Kobert cb46be0430 Emit the reducer extent shift and the flat-span materialization 2026-08-19 21:43:14 +00:00
Dennis Kobert 7ffc9b9e3b Add the folded subject to LayoutMeta and derive reducer depth from it 2026-08-19 21:43:14 +00:00
Dennis Kobert 58a65c69e9 Add the map, flat_map, and flatten_levels pilots 2026-08-18 11:02:25 +00:00
Dennis Kobert d1d50ec469 Classify routing sources through IList nesting 2026-08-18 11:02:25 +00:00
Dennis Kobert e25e32ee8a Add the per-copy inner extent accessor 2026-08-18 11:02:25 +00:00
Dennis Kobert d560a39856 Add the flatten pilot over graphic content 2026-08-18 10:06:11 +00:00
Dennis Kobert 00e08359a3 Park droppable elements in the record tail store 2026-08-18 10:06:11 +00:00
Dennis Kobert 116ce622d4 Test batch lane equivalence and single eager bind per batch 2026-08-18 08:53:38 +00:00
Dennis Kobert 082fb5d959 Hoist non-lazy inputs in the default batch implementation 2026-08-18 08:53:38 +00:00
Dennis Kobert 043f28cc23 Add StatusCell snapshot, List copy, and interrupt-to-batch conversion 2026-08-18 08:53:38 +00:00
Dennis Kobert b7413dd22c Add the replaced context derivation for same-level remaps 2026-08-17 14:47:41 +00:00
Dennis Kobert 586737247e Fold nested list levels flat in a single kernel 2026-08-17 14:47:24 +00:00
Dennis Kobert 055b7f0055 Add the rank-model mirror over a materialized level 2026-08-17 14:47:24 +00:00
Dennis Kobert 4a042bade2 Key materialization on declared list nesting and carriers on non-materialized subjects 2026-08-17 14:46:48 +00:00
Dennis Kobert 3aa018a15c Add the rank-model read-by-index family: omit, index elements, extract element 2026-08-17 11:59:40 +00:00
Dennis Kobert 8508dc6c9d Add the rank-model extend concatenating two sources at the top level 2026-08-17 11:42:52 +00:00
Dennis Kobert fbba0cd037 Gate the gpu converter imports the sweep wrongly removed 2026-08-17 10:56:45 +00:00
Dennis Kobert ae7c51a964 Drop stale imports left behind by the record-wire port 2026-08-17 10:28:29 +00:00
Dennis Kobert 0c49026c9a Error on out-of-range copy addressing instead of wrapping in the repeat family 2026-08-17 10:28:28 +00:00
Dennis Kobert bc29166d4c Add the rank-model repeat on points flattening every points row 2026-08-17 09:26:59 +00:00
Dennis Kobert 0f3e3f7337 Materialize ranked non-subject inputs whole and expose them to extent overrides 2026-08-17 09:26:59 +00:00
Dennis Kobert a03db0ac6c Decompose the flat index over the content extent in structure creators 2026-08-17 08:09:27 +00:00
Dennis Kobert 932ed8653e Add the rank-model repeat radial rotating each copy around the center 2026-08-16 18:17:30 +00:00
Dennis Kobert 5ab3f067fe Add the rank-model repeat array over a lazy transform-reading carrier 2026-08-16 17:47:25 +00:00
Dennis Kobert 3df028cb18 Wire record-io plain values as record edges in the registry, extracted at construction 2026-08-16 17:47:25 +00:00
Dennis Kobert e423dd96de Support lazy record carriers so a creator can read and rewrite attrs per copy 2026-08-16 17:13:19 +00:00
Dennis Kobert bef58bf395 Give the generic repeat its production shape with reverse in the index mapping 2026-08-16 17:13:19 +00:00
Dennis Kobert 131abf5883 Give extent overrides a typed input surface instead of the raw node form 2026-08-16 15:55:17 +00:00
Dennis Kobert 3859bd713e Install element layouts on the runtime test graphs 2026-08-16 11:29:20 +00:00
Dennis Kobert ac40f1838f Store record batches in caller-owned frame buffers instead of aliased stack pointers 2026-08-16 11:29:20 +00:00
Dennis Kobert 9055a5f3d5 Drop the stale layout unwraps in the math wire tests 2026-08-16 11:28:33 +00:00
Dennis Kobert d32caeab52 Add a generic lazy repeat that evaluates its content at each copy index 2026-08-16 11:28:11 +00:00
Dennis Kobert 15f4aa8f98 Strip IList nesting from kernel returns at parse time 2026-08-16 11:27:13 +00:00
Dennis Kobert 99ce2ea565 Require a node registry to compile so the layout pass always runs 2026-08-15 14:49:25 +00:00
Dennis Kobert 87200f3c2a Gate a flipped shader node's layout metadata out of the GPU build 2026-08-15 14:49:19 +00:00
Dennis Kobert 214632c5ec Reserve the record stack before direct edge evals in executor tests 2026-08-15 12:27:39 +00:00
Dennis Kobert 64fb4eda61 Fold the record-stack peak in the layout pass, not the executor 2026-08-15 12:20:52 +00:00
Dennis Kobert f9e30c4c77 Install record layouts from the pass via set_layout 2026-08-15 11:20:01 +00:00
Dennis Kobert bfa48439c8 Resolve coercion nodes and dynamic values in the layout pass 2026-08-15 08:48:29 +00:00
Dennis Kobert a717403db8 Diagnose a materializing node's missing InjectIndex and Copy bounds 2026-08-14 21:31:14 +00:00
Dennis Kobert fdf13f91cb Materialize a reducer's ranked input into a List and fold it 2026-08-14 21:19:20 +00:00
Dennis Kobert 65e0969721 Recognize a reducer's IList input level in build 2026-08-14 10:13:53 +00:00
Dennis Kobert 8f265e7660 Report a creator's pushed-level extent from its count 2026-08-14 09:56:31 +00:00
Dennis Kobert 98e6b97072 Reshape the extent trait to a written extent_at and a derived composite 2026-08-14 09:10:04 +00:00
Dennis Kobert a3e9074955 Scatter a creator's per-copy attribute from the copy index 2026-08-14 08:24:44 +00:00
Dennis Kobert 04afada5b3 Lower a creator's IList return to a level-pushing record 2026-08-14 08:22:29 +00:00
Dennis Kobert 3e183fbd28 Read a creator's IList return level in build 2026-08-14 08:11:59 +00:00
Dennis Kobert 849d6a17be Delete the Class taxonomy in favor of the intent IR 2026-08-13 23:46:07 +00:00
Dennis Kobert 20ba069fe0 Derive record-io construction wiring from the intent IR 2026-08-13 23:26:22 +00:00
Dennis Kobert c82093f153 Derive codegen node-kind predicates from the intent IR 2026-08-13 23:09:48 +00:00
Dennis Kobert 010785d8db Derive single-row registry entries from the intent IR 2026-08-13 22:08:04 +00:00
Dennis Kobert 69774d445c Derive the eval tail from the intent IR 2026-08-13 21:08:41 +00:00
Dennis Kobert b42c632474 Derive input bindings from the intent IR 2026-08-13 19:32:25 +00:00
Dennis Kobert f195e363a5 Emit layout metadata from the intent IR 2026-08-13 16:11:58 +00:00
Dennis Kobert 40f99152ce Bridge-verify build against the resolved class 2026-08-13 15:35:07 +00:00
Dennis Kobert 3b1170b148 Derive inputs, output, and monomorphizations in build 2026-08-13 15:18:35 +00:00
Dennis Kobert 3a20091d3a Derive the node-level intent axes in build 2026-08-13 14:19:49 +00:00
Dennis Kobert e5206c3b50 Add the node intent IR types 2026-08-13 14:00:15 +00:00
Dennis Kobert fbc736e1cc Verify computed layouts match construction at node construction 2026-08-13 10:25:00 +00:00
Dennis Kobert d7da2ba9e7 Add the resolve_types and compute_layouts compiler passes 2026-08-13 10:24:59 +00:00
Dennis Kobert a5784c8f0b Port the create_context render test onto record wires 2026-08-12 13:11:48 +00:00
Dennis Kobert 83fbaca6f2 Unify the layout metadata model and collapse the single-row entry emitters 2026-08-12 13:11:48 +00:00
Dennis Kobert b6f73b0691 Emit declarative LayoutMeta from the node macro into registry entries 2026-08-11 20:08:45 +00:00
Dennis Kobert 557f8020bb Add the leveled extent_at/depth trait surface and the push_level context helper 2026-08-11 20:08:45 +00:00
Dennis Kobert fb94d99807 Port the stale math-nodes and raster-nodes tests onto record wires 2026-08-11 09:54:48 +00:00
Dennis Kobert 264601c5f7 Return records from eval_batch through a RecordBatch view 2026-08-11 09:26:36 +00:00
Dennis Kobert 5db7e1816a Make Node::layout non-optional, defaulting to a shared empty layout 2026-08-11 09:20:02 +00:00
Dennis Kobert 5b02edfd9a Split the node macro codegen into classify, entries, and metadata modules 2026-08-10 16:15:31 +00:00
Dennis Kobert 7c0a4073e9 Select the eval tail form by class and dialect through an explicit Tail step 2026-08-10 15:57:58 +00:00
Dennis Kobert 275100eab0 Model the eval body as an EvalStep sequence with a structural stack discipline 2026-08-10 15:34:12 +00:00
Dennis Kobert 42cd2a4303 Resolve the dialect and input-role axes as node-model sum types 2026-08-10 15:21:59 +00:00
Dennis Kobert e4f81fc947 Drive the node macro from a single analyze pass, NodePlan, and shared NodeFields 2026-08-10 13:33:58 +00:00
Dennis Kobert 492cf18cb0 Flip the passthrough node onto record wires by dropping its dead lifetime 2026-08-10 13:33:58 +00:00
Dennis Kobert 05630bab6e Port the repeat node tests onto record-wire lazy inputs 2026-08-10 10:41:40 +00:00
Dennis Kobert a465948ad4 Always-spill records, retiring inline-16 and reclaiming read-out record frames 2026-08-10 10:29:22 +00:00
Dennis Kobert 63cf0151e2 Change stack return to standart sret semantics 2026-08-08 07:33:33 +00:00
Dennis Kobert 9c7a633d5b Adopt tuple attribute io and the carrier lowering, deleting the bridge adapters for record-only wires 2026-08-06 18:48:16 +00:00
Dennis Kobert 166241b0e8 Flip nested-generic nodes onto record wires by unifying row types against field types 2026-08-06 13:36:46 +00:00
Dennis Kobert ea49f3c2fc Delete the Ref wire type and its lend edge surface 2026-08-06 12:24:50 +00:00
Dennis Kobert 100f81c307 Retire the lend machinery and flip the clone node onto record wires 2026-08-06 11:57:18 +00:00
Dennis Kobert 886ff03ef2 Construct value nodes as native record sources 2026-08-06 10:24:44 +00:00
Dennis Kobert 7a1d1f3238 Define the frame memo through the record-opaque class over same-frame byte copies 2026-08-06 09:57:21 +00:00
Dennis Kobert 612afb7ebb Capture the input context snapshot on the monitor io record 2026-08-06 09:37:48 +00:00
Dennis Kobert daf3f25d21 Define the monitor through the record-opaque class and move introspection to element reads 2026-08-06 09:07:57 +00:00
Dennis Kobert a2de2a9c09 Add the record-opaque kernel class to the node macro and define memoize through it 2026-08-06 08:28:52 +00:00
Dennis Kobert 98be2b8c79 Carry erased element and re-park glue on layouts and collapse memoize to a generic record row 2026-08-06 08:01:19 +00:00
Dennis Kobert 83fda4f08c Update the core-types runtime tests to record wires 2026-08-06 06:46:28 +00:00
Dennis Kobert 20c6ba19d3 Flip async source nodes onto record wires by lifting their slot values 2026-08-05 23:54:42 +00:00
Dennis Kobert 7eeb7d84cd Flip poll kernels and derived-context lazy nodes onto record wires and land record roots at the host rim 2026-08-05 23:42:24 +00:00
Dennis Kobert 7ddc66adbe Flip lazy-input nodes onto record wires through the element lazy input 2026-08-05 23:12:43 +00:00
Dennis Kobert c20a243fc2 Flip lend-parameter nodes onto record wires and keep the clone adapter plain 2026-08-05 22:57:51 +00:00
Dennis Kobert 3eecc31bfd Flip generic value nodes onto record wires through phantom struct parameters 2026-08-05 22:39:25 +00:00
Dennis Kobert 7099f056dc Flip concrete value nodes onto record wires with bridge rows for every value type 2026-08-05 22:18:50 +00:00
Dennis Kobert 9680d34abf Carry record elements by the drop-glue rule and unify the lift and extract adapters 2026-08-05 22:17:50 +00:00
Dennis Kobert 592b2fbe32 Turn context modification into a generic record routing node and park droppable elements as arena references 2026-08-05 19:25:17 +00:00
Dennis Kobert 60f80682c5 Collapse duplicate proto nodes when assigning stable ids 2026-08-05 19:25:17 +00:00
Dennis Kobert 9fc4fcc7a0 Inline records of at most 16 bytes into the two-word RecordValue with layout-resolved storage 2026-08-05 17:23:09 +00:00
Dennis Kobert 7915800d73 Add per-field erased-read glue, the record monitor with introspection capture, and rename record constructors to new 2026-08-05 15:22:20 +00:00
Dennis Kobert c91be74a55 Add the Record wire type, record registry rows, lift and extract adapters, and executor stack reservation 2026-08-05 12:24:20 +00:00
Dennis Kobert abe2a565d1 Drop the list driver, make attribute values Copy over arena references, and land record-tier offset io on a per-thread record stack 2026-08-05 09:47:03 +00:00
Dennis Kobert 6154e4d219 Add the attribute census, node macro attribute io over list wires, and the rank-0 record tier 2026-08-04 22:05:02 +00:00
Dennis Kobert 62b7ccf40c Support bare reference parameters and lending outputs in the node macro and make the clone node the clone-out adapter 2026-08-03 18:29:16 +00:00
Dennis Kobert 9b45af854a Emit Ref wire types for lending rows and splice lend/clone_out adapters in the type checker 2026-08-03 16:33:27 +00:00
Dennis Kobert 562e6602eb Poll source tasks once at spawn and land inline completions in the first eval 2026-08-03 10:21:46 +00:00
Dennis Kobert 8fb18012cf Remove unuse allow dead code 2026-08-02 19:35:43 +02:00
Dennis Kobert 2b3161773f Propagate tokio runtime creation failure in graphene-cli 2026-08-02 19:29:33 +02:00
Dennis Kobert 167d733f02 Wire the async source runtimes into the hosts 2026-08-02 19:24:51 +02:00
Dennis Kobert ee499be31f Add test coverage for the repeat nodes 2026-08-02 16:18:07 +00:00
Dennis Kobert d385f3c69b Fix warnings 2026-08-02 15:06:11 +00:00
Dennis Kobert e372f78b7e Address pr review 2026-08-02 14:31:13 +00:00
Dennis Kobert 8686b2c891 Export the async-source flag from the macro and dispatch superseded type deltas in tests 2026-08-02 14:09:27 +00:00
Dennis Kobert e3aa32bc83 Fix wireing of async sources 2026-08-02 14:02:53 +02:00
Dennis Kobert 77d439ec35 Silence the dead-code warnings for groundwork the host wiring will use 2026-08-01 00:59:26 +02:00
Dennis Kobert c30054579f Adapt the cutover to the reviewed core-types API 2026-07-31 23:39:39 +02:00
Dennis Kobert 81a319430b Cut over to the graphene execution model 2026-07-31 23:19:42 +02:00
Dennis Kobert 1fb6fcb447 Remove the unused CtxSnapshot scope reconstruction 2026-07-31 22:55:53 +02:00
Dennis Kobert 32d244e700 Make the sources fields private and normalize them on every mutation 2026-07-31 22:00:22 +02:00
Dennis Kobert 0877f9d50e Park the arena during drop glue, guard filled batches, and normalize deserialized sources 2026-07-31 20:09:46 +02:00
Dennis Kobert 14c1dd0397 Guard the shared generation counter in tests and reject oversized batch ranges 2026-07-31 19:30:59 +02:00
Dennis Kobert daf7b3e7b9 Make arena generation exhaustion fallible with an unsafe counter rewind 2026-07-31 19:08:09 +02:00
Dennis Kobert bdf53070f2 Forward serialize through node wrappers and free abandoned frame table reservations 2026-07-31 18:12:53 +02:00
Dennis Kobert 0d0ec96709 Draw arena generations from a global counter so foreign handles never upgrade 2026-07-31 17:48:09 +02:00
Dennis Kobert 6feaf4ec9d Drop arena entries in reverse allocation order and require Send + Sync payloads 2026-07-31 17:21:11 +02:00
Dennis Kobert 5541769dc5 Fix frame table key aliasing and arena handle offset truncation 2026-07-31 16:46:20 +02:00
Dennis Kobert 1fccb112cb Add the core execution types, the borrowed context, and the seeded u64 fx hasher 2026-07-31 13:11:36 +00:00
Timon eb50be844b Remove now obsolete disable-registration special case from node macro (#4375) 2026-07-25 13:54:46 +00:00
Dennis Kobert 0f0f62c2e9 Enforce unwind safety on all public executor entry points (#4356) 2026-07-24 09:34:40 +00:00
Timon f5b1fee85f Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-22 09:38:07 +00:00
Timon 6f8c4b2adb 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:33:38 +00:00
284 changed files with 41956 additions and 18179 deletions

No files matched your search

+20 -4
View File
@@ -2,11 +2,25 @@
"image": "mcr.microsoft.com/devcontainers/base:debian",
"features": {
"ghcr.io/devcontainers/features/rust:1": {
"profile": "default"
"profile": "default",
"targets": "wasm32-unknown-unknown"
},
"ghcr.io/devcontainers/features/node:1": {}
"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"
},
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
@@ -16,14 +30,16 @@
"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",
// Helpful
// Git
"mhutchie.git-graph",
"qezhu.gitlink",
// Helpful
"wmaurer.change-case"
]
}
+34
View File
@@ -0,0 +1,34 @@
# 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
+24 -10
View File
@@ -58,6 +58,7 @@ 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:
@@ -302,9 +303,11 @@ 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.0"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
steps:
- name: 📥 Clone repository
@@ -341,7 +344,9 @@ jobs:
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/cargo-binstall@main
uses: cargo-bins/cargo-binstall@v1.23.0
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
- name: 🚧 Install native dependencies
shell: pwsh
@@ -497,9 +502,11 @@ 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.0"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
steps:
- name: 📥 Clone repository
@@ -535,6 +542,11 @@ 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 }}
@@ -544,8 +556,7 @@ jobs:
brew install \
pkg-config \
openssl@3 \
llvm \
cargo-binstall
llvm
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
@@ -650,17 +661,20 @@ 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"
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
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
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
+1
View File
@@ -13,3 +13,4 @@ flamegraph.svg
.direnv
.DS_Store
.nvim.lua
/.devcontainer/devcontainer-lock.json
+14 -12
View File
@@ -1,10 +1,10 @@
{ pkgs, ... }:
let
version = "149.0.5+g6770623+chromium-149.0.7827.197";
version = "151.3.24+g2384915+chromium-151.0.7922.174";
hashes = {
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
};
selectSystem =
@@ -12,17 +12,19 @@ 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 {
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
inherit url;
hash = selectSystem hashes;
};
in
pkgs.cef-binary.overrideAttrs (finalAttrs: {
pkgs.cef-binary.overrideAttrs {
version = builtins.head (builtins.split "\\+" version);
inherit src;
postInstall = ''
@@ -38,9 +40,9 @@ pkgs.cef-binary.overrideAttrs (finalAttrs: {
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
name = builtins.baseNameOf url;
sha1 = "";
}
}' > $out/archive.json
'';
})
}
+1
View File
@@ -6,6 +6,7 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
Generated
+49 -28
View File
@@ -370,15 +370,31 @@ 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]]
@@ -594,8 +610,8 @@ dependencies = [
[[package]]
name = "cef"
version = "149.2.0+149.0.5"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
version = "151.8.0+151.3.24"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-151#35712dc3948628245cf9810eadd045d9435442e8"
dependencies = [
"anyhow",
"cargo_metadata 0.23.1",
@@ -613,8 +629,8 @@ dependencies = [
[[package]]
name = "cef-dll-sys"
version = "149.2.0+149.0.5"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
version = "151.8.0+151.3.24"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-151#35712dc3948628245cf9810eadd045d9435442e8"
dependencies = [
"anyhow",
"cmake",
@@ -1246,7 +1262,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1356,7 +1372,7 @@ checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
[[package]]
name = "download-cef"
version = "2.3.2"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-151#35712dc3948628245cf9810eadd045d9435442e8"
dependencies = [
"bzip2",
"clap",
@@ -1525,7 +1541,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1672,9 +1688,9 @@ dependencies = [
[[package]]
name = "font-types"
version = "0.12.2"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a7299a780854a6d391be2ae1c8521c9368471b559dbfd6a8dbd9f407eaff100"
checksum = "75382bc7392ef10aad10935f92fc3db36d2d4dad0e5d96d8d65e04f89a07ec39"
dependencies = [
"bytemuck",
]
@@ -2040,6 +2056,7 @@ dependencies = [
"graphene-hash",
"graphic-types",
"gungraun",
"interpreted-executor",
"js-sys",
"log",
"mmap-io",
@@ -2208,6 +2225,7 @@ dependencies = [
name = "graphic-nodes"
version = "0.1.0"
dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
@@ -2223,6 +2241,7 @@ dependencies = [
name = "graphic-types"
version = "0.1.0"
dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
@@ -2365,6 +2384,7 @@ dependencies = [
"base64",
"bitflags 2.11.0",
"color",
"core-types",
"derivative",
"document-container",
"document-format",
@@ -2383,6 +2403,7 @@ dependencies = [
"kurbo",
"log",
"math-parser",
"node-macro",
"num_enum",
"once_cell",
"preprocessor",
@@ -2427,7 +2448,6 @@ dependencies = [
"graphite-proc-macros",
"js-sys",
"log",
"node-macro",
"serde",
"serde-wasm-bindgen",
"serde_bytes",
@@ -2971,6 +2991,7 @@ dependencies = [
"graph-craft",
"graphene-core",
"graphene-std",
"graphic-types",
"gungraun",
"log",
"once_cell",
@@ -4062,7 +4083,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.45.0",
]
[[package]]
@@ -4590,7 +4611,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4784,7 +4805,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types 0.12.2",
"font-types 0.12.3",
"once_cell",
]
@@ -4871,6 +4892,7 @@ name = "rendering"
version = "0.1.0"
dependencies = [
"base64",
"brush-types",
"core-types",
"dyn-any",
"glam",
@@ -4897,15 +4919,11 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"kurbo",
"log",
"node-macro",
"raster-types",
"serde",
"tokio",
"vector-nodes",
"vector-types",
]
@@ -5106,7 +5124,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5174,7 +5192,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5917,7 +5935,7 @@ dependencies = [
"getrandom 0.3.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -6653,8 +6671,9 @@ dependencies = [
[[package]]
name = "vello"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af76ceb17b2869be23598baef40a9c8db4de86b87c60510c3bc245559275a617"
dependencies = [
"bytemuck",
"futures-intrusive",
@@ -6671,8 +6690,9 @@ dependencies = [
[[package]]
name = "vello_encoding"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e31cd622201690d8dfe9fd8fea8d1ae59db1bfeea414856a617d1d03438418c"
dependencies = [
"bytemuck",
"guillotiere",
@@ -6683,8 +6703,9 @@ dependencies = [
[[package]]
name = "vello_shaders"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abf943bd2920bfd22928a9c1bad39866f7ffcc1109b6ed924ab52773e3868a83"
dependencies = [
"bytemuck",
"log",
@@ -7202,7 +7223,7 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[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 = "Apache-2.0"
license = "MIT OR Apache-2.0"
version = "0.0.0"
readme = "README.md"
publish = false
@@ -80,6 +80,7 @@ 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" }
@@ -139,7 +140,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 across CI workflows, devcontainer, Nix, and the `cargo-run` tool. 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 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-futures = "0.4"
js-sys = "=0.3.98"
web-sys = { version = "=0.3.98", features = [
@@ -166,9 +167,8 @@ 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"] }
# 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" }
vello = "0.10"
vello_encoding = "0.10"
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 = "149"
cef-dll-sys = "149"
cef = "151"
cef-dll-sys = "151"
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-149" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
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" }
View File
File renamed without changes.
+19
View File
@@ -0,0 +1,19 @@
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.
+3 -1
View File
@@ -80,4 +80,6 @@ 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.
*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).*
## 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.
-2
View File
@@ -22,8 +22,6 @@ 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
@@ -3,7 +3,7 @@ name = "graphite-desktop"
version = "0.1.0"
description = "Graphite Desktop"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
license = "MIT OR 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 = "Apache-2.0"
license = "MIT OR 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 = "Apache-2.0"
license = "MIT OR 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 = "Apache-2.0"
license = "MIT OR 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 = "Apache-2.0"
license = "MIT OR 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 = "Apache-2.0"
license = "MIT OR Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
+18 -14
View File
@@ -17,11 +17,11 @@ use winit::window::WindowId;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::input::{InputAction, InputState};
use crate::input::InputState;
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::ui::{UiCommand, UiInstance};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
@@ -98,6 +98,11 @@ 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,
@@ -280,6 +285,9 @@ 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();
@@ -547,20 +555,16 @@ impl ApplicationHandler for App {
if let Some(window) = &self.window {
window.end_pointer_lock();
}
self.ui.send(UiCommand::Input(WindowEvent::PointerMoved {
device_id: None,
position: pointer_lock_position,
primary: true,
source: winit::event::PointerSource::Mouse,
}));
self.ui.send(UiCommand::Input(
InputEvent::pointer().position(pointer_lock_position).moved().modifiers(self.input_state.modifiers()).build(),
));
}
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)),
}
}
self.input_state.process(
&event,
|message| self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Input(message))),
|input| self.ui.send(UiCommand::Input(input)),
);
match event {
WindowEvent::CloseRequested => {
+326 -118
View File
@@ -1,30 +1,33 @@
use std::time::Instant;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use winit::dpi::PhysicalPosition;
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
use winit::keyboard::ModifiersState;
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};
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)
}
}
pub(crate) struct InputState {
start: Instant,
viewport_info: Option<ViewportInfo>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
modifier_keys: ModifierKeys,
direct_input: bool,
modifiers: ModifiersState,
pointer_position: PhysicalPosition<f64>,
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))
}
pointer_state: PointerState,
click_tracker: ClickTracker,
shake_tracker: ShakeTracker,
}
impl InputState {
@@ -32,12 +35,12 @@ impl InputState {
Self {
start: Instant::now(),
viewport_info: None,
pointer_lock_position: None,
modifier_keys: ModifierKeys::empty(),
direct_input: false,
modifiers: ModifiersState::default(),
pointer_position: PhysicalPosition::default(),
pointer_keys: MouseKeys::empty(),
ui_capture: true,
multiclick: None,
pointer_state: PointerState::Hover { route: Route::Ui },
click_tracker: ClickTracker::default(),
shake_tracker: ShakeTracker::default(),
}
}
@@ -45,58 +48,97 @@ 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_lock_position = Some(self.pointer_position);
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,
},
};
}
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
let position = self.pointer_lock_position.take();
if let Some(position) = position {
self.pointer_position = position;
}
position
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)
}
pub(crate) fn pointer_locked(&self) -> bool {
self.pointer_lock_position.is_some()
matches!(self.pointer_state, PointerState::Locked { .. })
}
pub(crate) fn process(&mut self, event: &WindowEvent) -> Vec<InputAction> {
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)) {
match event {
WindowEvent::PointerMoved { position, source, .. } => {
self.pointer_position = *position;
let PointerSource::TabletTool { kind, data } = source else {
return vec![InputAction::Ui(event.clone())];
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 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())];
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 });
}
}
vec![InputAction::editor(InputMessage::PointerMove {
editor_mouse_state: self.tablet_pointer_state(kind, data),
modifier_keys: self.modifier_keys,
})]
}
WindowEvent::PointerEntered { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } => {
WindowEvent::PointerEntered { position, .. } => {
self.pointer_position = *position;
vec![InputAction::Ui(event.clone())]
ui_callback(InputEvent::pointer().position(*position).entered().modifiers(self.modifiers).build())
}
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,
@@ -106,43 +148,82 @@ impl InputState {
Some(MouseButton::Forward) => MouseKeys::FORWARD,
_ => MouseKeys::NONE,
};
match state {
ElementState::Pressed => self.pointer_keys.insert(keys),
ElementState::Released => self.pointer_keys.remove(keys),
}
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));
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
if self.pointer_locked() || !(back_or_forward || (tablet && !self.ui_capture)) {
return vec![InputAction::Ui(event.clone())];
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());
}
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 => 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::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::Released => editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys }),
}
}
WindowEvent::MouseWheel { delta, .. } => {
if self.pointer_locked() || !self.in_viewport(self.pointer_position) {
return vec![InputAction::Ui(event.clone())];
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;
}
let (x, y) = match delta {
@@ -152,34 +233,29 @@ impl InputState {
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
vec![InputAction::editor(InputMessage::WheelScroll {
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys,
})]
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys(),
});
}
WindowEvent::PinchGesture { delta, .. } => {
if self.pointer_locked() || !self.in_viewport(self.pointer_position) || !delta.is_normal() {
return vec![InputAction::Ui(event.clone())];
if self.pointer_locked() || self.ui_captures(self.pointer_position) || !delta.is_normal() {
ui_callback(InputEvent::pointer().zoomed(*delta).modifiers(self.modifiers).build());
return;
}
// 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.);
vec![InputAction::editor(InputMessage::WheelScroll {
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys | ModifierKeys::CONTROL,
})]
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys() | ModifierKeys::CONTROL,
});
}
WindowEvent::ModifiersChanged(modifiers) => {
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())]
self.modifiers = modifiers.state();
}
_ => vec![InputAction::Ui(event.clone())],
WindowEvent::KeyboardInput { event, .. } => ui_callback(InputEvent::key(event).modifiers(self.modifiers).build()),
_ => {}
}
}
@@ -187,21 +263,32 @@ impl InputState {
self.viewport_info.as_ref().map_or(1., |info| info.scale)
}
fn in_viewport(&self, position: PhysicalPosition<f64>) -> bool {
self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
fn ui_captures(&self, position: PhysicalPosition<f64>) -> bool {
!self.direct_input || !self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
}
fn pointer_state(&self) -> PointerState {
PointerState {
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 {
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) -> PointerState {
PointerState {
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> EditorPointerState {
EditorPointerState {
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),
@@ -211,19 +298,29 @@ impl InputState {
}
}
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
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
}
}
#[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,
@@ -238,8 +335,119 @@ impl ViewportInfo {
}
}
struct Multiclick {
button: MouseButton,
#[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 {
time: Instant,
position: PhysicalPosition<f64>,
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
}
}
+4 -5
View File
@@ -52,13 +52,12 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return srgb_to_linear(immediates.background_color);
}
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
if (ui_linear.a >= 0.999) {
return ui_linear;
let ui_sample = textureSample(t_ui, s_diffuse, ui_coordinate);
if (ui_sample.a >= 0.999) {
return srgb_to_linear(ui_sample);
}
// UI texture is premultiplied, we need to unpremultiply before blending
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
let ui_srgb = unpremultiply(ui_sample);
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::{WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
use crate::wrapper::{Texture, 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: std::sync::Arc<wgpu::Texture>,
transparent_texture: Texture,
sampler: wgpu::Sampler,
desired_width: u32,
desired_height: u32,
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
viewport_texture: Option<Texture>,
overlays_texture: Option<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 = std::sync::Arc::new(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("Transparent Texture"),
let transparent_texture = Texture::from(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("transparent_fallback"),
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: std::sync::Arc<wgpu::Texture>) {
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: 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 = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
match result {
Ok(texture) => {
self.overlays_texture = Some(texture.into());
self.overlays_texture = Some(texture);
}
Err(e) => {
self.overlays_texture = None;
+4 -6
View File
@@ -223,6 +223,7 @@ 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,
})
@@ -252,12 +253,8 @@ pub(crate) enum InitError {
pub(crate) struct CefContextHandle;
impl CefContextHandle {
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 process_input(&self, event: InputEvent) {
with_context(move |context| input::process(&mut context.input, &context.browser, &event));
}
pub(crate) fn update_view_info(&self, update: ViewInfoUpdate) {
@@ -276,6 +273,7 @@ impl CefContextHandle {
struct BrowserContext {
delegate: BrowserDelegate,
browser: Browser,
input: input::InputState,
view_info_sender: Sender<ViewInfoUpdate>,
_instance_dir: TempDir,
}
+195 -213
View File
@@ -1,253 +1,235 @@
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};
pub(crate) mod event;
pub(crate) use event::InputEvent;
mod keymap;
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
mod state;
pub(crate) use state::{CefModifiers, InputState};
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};
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};
/// 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),
#[derive(Default)]
pub(crate) struct InputState {
position: PhysicalPosition<f64>,
buttons: ButtonStates,
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct MouseData {
pub(crate) x: i32,
pub(crate) y: i32,
pub(crate) modifiers: u32,
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, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum MouseButtonKind {
Left,
Right,
Middle,
}
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 KeyEventKind {
RawKeyDown,
KeyUp,
Char,
}
// 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, 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();
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);
}
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
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();
};
InputEventKind::Key {
key,
key_without_modifiers,
physical_key,
location,
text,
action,
} => {
let mut flags = event_flags(&event.modifiers, &state.buttons);
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(),
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,
_ => 0,
};
match action {
KeyAction::Press | KeyAction::Repeat => flags |= own_flag,
KeyAction::Release => flags &= !own_flag,
}
let native_key_code = event.physical_key.to_native_keycode();
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 char_representation = event.logical_key.to_char_representation();
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();
#[allow(unused_mut)]
let mut character = 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;
let unmodified_character = 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 && event.text_with_all_modifiers.is_some() {
if character == 0 && unmodified_character == 0 && text.is_some() {
character = 1;
}
#[cfg(not(target_os = "macos"))]
let _ = text;
let key = KeyData {
kind,
modifiers,
let key_event = |kind: cef_key_event_type_t, windows_key_code: i32| KeyEvent {
type_: kind.into(),
modifiers: flags,
windows_key_code,
native_key_code,
character,
unmodified_character,
};
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(),
}
}
/// 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));
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)));
}
}
}
}
}
impl From<&MouseData> for MouseEvent {
fn from(data: &MouseData) -> Self {
MouseEvent {
x: data.x,
y: data.y,
modifiers: data.modifiers,
#[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 => {}
}
}
}
fn mouse_event(position: PhysicalPosition<f64>, flags: u32) -> MouseEvent {
MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: flags,
}
}
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
@@ -0,0 +1,245 @@
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
@@ -1,256 +0,0 @@
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;
}
}
+3 -15
View File
@@ -23,6 +23,7 @@ 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,
@@ -69,7 +70,6 @@ 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,7 +143,6 @@ 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<()>>,
@@ -154,18 +153,7 @@ impl UiInstance {
pub fn send(&self, command: UiCommand) {
let shared = &self.inner;
match command {
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::Input(event) => shared.host.send(HostControlMessage::Input(event)),
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),
@@ -222,7 +210,7 @@ impl Drop for UiInstanceInner {
#[derive(Debug)]
pub enum UiCommand {
Input(winit::event::WindowEvent),
Input(InputEvent),
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(events)) => context.apply_input(events),
Ok(HostControlMessage::Input(event)) => context.process_input(event),
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(Vec<InputEvent>),
Input(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 = "Apache-2.0"
license = "MIT OR 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, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, 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 => {
FrontendMessage::TriggerOpen { filters } => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Open Document".to_string(),
filters: vec![],
filters,
multiple: true,
context: OpenFileDialogContext::Open,
});
}
FrontendMessage::TriggerImport => {
FrontendMessage::TriggerImport { filters } => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters: vec![],
filters,
multiple: false,
context: OpenFileDialogContext::Import,
});
@@ -31,32 +31,29 @@ 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: vec![FileFilter {
name: "Graphite Document".to_string(),
extensions: vec![extension],
}],
filters,
context: SaveFileDialogContext::Document { document_id, content },
});
}
}
FrontendMessage::TriggerSaveFile { name, folder, content } => {
FrontendMessage::TriggerSaveFile { name, folder, filters, content } => {
let content = content.into_vec();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save File".to_string(),
default_filename: name,
default_folder: folder,
filters: Vec::new(),
filters,
context: SaveFileDialogContext::File { content },
});
}
@@ -125,6 +122,9 @@ 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);
}
+7 -2
View File
@@ -10,6 +10,7 @@ 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;
@@ -52,17 +53,21 @@ 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.map(Into::into)),
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
}
pub enum NodeGraphExecutionResult {
HasRun(Option<std::sync::Arc<wgpu::Texture>>),
HasRun(Option<Texture>),
NotRun,
}
+5 -7
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, PersistedState};
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileFilter, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState as PointerState, EditorPosition as Position, MouseKeys, ScrollDelta};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, 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,6 +40,9 @@ pub enum DesktopFrontendMessage {
UpdateUIScale {
scale: f64,
},
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
@@ -100,11 +103,6 @@ pub enum DesktopWrapperMessage {
LoadThirdPartyLicenses { text: String },
}
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
#[derive(Clone, Copy)]
pub enum OpenFileDialogContext {
Open,
@@ -1,6 +1,5 @@
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,7 +1,6 @@
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;
@@ -390,9 +389,6 @@ 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,7 +14,9 @@ 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()).map_err(|e| format!("Compilation failed: {:?}", e))?;
compiler
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
.map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
}
@@ -246,11 +248,6 @@ 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: [
@@ -260,7 +257,6 @@ 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()
@@ -294,8 +290,12 @@ 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 preserved
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features 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 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(),
})
}
+3 -1
View File
@@ -8,7 +8,7 @@ edition = "2024"
readme = "../README.md"
homepage = "https://graphite.art"
repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0"
license = "MIT OR Apache-2.0"
[features]
default = ["gpu"]
@@ -72,3 +72,5 @@ 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 4";
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 5";
fn main() {
// Instruct Cargo to rerun this build script if any of these environment variables change.
+3 -1
View File
@@ -135,7 +135,9 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
// BRUSH TOOL
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
pub const BRUSH_SIZE_DEFAULT: f64 = 40.;
pub const BRUSH_HARDNESS_DEFAULT: f64 = 0.;
pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
// EYEDROPPER TOOL
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
+3 -2
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,
tool_message_handler: ToolMessageHandler,
pub(crate) tool_message_handler: ToolMessageHandler,
viewport_message_handler: ViewportMessageHandler,
}
@@ -96,8 +96,9 @@ impl Dispatcher {
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::default();
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
pub enum AppWindowMessage {
PointerLock,
PointerLockMove { x: f64, y: f64 },
DirectInput { enabled: bool },
Restart,
Close,
Minimize,
@@ -17,6 +17,12 @@ 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);
@@ -275,11 +275,7 @@ impl PreferencesDialogMessageHandler {
let checkbox_id = CheckboxId::new();
let brush_tool_description = "
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\
Enable the Brush tool to support basic layer painting.\n\
\n\
*Default: Off.*
"
@@ -46,11 +46,15 @@ impl LayoutHolder for LicensesDialog {
let year = &self.localized_commit_year;
let description = format!(
"
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\
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\
\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\ndependencies. See \"Dependency Licenses\" for details.
Graphite is distributed with third-party open source code\n\
dependencies. 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, RasterizedImage};
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileFilter, 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,16 +87,24 @@ 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 {
@@ -128,8 +136,6 @@ pub enum FrontendMessage {
},
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpen,
TriggerImport,
TriggerSavePreferences {
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
preferences: PreferencesMessageHandler,
@@ -344,6 +350,10 @@ 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,6 +64,26 @@ 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))]
@@ -91,3 +111,10 @@ 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>,
}
@@ -14,7 +14,6 @@ use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
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,
};
@@ -30,7 +29,7 @@ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
use graphene_std::{Appearance, Artboard, Color, Context, Cover, Coverage, Graphic};
use graphene_std::{Appearance, Artboard, Color, Cover, Coverage, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -188,8 +187,8 @@ macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None }
$(
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() {
Some(io.output.layout_with_breadcrumb($data))
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
Some(element.layout_with_breadcrumb($data))
}
)*
else { None }
@@ -197,10 +196,14 @@ 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>> {
// `Item<NodeIdPath>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `NodeIdPath` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<NodeIdPath>>>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output.element().0, data));
if let Some(path) = introspected_data.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
}
// The path's bare list form, introspected off a leveled wire.
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
}
generate_layout_downcast!(introspected_data, data, [
List<Artboard>,
@@ -258,61 +261,61 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<QRCodeErrorCorrectionLevel>,
List<InterpolationDistribution>,
List<RowsOrColumns>,
Item<Artboard>,
Item<Graphic>,
Item<Vector>,
Item<Raster<CPU>>,
Item<Raster<GPU>>,
Item<Color>,
Item<Gradient>,
Item<String>,
Item<f64>,
Item<f32>,
Item<u32>,
Item<u64>,
Item<i32>,
Item<i64>,
Item<bool>,
Item<DVec2>,
Item<DAffine2>,
Item<BlendMode>,
Item<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>,
Artboard,
Graphic,
Vector,
Raster<CPU>,
Raster<GPU>,
Color,
Gradient,
String,
f64,
f32,
u32,
u64,
i32,
i64,
bool,
DVec2,
DAffine2,
BlendMode,
GradientForm,
GradientSpread,
GradientSpace,
GradientHueDirection,
GradientInterpolation,
DashPattern,
BoxCorners,
StrokeJoin,
StrokeAlign,
StrokeCap,
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,
])
}
@@ -478,7 +481,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
}
}
impl TableItemLayout for Artboard {
impl TableItemLayout for Artboard<'_> {
fn type_name() -> &'static str {
"Artboard"
}
@@ -494,6 +497,15 @@ impl TableItemLayout for Artboard {
}
}
impl TableItemLayout for graphene_std::brush::Stroke {
fn type_name() -> &'static str {
"Stroke"
}
fn identifier(&self) -> String {
format!("Stroke ({} {})", self.len(), if self.len() == 1 { "sample" } else { "samples" })
}
}
impl TableItemLayout for DashPattern {
fn type_name() -> &'static str {
"DashPattern"
@@ -585,28 +597,23 @@ impl TableItemLayout for graphene_std::core_types::none::None {
}
}
impl TableItemLayout for Graphic {
impl TableItemLayout for Graphic<'_> {
fn type_name() -> &'static str {
"Graphic"
}
fn identifier(&self) -> String {
// Our leaf variants hold the bare element, so they report the element's own identifier
match self {
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::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(),
Self::Vector(vector) => vector.identifier(),
Self::RasterCPU(raster) => raster.identifier(),
Self::RasterGPU(raster) => raster.identifier(),
Self::Color(color) => color.identifier(),
Self::Gradient(gradient) => gradient.identifier(),
Self::Text(text) => text.identifier(),
Self::Stroke(stroke) => stroke.identifier(),
Self::StrokeList(list) => list.identifier(),
Self::Group(_) => "Group".to_string(),
}
}
// Don't put a breadcrumb for Graphic
@@ -615,22 +622,16 @@ impl TableItemLayout for Graphic {
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
match self {
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::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),
Self::Vector(vector) => vector.layout_with_breadcrumb(data),
Self::RasterCPU(raster) => raster.layout_with_breadcrumb(data),
Self::RasterGPU(raster) => raster.layout_with_breadcrumb(data),
Self::Color(color) => color.layout_with_breadcrumb(data),
Self::Gradient(gradient) => gradient.layout_with_breadcrumb(data),
Self::Text(text) => text.layout_with_breadcrumb(data),
Self::Stroke(stroke) => stroke.layout_with_breadcrumb(data),
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
Self::Group(_) => Vec::new(),
}
}
}
@@ -1353,6 +1354,11 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, 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));
}
macro_rules! check {
( $($ty:ty),* $(,)? ) => {
$(
@@ -11,8 +11,9 @@ use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use glam::{DAffine2, IVec2};
use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::Color;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
use graphene_std::raster::Image;
use graphene_std::transform::Footprint;
@@ -244,10 +245,14 @@ pub enum DocumentMessage {
vector_data: HashMap<NodeId, Arc<Vector>>,
},
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it.
// `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
// `UpdateFillAttributes`/`UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so they never reach that serialization point.
#[serde(skip)]
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
UpdateFillAttributes {
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
},
#[serde(skip)]
UpdateStrokeAttributes {
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
},
Undo,
UngroupSelectedLayers,
@@ -10,6 +10,7 @@ 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};
@@ -34,9 +35,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::concrete;
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;
@@ -916,7 +917,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
responses.add(SelectToolMessage::Abort);
responses.add(DocumentMessage::DocumentHistoryForward);
responses.add(ToolMessage::Redo);
// 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(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
@@ -1066,7 +1074,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
(true, Some(storage)) => storage
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportOptions::default(),
document_format::ExportOptions {
include_history: false,
..Default::default()
},
export_load_handle.as_ref(),
Some(&legacy_document),
)
@@ -1086,6 +1097,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
name,
path,
folder,
filters: vec![FileFilter {
name: "Graphite Document".into(),
extensions: vec![extension.into()],
}],
content: content.into(),
})
});
@@ -1503,28 +1518,31 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_vector_data(layer_vector_data);
}
DocumentMessage::UpdateAppearanceAttributes { appearance_attributes } => {
// Convert NodeId keys to LayerNodeIdentifier keys, filtering to only layers
let layer_appearance_attributes = appearance_attributes
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, attrs)| {
self.network_interface.is_layer(&node_id, &[]).then(|| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, attrs)
})
})
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
DocumentMessage::UpdateFillAttributes { fill_attributes } => {
let layer_fill_attributes = self.layer_keyed(fill_attributes);
self.network_interface.update_fill_attributes(layer_fill_attributes);
}
DocumentMessage::UpdateStrokeAttributes { stroke_attributes } => {
let layer_stroke_attributes = self.layer_keyed(stroke_attributes);
self.network_interface.update_stroke_attributes(layer_stroke_attributes);
}
DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
responses.add(ToolMessage::PreUndo);
responses.add(DocumentMessage::DocumentHistoryBackward);
// 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(OverlaysMessage::Draw);
responses.add(ToolMessage::Undo);
responses.add(EventMessage::SelectionChanged);
}
DocumentMessage::UngroupSelectedLayers => {
@@ -1782,6 +1800,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
impl DocumentMessageHandler {
/// Rekeys a per-node attribute snapshot by layer, dropping nodes that are not layers.
fn layer_keyed<T>(&self, attributes: HashMap<NodeId, T>) -> HashMap<LayerNodeIdentifier, T> {
attributes
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, attrs)| self.network_interface.is_layer(&node_id, &[]).then(|| (LayerNodeIdentifier::new(node_id, &self.network_interface), attrs)))
.collect()
}
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
let mut document = Self {
@@ -2740,7 +2767,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::graphic::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::index_elements::IDENTIFIER).expect("Item at Index node should exist");
let mut resulting_layers: Vec<NodeId> = Vec::new();
@@ -2750,13 +2777,14 @@ impl DocumentMessageHandler {
continue;
}
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer);
let metadata = self.network_interface.document_metadata();
let fill_paint = metadata.layer_fill_attributes.get(&layer);
let stroke_paint = metadata.layer_stroke_attributes.get(&layer);
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
let has_fill = fill_paint.is_some_and(|paint| paint.element(0).is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent()));
// 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_guaranteed_fully_transparent())
let has_stroke = stroke_paint.is_some_and(|paint| {
graphene_std::renderer::stroke_params(paint).has_renderable_stroke() && paint.element(0).is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent())
});
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
@@ -3776,7 +3804,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(list!(graphene_std::Artboard)), -1, "", &[]);
network_interface.add_export(TaggedValue::TypeDefault(graph_craft::descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
network_interface
}
@@ -4326,8 +4354,9 @@ mod document_message_handler_tests {
let phantom_count = news
.iter()
.flat_map(|new| new.iter_element_values())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
// Our no-content graphic is an empty list rather than master's dedicated None variant
.filter(|graphic| graphic.is_empty())
.count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
assert_eq!(phantom_count, 0, "No stacked element should be a phantom empty graphic");
}
}
@@ -5,7 +5,6 @@ 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};
@@ -112,9 +111,23 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
modification_type: VectorModificationType,
},
Brush {
NewBrushGroupLayer {
id: NodeId,
strokes_node_id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
color: Color,
diameter: f64,
hardness: f64,
flow: f64,
},
NewBrushStrokesNode {
layer: LayerNodeIdentifier,
strokes: Vec<BrushStroke>,
strokes_node_id: NodeId,
color: Color,
diameter: f64,
hardness: f64,
flow: f64,
},
SetUpstreamToChain {
layer: LayerNodeIdentifier,
@@ -2,15 +2,16 @@ use super::transform_utils;
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, DefinitionIdentifier};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, DefinitionIdentifier, resolve_proto_node_type};
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::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
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};
@@ -172,10 +173,35 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.vector_modify(modification_type);
}
}
GraphOperationMessage::Brush { layer, strokes } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.brush_modify(strokes);
}
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::SetUpstreamToChain { layer } => {
let Some(OutputConnector::Node { node_id: first_chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(layer.to_node()), &[]) else {
@@ -226,7 +252,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
}
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true);
let bottom_input = NodeInput::type_default(graph_craft::descriptor!(graphene_std::list::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.
@@ -234,7 +260,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(list!(Artboard), true);
let bottom_input = NodeInput::type_default(graph_craft::descriptor!(graphene_std::list::List<Artboard>), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
}
}
@@ -847,6 +873,22 @@ 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);
@@ -3,7 +3,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
ARTBOARD_DIMENSIONS_INPUT_INDEX, ARTBOARD_LOCATION_INPUT_INDEX, DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type,
};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
@@ -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, list};
use graphene_std::brush::brush_stroke::BrushStroke;
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
use graphene_std::list::List;
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(list!(Artboard), true)),
Some(NodeInput::type_default(list!(Graphic), true)),
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
Some(NodeInput::type_default(descriptor!(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(list!(Graphic), true)),
Some(NodeInput::type_default(descriptor!(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(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(descriptor!(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(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -444,10 +444,6 @@ 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) {
@@ -493,21 +489,6 @@ 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) {
@@ -878,6 +859,9 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
// Our stroke node keeps a paint order input rather than encoding the order by Fill/Stroke node adjacency, and master's `Stroke` no longer carries one to copy
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(Default::default()), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
@@ -977,17 +961,6 @@ 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;
@@ -1026,59 +999,15 @@ impl<'a> ModifyInputsContext<'a> {
}
}
/// The wires feeding off a node's primary output.
fn primary_output_consumers(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], node_id: NodeId) -> Vec<InputConnector> {
network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(node_id, 0)).cloned())
.unwrap_or_default()
}
/// 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.
/// Sets the Stroke node's paint order input, which decides whether the stroke paints above or below the fill.
/// 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 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 {
let connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput);
if let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&connector, network_path)
&& **tagged_value == TaggedValue::PaintOrder(paint_order)
{
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;
};
let downstream_consumers = primary_output_consumers(network_interface, network_path, downstream);
network_interface.set_input(&InputConnector::node_at_index(downstream, 0), upstream_source, network_path);
network_interface.set_input(&InputConnector::node_at_index(upstream, 0), NodeInput::node(downstream, 0), network_path);
for consumer in &downstream_consumers {
if matches!(consumer, InputConnector::Node { node_id, .. } if *node_id == upstream || *node_id == downstream) {
continue;
}
network_interface.set_input(consumer, NodeInput::node(upstream, 0), network_path);
}
network_interface.set_input(&connector, NodeInput::value(TaggedValue::PaintOrder(paint_order), false), network_path);
true
}
@@ -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;
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
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,8 +13,10 @@ use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::{concrete, list};
use graph_craft::concrete;
use graph_craft::descriptor;
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)]
@@ -154,11 +156,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Primary (bottom) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -2)),
implementation: NodeTemplateImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default()
},
// Secondary (left) input type coercion
// Collection of the content into the layer's group; the wrap keeps the content level's element type for the legacy boundary
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
@@ -169,18 +171,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeTemplate {
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 0)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 1)),
..Default::default()
},
// 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::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(2), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
..Default::default()
},
@@ -196,7 +194,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(4), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -3)),
..Default::default()
},
]
@@ -206,7 +204,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
inputs: vec![NodeInput::type_default(descriptor!(List<Graphic>), true), NodeInput::type_default(descriptor!(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)),
@@ -226,11 +224,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![
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),
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),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default()
@@ -245,18 +243,14 @@ 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::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(1), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::stamp_layer_path::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(2), 0)],
inputs: vec![NodeInput::node(NodeId(7), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T),
skip_deduplication: true,
@@ -265,13 +259,37 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(List<Artboard>))), 0),
NodeInput::node(NodeId(3), 0),
],
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::to_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()
@@ -280,8 +298,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Artboard), true),
NodeInput::type_default(list!(Graphic), true),
NodeInput::type_default(descriptor!(List<Artboard>), true),
NodeInput::type_default(descriptor!(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),
@@ -353,7 +371,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(item!(f64), 1)],
inputs: vec![NodeInput::import(concrete!(f64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
@@ -441,8 +459,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(item!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4),
NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(concrete!(Vector), 4),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default()
@@ -476,11 +494,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::type_default(descriptor!(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(list!(Vector), false),
NodeInput::type_default(descriptor!(List<Vector>), false),
],
input_metadata: vec![
("Content", "TODO").into(),
@@ -566,7 +584,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Vector), true)],
inputs: vec![NodeInput::type_default(descriptor!(List<Vector>), true)],
input_metadata: vec![("Vector", "TODO").into()],
output_names: vec!["Vector".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
@@ -583,7 +601,12 @@ 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(item!(String), 1)],
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),
],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
@@ -631,7 +654,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
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),
],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
@@ -644,7 +674,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value(
TaggedValue::Footprint(Footprint {
transform: DAffine2::from_scale_angle_translation(DVec2::new(1000., 1000.), 0., DVec2::new(0., 0.)),
@@ -676,7 +706,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
nodes: [
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -686,7 +716,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -696,7 +726,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -706,7 +736,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -721,7 +751,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)],
inputs: vec![NodeInput::type_default(descriptor!(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()
@@ -737,14 +767,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(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
inputs: vec![NodeInput::import(concrete!(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(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
inputs: vec![NodeInput::import(concrete!(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)),
@@ -774,7 +804,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
category: "",
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Extract,
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)],
inputs: vec![NodeInput::type_default(descriptor!(DocumentNode), true)],
input_metadata: vec![("Node", "TODO").into()],
output_names: vec!["Document Node".to_string()],
..Default::default()
@@ -797,27 +827,27 @@ 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(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(f64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
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),
],
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
// 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)
// Node 1: extract_element at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::extract_element::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
// Node 2: omit_element 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(graphic::remove_at_index::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::omit_element::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
},
@@ -888,7 +918,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(item!(Vector), true),
NodeInput::type_default(descriptor!(Vector), true),
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
],
input_metadata: vec![("Content", "TODO").into(), ("Modification", "TODO").into()],
@@ -1485,26 +1515,127 @@ 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()
@@ -1578,3 +1709,80 @@ 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, list::Item};
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: Item<T>, _b: Item<bool>) -> Item<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: Item<T>, _b: Item<bool>) -> Item<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<(NodeConstructor, NodeIOTypes)> = Vec::new();
let empty_implementations: Vec<RegistryEntry> = Vec::new();
let context_type = concrete!(Context);
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
@@ -41,18 +41,17 @@ 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(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
implementations.iter().map(|(_, io)| &io.call_argument).collect()
implementations.iter().map(|entry| &entry.io.call_argument).collect()
} else if let Some(impls) = extended_node_registry.get(id) {
impls.keys().map(|io| &io.call_argument).collect()
impls.iter().map(|entry| &entry.io.call_argument).collect()
} else {
Vec::new()
};
@@ -74,7 +73,8 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
context_features: ContextDependencies::from(context_features.as_slice()),
// Context features are resolved from the registry at compile time, not persisted on the node
context_features: ContextDependencies::default(),
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
@@ -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, StrokeAlign, StrokeCap, StrokeJoin,
build_transform_with_y_preservation,
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintOrder, StrokeAlign, StrokeCap,
StrokeJoin, build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{NodeParameter, ParameterRef};
@@ -284,9 +284,10 @@ pub(crate) fn property_from_type(
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),
// A leveled f64 arrives peeled to its element, so only a genuinely list-typed input reaches this arm
Some(x) if id_is::<List<f64>>(x) => array_of_number_widget(default_info, TextInput::default()).into(),
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
// ============
@@ -342,14 +343,10 @@ pub(crate) fn property_from_type(
}
}
}
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,33 +457,6 @@ 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;
@@ -2321,7 +2291,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>();
let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
input_types.sort_by_key(|ty| ty.type_name());
let input_type = input_types.first().cloned();
@@ -2677,6 +2647,8 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
NumberInput::default().min(0.).disabled(miter_limit_disabled),
);
// Our stroke node keeps a paint order input rather than encoding the order by Fill/Stroke node adjacency
let paint_order = enum_choice::<PaintOrder>().for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput, true, context)).property_row();
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
let number_input = disabled_number_input;
@@ -2689,6 +2661,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
cap,
join,
LayoutGroup::row(miter_limit),
paint_order,
LayoutGroup::row(dash_lengths),
LayoutGroup::row(dash_offset),
]
@@ -1,5 +1,10 @@
use graph_craft::document::NodeId;
use graphene_std::{Type, simplify_identifier_name};
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};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
@@ -19,22 +24,20 @@ pub enum FrontendGraphDataType {
impl FrontendGraphDataType {
pub fn from_type(input: &Type) -> Self {
// 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,
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,
},
_ => Self::General,
}
}
@@ -102,6 +105,13 @@ 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 {
@@ -109,7 +119,7 @@ pub struct FrontendNodeType {
pub name: String,
pub category: String,
#[serde(rename = "inputTypes")]
pub input_types: Vec<String>,
pub input_types: Vec<InputTypeConstraint>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -1,9 +1,10 @@
use super::utility_types::{DrawHandles, OverlayContext};
use crate::consts::HIDE_HANDLE_DISTANCE;
use crate::consts::{HIDE_HANDLE_DISTANCE, SNAP_POINT_TOLERANCE};
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};
@@ -132,7 +133,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_layers(document.metadata()) {
for layer in document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface) {
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 {
@@ -201,25 +202,41 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
}
}
pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext) {
/// 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) {
if !overlay_context.visibility_settings.anchors() {
return;
}
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));
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 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);
for layer in selected_nodes.selected_visible_layers(&document.network_interface) {
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);
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);
}
}
// 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] {
@@ -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};
use graph_craft::application_io::resource::{DataSource, LoadResource, Resource, ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
use graphene_std::text::Font;
use std::sync::Arc;
use url::Url;
@@ -49,15 +49,8 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
responses.add(ResourceMessage::Resolve { resource_id });
}
ResourceMessage::ResolveAll => {
// 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();
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();
for id in ids {
if self.pending_resolves.contains(&id) {
continue;
@@ -74,9 +67,7 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
log::error!("Resolve for {resource_id}: no registry entry");
return;
};
// 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 {
if info.hash.is_some_and(|hash| resource_storage.resources_mut().contains(hash)) {
log::warn!("Resource {resource_id} already resolved");
return;
}
@@ -89,7 +80,7 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
.sources
.iter()
.map(|source| match source {
DataSource::Font { family, style } if !data_missing => {
DataSource::Font { family, style } => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
@@ -225,20 +216,16 @@ impl ResourceMessageHandler {
.resolved()
.filter(|info| info.sources.contains(&DataSource::Embedded))
.filter_map(|info| {
let (id, hash) = (info.id, *info.hash?);
let resource = resources_load_handle.load(hash);
Some(async move { (id, hash, resource.await) })
if let Some(hash) = info.hash {
let resource = resources_load_handle.load(*hash);
Some(async move { resource.await.map(|resource| (*hash, resource)) })
} else {
None
}
})
.collect::<Vec<_>>();
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))));
self.embedded = EmbeddedResources::from_iter(futures::future::join_all(embedded).await.into_iter().flatten());
}
pub fn collect_garbage(&mut self, used: &[ResourceId]) {
@@ -318,45 +305,28 @@ 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_data_is_missing() {
fn resolve_all_refetches_resources_whose_bytes_are_missing() {
let mut handler = ResourceMessageHandler::default();
let storage = ResourceStorageMessageHandler::default();
let fonts = FontsMessageHandler::default();
// 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 font = |style: &str| DataSource::Font {
family: "Lato".into(),
style: Some(style.into()),
};
// 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 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)"));
// 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 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)"));
let mut responses = VecDeque::new();
let fonts = FontsMessageHandler::default();
handler.process_message(
ResourceMessage::ResolveAll,
&mut responses,
@@ -368,9 +338,8 @@ mod tests {
);
let resolve_requested = |id: ResourceId| responses.contains(&Message::from(ResourceMessage::Resolve { resource_id: id }));
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");
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");
}
}
@@ -20,6 +20,27 @@ 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_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 mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
document_migration_upgrades(&mut document, reset);
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)> {
@@ -6,7 +6,8 @@ use crate::messages::portfolio::document::utility_types::network_interface::Flow
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
@@ -40,8 +41,12 @@ 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 `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
/// information that lives on the list.
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
/// stroke paint information that lives on the list.
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
}
@@ -231,11 +236,8 @@ impl DocumentMetadata {
/// bounds for non-vector layers (groups, raster, text, color, gradient).
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
if let Some(vector) = self.layer_vector_data.get(&layer) {
let stroke = self
.layer_appearance_attributes
.get(&layer)
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
.map(graphene_std::Coverage::stroke_params);
// The stroke geometry rides the stroke paint list's own attribute columns, the carrier that replaced the deleted `Vector::stroke`.
let stroke = self.layer_stroke_attributes.get(&layer).map(|paint| graphene_std::renderer::stroke_params(paint));
if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) {
return Some(bounds);
}
@@ -40,7 +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::Graphic;
use graphene_std::list::List;
use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad;
use graphene_std::transform::Footprint;
@@ -650,17 +650,6 @@ 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,
@@ -841,6 +841,13 @@ 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,15 +57,26 @@ impl TypeSource {
}
}
/// 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.
/// Whether the compiled type is a packed `Record` lane, as opposed to a bare rank-0 value.
pub fn is_list(&self) -> bool {
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some())
// `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,
}
}
/// The element type with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic.
/// The element type, so semantic type checks can be rank-agnostic.
pub fn compiled_element_type(&self) -> Option<&Type> {
Some(element_of(self.compiled_nested_type()?))
self.compiled_nested_type()
}
/// The identifier name of [`Self::compiled_element_type`].
@@ -109,14 +120,6 @@ 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 {
@@ -191,7 +194,7 @@ impl NodeNetworkInterface {
log::error!("Proto node {node:?} not found in the node registry, in layer_chain_hosts_node");
return false;
};
implementations.keys().any(|node_io| node_io.inputs.first().is_some_and(|content| element_of(content) == element))
implementations.iter().map(|entry| &entry.io).any(|node_io| node_io.inputs.first().is_some_and(|content| content.nested_type() == element))
}
None => !matches!(chain_type, TypeSource::Invalid),
}
@@ -243,18 +246,7 @@ impl NodeNetworkInterface {
}
};
// 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` recurses through `Record` to the element, so a record default already drops to rank 0
TaggedValue::from_type_or_none(&guaranteed_type)
}
@@ -300,8 +292,9 @@ impl NodeNetworkInterface {
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations
.keys()
.filter_map(|node_io| {
.iter()
.filter_map(|entry| {
let node_io = &entry.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);
@@ -340,8 +333,9 @@ impl NodeNetworkInterface {
let valid_output_types = self.valid_output_types(&OutputConnector::primary_output(*node_id), network_path);
implementations
.keys()
.filter_map(|node_io| {
.iter()
.filter_map(|entry| {
let node_io = &entry.io;
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None;
}
@@ -370,7 +364,7 @@ impl NodeNetworkInterface {
log::error!("Protonode {render_node:?} not found in registry");
return Vec::new();
};
implementations.keys().map(|types| types.inputs[1].clone()).collect()
implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
}
}
}
@@ -186,8 +186,13 @@ impl NodeNetworkInterface {
self.document_metadata.layer_vector_data = new_layer_vector_data;
}
/// 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;
/// Update the per-layer `ATTR_FILL` snapshot.
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
}
/// Update the per-layer `ATTR_STROKE` snapshot.
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
}
}
@@ -52,13 +52,7 @@ pub struct SelectedNodes(pub Vec<NodeId>);
impl SelectedNodes {
pub fn layer_visible(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
layer.ancestors(network_interface.document_metadata()).all(|layer| {
if layer != LayerNodeIdentifier::ROOT_PARENT {
network_interface.is_visible(&layer.to_node(), &[])
} else {
true
}
})
network_interface.is_layer_visible(layer)
}
pub fn selected_visible_layers<'a>(&'a self, network_interface: &'a NodeNetworkInterface) -> impl Iterator<Item = LayerNodeIdentifier> + 'a {
@@ -1,7 +1,6 @@
// TODO: Eventually remove this document upgrade code
// This file contains lots of hacky code for upgrading old documents to the new format
use crate::messages::portfolio::document::graph_operation::utility_types::set_stroke_paint_order;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
@@ -10,10 +9,11 @@ use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::{Type, item, list};
use graph_craft::{Type, concrete, descriptor};
use graphene_std::Color;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::list::List;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
@@ -76,25 +76,6 @@ 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 {
@@ -167,7 +148,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
},
NodeReplacement {
node: graphene_std::graphic::item_at_index::IDENTIFIER,
node: graphene_std::graphic::index_elements::IDENTIFIER,
aliases: &[
"graphene_core::graphic_element::IndexNode",
"graphene_core::graphic::IndexNode",
@@ -177,15 +158,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
},
NodeReplacement {
node: graphene_std::graphic::remove_at_index::IDENTIFIER,
node: graphene_std::graphic::omit_element::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode"],
},
NodeReplacement {
@@ -1083,6 +1056,7 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
return true;
}
false
}
@@ -1189,30 +1163,6 @@ 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.
// 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
@@ -1451,6 +1401,34 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
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
@@ -1465,6 +1443,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
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));
@@ -1749,6 +1739,19 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// Master retired the stroke paint order input, encoding the order as coverage list position instead. Ours keeps the
// input and carries it LAST, so a master-era stroke node arrives one input short and is padded with the default order.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 9 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 9), NodeInput::value(TaggedValue::PaintOrder(Default::default()), false), network_path);
}
// Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix. The modern
// shape is also 7 inputs, so this era is identified by its `_spread_method` input at 5 or its optional transform at 6.
let is_pre_transform_split_fill = inputs_count == 7
@@ -1820,12 +1823,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#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)?;
let align_input = NodeInput::value(TaggedValue::StrokeAlign(StrokeAlign::Center), false);
let paint_order_input = NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeAbove), false);
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);
@@ -1834,34 +1838,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[5].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 5), old_inputs[6].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 6), old_inputs[7].clone(), network_path);
// Our stroke node keeps the paint order input, so the dash pair lands at 8 and 9
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), paint_order_input, network_path);
let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone());
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), old_inputs[4].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 9), old_inputs[4].clone(), network_path);
inputs_count = 9;
}
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
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)?;
// A wired paint order input cannot be evaluated statically, so it degrades to the default and leaves its source disconnected
let paint_order = match old_inputs.get(7).and_then(|input| input.as_value()) {
Some(&TaggedValue::PaintOrder(value)) => value,
_ => PaintOrder::StrokeAbove,
};
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);
}
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);
inputs_count = 9;
set_stroke_paint_order(&mut document.network_interface, network_path, *node_id, paint_order);
inputs_count = 10;
}
// A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color,
@@ -1909,7 +1892,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// 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 legacy_no_paint = TaggedValue::TypeDefault(descriptor!(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()) {
@@ -2229,36 +2212,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
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);
@@ -2720,15 +2673,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
// 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();
@@ -2767,7 +2711,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 0),
NodeInput::type_default(item!(graphene_std::vector::Vector), true),
NodeInput::type_default(descriptor!(graphene_std::vector::Vector), true),
network_path,
);
@@ -2817,7 +2761,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.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 matches!(stored_type, Type::List(_)) && !tagged_value.is_no_paint() => {
// Our type defaults name their type rather than carrying a structural rank, so a list-carrying wire is recognized by its name.
TaggedValue::TypeDefault(stored_type) if stored_type.name.contains("list::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,
@@ -2955,11 +2900,15 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Upload Texture"
{
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
// Our `upload_texture` node belongs to the optional wgpu-executor crate rather than to platform_application_io, so the conversion only exists in a GPU build.
#[cfg(feature = "gpu")]
{
let mut node_template = resolve_proto_node_type(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
}
}
}
@@ -2974,7 +2923,8 @@ mod tests {
#[test]
fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
#[cfg(feature = "gpu")]
assert!(resolve_proto_node_type(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER).is_some());
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
@@ -3078,6 +3028,15 @@ mod tests {
}
}
#[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"}}}"#
));
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -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, PersistedState};
use crate::messages::frontend::utility_types::{DocumentInfo, FileFilter, 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::*;
@@ -501,6 +501,10 @@ 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 {
@@ -508,6 +512,10 @@ 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) => {
@@ -652,11 +660,28 @@ 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);
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()],
},
],
});
}
PortfolioMessage::Import => {
// 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::TriggerImport);
// 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()],
}],
});
}
PortfolioMessage::OpenFile { path, content } => {
let name = path.file_stem().map(|n| n.to_string_lossy().to_string());
@@ -93,6 +93,7 @@ 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,11 +48,6 @@ 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 {
@@ -682,7 +682,10 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
Some(TaggedValue::F64(value)) => *value,
_ => 4.,
};
let paint_order = get_stroke_paint_order(layer, network_interface);
let paint_order = match parameters.value(stroke::PaintOrderInput) {
Some(TaggedValue::PaintOrder(value)) => *value,
_ => PaintOrder::default(),
};
let dash_lengths = match parameters.value(stroke::DashPatternInput) {
Some(TaggedValue::DashPattern(lengths)) => lengths.clone(),
_ => Vec::new(),
@@ -708,64 +711,16 @@ 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.
/// Whether the paint order can act on the layer: it rides the Stroke node's paint order input, so any layer with a Stroke node qualifies.
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)
get_stroke_id(layer, network_interface).is_some()
}
/// 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.
/// The paint order of a layer's stroke, read from the Stroke node's paint order input rather than from the chain topology.
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,
match NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::PaintOrderInput) {
Some(TaggedValue::PaintOrder(paint_order)) => *paint_order,
_ => PaintOrder::default(),
}
}
@@ -23,6 +23,12 @@ 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>(
@@ -35,19 +41,32 @@ 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 {
let viewspace = document.metadata().transform_to_viewport(layer);
if !document.network_interface.is_layer_visible(layer) {
continue;
}
let viewspace = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
for id in vector.anchor_points() {
if exclude(id) {
continue;
}
for id in candidates(&vector) {
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;
-3
View File
@@ -76,8 +76,6 @@ pub enum ToolMessage {
},
DeactivateTools,
InitTools,
PreUndo,
Redo,
RefreshToolOptions,
RefreshToolShelf,
ResetColors,
@@ -90,7 +88,6 @@ pub enum ToolMessage {
},
ToggleSelectVsPath,
SwapColors,
Undo,
UpdateCursor,
UpdateHints,
UpdateSelectionMode {
@@ -243,18 +243,6 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
responses.add(OverlaysMessage::AddProvider { provider: ARTBOARD_OVERLAY_PROVIDER });
}
ToolMessage::PreUndo => {
let tool_data = &mut self.tool_state.tool_data;
if tool_data.active_tool_type != ToolType::Pen {
responses.add(EventMessage::ToolAbort);
}
}
ToolMessage::Redo => {
let tool_data = &mut self.tool_state.tool_data;
if tool_data.active_tool_type == ToolType::Pen {
responses.add(PenToolMessage::Redo);
}
}
ToolMessage::RefreshToolOptions => {
let tool_data = &mut self.tool_state.tool_data;
@@ -318,12 +306,6 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
document_data.update_working_colors(responses); // TODO: Make this an event
}
ToolMessage::Undo => {
let tool_data = &mut self.tool_state.tool_data;
if tool_data.active_tool_type == ToolType::Pen {
responses.add(PenToolMessage::Undo);
}
}
// Sub-messages
tool_message => {
@@ -390,8 +372,6 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
SelectRandomWorkingColor,
ResetColors,
SwapColors,
Undo,
);
list.extend(self.tool_state.tool_data.active_tool().actions());
list.extend(self.transform_layer_handler.actions());
@@ -574,15 +574,22 @@ mod test_artboard {
use graphene_std::Artboard;
use graphene_std::list::List;
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
/// A leveled wire introspects as its whole legacy list, so each `extend`
/// occurrence yields one list rather than one element.
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard<'_>> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime)
.flatten()
.collect()
let mut artboards = List::new();
for list in instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime) {
for index in 0..list.len() {
if let Some(item) = list.clone_item(index) {
artboards.push(item);
}
}
}
artboards
}
#[derive(Debug, PartialEq)]
@@ -1,27 +1,23 @@
use super::tool_prelude::*;
use crate::consts::DEFAULT_BRUSH_SIZE;
use crate::application::generate_uuid;
use crate::consts::{BRUSH_FLOW_DEFAULT, BRUSH_HARDNESS_DEFAULT, BRUSH_SIZE_DEFAULT};
use crate::messages::portfolio::document::graph_operation::transform_utils::get_current_transform;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, solid};
use graph_craft::document::NodeId;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, OutputConnector};
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, selection_changed_since_last_sync, solid};
use crate::messages::tool::common_functionality::resize::viewport_zoom;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::Color;
use graphene_std::brush::brush_stroke::{BrushInputSample, BrushStroke, BrushStyle};
use graphene_std::NodeParameter;
use graphene_std::brush::basic_brush::basic_brush as active_brush;
use graphene_std::brush::{Channel, Stroke, brush_strokes};
use graphene_std::color::SRGBA8;
use graphene_std::raster::BlendMode;
use graphene_std::vector::style::FillChoice;
const BRUSH_MAX_SIZE: f64 = 5000.;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DrawMode {
Draw = 0,
Erase,
Restore,
}
const SAMPLE_MERGE_DISTANCE: f64 = 1.;
const SAMPLE_MERGE_PRESSURE: f64 = 0.01;
#[derive(Default, ExtractField)]
pub struct BrushTool {
@@ -34,32 +30,41 @@ pub struct BrushOptions {
diameter: f64,
hardness: f64,
flow: f64,
spacing: f64,
color: ToolColorOptions,
blend_mode: BlendMode,
draw_mode: DrawMode,
scale_with_viewport: bool,
last_synced_selection: Vec<LayerNodeIdentifier>,
}
impl Default for BrushOptions {
fn default() -> Self {
Self {
diameter: DEFAULT_BRUSH_SIZE,
hardness: 0.,
flow: 100.,
spacing: 20.,
diameter: BRUSH_SIZE_DEFAULT,
hardness: BRUSH_HARDNESS_DEFAULT,
flow: BRUSH_FLOW_DEFAULT,
color: ToolColorOptions::default(),
blend_mode: BlendMode::Normal,
draw_mode: DrawMode::Draw,
scale_with_viewport: false,
last_synced_selection: Vec::new(),
}
}
}
impl BrushOptions {
fn active_color(&self) -> Color {
self.color.active_color().unwrap_or_default()
}
fn stroke_diameter(&self, document: &DocumentMessageHandler) -> f64 {
if self.scale_with_viewport { self.diameter / viewport_zoom(document) } else { self.diameter }
}
}
#[impl_message(Message, ToolMessage, Brush)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum BrushToolMessage {
// Standard messages
Abort,
SelectionChanged,
WorkingColorChanged,
// Tool-specific messages
@@ -72,14 +77,12 @@ pub enum BrushToolMessage {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum BrushToolMessageOptionsUpdate {
BlendMode(BlendMode),
ChangeDiameter(f64),
Color(Option<Color>),
Diameter(f64),
DrawMode(DrawMode),
Flow(f64),
Hardness(f64),
Spacing(f64),
Flow(f64),
ScaleWithViewport(bool),
WorkingColorsChanged,
}
@@ -104,7 +107,7 @@ impl ToolMetadata for BrushTool {
impl LayoutHolder for BrushTool {
fn layout(&self) -> Layout {
let mut widgets = vec![
let widgets = vec![
ColorInput::new(FillChoice::<SRGBA8>::from(self.options.color.fill_choice.as_ref().unwrap_or(&FillChoice::None)))
.mixed(self.options.color.fill_choice.is_none())
.narrow(true)
@@ -119,9 +122,39 @@ impl LayoutHolder for BrushTool {
NumberInput::new(Some(self.options.diameter))
.label("Diameter")
.min(1.)
.max(BRUSH_MAX_SIZE) /* Anything bigger would cause the application to be unresponsive and eventually die */
.unit(" px")
.on_update(|number_input: &NumberInput| BrushToolMessage::UpdateOptions { options: BrushToolMessageOptionsUpdate::Diameter(number_input.value.unwrap()) }.into())
.on_update(|number_input: &NumberInput| {
BrushToolMessage::UpdateOptions {
options: BrushToolMessageOptionsUpdate::Diameter(number_input.value.unwrap()),
}
.into()
})
.widget_instance(),
PopoverButton::new()
.popover_layout(Layout(vec![LayoutGroup::row({
let scale_with_viewport_label = "Scale with Viewport";
let scale_with_viewport_description = "Automatically scale the brush with viewport zoom.";
let checkbox_id = CheckboxId::new();
vec![
CheckboxInput::new(self.options.scale_with_viewport)
.tooltip_label(scale_with_viewport_label)
.tooltip_description(scale_with_viewport_description)
.for_label(checkbox_id)
.on_update(|checkbox_input: &CheckboxInput| {
BrushToolMessage::UpdateOptions {
options: BrushToolMessageOptionsUpdate::ScaleWithViewport(checkbox_input.checked),
}
.into()
})
.widget_instance(),
TextLabel::new(scale_with_viewport_label)
.tooltip_label(scale_with_viewport_label)
.tooltip_description(scale_with_viewport_description)
.for_checkbox(checkbox_id)
.widget_instance(),
]
})]))
.tooltip_label("Diameter Options")
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(self.options.hardness))
@@ -151,63 +184,8 @@ impl LayoutHolder for BrushTool {
.into()
})
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(self.options.spacing))
.label("Spacing")
.min(1.)
.max(100.)
.mode_range()
.unit("%")
.on_update(|number_input: &NumberInput| {
BrushToolMessage::UpdateOptions {
options: BrushToolMessageOptionsUpdate::Spacing(number_input.value.unwrap()),
}
.into()
})
.widget_instance(),
];
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let draw_mode_entries: Vec<_> = [DrawMode::Draw, DrawMode::Erase, DrawMode::Restore]
.into_iter()
.map(|draw_mode| {
RadioEntryData::new(format!("{draw_mode:?}")).label(format!("{draw_mode:?}")).on_update(move |_| {
BrushToolMessage::UpdateOptions {
options: BrushToolMessageOptionsUpdate::DrawMode(draw_mode),
}
.into()
})
})
.collect();
widgets.push(RadioInput::new(draw_mode_entries).selected_index(Some(self.options.draw_mode as u32)).widget_instance());
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
let blend_mode_entries: Vec<Vec<_>> = BlendMode::list()
.iter()
.map(|section| {
section
.iter()
.map(|blend_mode| {
MenuListEntry::new(format!("{blend_mode:?}")).label(blend_mode.to_string()).on_commit(|_| {
BrushToolMessage::UpdateOptions {
options: BrushToolMessageOptionsUpdate::BlendMode(*blend_mode),
}
.into()
})
})
.collect()
})
.collect();
widgets.push(
DropdownInput::new(blend_mode_entries)
.selected_index(self.options.blend_mode.index_in_list().map(|index| index as u32))
.tooltip_description("The blend mode used with the background when performing a brush stroke. Only used in draw mode.")
.disabled(self.options.draw_mode != DrawMode::Draw)
.widget_instance(),
);
Layout(vec![LayoutGroup::row(widgets)])
}
}
@@ -215,12 +193,18 @@ impl LayoutHolder for BrushTool {
#[message_handler_data]
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for BrushTool {
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
if matches!(&message, ToolMessage::Brush(BrushToolMessage::SelectionChanged)) {
if self.fsm_state == BrushToolFsmState::Ready && selection_changed_since_last_sync(&mut self.options.last_synced_selection, context.document) {
self.sync_options_from_selection(context.document, responses);
}
return;
}
let ToolMessage::Brush(BrushToolMessage::UpdateOptions { options }) = message else {
self.fsm_state.process_event(message, &mut self.data, context, &self.options, responses, true);
return;
};
match options {
BrushToolMessageOptionsUpdate::BlendMode(blend_mode) => self.options.blend_mode = blend_mode,
BrushToolMessageOptionsUpdate::ChangeDiameter(change) => {
let needs_rounding = ((self.options.diameter + change.abs() / 2.) % change.abs() - change.abs() / 2.).abs() > 0.5;
if needs_rounding && change > 0. {
@@ -234,16 +218,14 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Brus
self.send_layout(responses, LayoutTarget::ToolOptions);
}
BrushToolMessageOptionsUpdate::Diameter(diameter) => self.options.diameter = diameter,
BrushToolMessageOptionsUpdate::DrawMode(draw_mode) => self.options.draw_mode = draw_mode,
BrushToolMessageOptionsUpdate::Hardness(hardness) => self.options.hardness = hardness,
BrushToolMessageOptionsUpdate::Flow(flow) => self.options.flow = flow,
BrushToolMessageOptionsUpdate::Spacing(spacing) => self.options.spacing = spacing,
BrushToolMessageOptionsUpdate::Color(color) => {
// User picked a color: push to the global primary working color (no tool-local customization).
if let Some(color) = color {
responses.add(ToolMessage::SelectWorkingColor { color, primary: true });
}
}
BrushToolMessageOptionsUpdate::ScaleWithViewport(scale_with_viewport) => self.options.scale_with_viewport = scale_with_viewport,
BrushToolMessageOptionsUpdate::WorkingColorsChanged => {
self.options.color.fill_choice = Some(solid(context.global_tool_data.primary_color));
}
@@ -273,30 +255,111 @@ impl ToolTransition for BrushTool {
fn event_to_message_map(&self) -> EventToMessageMap {
EventToMessageMap {
tool_abort: Some(BrushToolMessage::Abort.into()),
selection_changed: Some(BrushToolMessage::SelectionChanged.into()),
working_color_changed: Some(BrushToolMessage::WorkingColorChanged.into()),
..Default::default()
}
}
}
impl BrushTool {
fn sync_options_from_selection(&mut self, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let Some(strokes_node) = selected_strokes_node(document) else { return };
let Some(node) = document.network_interface.document_network().nodes.get(&strokes_node) else {
return;
};
let value = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
if let Some(TaggedValue::F64(diameter)) = value(brush_strokes::DiameterInput::INDEX) {
self.options.diameter = if self.options.scale_with_viewport { *diameter * viewport_zoom(document) } else { *diameter };
}
if let Some(TaggedValue::F64(hardness)) = value(brush_strokes::HardnessInput::INDEX) {
self.options.hardness = *hardness;
}
if let Some(TaggedValue::F64(flow)) = value(brush_strokes::FlowInput::INDEX) {
self.options.flow = *flow;
}
if let Some(TaggedValue::Color(color)) = value(brush_strokes::ColorInput::INDEX)
&& *color != self.options.active_color()
{
responses.add(ToolMessage::SelectWorkingColor { color: *color, primary: true });
} else {
self.send_layout(responses, LayoutTarget::ToolOptions);
}
}
}
#[derive(Clone, Debug, Default)]
struct BrushToolData {
strokes: Vec<BrushStroke>,
stroke: Stroke,
stroke_node_id: Option<NodeId>,
strokes_before: Vec<Stroke>,
layer: Option<LayerNodeIdentifier>,
transform: DAffine2,
last_sample: (DVec2, Option<f64>),
}
enum BrushTarget {
Existing { strokes_node_id: NodeId, strokes: Vec<Stroke> },
NewGroup { parent: LayerNodeIdentifier, insert_index: usize },
FillEmpty { layer: LayerNodeIdentifier },
}
impl BrushToolData {
fn load_existing_strokes(&mut self, document: &DocumentMessageHandler) -> Option<LayerNodeIdentifier> {
fn resolve_target(&mut self, document: &DocumentMessageHandler, options: &BrushOptions) -> Option<(LayerNodeIdentifier, BrushTarget)> {
self.layer = None;
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
let selected_layer = selected_layers.next().filter(|_| selected_layers.next().is_none())?;
if self.load_brush_layer(document, selected_layer) {
return Some((
selected_layer,
BrushTarget::NewGroup {
parent: selected_layer,
insert_index: 0,
},
));
}
let parent = selected_layer.parent(document.metadata()).filter(|&parent| parent != LayerNodeIdentifier::ROOT_PARENT)?;
let brush_layer = parent
.ancestors(document.metadata())
.take_while(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT)
.find(|&ancestor| self.load_brush_layer(document, ancestor))?;
let Some(output) = document.network_interface.upstream_output_connector(&InputConnector::node_at_index(selected_layer.to_node(), 1), &[]) else {
return Some((brush_layer, BrushTarget::FillEmpty { layer: selected_layer }));
};
let new_group = || {
let insert_index = parent.children(document.metadata()).position(|child| child == selected_layer).unwrap_or_default();
BrushTarget::NewGroup { parent, insert_index }
};
let OutputConnector::Node { node_id: strokes_node_id, .. } = output else {
return Some((brush_layer, new_group()));
};
if document.network_interface.reference(&strokes_node_id, &[]) != Some(DefinitionIdentifier::ProtoNode(brush_strokes::IDENTIFIER)) {
return Some((brush_layer, new_group()));
}
let strokes = document
.network_interface
.document_network()
.nodes
.get(&strokes_node_id)
.and_then(|node| node.inputs.get(brush_strokes::StrokesInput::INDEX))
.and_then(|input| input.as_value())
.and_then(|value| if let TaggedValue::Strokes(strokes) = value { Some(strokes.clone()) } else { None });
match strokes {
Some(strokes) if Self::style_matches(document, strokes_node_id, options) => Some((brush_layer, BrushTarget::Existing { strokes_node_id, strokes })),
_ => Some((brush_layer, new_group())),
}
}
fn load_brush_layer(&mut self, document: &DocumentMessageHandler, candidate: LayerNodeIdentifier) -> bool {
self.transform = DAffine2::IDENTITY;
if document.network_interface.selected_nodes().selected_layers(document.metadata()).count() != 1 {
return None;
}
let layer = document.network_interface.selected_nodes().selected_layers(document.metadata()).next()?;
self.layer = Some(layer);
for node_id in document.network_interface.upstream_flow_back_from_nodes(vec![layer.to_node()], &[], FlowType::HorizontalFlow) {
for node_id in document.network_interface.upstream_flow_back_from_nodes(vec![candidate.to_node()], &[], FlowType::HorizontalFlow) {
let Some(node) = document.network_interface.document_network().nodes.get(&node_id) else {
continue;
};
@@ -304,12 +367,9 @@ impl BrushToolData {
continue;
};
if reference == DefinitionIdentifier::ProtoNode(graphene_std::brush::brush::brush::IDENTIFIER) && node_id != layer.to_node() {
let points_input = node.inputs.get(1)?;
let Some(TaggedValue::BrushStrokes(strokes)) = points_input.as_value() else { continue };
self.strokes = strokes.clone();
return Some(layer);
if reference == DefinitionIdentifier::ProtoNode(active_brush::IDENTIFIER) && node_id != candidate.to_node() {
self.layer = Some(candidate);
return true;
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER) {
@@ -318,13 +378,41 @@ impl BrushToolData {
}
self.transform = DAffine2::IDENTITY;
None
false
}
fn update_strokes(&self, responses: &mut VecDeque<Message>) {
let Some(layer) = self.layer else { return };
let strokes = self.strokes.clone();
responses.add(GraphOperationMessage::Brush { layer, strokes });
fn style_matches(document: &DocumentMessageHandler, strokes_node: NodeId, options: &BrushOptions) -> bool {
let Some(node) = document.network_interface.document_network().nodes.get(&strokes_node) else {
return false;
};
let value = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
matches!(value(brush_strokes::ColorInput::INDEX), Some(TaggedValue::Color(color)) if *color == options.active_color())
&& matches!(value(brush_strokes::DiameterInput::INDEX), Some(TaggedValue::F64(diameter)) if {
let target = options.stroke_diameter(document);
(*diameter - target).abs() <= diameter.abs().max(target.abs()) * (f64::EPSILON * 8.)
}) && matches!(value(brush_strokes::HardnessInput::INDEX), Some(TaggedValue::F64(hardness)) if *hardness == options.hardness)
&& matches!(value(brush_strokes::FlowInput::INDEX), Some(TaggedValue::F64(flow)) if *flow == options.flow)
}
fn push_sample(&mut self, position: DVec2, pressure: Option<f64>, elapsed_milliseconds: f64) {
self.stroke.position.push(position);
if let Channel::Samples(times) = &mut self.stroke.time {
times.push(elapsed_milliseconds / 1000.);
}
if let Channel::Samples(pressures) = &mut self.stroke.pressure {
pressures.push(pressure.unwrap_or(1.) as f32);
}
}
fn update_stroke(&self, responses: &mut VecDeque<Message>) {
let Some(stroke_node_id) = self.stroke_node_id else { return };
let mut strokes = self.strokes_before.clone();
strokes.push(self.stroke.clone());
responses.add(NodeGraphMessage::SetInputValue {
node_id: stroke_node_id,
input_index: brush_strokes::StrokesInput::INDEX,
value: TaggedValue::Strokes(strokes).into(),
});
}
}
@@ -346,60 +434,96 @@ impl Fsm for BrushToolFsmState {
match (self, event) {
(BrushToolFsmState::Ready, BrushToolMessage::DragStart) => {
responses.add(DocumentMessage::StartTransaction);
let loaded_layer = tool_data.load_existing_strokes(document);
if let Some(layer) = loaded_layer {
let pos = document
.network_interface
.document_metadata()
.downstream_transform_to_viewport(layer)
.inverse()
.transform_point2(input.mouse.position);
let layer_position = tool_data.transform.inverse().transform_point2(pos);
let layer_document_scale = document.metadata().downstream_transform_to_viewport(layer) * tool_data.transform;
// TODO: Also scale it based on the input image ('Background' input).
// TODO: Resizing the input image results in a different brush size from the chosen diameter.
let layer_scale = 0.0001_f64 // Safety against division by zero
.max((layer_document_scale.matrix2 * glam::DVec2::X).length())
.max((layer_document_scale.matrix2 * glam::DVec2::Y).length());
// Start a new stroke with a single sample
let blend_mode = match tool_options.draw_mode {
DrawMode::Draw => tool_options.blend_mode,
DrawMode::Erase => BlendMode::Erase,
DrawMode::Restore => BlendMode::Restore,
};
tool_data.strokes.push(BrushStroke {
trace: vec![BrushInputSample { position: layer_position }],
style: BrushStyle {
color: tool_options.color.active_color().unwrap_or_default(),
diameter: tool_options.diameter / layer_scale,
hardness: tool_options.hardness,
flow: tool_options.flow,
spacing: tool_options.spacing,
blend_mode,
},
});
tool_data.update_strokes(responses);
BrushToolFsmState::Drawing
}
// Create the new layer, wait for the render output to return its transform, and then create the rest of the layer
else {
// A new brush layer needs a graph run before the stroke can start.
let Some((brush_layer, target)) = tool_data.resolve_target(document, tool_options) else {
new_brush_layer(document, responses);
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(DeferMessage::AfterGraphRun {
messages: vec![BrushToolMessage::DragStart.into()],
});
BrushToolFsmState::Ready
return BrushToolFsmState::Ready;
};
let pos = document
.network_interface
.document_metadata()
.downstream_transform_to_viewport(brush_layer)
.inverse()
.transform_point2(input.mouse.position);
let layer_position = tool_data.transform.inverse().transform_point2(pos);
let pressure = input.mouse.pressure;
tool_data.stroke = Stroke {
time: Channel::Samples(Vec::new()),
seed: generate_uuid(),
..Default::default()
};
if pressure.is_some() {
tool_data.stroke.pressure = Channel::Samples(Vec::new());
}
tool_data.push_sample(layer_position, pressure, input.mouse.time.unwrap_or(0.));
tool_data.last_sample = (input.mouse.position, pressure);
match target {
BrushTarget::Existing { strokes_node_id, strokes } => {
tool_data.stroke_node_id = Some(strokes_node_id);
tool_data.strokes_before = strokes;
}
BrushTarget::NewGroup { parent, insert_index } => {
let group_id = NodeId::new();
let strokes_node_id = NodeId::new();
tool_data.stroke_node_id = Some(strokes_node_id);
tool_data.strokes_before = Vec::new();
responses.add(GraphOperationMessage::NewBrushGroupLayer {
id: group_id,
strokes_node_id,
parent,
insert_index,
color: tool_options.active_color(),
diameter: tool_options.stroke_diameter(document),
hardness: tool_options.hardness,
flow: tool_options.flow,
});
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![group_id] });
}
BrushTarget::FillEmpty { layer } => {
let strokes_node_id = NodeId::new();
tool_data.stroke_node_id = Some(strokes_node_id);
tool_data.strokes_before = Vec::new();
responses.add(GraphOperationMessage::NewBrushStrokesNode {
layer,
strokes_node_id,
color: tool_options.active_color(),
diameter: tool_options.stroke_diameter(document),
hardness: tool_options.hardness,
flow: tool_options.flow,
});
}
}
tool_data.update_stroke(responses);
BrushToolFsmState::Drawing
}
(BrushToolFsmState::Drawing, BrushToolMessage::PointerMove) => {
if let Some(layer) = tool_data.layer
&& let Some(stroke) = tool_data.strokes.last_mut()
{
let pressure = input.mouse.pressure;
if pressure == Some(0.) {
return BrushToolFsmState::Drawing;
}
let (last_position, last_pressure) = tool_data.last_sample;
let moved = input.mouse.position.distance(last_position) >= SAMPLE_MERGE_DISTANCE;
let pressure_changed = match (pressure, last_pressure) {
(Some(pressure), Some(last_pressure)) => (pressure - last_pressure).abs() >= SAMPLE_MERGE_PRESSURE,
(pressure, last_pressure) => pressure.is_some() != last_pressure.is_some(),
};
if !moved && !pressure_changed {
return BrushToolFsmState::Drawing;
}
if let Some(layer) = tool_data.layer {
let layer_position = document
.network_interface
.document_metadata()
@@ -408,26 +532,31 @@ impl Fsm for BrushToolFsmState {
.transform_point2(input.mouse.position);
let layer_position = tool_data.transform.inverse().transform_point2(layer_position);
stroke.trace.push(BrushInputSample { position: layer_position })
tool_data.push_sample(layer_position, pressure, input.mouse.time.unwrap_or(0.));
tool_data.last_sample = (input.mouse.position, pressure);
}
tool_data.update_strokes(responses);
tool_data.update_stroke(responses);
BrushToolFsmState::Drawing
}
(BrushToolFsmState::Drawing, BrushToolMessage::DragStop) => {
if !tool_data.strokes.is_empty() {
if tool_data.stroke_node_id.is_some() {
responses.add(DocumentMessage::EndTransaction);
} else {
responses.add(DocumentMessage::AbortTransaction);
}
tool_data.strokes.clear();
tool_data.stroke_node_id = None;
tool_data.stroke = Stroke::default();
tool_data.strokes_before = Vec::new();
BrushToolFsmState::Ready
}
(BrushToolFsmState::Drawing, BrushToolMessage::Abort) => {
responses.add(DocumentMessage::AbortTransaction);
tool_data.strokes.clear();
tool_data.stroke_node_id = None;
tool_data.stroke = Stroke::default();
tool_data.strokes_before = Vec::new();
BrushToolFsmState::Ready
}
@@ -458,12 +587,44 @@ impl Fsm for BrushToolFsmState {
}
}
fn selected_strokes_node(document: &DocumentMessageHandler) -> Option<NodeId> {
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
let selected_layer = selected_layers.next().filter(|_| selected_layers.next().is_none())?;
let group = if is_brush_layer(document, selected_layer) {
selected_layer.children(document.metadata()).next()?
} else {
let parent = selected_layer.parent(document.metadata()).filter(|&parent| parent != LayerNodeIdentifier::ROOT_PARENT)?;
if !parent
.ancestors(document.metadata())
.take_while(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT)
.any(|ancestor| is_brush_layer(document, ancestor))
{
return None;
}
selected_layer
};
let OutputConnector::Node { node_id, .. } = document.network_interface.upstream_output_connector(&InputConnector::node_at_index(group.to_node(), 1), &[])? else {
return None;
};
(document.network_interface.reference(&node_id, &[]) == Some(DefinitionIdentifier::ProtoNode(brush_strokes::IDENTIFIER))).then_some(node_id)
}
fn is_brush_layer(document: &DocumentMessageHandler, candidate: LayerNodeIdentifier) -> bool {
document
.network_interface
.upstream_flow_back_from_nodes(vec![candidate.to_node()], &[], FlowType::HorizontalFlow)
.any(|node_id| node_id != candidate.to_node() && document.network_interface.reference(&node_id, &[]) == Some(DefinitionIdentifier::ProtoNode(active_brush::IDENTIFIER)))
}
fn new_brush_layer(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
responses.add(DocumentMessage::DeselectAllLayers);
let brush_node = resolve_proto_node_type(graphene_std::brush::brush::brush::IDENTIFIER)
let brush_node = resolve_proto_node_type(active_brush::IDENTIFIER)
.expect("Brush node does not exist")
.default_node_template();
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::BrushCache(Default::default()), false))]);
let id = NodeId::new();
responses.add(GraphOperationMessage::NewCustomLayer {
@@ -264,17 +264,20 @@ fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHand
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::list::Item;
use graphene_std::list::List;
use graphene_std::vector::fill;
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
/// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).collect()
instrumented
.grab_all_input::<fill::PaintInput, List<Color>>(&editor.runtime)
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
.collect()
}
#[tokio::test]
@@ -304,8 +307,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element();
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::GREEN));
}
#[tokio::test]
@@ -317,8 +319,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element();
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::YELLOW));
}
#[tokio::test]
@@ -1,6 +1,7 @@
use super::tool_prelude::*;
use crate::consts::SNAP_POINT_TOLERANCE;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::tool::common_functionality::color_selector::{
@@ -10,7 +11,7 @@ use crate::messages::tool::common_functionality::color_selector::{
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::resize::translation_transform_set;
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
use crate::messages::tool::common_functionality::utility_functions::should_extend;
use crate::messages::tool::common_functionality::utility_functions::closest_open_path_endpoint;
use glam::DVec2;
use graph_craft::document::NodeId;
use graphene_std::Color;
@@ -200,6 +201,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Free
FreehandToolFsmState::Ready => actions!(FreehandToolMessageDiscriminant;
DragStart,
DragStop,
PointerMove,
),
FreehandToolFsmState::Drawing => actions!(FreehandToolMessageDiscriminant;
DragStop,
@@ -248,16 +250,20 @@ impl Fsm for FreehandToolFsmState {
let ToolActionMessageContext {
document,
input,
shape_editor,
viewport,
shape_editor,
..
} = tool_action_data;
let ToolMessage::Freehand(event) = event else { return self };
match (self, event) {
(_, FreehandToolMessage::Overlays { context: mut overlay_context }) => {
path_endpoint_overlays(document, shape_editor, &mut overlay_context);
let pointer = (self == FreehandToolFsmState::Ready).then_some(input.mouse.position);
open_path_endpoint_overlays(document, shape_editor, pointer, &mut overlay_context);
self
}
(FreehandToolFsmState::Ready, FreehandToolMessage::PointerMove) => {
responses.add(OverlaysMessage::Draw);
self
}
(FreehandToolFsmState::Ready, FreehandToolMessage::DragStart { append_to_selected }) => {
@@ -267,25 +273,25 @@ impl Fsm for FreehandToolFsmState {
tool_data.end_point = None;
tool_data.new_layer_viewport_start = None;
// Extend an endpoint of the selected path
// Pressing on the endpoint of a selected open path continues that path in place, keeping the layer, its selection, and its style
let selected_nodes = document.network_interface.selected_nodes();
let tolerance = crate::consts::SNAP_POINT_TOLERANCE;
if let Some((layer, point, position)) = should_extend(document, input.mouse.position, tolerance, selected_nodes.selected_layers(document.metadata())) {
let selected_visible_layers = selected_nodes.selected_visible_layers(&document.network_interface);
if let Some((layer, endpoint, position)) = closest_open_path_endpoint(document, input.mouse.position, SNAP_POINT_TOLERANCE, selected_visible_layers) {
tool_data.layer = Some(layer);
tool_data.end_point = Some((position, point));
extend_path_with_next_segment(tool_data, position, true, responses);
tool_data.end_point = Some((position, endpoint));
return FreehandToolFsmState::Drawing;
}
if input.keyboard.key(append_to_selected) {
let mut selected_layers_except_artboards = selected_nodes.selected_layers_except_artboards(&document.network_interface);
let existing_layer = selected_layers_except_artboards.next().filter(|_| selected_layers_except_artboards.next().is_none());
let mut appendable_layers = selected_nodes
.selected_visible_layers(&document.network_interface)
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]));
let existing_layer = appendable_layers.next().filter(|_| appendable_layers.next().is_none());
if let Some(layer) = existing_layer {
tool_data.layer = Some(layer);
let transform = document.metadata().transform_to_viewport(layer);
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
let position = transform.inverse().transform_point2(input.mouse.position);
extend_path_with_next_segment(tool_data, position, false, responses);
@@ -318,7 +324,7 @@ impl Fsm for FreehandToolFsmState {
}
(FreehandToolFsmState::Drawing, FreehandToolMessage::PointerMove) => {
if let Some(layer) = tool_data.layer {
let transform = document.metadata().transform_to_viewport(layer);
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
// For newly created layers, the deferred TransformSet may not yet be reflected
// in the metadata, so compute local position from the known viewport start.
@@ -428,7 +434,7 @@ mod test_freehand {
use crate::messages::tool::common_functionality::stroke_options::StrokeOptionsUpdate;
use crate::messages::tool::tool_messages::freehand_tool::FreehandOptionsUpdate;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, DVec2};
use glam::{DAffine2, DMat2, DVec2};
use graphene_std::vector::Vector;
async fn get_vector_and_transform_list(editor: &mut EditorTestUtils) -> Vec<(Vector, DAffine2)> {
@@ -510,119 +516,6 @@ mod test_freehand {
verify_path_points(&vector_and_transform_list, expected_captured_points, 1.).expect("Path points verification failed");
}
#[tokio::test]
async fn test_extend_existing_path() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let initial_points = [DVec2::new(100., 100.), DVec2::new(200., 200.), DVec2::new(300., 100.)];
editor.select_tool(ToolType::Freehand).await;
let first_point = initial_points[0];
editor.move_mouse(first_point.x, first_point.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(first_point.x, first_point.y, ModifierKeys::empty()).await;
for &point in &initial_points[1..] {
editor.move_mouse(point.x, point.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
}
let last_initial_point = initial_points[initial_points.len() - 1];
editor
.mouseup(
EditorPointerState {
editor_position: last_initial_point,
mouse_keys: MouseKeys::empty(),
..Default::default()
},
ModifierKeys::empty(),
)
.await;
let initial_vector_and_transform_list = get_vector_and_transform_list(&mut editor).await;
assert!(!initial_vector_and_transform_list.is_empty(), "No Vector geometry found after initial drawing");
let (initial_vector, initial_transform) = &initial_vector_and_transform_list[0];
let initial_point_count = initial_vector.point_domain.ids().len();
let initial_segment_count = initial_vector.segment_domain.ids().len();
assert!(initial_point_count >= 2, "Expected at least 2 points in initial path, found {initial_point_count}");
assert_eq!(
initial_segment_count,
initial_point_count - 1,
"Expected {} segments in initial path, found {}",
initial_point_count - 1,
initial_segment_count
);
let endpoints = initial_vector.anchor_endpoints().collect::<Vec<_>>();
assert!(!endpoints.is_empty(), "No extendable points found in the path");
let endpoint_id = endpoints[0];
let endpoint_pos_option = initial_vector.point_domain.position_from_id(endpoint_id);
assert!(endpoint_pos_option.is_some(), "Could not find position for endpoint");
let endpoint_pos = endpoint_pos_option.unwrap();
let endpoint_viewport_pos = initial_transform.transform_point2(endpoint_pos);
assert!(endpoint_viewport_pos.is_finite(), "Endpoint position is not finite");
let extension_points = [DVec2::new(400., 200.), DVec2::new(500., 100.)];
let layer_node_id = {
let document = editor.active_document();
let layer = document.metadata().all_layers().next().unwrap();
layer.to_node()
};
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer_node_id] }).await;
editor.select_tool(ToolType::Freehand).await;
editor.move_mouse(endpoint_viewport_pos.x, endpoint_viewport_pos.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(endpoint_viewport_pos.x, endpoint_viewport_pos.y, ModifierKeys::empty()).await;
for &point in &extension_points {
editor.move_mouse(point.x, point.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
}
let last_extension_point = extension_points[extension_points.len() - 1];
editor
.mouseup(
EditorPointerState {
editor_position: last_extension_point,
mouse_keys: MouseKeys::empty(),
..Default::default()
},
ModifierKeys::empty(),
)
.await;
let extended_vector_and_transform = get_vector_and_transform_list(&mut editor).await;
assert!(!extended_vector_and_transform.is_empty(), "No Vector geometry found after extension");
let (extended_vector, _) = &extended_vector_and_transform[0];
let extended_point_count = extended_vector.point_domain.ids().len();
let extended_segment_count = extended_vector.segment_domain.ids().len();
assert!(
extended_point_count > initial_point_count,
"Expected more points after extension, initial: {initial_point_count}, after extension: {extended_point_count}"
);
assert_eq!(
extended_segment_count,
extended_point_count - 1,
"Expected segments to be one less than points, points: {extended_point_count}, segments: {extended_segment_count}"
);
let layer_count = {
let document = editor.active_document();
document.metadata().all_layers().count()
};
assert_eq!(layer_count, 1, "Expected only one layer after extending path");
}
#[tokio::test]
async fn test_append_to_selected_layer_with_shift() {
let mut editor = EditorTestUtils::create();
@@ -791,4 +684,274 @@ mod test_freehand {
stroke_width.unwrap()
);
}
/// Draws a Freehand stroke through the given viewport positions and returns the layer it created, which the tool leaves selected.
async fn draw_freehand_stroke(editor: &mut EditorTestUtils, points: &[DVec2]) -> LayerNodeIdentifier {
editor.select_tool(ToolType::Freehand).await;
editor.drag_path(points, ModifierKeys::empty()).await;
editor.get_selected_layer().await.expect("The Freehand stroke should create and select a layer")
}
fn layer_count(editor: &EditorTestUtils) -> usize {
editor.active_document().metadata().all_layers().count()
}
fn point_and_segment_counts(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> (usize, usize) {
let vector = editor.active_document().network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry");
(vector.point_domain.ids().len(), vector.segment_domain.ids().len())
}
/// The viewport positions of the layer's anchors, split into the endpoints of its open paths and every other anchor.
fn endpoint_and_other_anchor_viewport_positions(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> (Vec<DVec2>, Vec<DVec2>) {
let document = editor.active_document();
let vector = document.network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry");
let transform = document.metadata().transform_to_viewport(layer);
let endpoints: Vec<_> = vector.anchor_endpoints().collect();
let viewport_position = |id| vector.point_domain.position_from_id(id).map(|position| transform.transform_point2(position));
let endpoint_positions = endpoints.iter().filter_map(|&id| viewport_position(id)).collect();
let other_positions = vector.anchor_points().filter(|id| !endpoints.contains(id)).filter_map(viewport_position).collect();
(endpoint_positions, other_positions)
}
const INITIAL_STROKE: [DVec2; 3] = [DVec2::new(100., 100.), DVec2::new(200., 150.), DVec2::new(300., 100.)];
#[tokio::test]
async fn test_extend_open_path_from_endpoint() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let (initial_point_count, initial_segment_count) = point_and_segment_counts(&editor, layer);
assert_eq!(initial_segment_count, initial_point_count - 1, "The initial stroke should be a single open path");
// Press just inside the snapping tolerance of an endpoint, then keep drawing
let (endpoints, _) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let endpoint = *endpoints.last().expect("The stroke should have endpoints");
let continuation = [endpoint + DVec2::new(2., -2.), DVec2::new(400., 150.), DVec2::new(500., 100.)];
editor.drag_path(&continuation, ModifierKeys::empty()).await;
assert_eq!(layer_count(&editor), 1, "Continuing from an endpoint should not create a new layer");
assert_eq!(editor.get_selected_layer().await, Some(layer), "The selection should be left as it was");
let (point_count, segment_count) = point_and_segment_counts(&editor, layer);
assert_eq!(point_count, initial_point_count + continuation.len() - 1, "Each pointer move after the press should add a point");
assert_eq!(segment_count, point_count - 1, "The continued stroke should form a single open path");
}
#[tokio::test]
async fn test_stroke_away_from_endpoint_creates_new_layer() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let initial_counts = point_and_segment_counts(&editor, layer);
editor.drag_path(&[DVec2::new(100., 300.), DVec2::new(200., 350.), DVec2::new(300., 300.)], ModifierKeys::empty()).await;
assert_eq!(layer_count(&editor), 2, "A stroke starting away from any endpoint should create a new layer");
assert_eq!(point_and_segment_counts(&editor, layer), initial_counts, "The existing path should be untouched");
}
#[tokio::test]
async fn test_middle_anchor_does_not_extend() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Four pointer positions capture three points, so the path has an anchor that is not an endpoint
let layer = draw_freehand_stroke(&mut editor, &[DVec2::new(100., 100.), DVec2::new(200., 150.), DVec2::new(300., 100.), DVec2::new(400., 150.)]).await;
let initial_counts = point_and_segment_counts(&editor, layer);
let (_, other_anchors) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let middle_anchor = *other_anchors.first().expect("The stroke should have an anchor between its endpoints");
editor
.drag_path(&[middle_anchor, middle_anchor + DVec2::new(0., 100.), middle_anchor + DVec2::new(0., 200.)], ModifierKeys::empty())
.await;
assert_eq!(layer_count(&editor), 2, "Only the endpoints of a path should be continued from");
assert_eq!(point_and_segment_counts(&editor, layer), initial_counts, "The existing path should be untouched");
}
#[tokio::test]
async fn test_closed_path_never_extends() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(100., 100., 300., 300.).await;
let rectangle = editor.get_selected_layer().await.expect("The rectangle should be selected");
let (endpoints, corners) = endpoint_and_other_anchor_viewport_positions(&editor, rectangle);
assert!(endpoints.is_empty(), "A closed path has no endpoints");
let corner = *corners.first().expect("The rectangle should have corner anchors");
editor.select_tool(ToolType::Freehand).await;
editor.drag_path(&[corner, corner + DVec2::new(100., 50.), corner + DVec2::new(200., 0.)], ModifierKeys::empty()).await;
assert_eq!(layer_count(&editor), 2, "Pressing on a closed path's anchor should start a new layer");
}
#[tokio::test]
async fn test_extend_after_layer_transform() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let (initial_point_count, _) = point_and_segment_counts(&editor, layer);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale_angle_translation(DVec2::new(1.5, 0.8), 0.3, DVec2::new(40., -25.)),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
let transform = editor.active_document().metadata().transform_to_viewport(layer);
assert!(!transform.matrix2.abs_diff_eq(DMat2::IDENTITY, 1e-6), "The layer should be rotated and scaled");
// Press within tolerance of where an endpoint now sits in the viewport, then keep drawing
let (endpoints, _) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let endpoint = *endpoints.first().expect("The stroke should have endpoints");
let continuation = [endpoint + DVec2::new(-2., 2.), endpoint + DVec2::new(80., 60.), endpoint + DVec2::new(160., 20.)];
editor.drag_path(&continuation, ModifierKeys::empty()).await;
assert_eq!(layer_count(&editor), 1, "Continuing from a transformed layer's endpoint should not create a new layer");
let (point_count, segment_count) = point_and_segment_counts(&editor, layer);
assert_eq!(point_count, initial_point_count + continuation.len() - 1, "Each pointer move after the press should add a point");
assert_eq!(segment_count, point_count - 1, "The continued stroke should form a single open path");
// The new points are stored in the layer's local space, so they should sit under the pointer once transformed back to the viewport
let document = editor.active_document();
let vector = document.network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry");
let transform = document.metadata().transform_to_viewport(layer);
for &pointer_position in &continuation[1..] {
let under_pointer = vector
.point_domain
.positions()
.iter()
.any(|&position| transform.transform_point2(position).distance(pointer_position) < 1.);
assert!(under_pointer, "Expected a point under the pointer at {pointer_position:?}");
}
}
#[tokio::test]
async fn test_endpoint_takes_priority_over_shift_append() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let (initial_point_count, _) = point_and_segment_counts(&editor, layer);
let (endpoints, _) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let endpoint = *endpoints.last().expect("The stroke should have endpoints");
let continuation = [endpoint + DVec2::new(2., 2.), DVec2::new(400., 150.), DVec2::new(500., 100.)];
editor.drag_path(&continuation, ModifierKeys::SHIFT).await;
assert_eq!(layer_count(&editor), 1, "Shift should keep drawing on the selected layer");
// Appending a disconnected subpath would leave the layer with one fewer segment than a single continued path has
let (point_count, segment_count) = point_and_segment_counts(&editor, layer);
assert_eq!(point_count, initial_point_count + continuation.len() - 1, "Each pointer move after the press should add a point");
assert_eq!(segment_count, point_count - 1, "Shift on an endpoint should continue the path rather than append a new subpath");
}
#[tokio::test]
async fn test_press_and_release_on_endpoint_leaves_path_unchanged() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let initial_counts = point_and_segment_counts(&editor, layer);
let (endpoints, _) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let endpoint = *endpoints.last().expect("The stroke should have endpoints");
editor.move_mouse(endpoint.x, endpoint.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(endpoint.x, endpoint.y, ModifierKeys::empty()).await;
editor.left_mouseup(endpoint.x, endpoint.y, ModifierKeys::empty()).await;
assert_eq!(layer_count(&editor), 1, "Releasing without moving should not create a layer");
assert_eq!(point_and_segment_counts(&editor, layer), initial_counts, "Releasing without moving should leave the path unchanged");
}
#[tokio::test]
async fn test_hidden_layer_endpoint_is_not_extended() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let initial_counts = point_and_segment_counts(&editor, layer);
let (endpoints, _) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let endpoint = *endpoints.first().expect("The stroke should have endpoints");
// Where the hidden layer's endpoint would land without its transform
let metadata = editor.active_document().metadata();
let untransformed_endpoint = metadata
.document_to_viewport
.transform_point2(metadata.transform_to_viewport(layer).inverse().transform_point2(endpoint));
editor
.handle_message(NodeGraphMessage::ToggleVisibility {
node_id: layer.to_node(),
network_path: Vec::new(),
})
.await;
assert_eq!(editor.get_selected_layer().await, Some(layer), "Hiding the layer should leave it selected");
editor
.drag_path(&[endpoint + DVec2::new(2., -2.), DVec2::new(400., 150.), DVec2::new(500., 100.)], ModifierKeys::empty())
.await;
assert_eq!(layer_count(&editor), 2, "A stroke at a hidden layer's endpoint should create a new layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor
.drag_path(
&[untransformed_endpoint, untransformed_endpoint + DVec2::new(100., 50.), untransformed_endpoint + DVec2::new(200., 0.)],
ModifierKeys::empty(),
)
.await;
assert_eq!(
layer_count(&editor),
3,
"A stroke where the hidden layer's untransformed endpoint would sit should also create a new layer"
);
editor
.handle_message(NodeGraphMessage::ToggleVisibility {
node_id: layer.to_node(),
network_path: Vec::new(),
})
.await;
assert_eq!(point_and_segment_counts(&editor, layer), initial_counts, "The hidden layer should be untouched");
}
#[tokio::test]
async fn test_locked_layer_endpoint_is_extended() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = draw_freehand_stroke(&mut editor, &INITIAL_STROKE).await;
let (initial_point_count, _) = point_and_segment_counts(&editor, layer);
let (endpoints, _) = endpoint_and_other_anchor_viewport_positions(&editor, layer);
let endpoint = *endpoints.last().expect("The stroke should have endpoints");
editor
.handle_message(NodeGraphMessage::ToggleLocked {
node_id: layer.to_node(),
network_path: Vec::new(),
})
.await;
assert_eq!(editor.get_selected_layer().await, Some(layer), "Locking the layer should leave it selected");
let continuation = [endpoint + DVec2::new(2., -2.), DVec2::new(400., 150.), DVec2::new(500., 100.)];
editor.drag_path(&continuation, ModifierKeys::empty()).await;
// Locking only blocks viewport picking by the Select tool, so a selected locked layer stays editable
assert_eq!(layer_count(&editor), 1, "A selected locked layer's endpoint should still be continued from");
let (point_count, segment_count) = point_and_segment_counts(&editor, layer);
assert_eq!(point_count, initial_point_count + continuation.len() - 1, "Each pointer move after the press should add a point");
assert_eq!(segment_count, point_count - 1, "The continued stroke should form a single open path");
}
}
@@ -1587,7 +1587,7 @@ impl Fsm for PathToolFsmState {
match (self, event) {
(_, PathToolMessage::SelectionChanged) => {
// Set the newly targeted layers to visible
let target_layers = document.network_interface.selected_nodes().selected_layers(document.metadata()).collect();
let target_layers = document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface).collect();
shape_editor.set_selected_layers(target_layers);
@@ -83,8 +83,10 @@ pub enum PenToolMessage {
colinear: Key,
move_anchor_with_handles: Key,
},
Redo,
/// Sent once the document has reverted a history step and the graph has re-evaluated, so an in-progress drawing rewinds to the previous anchor.
Undo,
/// Sent once the document has re-applied a history step and the graph has re-evaluated, so an in-progress drawing advances to the restored anchor.
Redo,
UpdateOptions {
options: PenOptionsUpdate,
},
@@ -287,7 +289,6 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for PenT
fn actions(&self) -> ActionList {
match self.fsm_state {
PenToolFsmState::Ready | PenToolFsmState::GRSHandle => actions!(PenToolMessageDiscriminant;
Undo,
DragStart,
DragStop,
Confirm,
@@ -485,30 +486,6 @@ impl PenToolData {
}
}
/// Re-renders the preview after an undo/redo once the graph has re-evaluated, since the layer transform is
/// briefly stale until then and would place the preview off in the wrong space. Also suppresses the angle
/// modifiers (Ctrl, Shift) still held from the shortcut until each is released and pressed again.
fn refresh_preview_after_history(&mut self, responses: &mut VecDeque<Message>) {
self.suppress_lock_angle = true;
self.suppress_snap_angle = true;
self.modifiers.lock_angle = false;
self.modifiers.snap_angle = false;
self.angle_locked = false;
responses.add(DeferMessage::AfterGraphRun {
messages: vec![
PenToolMessage::PointerMove {
snap_angle: Key::Shift,
break_handle: Key::Alt,
lock_angle: Key::Control,
colinear: Key::KeyC,
move_anchor_with_handles: Key::Space,
}
.into(),
],
});
}
/// Check whether target handle is primary, end, or `self.handle_end`
fn check_end_handle_type(&self, vector: &Vector) -> TargetHandle {
match (self.handle_end, self.prior_segment_endpoint, self.prior_segment, self.path_closed) {
@@ -630,7 +607,7 @@ impl PenToolData {
/// Check whether moving the initially created point.
fn moving_start_point(&self) -> bool {
self.latest_points.len() == 1 && self.latest_point().is_some_and(|point| point.pos == self.next_point)
self.point_index == 0 && self.latest_point().is_some_and(|point| point.pos == self.next_point)
}
// When the vector transform changes, the positions of the points must be recalculated.
@@ -647,6 +624,31 @@ impl PenToolData {
}
}
/// Re-anchors the in-progress preview segment on the current anchor after undo or redo moved it, using the re-evaluated layer transform.
fn resume_preview_from_current_anchor(&mut self, snap_data: SnapData, transform: DAffine2, vector: &Vector, responses: &mut VecDeque<Message>) {
// The segments meeting the current anchor are the ones whose handles the overlays show and the angle lock references
let connected_segments: Vec<SegmentId> = self
.latest_point()
.map(|point| vector.all_connected(point.id).map(|handle| handle.segment).collect())
.unwrap_or_default();
(self.prior_segment, self.prior_segments) = match connected_segments.as_slice() {
[] => (None, None),
[segment] => (Some(*segment), None),
_ => (None, Some(connected_segments)),
};
// Release any engaged angle lock, and ignore the lock-angle and snap-angle keys still held from the shortcut until they are pressed anew
self.angle_locked = false;
self.switch_to_free_on_ctrl_release = false;
self.suppress_lock_angle = true;
self.suppress_snap_angle = true;
self.modifiers.lock_angle = false;
self.modifiers.snap_angle = false;
let mouse = snap_data.input.mouse.position;
self.place_anchor(snap_data, transform, mouse, responses);
}
/// If the user places the anchor on top of the previous anchor, it becomes sharp and the outgoing handle may be dragged.
fn bend_from_previous_point(&mut self, snap_data: SnapData, transform: DAffine2, layer: LayerNodeIdentifier, shape_editor: &mut ShapeState, responses: &mut VecDeque<Message>) {
self.g1_continuous = true;
@@ -735,7 +737,15 @@ impl PenToolData {
false
}
/// Finishes the drag by placing the handle or segment, then closes the history step that the click opened.
fn finish_placing_handle(&mut self, snap_data: SnapData, transform: DAffine2, responses: &mut VecDeque<Message>) -> Option<PenToolFsmState> {
let state = self.place_handle_or_segment(snap_data, transform, responses);
responses.add(DocumentMessage::EndTransaction);
state
}
/// The first drag of a path only records the initial anchor's outgoing handle, and every later drag inserts a segment.
fn place_handle_or_segment(&mut self, snap_data: SnapData, transform: DAffine2, responses: &mut VecDeque<Message>) -> Option<PenToolFsmState> {
let document = snap_data.document;
let next_handle_start = self.next_handle_start;
let handle_start = self.latest_point()?.handle_start;
@@ -744,7 +754,6 @@ impl PenToolData {
self.handle_end_offset = None;
self.handle_start_offset = None;
let Some(handle_end) = self.handle_end else {
responses.add(DocumentMessage::EndTransaction);
self.handle_end = Some(next_handle_start);
self.place_anchor(snap_data, transform, mouse, responses);
self.latest_point_mut()?.handle_start = next_handle_start;
@@ -842,7 +851,6 @@ impl PenToolData {
}
self.path_closed = false;
self.prior_segment_endpoint = None;
responses.add(DocumentMessage::EndTransaction);
Some(if close_subpath { PenToolFsmState::Ready } else { PenToolFsmState::PlacingAnchor })
}
@@ -1926,9 +1934,9 @@ impl Fsm for PenToolFsmState {
tool_data.buffering_merged_vector = false;
PenToolFsmState::DraggingHandle(tool_data.handle_mode)
} else {
if tool_data.handle_end.is_some() {
responses.add(DocumentMessage::StartTransaction);
}
// Each segment placement is its own history step, spanning from this click through the release that finalizes it
responses.add(DocumentMessage::StartTransaction);
// Merge two layers if the point is connected to the end point of another path
// This might not be the correct solution to artboards being included as the other layer,
@@ -1955,7 +1963,7 @@ impl Fsm for PenToolFsmState {
}
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::RemovePreviousHandle) => {
if let Some(last_point) = tool_data.latest_points.last_mut() {
if let Some(last_point) = tool_data.latest_point_mut() {
last_point.handle_start = last_point.pos;
responses.add(OverlaysMessage::Draw);
} else {
@@ -1963,6 +1971,57 @@ impl Fsm for PenToolFsmState {
}
self
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => {
let vector = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer));
let anchor_exists = |point: &LastPoint| vector.as_ref().is_some_and(|vector| vector.point_domain.position_from_id(point.id).is_some());
// Rewind past the anchors the reverted path no longer contains, remembering them so redo can advance back through them
while tool_data.point_index > 0 && !tool_data.latest_point().is_some_and(anchor_exists) {
tool_data.point_index -= 1;
}
// Undoing the initial anchor removed the whole in-progress path, so the drawing is over
let initial_anchor_remains = tool_data.latest_point().is_some_and(anchor_exists);
let Some(vector) = vector.filter(|_| initial_anchor_remains) else {
tool_data.cleanup(responses);
tool_data.cleanup_target_selections(shape_editor, layer, document, responses);
responses.add(OverlaysMessage::Draw);
return PenToolFsmState::Ready;
};
tool_data.resume_preview_from_current_anchor(SnapData::new(document, input, viewport), transform, &vector, responses);
self
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::Redo) => {
let Some(vector) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)) else {
return self;
};
// Advance only through the remembered anchors the re-applied step actually brought back
let anchor_exists = |point: &LastPoint| vector.point_domain.position_from_id(point.id).is_some();
let mut advanced = false;
while tool_data.latest_points.get(tool_data.point_index + 1).is_some_and(anchor_exists) {
tool_data.point_index += 1;
advanced = true;
}
if advanced {
tool_data.resume_preview_from_current_anchor(SnapData::new(document, input, viewport), transform, &vector, responses);
}
self
}
// The history step changed the path beneath the handle being transformed, so cancel the transform (returning to anchor placement) before catching up
(PenToolFsmState::GRSHandle, PenToolMessage::Undo) => {
responses.add(TransformLayerMessage::CancelTransformOperation);
responses.add(PenToolMessage::Undo);
self
}
(PenToolFsmState::GRSHandle, PenToolMessage::Redo) => {
responses.add(TransformLayerMessage::CancelTransformOperation);
responses.add(PenToolMessage::Redo);
self
}
(PenToolFsmState::DraggingHandle(_), PenToolMessage::DragStop) => {
tool_data.cleanup_target_selections(shape_editor, layer, document, responses);
tool_data
@@ -2175,7 +2234,7 @@ impl Fsm for PenToolFsmState {
if let Some((vector, layer)) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)).zip(layer) {
let single_point_in_layer = vector.point_domain.ids().len() == 1;
tool_data.finish_placing_handle(SnapData::new(document, input, viewport), transform, responses);
let latest_points = tool_data.latest_points.len() == 1;
let latest_points = tool_data.point_index == 0;
if latest_points && single_point_in_layer {
responses.add(NodeGraphMessage::DeleteNodes {
@@ -2248,24 +2307,6 @@ impl Fsm for PenToolFsmState {
PenToolFsmState::Ready
}
(_, PenToolMessage::Abort) => PenToolFsmState::Ready,
(PenToolFsmState::DraggingHandle(..) | PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => {
if tool_data.point_index > 0 {
tool_data.point_index -= 1;
tool_data.refresh_preview_after_history(responses);
PenToolFsmState::PlacingAnchor
} else {
responses.add(PenToolMessage::Abort);
self
}
}
(_, PenToolMessage::Redo) => {
tool_data.point_index = (tool_data.point_index + 1).min(tool_data.latest_points.len().saturating_sub(1));
tool_data.refresh_preview_after_history(responses);
match tool_data.point_index {
0 => PenToolFsmState::Ready,
_ => PenToolFsmState::PlacingAnchor,
}
}
_ => self,
}
}
@@ -2336,3 +2377,243 @@ impl Fsm for PenToolFsmState {
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Default });
}
}
#[cfg(test)]
mod test_pen_tool {
use crate::test_utils::test_prelude::*;
use graphene_std::vector::Vector;
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, Vector)> {
let document = editor.active_document();
let path_identifier = DefinitionIdentifier::Network("Path".into());
let mut path_layers = document
.metadata()
.all_layers()
.filter(|&layer| is_layer_fed_by_node_of_name(layer, &document.network_interface, &path_identifier));
let layer = path_layers.next()?;
assert!(path_layers.next().is_none(), "Expected a single path layer");
let vector = document.network_interface.compute_modified_vector(layer).expect("Path layer has no vector");
Some((layer, vector))
}
fn assert_path_shape(editor: &EditorTestUtils, points: usize, segments: usize) {
let (_, vector) = drawn_path(editor).expect("Expected a drawn path");
assert_eq!(vector.point_domain.ids().len(), points, "Unexpected point count");
assert_eq!(vector.segment_domain.ids().len(), segments, "Unexpected segment count");
}
/// Asserts the path's anchors sit at the given viewport positions, in placement order, and that each segment joins consecutive anchors.
fn assert_anchors(editor: &EditorTestUtils, expected: &[DVec2]) {
let (layer, vector) = drawn_path(editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let anchor_ids = vector.point_domain.ids();
assert_eq!(anchor_ids.len(), expected.len(), "Unexpected point count");
for (index, (&id, &expected_position)) in anchor_ids.iter().zip(expected).enumerate() {
let position = layer_to_viewport.transform_point2(vector.point_domain.position_from_id(id).unwrap());
assert!(
position.distance(expected_position) < 1e-6,
"Anchor {index} is at {position:?} but was expected at {expected_position:?}"
);
}
let segment_ids = vector.segment_domain.ids();
assert_eq!(segment_ids.len(), expected.len().saturating_sub(1), "Unexpected segment count");
for (index, &segment) in segment_ids.iter().enumerate() {
assert_eq!(vector.segment_start_from_id(segment), Some(anchor_ids[index]), "Segment {index} does not start at anchor {index}");
assert_eq!(vector.segment_end_from_id(segment), Some(anchor_ids[index + 1]), "Segment {index} does not end at anchor {}", index + 1);
}
}
async fn click_pen(editor: &mut EditorTestUtils, position: DVec2) {
editor.click_tool(ToolType::Pen, MouseKeys::LEFT, position, ModifierKeys::empty()).await;
}
async fn undo(editor: &mut EditorTestUtils) {
editor.handle_message(DocumentMessage::Undo).await;
}
async fn redo(editor: &mut EditorTestUtils) {
editor.handle_message(DocumentMessage::Redo).await;
}
const A: DVec2 = DVec2::new(100., 100.);
const B: DVec2 = DVec2::new(200., 100.);
const C: DVec2 = DVec2::new(200., 200.);
const D: DVec2 = DVec2::new(100., 200.);
#[tokio::test]
async fn each_segment_and_the_closing_click_are_their_own_history_steps() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
click_pen(&mut editor, A).await;
assert_path_shape(&editor, 3, 3);
undo(&mut editor).await;
assert_path_shape(&editor, 3, 2);
undo(&mut editor).await;
assert_path_shape(&editor, 2, 1);
undo(&mut editor).await;
assert_path_shape(&editor, 1, 0);
undo(&mut editor).await;
assert!(drawn_path(&editor).is_none(), "Undoing the initial point should remove the path layer");
for (points, segments) in [(1, 0), (2, 1), (3, 2), (3, 3)] {
redo(&mut editor).await;
assert_path_shape(&editor, points, segments);
}
}
#[tokio::test]
async fn undo_while_drawing_rewinds_one_segment_and_keeps_drawing_from_the_previous_anchor() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
assert_anchors(&editor, &[A, B, C]);
undo(&mut editor).await;
assert_anchors(&editor, &[A, B]);
// The next anchor continues the same path from B, and placing it discards the rewound tail so redo has nothing left to re-apply
click_pen(&mut editor, D).await;
assert_anchors(&editor, &[A, B, D]);
redo(&mut editor).await;
assert_anchors(&editor, &[A, B, D]);
// Rewinding twice in a row walks back one anchor each time
undo(&mut editor).await;
undo(&mut editor).await;
assert_anchors(&editor, &[A]);
click_pen(&mut editor, C).await;
assert_anchors(&editor, &[A, C]);
}
#[tokio::test]
async fn redo_while_drawing_advances_one_segment_and_keeps_drawing_from_the_restored_anchor() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
undo(&mut editor).await;
undo(&mut editor).await;
assert_anchors(&editor, &[A]);
redo(&mut editor).await;
assert_anchors(&editor, &[A, B]);
// Redo with nothing further to re-apply changes nothing
redo(&mut editor).await;
assert_anchors(&editor, &[A, B, C]);
redo(&mut editor).await;
assert_anchors(&editor, &[A, B, C]);
click_pen(&mut editor, D).await;
assert_anchors(&editor, &[A, B, C, D]);
}
#[tokio::test]
async fn undo_of_the_initial_point_ends_the_drawing() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
assert_anchors(&editor, &[A]);
undo(&mut editor).await;
assert!(drawn_path(&editor).is_none(), "Undoing the initial point should remove the path layer");
// The tool is idle again, so the next clicks start a fresh path
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
assert_anchors(&editor, &[B, C]);
}
#[tokio::test]
async fn undo_is_refused_while_a_segment_is_being_placed() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
editor.move_mouse(B.x, B.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(B.x, B.y, ModifierKeys::empty()).await;
undo(&mut editor).await;
assert_anchors(&editor, &[A]);
editor.left_mouseup(B.x, B.y, ModifierKeys::empty()).await;
assert_anchors(&editor, &[A, B]);
undo(&mut editor).await;
assert_anchors(&editor, &[A]);
}
#[tokio::test]
async fn undo_during_a_handle_transform_cancels_the_transform_and_rewinds() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
click_pen(&mut editor, B).await;
// Drag out C's handle so there is one to transform, then start grabbing it
let handle = C + DVec2::new(50., 50.);
editor.move_mouse(C.x, C.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(C.x, C.y, ModifierKeys::empty()).await;
editor.move_mouse(handle.x, handle.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor.left_mouseup(handle.x, handle.y, ModifierKeys::empty()).await;
assert_anchors(&editor, &[A, B, C]);
editor.press(Key::KeyG, ModifierKeys::empty()).await;
assert!(transforming(&editor), "Expected the handle transform to be in progress");
undo(&mut editor).await;
assert!(!transforming(&editor), "Expected the undo to cancel the handle transform");
assert_anchors(&editor, &[A, B]);
click_pen(&mut editor, D).await;
assert_anchors(&editor, &[A, B, D]);
}
fn transforming(editor: &EditorTestUtils) -> bool {
editor.editor.dispatcher.message_handlers.tool_message_handler.transform_layer_handler.is_transforming()
}
#[tokio::test]
async fn modifiers_held_from_the_undo_shortcut_do_not_constrain_the_rewound_preview() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let along_the_line = DVec2::new(300., 100.);
let off_the_line = DVec2::new(300., 200.);
click_pen(&mut editor, A).await;
click_pen(&mut editor, B).await;
click_pen(&mut editor, along_the_line).await;
// Ctrl stays held through the undo, as it does when pressing Ctrl+Z
let key_down = InputPreprocessorMessage::KeyDown {
key: Key::Control,
modifier_keys: ModifierKeys::CONTROL,
key_repeat: false,
};
editor.handle_message(key_down).await;
undo(&mut editor).await;
assert_anchors(&editor, &[A, B]);
// Were the still-held Ctrl treated as lock-angle, this anchor would be projected onto the horizontal line through B
editor.move_mouse(off_the_line.x, off_the_line.y, ModifierKeys::CONTROL, MouseKeys::empty()).await;
editor.left_mousedown(off_the_line.x, off_the_line.y, ModifierKeys::CONTROL).await;
editor.left_mouseup(off_the_line.x, off_the_line.y, ModifierKeys::CONTROL).await;
assert_anchors(&editor, &[A, B, off_the_line]);
}
}
@@ -2,7 +2,7 @@ use super::tool_prelude::*;
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
@@ -306,8 +306,8 @@ impl Fsm for SplineToolFsmState {
let ToolActionMessageContext {
document,
input,
shape_editor,
viewport,
shape_editor,
..
} = tool_action_data;
@@ -315,7 +315,8 @@ impl Fsm for SplineToolFsmState {
match (self, event) {
(_, SplineToolMessage::CanvasTransformed) => self,
(_, SplineToolMessage::Overlays { context: mut overlay_context }) => {
path_endpoint_overlays(document, shape_editor, &mut overlay_context);
let pointer = (self == SplineToolFsmState::Ready).then_some(input.mouse.position);
open_path_endpoint_overlays(document, shape_editor, pointer, &mut overlay_context);
tool_data.snap_manager.draw_overlays(SnapData::new(document, input, viewport), &mut overlay_context);
self
}
@@ -573,7 +574,10 @@ fn try_merging_lastest_endpoint(document: &DocumentMessageHandler, tool_data: &m
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]));
let exclude = |p: PointId| preview_point.is_some_and(|pp| pp == p) || *last_endpoint == p;
let position = document.metadata().transform_to_viewport(current_layer).transform_point2(*last_endpoint_position);
let position = document
.metadata()
.transform_to_viewport_if_feeds(current_layer, &document.network_interface)
.transform_point2(*last_endpoint_position);
let (layer, endpoint, _) = closest_point(document, position, PATH_JOIN_THRESHOLD, layers, exclude)?;
tool_data.merge_layers.insert(layer);
@@ -584,7 +584,7 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
self.mouse_position = input.mouse.position;
}
TransformLayerMessage::SelectionChanged => {
let target_layers = document.network_interface.selected_nodes().selected_layers(document.metadata()).collect();
let target_layers = document.network_interface.selected_nodes().selected_visible_layers(&document.network_interface).collect();
shape_editor.set_selected_layers(target_layers);
}
TransformLayerMessage::TypeBackspace => {
+38 -44
View File
@@ -10,12 +10,11 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, graphic_types};
use graphene_std::{ATTR_TRANSFORM, Context, Graphic};
use graphene_std::{ATTR_TRANSFORM, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -26,7 +25,7 @@ pub use runtime_io::NodeRuntimeIO;
mod runtime;
pub use runtime::*;
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecutionRequest {
execution_id: u64,
render_config: RenderConfig,
@@ -59,6 +58,9 @@ pub struct NodeGraphExecutor {
runtime_io: NodeRuntimeIO,
current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>,
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
/// (sent after an async source completion) finds its context again.
last_execution_context: Option<(u64, ExecutionContext)>,
node_graph_hash: u64,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
@@ -108,6 +110,7 @@ impl NodeGraphExecutor {
let node_executor = Self {
futures: Default::default(),
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
last_execution_context: None,
node_graph_hash: 0,
current_execution_id: 0,
previous_node_to_inspect: Vec::new(),
@@ -375,10 +378,22 @@ impl NodeGraphExecutor {
}
}
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else {
panic!("InvalidGenerationId")
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("front was just matched");
self.last_execution_context = Some((execution_id, execution_context.clone()));
execution_context
} else {
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
match &self.last_execution_context {
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
continue;
}
execution_context.clone()
}
_ => panic!("InvalidGenerationId"),
}
};
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
// TODO: Eventually remove this document upgrade code
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
@@ -697,7 +712,8 @@ impl NodeGraphExecutor {
text_frames,
clip_targets,
vector_data,
appearance_attributes,
fill_attributes,
stroke_attributes,
backgrounds: _,
} = render_output.metadata;
@@ -712,7 +728,8 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
responses.add(DocumentMessage::UpdateFillAttributes { fill_attributes });
responses.add(DocumentMessage::UpdateStrokeAttributes { stroke_attributes });
responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw);
@@ -730,17 +747,13 @@ impl NodeGraphExecutor {
..
} = export_config;
let file_extension = match file_type {
FileType::Svg => "svg",
FileType::Png => "png",
FileType::Jpg => "jpg",
};
let base_name = match (artboard_name, artboard_count) {
(Some(artboard_name), count) if count > 1 => format!("{name} - {artboard_name}"),
_ => name,
};
let name = format!("{base_name}.{file_extension}");
let name = format!("{base_name}.{}", file_type.extension());
let folder = document.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
let filters = vec![file_type.file_filter()];
match node_graph_output {
TaggedValue::RenderOutput(RenderOutput {
@@ -751,6 +764,7 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::TriggerSaveFile {
name,
folder,
filters,
content: svg.into_bytes().into(),
});
} else {
@@ -804,6 +818,7 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::TriggerSaveFile {
name,
folder,
filters,
content: encoded.into(),
});
}
@@ -884,18 +899,9 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
}
// TODO: Eventually remove this document upgrade code
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
/// Extract a monitor node's captured output element.
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
return Some(io.output.clone());
}
None
data.downcast_ref::<T>().cloned()
}
// Re-export for usage by tests in other modules
@@ -911,10 +917,7 @@ mod test {
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::NodeNetwork;
use graphene_std::Context;
use graphene_std::NodeParameter;
use graphene_std::list::Item;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph
@@ -977,24 +980,17 @@ mod test {
instrumented
}
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
/// Pulls a concrete output type out of what the monitor introspects as.
/// Our monitor stores only the context snapshot, so `introspect` recreates the value itself rather than an `IORecord`.
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
Some(x.output.clone())
} else {
None
}
dynamic.downcast_ref::<Output>().cloned()
}
/// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type.
/// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
self.protonodes_by_name
.get(&Input::NODE_IDENTIFIER)
.get(&Input::identifier())
.map_or([].as_slice(), |x| x.as_slice())
.iter()
.filter_map(|inputs| inputs.get(Input::INDEX))
@@ -1011,11 +1007,9 @@ mod test {
}
/// Grabs a ranked input's recorded value as its bare element `Element`.
/// A stored value materializes as an `Item<Element>` wire, so the monitor records the whole cell and this unwraps its element.
/// `introspect` serves a rank-0 input as its element, so no cell unwrapping is needed here.
pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> {
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Item<Element>>(dynamic).map(|item| item.into_element())
self.grab_protonode_input::<Input, Element>(path, runtime)
}
pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(
@@ -1025,7 +1019,7 @@ mod test {
runtime: &NodeRuntime,
) -> Option<Output> {
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
let node = node_graph_layer.upstream_node_id_from_protonode(Input::NODE_IDENTIFIER)?;
let node = node_graph_layer.upstream_node_id_from_protonode(Input::identifier())?;
self.grab_protonode_input::<Input, Output>(&vec![node], runtime)
}
}
+186 -93
View File
@@ -3,25 +3,24 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::concrete;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::list::{Item, List};
use graphene_std::memo::IORecord;
use graphene_std::ops::Convert;
use graphene_std::core_types::gpoll::GPoll;
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode;
use graphene_std::{Artboard, Context, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta};
use graphene_std::{Artboard, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use spin::Mutex;
use std::sync::Arc;
@@ -40,6 +39,9 @@ pub struct NodeRuntime {
editor_preferences: EditorPreferences,
old_graph: Option<NodeNetwork>,
update_thumbnails: bool,
graph_runtime: Arc<DynGraphRuntime>,
/// The last plain render request, replayed when an async source completion marks the graph dirty.
last_render: Option<ExecutionRequest>,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
@@ -119,20 +121,88 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
#[cfg(not(target_family = "wasm"))]
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
pub fn new() -> Self {
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
}
}
#[cfg(not(target_family = "wasm"))]
impl Default for TokioSpawner {
fn default() -> Self {
Self::new()
}
}
#[cfg(not(target_family = "wasm"))]
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
/// [`NodeRuntime`] from one, so shut down in the background instead.
#[cfg(not(target_family = "wasm"))]
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[cfg(target_family = "wasm")]
pub struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl Spawner for WasmSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
wasm_bindgen_futures::spawn_local(task);
false
}
}
impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
#[cfg(not(target_family = "wasm"))]
// The box is a trait object, so `Box::default()` cannot name the concrete spawner.
#[allow(clippy::box_default)]
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
#[cfg(target_family = "wasm")]
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
let mut executor = DynamicExecutor::default();
executor.set_runtime(Arc::clone(&graph_runtime));
Self {
executor: DynamicExecutor::default(),
executor,
receiver,
sender: InternalNodeGraphUpdateSender(sender.clone()),
editor_preferences: EditorPreferences::default(),
old_graph: None,
resources: ResourceRegistry::default(),
update_thumbnails: true,
graph_runtime: Arc::clone(&graph_runtime),
last_render: None,
editor_api: PlatformEditorApi {
editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
runtime: RuntimeHandle(graph_runtime),
#[cfg(not(test))]
application_io: None,
@@ -157,6 +227,11 @@ impl NodeRuntime {
}
}
#[cfg(test)]
pub fn take_dirty(&self) -> bool {
self.executor.take_dirty()
}
pub async fn run(&mut self) -> Option<Texture> {
let mut preferences = None;
let mut graph = None;
@@ -173,6 +248,9 @@ impl NodeRuntime {
}
let for_export = execution_request.render_config.for_export;
if !for_export {
self.last_render = Some(execution_request.clone());
}
execution = Some(request);
@@ -193,6 +271,10 @@ impl NodeRuntime {
eyedropper.render_config.pointer = execution.render_config.pointer;
}
if self.executor.take_dirty() && execution.is_none() {
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
}
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
for request in requests {
@@ -203,11 +285,12 @@ impl NodeRuntime {
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(preferences),
runtime: self.editor_api.runtime.clone(),
}
.into();
if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph).await;
let _ = self.update_network(graph);
}
}
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
@@ -222,7 +305,7 @@ impl NodeRuntime {
self.resources = resources;
self.node_graph_errors.clear();
let result = self.update_network(network).await;
let result = self.update_network(network);
let node_graph_errors = self.node_graph_errors.clone();
self.update_thumbnails = true;
@@ -237,7 +320,7 @@ impl NodeRuntime {
render_config.export_format = ExportFormat::Svg;
}
let result = self.execute_network(render_config).await;
let result = self.execute_network(render_config);
let mut responses = VecDeque::new();
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
if !render_config.for_eyedropper {
@@ -258,10 +341,10 @@ impl NodeRuntime {
.application_io
.as_ref()
.unwrap()
.gpu_executor()
.gpu_executor_arc()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
let (data, width, height) = raster_cpu.to_flat_u8();
@@ -282,10 +365,10 @@ impl NodeRuntime {
.application_io
.as_ref()
.unwrap()
.gpu_executor()
.gpu_executor_arc()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
self.sender.send_eyedropper_preview(raster_cpu);
continue;
@@ -345,7 +428,7 @@ impl NodeRuntime {
None
}
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
@@ -356,7 +439,7 @@ impl NodeRuntime {
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {};
let proto_network = match c.compile_single(scoped_network) {
let proto_network = match c.compile_single(scoped_network, &interpreted_executor::node_registry::NODE_REGISTRY) {
Ok(network) => network,
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
};
@@ -368,20 +451,24 @@ impl NodeRuntime {
.collect::<Vec<_>>();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
self.executor.update(proto_network).await.map_err(|(types, e)| {
self.executor.update(proto_network).map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
})
}
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
use graph_craft::graphene_compiler::Executor;
match self.executor.input_type() {
Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()),
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
Some(t) => Err(format!("Invalid input type {t:?}")),
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
match (&self.executor).execute(render_config).map_err(|e| e.to_string())? {
GPoll::Final(value) | GPoll::Partial(value) => Ok(value),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
Ok(value)
}
GPoll::Pending => Err("Node graph evaluation is pending".to_string()),
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}")),
}
}
@@ -406,66 +493,71 @@ impl NodeRuntime {
continue;
};
// Extract the monitor node's stored `Graphic` data
let Ok(introspected_data) = self.executor.introspect(monitor_node_path) else {
// Read the monitored run directly, inside the introspection window
let thumbnail_renders = &mut self.thumbnail_renders;
let vector_modify = &mut self.vector_modify;
let result = self.executor.introspect_with(monitor_node_path, |layout, batch, _arena| {
use graphene_std::core_types::record::{Group, GroupItem, RunView};
let type_id = layout.element.type_id;
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if type_id == std::any::TypeId::of::<Graphic>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
let group = Graphic::Group(Group { row: None, content: item });
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &group, bounds, responses)
}
Some(())
}
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
// clips content to those rectangles so anything outside isn't visible
else if type_id == std::any::TypeId::of::<Artboard>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Artboard>::new(&item)?;
let bounds = artboard_clip_bounds(&run);
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
}
Some(())
}
// Vector run: vector modifications
else if type_id == std::any::TypeId::of::<Vector>() {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Vector>::new(&item)?;
use graphene_std::core_types::lane::LaneSource;
vector_modify.insert(parent_network_node_id, run.element(0).cloned().unwrap_or_default());
Some(())
}
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if type_id == std::any::TypeId::of::<String>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<String>::new(&item)?;
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
}
Some(())
} else {
log::warn!("Failed to read monitor node output {parent_network_node_id:?}");
Some(())
}
});
if let Err(_error) = result {
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
#[cfg(debug_assertions)]
warn!("Failed to introspect monitor node {}", self.executor.introspect(monitor_node_path).unwrap_err());
continue;
};
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::TextList` content)
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() {
if update_thumbnails {
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
// clips content to those rectangles so anything outside isn't visible
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Artboard>>>() {
if update_thumbnails {
let bounds = artboard_clip_bounds(&io.output);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Vector list: vector modifications
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Vector>>>() {
// Insert the vector modify
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
}
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() {
if update_thumbnails {
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Rank-0 wires record single items; each arm mirrors its list counterpart through a singleton raise
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Graphic>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = graphene_std::renderer::graphic_list_bounding_box(&singleton, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Artboard>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = artboard_clip_bounds(&singleton);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Vector>>>() {
self.vector_modify.insert(parent_network_node_id, io.output.element().clone());
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<String>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = graphene_std::renderer::text_list_bounding_box(&singleton, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
}
// Other
else {
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
warn!("Failed to introspect monitor node {}", _error);
}
}
}
@@ -533,11 +625,12 @@ impl NodeRuntime {
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
fn artboard_clip_bounds<'a, S: graphene_std::core_types::lane::LaneSource<Element = Artboard<'a>>>(artboards: &S) -> RenderBoundingBox {
use graphene_std::core_types::attribute::{Dimensions, Location};
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
for index in 0..artboards.lane_count() {
let location: DVec2 = artboards.attr::<Location>(index);
let dimensions: DVec2 = artboards.attr::<Dimensions>(index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
@@ -566,14 +659,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
[center - half, center + half]
}
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let runtime = NODE_RUNTIME.lock();
if let Some(ref mut runtime) = runtime.as_ref() {
return runtime.executor.introspect(path);
}
Err(IntrospectError::RuntimeNotReady)
}
pub async fn run_node_graph() -> (bool, Option<Texture>) {
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
if let Some(ref mut runtime) = runtime.as_mut() {
@@ -593,12 +678,20 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
}
}
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
let node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &*node_runtime {
node_runtime.graph_runtime.set_notifier(notifier);
}
}
impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi {
application_io: Some(application_io.into()),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
runtime: self.editor_api.runtime.clone(),
}
.into();
}
+21
View File
@@ -51,6 +51,27 @@ impl EditorTestUtils {
}
runtime.run().await;
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
// dispatched, or the editor's type map desyncs permanently.
while runtime.take_dirty() {
let mut superseded_messages = VecDeque::new();
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
for message in superseded_messages {
editor.handle_message(message);
}
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
}
let mut messages = VecDeque::new();
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}"));
Generated
+10 -9
View File
@@ -2,11 +2,11 @@
"nodes": {
"crane": {
"locked": {
"lastModified": 1781825982,
"narHash": "sha256-SlXKwIRIhrOSAcTjCB3ftPLzJWZStQIPS7J1FlZPnKk=",
"lastModified": 1787326676,
"narHash": "sha256-lWhBbBvC05/xwivKBBiM2YNizpmgqCgyOIzomvRuwxs=",
"owner": "ipetkov",
"repo": "crane",
"rev": "469fd08d0bcf6926321fa973c6777fbc87785dd7",
"rev": "692f7e9ef2ece8125b466f66f2af532b3edaed0d",
"type": "github"
},
"original": {
@@ -17,11 +17,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1782723713,
"narHash": "sha256-oPXCU/SSUokcGaJREHibG1CBX3+s/W7orDWQOZDsEeQ=",
"lastModified": 1787900134,
"narHash": "sha256-VYXO0XZlgj06dxJZRhrD3WoSsvq/c7+/Akyoa22pefw=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "b5aa0fbd538984f6e3d201be0005b4463d8b09f8",
"rev": "83199d0d373dd3ac2b9a1996b1d0263f76ab7a4c",
"type": "github"
},
"original": {
@@ -45,11 +45,11 @@
]
},
"locked": {
"lastModified": 1782789458,
"narHash": "sha256-CR55gKCChD9ffN1Ag5az20Z3RD4tylHlcM1SSohkMA8=",
"lastModified": 1788077403,
"narHash": "sha256-c20YZQKzQ27qC6Wh729fWRTpI7oV4+7Ur4icKssD4Wc=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "067959ef838c440558ca519cf08ca87f43c3db3a",
"rev": "89e26eeaafa88a2ede4778734acc794ff0299beb",
"type": "github"
},
"original": {
@@ -62,3 +62,4 @@
"root": "root",
"version": 7
}
+1 -1
View File
@@ -5,7 +5,7 @@
"packages": {
"": {
"name": "graphite-web-frontend",
"license": "Apache-2.0",
"license": "MIT OR Apache-2.0",
"dependencies": {
"source-code-pro": "2.42.0",
"source-sans-pro": "2.45.0"
+1 -1
View File
@@ -35,7 +35,7 @@
"vite": "^8.0.3"
},
"homepage": "https://graphite.art",
"license": "Apache-2.0",
"license": "MIT OR Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/GraphiteEditor/Graphite.git"
@@ -416,11 +416,6 @@
export function setHighlighted(newHighlight: MenuListEntry | undefined) {
highlighted = newHighlight;
// Interactive menus should keep the active entry the same as the highlighted one
// if (interactive && newHighlight?.value !== activeEntry?.value && newHighlight) {
// dispatch("activeEntry", newHighlight);
// }
// Scroll into view
let container = scroller?.div?.();
if (!container || !highlighted) return;
@@ -46,7 +46,7 @@
let matchesRemainingTerms = true;
if (isTypeSearch && typeSearchTerm) {
matchesTypeSearch = node.inputTypes?.some((inputType) => inputType.toLowerCase().includes(typeSearchTerm)) || false;
matchesTypeSearch = node.inputTypes?.some((constraint) => constraint === "All" || constraint.Limited.some((inputType) => inputType.toLowerCase().includes(typeSearchTerm))) || false;
}
if (remainingSearchTerms.length > 0) {
@@ -17,10 +17,11 @@
</script>
<script lang="ts">
import { onMount, onDestroy, afterUpdate, createEventDispatcher, tick } from "svelte";
import { getContext, onMount, onDestroy, afterUpdate, createEventDispatcher, tick } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import { onFloatingMenuOpenChange } from "/src/utility-functions/input";
import { browserVersion } from "/src/utility-functions/platform";
import type { MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { EditorWrapper, MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
const BUTTON_LEFT = 0;
const POINTER_STRAY_DISTANCE = 100;
@@ -42,6 +43,9 @@
export let escapeCloses = true;
export let strayCloses = true;
const editor = getContext<EditorWrapper>("editor");
const menuId = String(Math.random()).substring(2);
let tail: HTMLDivElement | undefined;
let self: HTMLDivElement | undefined;
let floatingMenuContainer: HTMLDivElement | undefined;
@@ -65,6 +69,8 @@
$: watchOpenChange(open);
$: onFloatingMenuOpenChange(menuId, open && type !== "Tooltip" && type !== "Cursor", editor);
$: minWidthStyleValue = measuringOngoing ? "0" : `${Math.max(minWidth, minWidthParentWidth)}px`;
$: displayTail = open && type === "Popover";
$: displayContainer = open || measuringOngoing;
@@ -157,6 +163,7 @@
});
onDestroy(() => {
onFloatingMenuOpenChange(menuId, false, editor);
containerResizeObserver.disconnect();
dialogResizeObserver?.disconnect();
window.removeEventListener("pointermove", pointerMoveHandler);
@@ -15,6 +15,7 @@
import type { MessageBody } from "/src/subscriptions-router";
import { fillChoiceColor, createSRgba8 } from "/src/utility-functions/colors";
import { pasteFile } from "/src/utility-functions/files";
import { cleanupInputField } from "/src/utility-functions/input";
import { textInputCleanup } from "/src/utility-functions/keyboard-entry";
import { rasterizeSVGCanvas } from "/src/utility-functions/rasterization";
import { setupViewportResizeObserver, hasFirstArtworkBeenReceived, markFirstArtworkReceived } from "/src/utility-functions/viewports";
@@ -566,6 +567,7 @@
viewportResizeObserver?.disconnect();
removeUpdatePixelRatio?.();
addedFontFaces.forEach((face) => window.document.fonts.delete(face));
cleanupInputField(editor);
subscriptions.unsubscribeFrontendMessage("UpdateDocumentArtwork");
subscriptions.unsubscribeFrontendMessage("UpdateEyedropperSamplingState");
+1 -2
View File
@@ -895,10 +895,9 @@
height: 100%;
background-size: var(--grid-spacing) var(--grid-spacing);
background-position: calc(var(--grid-offset-x) - var(--grid-dot-radius)) calc(var(--grid-offset-y) - var(--grid-dot-radius));
background-image: radial-gradient(circle at var(--grid-dot-radius) var(--grid-dot-radius), var(--color-3-darkgray) var(--grid-dot-radius), transparent 0);
background-image: radial-gradient(circle at var(--grid-dot-radius) var(--grid-dot-radius), rgb(from var(--color-f-white) r g b / 0.2) var(--grid-dot-radius), transparent 0);
background-repeat: repeat;
image-rendering: pixelated;
mix-blend-mode: screen;
}
}
@@ -74,7 +74,6 @@
if (activeEntrySkipWatcher) {
activeEntrySkipWatcher = false;
} else if (activeEntry !== DASH_ENTRY) {
// We need to set to the initial value first to track a right history step, as if we hover in initial selection.
if (initialSelectedIndex !== undefined) dispatch("hoverInEntry", initialSelectedIndex);
const index = entries.flat().findIndex((entry) => entry.value === activeEntry.value);
if (index !== -1) {
+4 -1
View File
@@ -19,6 +19,7 @@ import {
onContextMenu,
onPaste,
onPointerLockChange,
updateDirectInput,
} from "/src/utility-functions/input";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -42,7 +43,7 @@ const listeners: Listener[] = [
{ target: window, eventName: "mousedown", action: (e: MouseEvent) => onMouseDown(e) },
{ target: window, eventName: "mouseup", action: (e: MouseEvent) => editorWrapper && onPotentialDoubleClick(e, editorWrapper) },
{ target: window, eventName: "wheel", action: (e: WheelEvent) => editorWrapper && onWheelScroll(e, editorWrapper), options: { passive: false } },
{ target: window, eventName: "modifyinputfield", action: (e: CustomEvent) => onModifyInputField(e) },
{ target: window, eventName: "modifyinputfield", action: (e: CustomEvent) => editorWrapper && onModifyInputField(e, editorWrapper) },
{ target: window, eventName: "focusout", action: () => onFocusOut() },
{ target: window.document, eventName: "contextmenu", action: (e: MouseEvent) => onContextMenu(e) },
{ target: window.document, eventName: "fullscreenchange", action: () => fullscreenModeChanged() },
@@ -79,6 +80,8 @@ export function createInputManager(subscriptions: SubscriptionsRouter, editor: E
// Add event bindings for the lifetime of the application
listeners.forEach(({ target, eventName, action, options }) => target.addEventListener(eventName, action, options));
updateDirectInput(editor);
// Focus the app container
const app = window.document.querySelector("[data-app-container]");
if (app instanceof HTMLElement) app.focus();
+5 -6
View File
@@ -3,7 +3,7 @@ import { SvelteMap } from "svelte/reactivity";
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import { downloadFile, downloadFileBlob, upload } from "/src/utility-functions/files";
import { acceptStringFromFilters, downloadFile, downloadFileBlob, upload } from "/src/utility-functions/files";
import { rasterizeSVG } from "/src/utility-functions/rasterization";
import { patchLayout } from "/src/utility-functions/widgets";
import type { EditorWrapper, DocumentInfo, LayerPanelEntry, LayerStructureEntry, Layout, WorkspacePanelLayout } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -93,14 +93,13 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
}
});
subscriptions.subscribeFrontendMessage("TriggerOpen", async () => {
const files = await upload(`image/*,.${editor.fileExtension()},.${editor.gddFileExtension()}`, "data", true);
subscriptions.subscribeFrontendMessage("TriggerOpen", async ({ filters }) => {
const files = await upload(acceptStringFromFilters(filters), "data", true);
files.forEach((file) => editor.openFile(file.filename, file.content));
});
subscriptions.subscribeFrontendMessage("TriggerImport", async () => {
// TODO: Use the same `accept` string as in the `TriggerOpen` handler once importing Graphite documents as nodes is supported
const data = await upload("image/*", "data");
subscriptions.subscribeFrontendMessage("TriggerImport", async ({ filters }) => {
const data = await upload(acceptStringFromFilters(filters), "data");
editor.importFile(data.filename, data.content);
});
+8 -2
View File
@@ -1,5 +1,5 @@
import { extractPixelData } from "/src/utility-functions/rasterization";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { EditorWrapper, FileFilter } from "/wrapper/pkg/graphite_wasm_wrapper";
export function downloadFileURL(filename: string, url: string) {
const element = document.createElement("a");
@@ -91,8 +91,14 @@ export async function pasteFile(item: DataTransferItem, editor: EditorWrapper, m
} else if (file.type.startsWith("image/")) {
const imageData = await extractPixelData(file);
editor.pasteImage(file.name, new Uint8Array(imageData.data), imageData.width, imageData.height, mouse?.[0], mouse?.[1], insertParentId, insertIndex);
} else if (file.name.endsWith("." + editor.fileExtension())) {
} else {
// TODO: When we eventually have sub-documents, this should be changed to import the document as a node instead of opening it in a separate tab
editor.openFile(file.name, await file.bytes());
}
}
export function acceptStringFromFilters(filters: FileFilter[]): string {
const extensions = filters.flatMap((filter) => filter.extensions);
const imageMime = extensions.some((extension) => ["svg", "png", "jpg", "jpeg", "bmp", "gif", "webp", "avif", "tif", "tiff"].includes(extension)) ? ["image/*"] : [];
return [...imageMime, ...extensions.map((extension) => `.${extension}`)].join(",");
}
+49 -6
View File
@@ -20,6 +20,7 @@ let canvasFocused = true;
let inPointerLock = false;
let lastShakeTime = 0;
const shakeSamples: { x: number; y: number; time: number }[] = [];
const openFloatingMenus = new Set<string>();
// Keyboard events
@@ -107,12 +108,19 @@ export async function onKeyUp(e: KeyboardEvent, editor: EditorWrapper, dialogSto
// Pointer events
// On desktop, num lock marks events as observe-only, do not redirect them to the editor.
function isObserveOnly(e: MouseEvent): boolean {
return import.meta.env.MODE === "native" && e.getModifierState("NumLock");
}
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events and these are handled in the backend
export function onPointerMove(e: PointerEvent, editor: EditorWrapper, documentStore: DocumentStore) {
potentiallyRestoreCanvasFocus(e);
if (!e.buttons) viewportPointerInteractionOngoing = false;
if (isObserveOnly(e)) return;
// Don't redirect pointer movement to the backend if there's no ongoing interaction and it's over a floating menu, or the graph overlay, on top of the canvas
// TODO: A better approach is to pass along a boolean to the backend's input preprocessor so it can know if it's being occluded by the GUI.
// TODO: This would allow it to properly decide to act on removing hover focus from something that was hovered in the canvas before moving over the GUI.
@@ -123,13 +131,18 @@ export function onPointerMove(e: PointerEvent, editor: EditorWrapper, documentSt
const modifiers = makeKeyboardModifiersBitfield(e);
if (detectShake(e)) editor.onMouseShake(e.clientX, e.clientY, e.buttons, modifiers);
editor.onMouseMove(e.clientX, e.clientY, e.buttons, modifiers);
const coalesced = e.pointerType === "pen" && typeof e.getCoalescedEvents === "function" ? e.getCoalescedEvents() : [];
const samples = coalesced.length > 0 ? coalesced : [e];
for (const sample of samples) editor.onMouseMove(sample.clientX, sample.clientY, sample.buttons, modifiers, ...pointerAttributes(sample));
}
export function onPointerDown(e: PointerEvent, editor: EditorWrapper, dialogStore: DialogStore) {
potentiallyRestoreCanvasFocus(e);
potentiallyClearTextSelection(e);
if (isObserveOnly(e)) return;
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
const isTargetingCanvas = !inFloatingMenu && e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
const inDialog = e.target instanceof Element && e.target.closest("[data-dialog] [data-floating-menu-content]");
@@ -153,7 +166,7 @@ export function onPointerDown(e: PointerEvent, editor: EditorWrapper, dialogStor
if (viewportPointerInteractionOngoing && isTargetingCanvas instanceof Element) {
const modifiers = makeKeyboardModifiersBitfield(e);
editor.onMouseDown(e.clientX, e.clientY, e.buttons, modifiers);
editor.onMouseDown(e.clientX, e.clientY, e.buttons, modifiers, ...pointerAttributes(e));
}
}
@@ -168,16 +181,16 @@ export function onPointerUp(e: PointerEvent, editor: EditorWrapper) {
if (!e.buttons) viewportPointerInteractionOngoing = false;
if (textToolInteractiveInputElement) return;
if (isObserveOnly(e) || textToolInteractiveInputElement) return;
const modifiers = makeKeyboardModifiersBitfield(e);
editor.onMouseUp(e.clientX, e.clientY, e.buttons, modifiers);
editor.onMouseUp(e.clientX, e.clientY, e.buttons, modifiers, ...pointerAttributes(e));
}
// Mouse events
export function onPotentialDoubleClick(e: MouseEvent, editor: EditorWrapper) {
if (textToolInteractiveInputElement || inPointerLock) return;
if (isObserveOnly(e) || textToolInteractiveInputElement || inPointerLock) return;
// Allow only events within the viewport or node graph boundaries
const isTargetingCanvas = e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
@@ -240,8 +253,14 @@ export function onWheelScroll(e: WheelEvent, editor: EditorWrapper) {
// Receives a custom event dispatched when the user begins interactively editing with the text tool.
// We keep a copy of the text input element to check against when it's active for text entry.
export function onModifyInputField(e: CustomEvent) {
export function onModifyInputField(e: CustomEvent, editor: EditorWrapper) {
textToolInteractiveInputElement = e.detail;
updateDirectInput(editor);
}
export function cleanupInputField(editor: EditorWrapper) {
textToolInteractiveInputElement = undefined;
updateDirectInput(editor);
}
// Window events
@@ -278,6 +297,13 @@ export function onFocusOut() {
canvasFocused = false;
}
function pointerAttributes(e: PointerEvent): [number, number | undefined, number | undefined, number | undefined, number | undefined, number | undefined, boolean] {
const isPen = e.pointerType === "pen";
const eraser = isPen && (e.buttons & 0b10_0000) !== 0; // Pen eraser end is reported as the 32 button bit
return [e.timeStamp, isPen ? e.pressure : undefined, isPen ? e.tiltX : undefined, isPen ? e.tiltY : undefined, isPen ? e.twist : undefined, isPen ? e.tangentialPressure : undefined, eraser];
}
// Keep heuristic and constants in sync with `ShakeTracker` in `desktop/src/input.rs`.
function detectShake(e: PointerEvent | MouseEvent): boolean {
const SENSITIVITY_DIRECTION_CHANGES = 3;
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO = 0.1;
@@ -378,3 +404,20 @@ function potentiallyRestoreCanvasFocus(e: Event) {
app?.focus();
}
}
// Direct input (desktop only)
// Desktop may route viewport pointer input directly to the editor if no floating menus are open
export function updateDirectInput(editor: EditorWrapper) {
if (import.meta.env.MODE !== "native") return;
const uiCapturesViewport = openFloatingMenus.size > 0 || textToolInteractiveInputElement !== undefined;
editor.appWindowDirectInput(!uiCapturesViewport);
}
export function onFloatingMenuOpenChange(menuId: string, open: boolean, editor: EditorWrapper) {
if (open) openFloatingMenus.add(menuId);
else openFloatingMenus.delete(menuId);
updateDirectInput(editor);
}
+2 -2
View File
@@ -40,11 +40,11 @@ export async function loadDemoArtwork(editor: EditorWrapper) {
if (!demoArtwork) return;
try {
const url = new URL(`/demo-artwork/${demoArtwork}.${editor.fileExtension()}`, document.location.href);
const url = new URL(`/demo-artwork/${demoArtwork}.graphite`, document.location.href);
const response = await fetch(url);
if (!response.ok) throw new Error();
const filename = url.pathname.split("/").pop() || `Untitled.${editor.fileExtension()}`;
const filename = url.pathname.split("/").pop() || "Untitled.graphite";
const content = await response.bytes();
editor.openFile(filename, content);
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more