Compare commits

...
Author SHA1 Message Date
Timon b1e872f797 WIP 2026-02-14 23:41:46 +00:00
Timon 88eb489352 WIP 2026-02-13 19:55:30 +00:00
Timon 40b40f9239 WIP 2026-02-13 19:50:13 +00:00
Timon 5bb5b16552 WIP 2026-02-13 16:24:20 +00:00
KulcodeandKeavon Chambers e606efd008 Improve the Gradient tool by visualizing color stops (#3698)
* Gradient

* improvement

* removed unnecessary code

* corrected error

* Partical changes

* Improveded

* remove from advertised actions

* Mousedown

* Partial code review

* changes as per recommendation

* corrected error

* corrected error -2

* changes as per recommendation

* error corrected

* changes as suggested

* Bug Fix

* Fix hints

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-02-13 00:25:15 +00:00
ea68d62ec4 Add gizmos for interacting with the Spiral node (#2851)
* made spiral node

* number of turns in decimal and arc-angle implementation

* logarithmic spiral

* unified log and arc spiral into spiral node

* add spiral shape in shape tool

* fix min value and degree unit

* make it compile

* impl turns handle gizmo

* chore : Refactoring PR #2851 for current code base with some fixes

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
Co-authored-by: Annonnymmousss <[email protected]>
2026-02-12 22:33:40 +00:00
Ayush Amawate cd241095a2 Fix history steps not being given to Line tool endpoint movements (#3739)
start transaction when dragging line endpoints to enable abort
2026-02-12 20:33:19 +00:00
Ayush AmawateandKeavon Chambers 9ae13634d0 Simplify the Layers panel tree structure Rust -> JS encoding (#3744)
* replace custom layer structure encoding with simple JSON tree

* add leftover files

* Renames

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-02-12 20:06:58 +00:00
Jatin Bharti bb6fea95e4 Fix regression preventing the selection of other pivot modes (#3751)
fix : custom pivot's origin selection not updating
2026-02-12 19:10:49 +00:00
Jatin Bharti f4a5c77df8 Fix regression preventing the renaming of graph imports/exports (#3752)
fix : Node Renaming error
2026-02-12 10:42:38 -08:00
Keavon Chambers 1ec75ab213 Add application privacy policy to the website 2026-02-11 19:54:41 -08:00
Timon d2eaa03498 Desktop: Disable more CEF optional features (#3747) 2026-02-11 23:36:34 +00:00
Jatin BhartiandKeavon Chambers a1a9abd6a2 Fix the Gradient tool's linear/radial type toggle resetting the gradient color stops (#3499)
* fix : sync the linear/radial option in menu bar and property panal

* fix : fmt

* Promote vector meshes from experimental by removing it from preferences

* fix : change reverting bug

* chore : refactor

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-02-11 13:49:23 -08:00
Timon 4cdfbb22e8 Desktop: Fix new document offset on first startup (#3738)
Desktop: Fix new document offset
2026-02-11 13:08:17 -08:00
Keavon Chambers 4cda1ddd29 Update student projects list on the website 2026-02-11 01:35:08 -08:00
Timon 9633de5929 Desktop: Push builds to Nix binary cache in CI (#3740)
Desktop: Add Nix Cache
2026-02-09 19:17:14 +00:00
Timon 0f10c242e2 Desktop: Enable manual trigger for Mac and Windows builds (#3736) 2026-02-08 23:39:23 +00:00
Timon 2f5ccad5ea Desktop: Reduce Nix package closure size (#3737) 2026-02-08 21:31:38 +00:00
Timon acab171bc5 Desktop: Build and Sign Mac and Windows Bundles in CI (#3728)
* Desktop: Build and Sign Mac and Windows Bundles in CI

* Desktop: Remove unnecessary CEF files from Windows Bundle

* Desktop: Use a temp file for license generation on Windows to avoid PowerShell modifying stdout
2026-02-06 13:37:07 +00:00
Dennis Kobert 5efa81df85 Store click targets in Arc (#3726) 2026-02-06 12:35:32 +00:00
Dennis Kobert 1a9f0a543c Fix pointer position node (#3725)
Fix PointerPosition traits
2026-02-05 23:43:58 +01:00
Timon 9c56c852ca Desktop: Snap overlays to physical instead of logical pixels (#3493)
WIP
2026-02-04 07:24:16 +00:00
Timon c7e3d01e2b Improve font loading (#3705)
Fix fonts not loading
2026-02-04 07:23:50 +00:00
Dennis KobertandKeavon Chambers 46989438c1 Add merge_group trigger to CI to enable merge queues (#3716)
* Add merge_group trigger to ci to enable merge queues

* Update .github/workflows/build-dev-and-ci.yml

Co-authored-by: Keavon Chambers <[email protected]>

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-02-04 06:07:16 +00:00
Dennis Kobert 3f97ae4c57 Add JSON get node (#3708)
* Add JSON get node

* Return "" on error and print to console
2026-02-03 22:07:46 +00:00
Timon d04def886d Ensure non-negative lengths for stroke dash pattern (#3710)
Caused Vello rendering to fail
2026-02-03 17:19:31 +00:00
Vishnu Tejas 7e436f48f9 Expose the secondary input for Logical And and Or nodes (#3711) 2026-02-03 14:19:23 +00:00
Dennis KobertandTimon f36d455d03 Desktop: Only rerender the UI if it has changed (#3688)
* Only rerender ui if it has changed

* Don't immedeatly request new frame at the end of the event loop

* Request redraw after ui update

* Always request redraw after timeout

* Fix setting control flow in all cases

* Remove comment

---------

Co-authored-by: Timon <[email protected]>
2026-02-03 13:04:44 +00:00
Vishnu TejasandTimon 2e297777a0 Desktop: Support triple-click inputs (#3671)
* Fix triple-click text to select paragraph on desktop

* fixup

---------

Co-authored-by: Timon <[email protected]>
2026-02-03 12:15:08 +00:00
Dennis Kobert 8e8428a572 Add headers input to http nodes (#3709) 2026-02-03 11:47:53 +00:00
KulcodeandKeavon Chambers ba361cdd6a Add "Exclude Layers" Ctrl modifier when dragging to box select in the node graph (#3665)
* Added Ctrl modifier that filters selection to include only child nodes

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-02-02 14:19:43 -08:00
Timon 910fb54c15 Add quantize time nodes (#3703)
add quantize time nodes
2026-02-02 12:55:53 +00:00
Timon 5ace2c9660 Desktop: Use tokio async runtime (#3704)
Use tokio because hyper needs it
2026-02-02 12:49:15 +01:00
Jatin Bharti da518857ad Fix selection jumping back to previously selected node after its drag abort, upon clicking to select a new node (#3696)
* fix : Selection jumps back to previously selected node after its drag abort, upon clicking to select new node

* fix : Selection jumps back to previously selected node after its drag abort via esc key, upon clicking to select new node
2026-01-28 14:36:17 -08:00
Keavon Chambers 390004897b Add "Loop Level" to the Position context reader node (#3679)
* Add "Loop Level" to the Position context reader node

* Remove InjectPosition
2026-01-28 10:52:39 +00:00
Keavon Chambers ea293575e0 Fix inability to click node in catalog, a Svelte 5 regression
Closes #3693
2026-01-27 15:25:56 -08:00
Keavon Chambers 84e9d8c192 Prep for the RC3 release of the desktop app 2026-01-26 17:32:58 -08:00
5fd1a24f16 Desktop: Add Eyedropper tool support with native Vello (#3684)
* mostly done

* fix

* kinda works but tilt and flip broken

* fix footprint

Co-authored-by: James Lindsay <[email protected]>

* Code review

* fix cursor hiding

* Remove console.log

---------

Co-authored-by: James Lindsay <[email protected]>
Co-authored-by: Keavon Chambers <[email protected]>
2026-01-27 01:24:09 +00:00
Keavon Chambers 19e9af3d43 Fix 'Apply Transform' node applying only to anchors but not also handles (#3687) 2026-01-26 12:32:17 -08:00
Keavon Chambers 3488d5b8e7 Fix color picker's broken gradient stop selection due to Svelte 5 not treating components as classes 2026-01-26 11:50:01 -08:00
Timon 5e61d59e50 Desktop: Restart without UI acceleration when it fails on Linux (#3668)
* Desktop: Restart without UI Acceleration when it fails on Linux

* fix spelling
2026-01-26 14:33:09 +00:00
Timon b4e9d7b9eb Desktop: Fix bitmap file export not preserving alpha (#3673)
Fix Export not preserving alpha
2026-01-26 13:51:48 +00:00
c07124332b Fix GPU out-of-memory crash by reusing overlay textures (#3614)
* Refactor TargetTexture into proper abstraction with ensure_size() method

* Remove redundant overlays_texture field, use view() directly

* Use if-let syntax in render_vello_scene_to_target_texture to avoid explicit unwrap

* Implement TargetTexture::new() constructor to avoid dummy textures

* fix compile error

* cleanup

* Avoid cloning texture view

---------

Co-authored-by: Timon <[email protected]>
Co-authored-by: Dennis Kobert <[email protected]>
2026-01-26 12:44:41 +00:00
Keavon Chambers a88342b8da Add the "Rate" multiplier parameter to the Animation Time node (#3685) 2026-01-26 00:37:15 -08:00
Keavon Chambers 568831bd2f Fix regression breaking Into/Convert node type coercion (#3681) 2026-01-25 16:26:05 -08:00
Ayush AmawateandKeavon Chambers ede34b1b9f Fix context menu blocking keyboard input after closing node graph (#3571)
* Fix context menu blocking keyboard input after closing node graph

* Formatting

* move context menu logic to Graph component

* revert editior.svelte to original state

* revert try 2

* fix import order issues

* remove redundant paranthesis

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-24 02:32:05 -08:00
Timon 7a5790744f Add focus document toggle (#3672) 2026-01-23 15:28:02 +00:00
TimonandKeavon Chambers 2be7790d4d Improve UX of importing vs. opening files (#3661)
* wip

* fix drag and drop

* fix

* fix tests

* fix tests

* fix warning

* Partial code review

* add dialog

* fix web

* fix web

* push back release candidate expiry

* Code review

* Reduce code duplication for pasting files in frontend

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-22 01:37:49 -08:00
Keavon Chambers 781fa7ae95 Move contributor docs editor message structure tree generator from test to tools directory (#3663) 2026-01-20 23:53:15 -08:00
Keavon Chambers 7af60e02a3 Add the auto-generated node catalog to the website's user manual (#3662)
* Generate the MVP node catalog in the manual (with some placeholders)

* Implement nearly the rest of everything

* Move to the tools directory and make it generate nicer default values

* Add category descriptions

* Organize file structure and improve type naming

* Improve book table of contents code

* Add collapsing chapter navigation to the book template

* Add to build workflow

* Clean up site structure
2026-01-20 22:52:03 -08:00
Keavon Chambers 5543afd44b Clean up old website code and files (#3658) 2026-01-19 22:09:51 -08:00
TimonandKeavon Chambers 95d3556204 Replace globals with editor environment (#3656)
Co-authored-by: Keavon Chambers <[email protected]>
2026-01-19 17:06:02 +00:00
Timon 07fbcd489c Desktop: Add fullscreen window mode (#3625) 2026-01-19 16:32:03 +00:00
Keavon Chambers fd0addf61c Update website to use Zola 0.22 with new code block syntax highlighting 2026-01-18 00:11:12 -08:00
TimonandKeavon Chambers 00718c5b61 Remove the need for Nix npm dependency hash (#3652)
* Remove the need for nix npmDeps hash

* Use 2.x

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-17 22:22:59 +00:00
Keavon Chambers 2ffb87c9d2 Bump website npm tooling dependencies (#3649) 2026-01-17 16:26:16 +00:00
Keavon Chambers 915a344a05 Bump frontend dependencies to Svelte 5 (#3648)
* Add more recommended VS Code default configs

* Upgrade frontend dependencies including Svelte 5

* Fix derived_references_self runtime error

* Fix lint warnings
2026-01-17 14:31:50 +00:00
Keavon Chambers 3b55064f44 Add tooltip documentation to the Text node and tidy up node catalog categorization (#3645)
* Add more node doc comments

* Tidy up node categories
2026-01-16 01:27:56 -08:00
Adam GerhantandKeavon Chambers c13647aef4 Fix regression where tooltip node descriptions in the graph stopped showing (#3639)
* Fix tooltips

* Convert DefinitionIdentifier to string in JavaScript

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-15 23:30:16 -08:00
Adam GerhantandKeavon Chambers c60ddcf875 Fix the Text node's Max Width/Height parameters with OptionalF64 losing the value when unticked (#3643)
* WIP

* Fix widget

* Fix migration

* Remove OptionalF64

* Custom attributes for optional f64 widget

* Code review

* Move comments to another PR

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-16 06:13:32 +00:00
Timon 73682b482b Desktop: Implement pointer lock for NumberInput (#3638)
* Desktop: Implement pointer lock for NumberInput

* add shift and ctrl modifiers

* fixup
2026-01-15 11:27:31 +00:00
Timon 6616d1bfb1 Desktop: Add commit info to binaries build with Nix (#3635) 2026-01-15 10:34:01 +00:00
Keavon Chambers 39849c9c02 Simplify Svelte component structure in the window subfolder 2026-01-14 19:06:22 -08:00
James LindsayandKeavon Chambers aadc989134 Include path endpoints as extrema in the Extrude node (#3469)
* Include single connected points as extrema in the extrude node

* Update styling of loading indicator

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-14 02:31:18 -08:00
James LindsayandKeavon Chambers c46060db44 Add a Select tool overlay for the layer origin (#3471)
* Add blue layer origin cross overlay

* Apply suggestion from @Keavon

* Skip layers without local transforms

* Disable the Custom Pivot by default

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-14 01:50:03 -08:00
Keavon Chambers 20a595db39 Fix a bug where Transform nodes would cause a reversal of the 'Instance Index' node's 'Loop Level' counting direction 2026-01-13 23:15:42 -08:00
Timon 654a05bb41 Desktop: Build Flatpak in CI (#3633) 2026-01-13 23:46:36 +00:00
JoandKeavon Chambers e3ad59ad9c Add tooltip documentation to web request and brush related nodes (#3427)
* Add tooltip documentation to web request, text, and brush nodes

  - Add descriptive tooltips to web request nodes (GET/POST, string/image conversion, resource loading, image decoding)
  - Add tooltip to GPU rasterization node explaining footprint usage
  - Improve text node tooltip with clearer per_glyph_instances parameter explanation
  - Add tooltips to brush stamp generator and blit operations explaining their internal roles
  - Fix typos in tooltip and variable names (it's→its, perview→preview, instnace→instance)

* Fixed 2 issues with previous changes. Reversed order of documentation about per_glyph_instances. Can it be 3 lines?

* Improve post_request node documentation

Change doc comment to describe the node's purpose rather than focusing
only on the "Discard Result" parameter. Now clearly states this is an
HTTP POST operation with optional async behavior.

* Fix post_request documentation error

Corrected doc comment to say "HTTP POST" instead of "HTTP GET" since
this function performs POST requests with binary data.

* Review changes

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-13 08:35:14 +00:00
Adam GerhantandKeavon Chambers a6052c5819 Replace node definition string-based lookups with DefinitionIdentifier instances (#3451)
* create definition identifier and integrate it

* Bug fixes and code review

* formatting

* Fix migrations

* Fix remove handles migration

* formatting

* Fix test

* Fix tests 2

* fix deserialization

* Code review

* Small fixes

* Consolidate 'Morph' node migrations

* Add old SamplePointsNode name to migrations list

* Fix tests

* Unrelated small fix

* Fix migration crashes

* Fix tests

* Final code review

* fmt

* Add metadata

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-12 23:09:43 -08:00
Vatsal KumarandTimon 4fea2b0fe7 Add an arrow to the Shape tool (#3343)
* add arrow shape feature in editor

Signed-off-by: krVatsal <[email protected]>

* fix the arrow tool to show arrow in viewport space

Signed-off-by: krVatsal <[email protected]>

* fix the direction of arrow and make the new arrow node

Signed-off-by: krVatsal <[email protected]>

* updated arrow tool to hae start and end points

Signed-off-by: krVatsal <[email protected]>

* fixed calculate point bug

Signed-off-by: krVatsal <[email protected]>

* fixed some bugs of arrow positioning

Signed-off-by: krVatsal <[email protected]>

* fixed formatting in whole codebase and added fill to arrow

Signed-off-by: krVatsal <[email protected]>

* fix

---------

Signed-off-by: krVatsal <[email protected]>
Co-authored-by: Timon <[email protected]>
2026-01-12 00:58:28 +00:00
Kulcode 479688d86b Fix integer underflow in Index Points node (#3623)
Fix: Prevent integer underflow in Index Points node
2026-01-11 23:51:55 +00:00
Ayush AmawateandDennis Kobert 5dd11bf138 Ignore out-of-range mouse button values using from_bits_truncate (#3541)
* fix: ignore out-of-range mouse button values using from_bits_truncate

* Apply suggestion from @TrueDoctor

* Fix formatting

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-01-11 22:31:15 +00:00
Ayush AmawateandJames Lindsay 33e3a88458 Fix joining paths from different layers with Ctrl+J fails (#3534)
* fix: handle PointId remapping when joining paths from different layers

When using Ctrl+J to join two points from different layers, the operation
failed because PointIds change during merge due to collision resolution.

The fix uses index-based point tracking instead of PointIds:
1. Before merge: Record the index of each selected point in its layer
2. Calculate post-merge indices using the point offset from layer1
3. After merge: Retrieve the actual PointIds at those indices
4. Create the connecting segment using the resolved PointIds

This works because Vector::concat() preserves point ordering during merge,
so we can use exact index arithmetic to find points after remapping.

Fixes #3519

* fix: use position-based lookup when joining paths from different layers

* fix cmd + g group case

* fix check for grouped folder

* add in the single layer inside a group case

* use ApplyPointDelta instead of creating a dummy segment

* Update editor/src/messages/tool/common_functionality/shape_editor.rs

Co-authored-by: James Lindsay <[email protected]>

* Update editor/src/messages/tool/common_functionality/shape_editor.rs

Co-authored-by: James Lindsay <[email protected]>

* encapsulate point connection logic in defer_connect_points_by_position

* reduce tolerance to 1e-6

* remove wrong comments

---------

Co-authored-by: James Lindsay <[email protected]>
2026-01-11 12:56:48 +00:00
Ayush Amawate d98f19bf4a Add artboard name to the export when exporting a single artboard (#3613)
* add artboard name to the export

* change file name to {docname}-{artboard} for more than 1 arboard

* add switch statement instead of if else
2026-01-11 13:28:19 +01:00
Keavon Chambers 1b91198b28 Fix 'Regular Polygon' and 'Star' shapes incorrectly having cubic handles, not linear (#3606)
Fix shape nodes creating cubic-curved polylines
2026-01-06 20:58:08 -08:00
Keavon Chambers bd847034f3 Bump year references to 2026 2026-01-06 15:12:55 -08:00
Ayush Amawate f808e6d37c Fix freehand tool showing all anchors in overlay (#3585)
Use anchor_endpoints() instead of anchor_points() in path_endpoint_overlays() to only show overlays at true path endpoints, not intermediate points
2026-01-06 20:04:38 +01:00
Ayush Amawate fcf32b3cff Fix PNG exports being off by 1 pixel (#3582)
use round() instead of as_uvec2() while exporting
2026-01-06 13:50:32 +00:00
9cb856eee4 Feature: Add median filter option to blur node (#3196)
* Add median filter option to blur node:

- Add median parameter to blur function for noise reduction
- Implement median_filter_algorithm with efficient quickselect
- Support gamma space calculations for median filtering
- Preserve edges while removing noise, complementing existing blur options

Feature in Issue: #912

* Optimize median filter algorithm by reusing buffers and improving pixel neighborhood collection

* Add median filter option to blur node:

- Add median parameter to blur function for noise reduction
- Implement median_filter_algorithm with efficient quickselect
- Support gamma space calculations for median filtering
- Preserve edges while removing noise, complementing existing blur options

Feature in Issue: #912

* Optimize median filter algorithm by reusing buffers and improving pixel neighborhood collection

* Improve median filter's NaN handling by using total_cmp for safe comparisons

* Add median filter node for noise reduction

- Create dedicated median_filter node separate from blur functionality
- Implement median_filter_algorithm with efficient quickselect
- Support gamma space calculations for consistency
- Use safe NaN handling with f32::total_cmp to prevent panics
- Optimize performance with memory reuse and O(n) median selection

* Refactor median filter to remove gamma handling and simplify algorithm

---------

Co-authored-by: Keavon Chambers <[email protected]>
Co-authored-by: Dennis Kobert <[email protected]>
2026-01-06 14:22:11 +01:00
Dennis Kobert e88db022af Exclude node registry functions from desktop frontend builds (#3584)
* Exclude node registry functions from desktop frontend builds

This reduces compile times and file sizes

* Use early return

* Fix branch name in build-linux pipeline
2026-01-06 12:34:15 +00:00
Keavon Chambers 02e3293e72 Prep for the RC2 release of the desktop app 2026-01-06 04:38:52 +01:00
Timon a42cad8bfb Desktop: Pin the muda crate to commit that includes a necessary dependency update 2026-01-06 04:25:29 +01:00
Keavon Chambers 4f4ec7ffff Add the new AI contribution policy 2026-01-05 17:03:42 -08:00
Timon Schelling 2a59bd50bd Desktop: Capitalize the app directory name on Mac and Windows 2026-01-06 00:46:35 +00:00
Timon cf85ec736f Desktop: Bundle for Linux with Nix (#3569)
bundle for linux with nix
2026-01-06 00:32:55 +00:00
Timon c2a29470c3 Desktop: Fix serde-based document migrations not being applied in non-Wasm environments (#3580)
Desktop: Fix serde based migrations not beeing applied
2026-01-05 23:45:31 +00:00
Timon bd1f7eefdb Desktop: Fix resize helper window Z-order and attach to parent console on Windows (#3572)
* Desktop: Fix helper window zorder on Windows

* Attach to parent console if launched from a terminal

* Workaround for a Windows-specific exception that occurs when `app` is dropped
2026-01-05 23:02:41 +00:00
Dennis KobertandKeavon Chambers fafc687d84 Migrate memo nodes to node macro and make implementing other persistent nodes easier (#3552)
* Add #[data] and #[serialize] attributes to node macro

- Add #[data] attribute for struct fields that aren't node parameters
  - Data fields are initialized with Default::default()
  - Passed as references to the underlying function
  - Excluded from registry metadata (internal state)
  - Generic types in data fields allowed without #[implementations]

- Add #[serialize] attribute for custom Node::serialize() implementation
  - Receives references to all data fields
  - Generates serialize() method in Node trait impl

- Conditional derives based on data field presence
  - With data fields: Debug, Clone only
  - Without data fields: Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash

* Refactor Memo and Monitor Node to use node macro

* Move Complex type into type alias

* Fix format

* Update node-graph/nodes/gcore/src/memo.rs

Co-authored-by: Keavon Chambers <[email protected]>

* Update node-graph/nodes/gcore/src/memo.rs

Co-authored-by: Keavon Chambers <[email protected]>

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-01-05 22:28:02 +01:00
Timon 8f25eb6ca4 Desktop: Fix crash during shutdown caused by clipboard being dropped after the window (#3578)
Desktop: Fix crash during shutdown that was caused by clipboard
2026-01-05 15:38:52 +00:00
Ayush AmawateandDennis Kobert 42440c0d0b Fix rasterize node document leakage with hashmap and eq check (#3550)
* fix: rasterize node document leakage with hashmap and eq check

* Use single Hashmap and ignore source id

* use or_insert_with instead of Entry match

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-01-04 11:33:18 +00:00
Timon ee2e61f38f Provide shaders via artifact repo (#3250)
* raster_nodes_shaders_entrypoint.wgsl upload
2026-01-02 17:17:56 +00:00
James Lindsay 403ab7ba31 Fix math error affecting the linear segment -> polynomial logic (#3562)
Fix typo in the linear segment -> polynomial code
2026-01-02 10:00:02 +00:00
Keavon Chambers 2fa958aa79 Remove generics from the user-facing name for the Vector data type 2026-01-01 21:26:02 -08:00
Keavon Chambers fa45efa9e2 New node: Pointer Position (#3535)
* New node: Pointer Position

* Fix test
2025-12-27 16:02:23 -08:00
Keavon Chambers 4ab75c9c1c Update the website with end-of-year details 2025-12-25 05:45:56 -08:00
0b38beb79b Fix Pen tool anchor point overlays disappearing forever after viewing the node graph (#3523)
* Promote vector meshes from experimental by removing it from preferences

* fix : pen tool anchor point issue with node graph open/close

* fix : Memory allocation by removing .collct()

* fix : remove the reduntant if condition

---------

Co-authored-by: Keavon Chambers <[email protected]>
Co-authored-by: Adesh Gupta <[email protected]>
2025-12-25 05:43:26 -08:00
Keavon Chambers 9f25c50ca1 Prep for the RC1 release of the desktop app 2025-12-24 22:45:08 -08:00
Keavon Chambers 63217feac6 Organize the categories of widget component props 2025-12-23 21:23:13 -08:00
Keavon Chambers 6dea184b03 Update the color of scrollbars to match the latest design 2025-12-23 15:13:12 -08:00
Keavon Chambers 2f880fa035 Fix missing artboard layer icon 2025-12-23 14:43:13 -08:00
Keavon Chambers 415d4b578a Fix markdown tooltips treating Rust type labels as HTML tags
Closes #3520, a regression introduced in #3488.
2025-12-22 15:23:40 -08:00
TimonandKeavon Chambers 11e2882cb2 Desktop: Fix Windows build (#3522)
* fix win build

* fix mac

* Change window button colors to match Windows colors

---------

Co-authored-by: Keavon Chambers <[email protected]>
2025-12-22 14:48:13 -08:00
Keavon Chambers 9d26c040e9 Box the widget: Widget field of WidgetInstance (#3506)
Box the `pub widget: Box<Widget>` field of `WidgetInstance`
2025-12-22 04:18:33 -08:00
James Lindsay 20bbe6cdcc Avoid running cargo audit on forks (#3473)
Don't run the cargo audit nonsense on forks
2025-12-22 11:27:10 +00:00
Keavon Chambers 64ed21f694 Clean up code with better naming 2025-12-21 23:35:00 -08:00
Timon f705d0080d Desktop: Switch to immediate frame present mode on Mac (#3495)
* mac immediate render mode

* fix key modifier flags on mac
2025-12-21 20:14:47 -08:00
Keavon Chambers 123108c813 Promote vector meshes from experimental by removing it from preferences 2025-12-21 19:33:42 -08:00
376 changed files with 10520 additions and 7320 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/f8b02e68c92f5bbd27626bdd7a51102303b70a40.tar.gz
d06fd7b79fa9b7509c23072fa56745415fdc6eb98575d15214b0acc47ea4dd42
https://github.com/Keavon/graphite-branded-assets/archive/f44aa2f362ae4fed8d634878b817a1d3948a7dcb.tar.gz
dffe2b483e491979ef57c320d61446ada5400ef73ff26582976631d9c36efefc
+12 -2
View File
@@ -1,3 +1,13 @@
<!-- Please reference any relevant issue number below, optionally with a "Closes"/"Resolves"/"Fixes" prefix -->
<!--
Graphite has ZERO-TOLERANCE for contributing undisclosed AI-generated content.
If your PR involves AI, you must read our AI contribution policy (it's short):
https://graphite.art/volunteer/guide/starting-a-task/ai-contribution-policy
Closes #
REMEMBER:
- You are responsible for thoroughly testing the successful implementation of your changes and ensuring no obvious regressions occur.
- Egregiously dysfunctional PRs may be assumed to be undisclosed AI slop. If in doubt, ask on Discord before attempting a PR.
- You are highly recommended to include a video showing the before-and-after behavior of your changes and screenshots of any new or modified UI.
- Remember that Graphite maintains high standards for quality and the project is not a classroom for inexperienced developers to gain industry experience.
- In this PR description, reference any relevant tasks by writing "Closes", "Resolves", or "Fixes" with the issue # or the URL of a Discord message documenting the task.
- To acknowledge that you've read this, you must delete these rules and fill in the (strictly human-written) PR description in its place.
-->
+5 -2
View File
@@ -5,6 +5,7 @@ on:
branches:
- master
pull_request: {}
merge_group: {}
env:
CARGO_TERM_COLOR: always
INDEX_HTML_HEAD_REPLACEMENT: <script defer data-domain="dev.graphite.art" data-api="https://graphite.art/visit/event" src="https://graphite.art/visit/script.hash.js"></script>
@@ -113,9 +114,11 @@ jobs:
- name: 📃 Generate code documentation info for website
if: github.ref == 'refs/heads/master'
run: |
cargo test --package graphite-editor --lib -- messages::message::test::generate_message_tree
cd tools/editor-message-tree
cargo run
cd ../..
mkdir -p artifacts-generated
mv hierarchical_message_system_tree.txt artifacts-generated/hierarchical_message_system_tree.txt
mv website/generated/hierarchical_message_system_tree.txt artifacts-generated/hierarchical_message_system_tree.txt
- name: 💿 Obtain cache of auto-generated code docs artifacts, to check if they've changed
if: github.ref == 'refs/heads/master'
+75
View File
@@ -0,0 +1,75 @@
name: Build Linux Bundle
on:
push:
branches:
- master
workflow_dispatch:
inputs:
push_to_cache:
description: "Push to Nix Cache"
required: false
type: boolean
default: false
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
- name: Free disk space
run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache
- name: Build Nix Package
run: nix build .nix --no-link --print-out-paths
- name: Push to Nix Cache
if: github.ref == 'refs/heads/master' || inputs.push_to_cache == true
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .nix --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
- name: Build Linux Bundle
run: nix build .nix#graphite-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
- name: Upload Linux Bundle
uses: actions/upload-artifact@v4
with:
name: graphite-linux-bundle
path: graphite-linux-bundle.tar.xz
compression-level: 0
- name: Setup Flatpak Tooling
run: |
sudo apt-get update
sudo apt-get install -y flatpak flatpak-builder
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
- name: Build Flatpak
run: |
nix build .nix#graphite-flatpak-manifest
rm -rf .flatpak
mkdir -p .flatpak
cp ./result .flatpak/manifest.json
cd .flatpak
mkdir -p repo
flatpak-builder --user --force-clean --install-deps-from=flathub --repo=repo build ./manifest.json
flatpak build-bundle repo graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
- name: Upload Flatpak
uses: actions/upload-artifact@v4
with:
name: graphite-flatpak
path: .flatpak/graphite.flatpak
compression-level: 0
+157
View File
@@ -0,0 +1,157 @@
name: Build Mac Bundle
on:
workflow_dispatch: {}
push:
branches:
- master
jobs:
build:
runs-on: macos-latest
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
rustflags: ""
target: wasm32-unknown-unknown
- name: Cache Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
frontend/package-lock.json
- name: Install Native Dependencies
env:
GITHUB_TOKEN: ${{ github.token }}
BINSTALL_DISABLE_TELEMETRY: "true"
run: |
brew update
brew install \
pkg-config \
openssl@3 \
binaryen \
llvm \
cargo-binstall
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
echo "$(brew --prefix llvm)/bin" >> $GITHUB_PATH
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
- name: Build Mac Bundle
env:
CARGO_TERM_COLOR: always
run: npm run build-desktop
- name: Stage Artifacts
shell: bash
run: |
rm -rf target/artifacts
mkdir -p target/artifacts
cp -R target/release/Graphite.app target/artifacts/Graphite.app
- name: Upload Mac Bundle
uses: actions/upload-artifact@v4
with:
name: graphite-mac-bundle
path: target/artifacts
- name: Sign and Notarize Mac Bundle Preparation
if: github.ref == 'refs/heads/master'
env:
APPLE_CERT_BASE64: ${{ secrets.APPLE_CERT_BASE64 }}
APPLE_CERT_PASSWORD: ${{ secrets.APPLE_CERT_PASSWORD }}
run: |
mkdir -p .sign
echo "$APPLE_CERT_BASE64" | base64 --decode > .sign/certificate.p12
security create-keychain -p "" .sign/main.keychain
security default-keychain -s .sign/main.keychain
security unlock-keychain -p "" .sign/main.keychain
security set-keychain-settings -t 3600 -u .sign/main.keychain
security import .sign/certificate.p12 -k .sign/main.keychain -P "$APPLE_CERT_PASSWORD" -T /usr/bin/codesign -T /usr/bin/productsign
security set-key-partition-list -S apple-tool:,apple: -s -k "" .sign/main.keychain
cat > .sign/entitlements.plist <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-executable-page-protection</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
EOF
- name: Sign and Notarize Mac Bundle
if: github.ref == 'refs/heads/master'
env:
APPLE_EMAIL: ${{ secrets.APPLE_EMAIL }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_CERT_NAME: ${{ secrets.APPLE_CERT_NAME }}
run: |
CERTIFICATE="$APPLE_CERT_NAME"
ENTITLEMENTS=".sign/entitlements.plist"
APP_PATH="target/artifacts/Graphite.app"
ZIP_PATH=".sign/Graphite.zip"
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"
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"
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
spctl -a -vv "$APP_PATH"
- name: Upload Mac Bundle Signed
if: github.ref == 'refs/heads/master'
uses: actions/upload-artifact@v4
with:
name: graphite-mac-bundle-signed
path: target/artifacts
+172
View File
@@ -0,0 +1,172 @@
name: Build Windows Bundle
on:
workflow_dispatch: {}
push:
branches:
- master
permissions:
contents: read
id-token: write
jobs:
build:
runs-on: windows-latest
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
rustflags: ""
target: wasm32-unknown-unknown
- name: Cache Cargo
uses: actions/cache@v4
with:
path: |
${{ env.USERPROFILE }}\.cargo\registry
${{ env.USERPROFILE }}\.cargo\git
target
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
frontend/package-lock.json
- name: Setup Cargo Binstall
uses: cargo-bins/cargo-binstall@main
- name: Install Native Dependencies
shell: pwsh
env:
GITHUB_TOKEN: ${{ github.token }}
BINSTALL_DISABLE_TELEMETRY: "true"
run: |
winget install --id LLVM.LLVM -e --accept-package-agreements --accept-source-agreements
winget install --id Kitware.CMake -e --accept-package-agreements --accept-source-agreements
winget install --id OpenSSL.OpenSSL -e --accept-package-agreements --accept-source-agreements
winget install --id WebAssembly.Binaryen -e --accept-package-agreements --accept-source-agreements
winget install --id GnuWin32.PkgConfig -e --accept-package-agreements --accept-source-agreements
"OPENSSL_DIR=C:\Program Files\OpenSSL-Win64" | Out-File -FilePath $env:GITHUB_ENV -Append
"PKG_CONFIG_PATH=C:\Program Files\OpenSSL-Win64\lib\pkgconfig" | Out-File -FilePath $env:GITHUB_ENV -Append
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
- name: Build Windows Bundle
env:
CARGO_TERM_COLOR: always
run: npm run build-desktop
- name: Stage Artifacts
shell: bash
run: |
rm -rf target/artifacts
mkdir -p target/artifacts
cp -R target/release/Graphite target/artifacts/Graphite
- name: Upload Windows Bundle
uses: actions/upload-artifact@v4
with:
name: graphite-windows-bundle
path: target/artifacts
- name: Azure login
if: github.ref == 'refs/heads/master'
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: Sign
if: github.ref == 'refs/heads/master'
uses: azure/artifact-signing-action@v1
with:
endpoint: https://eus.codesigning.azure.net/
signing-account-name: Graphite
certificate-profile-name: Graphite
files: |
${{ github.workspace }}\target\artifacts\Graphite\Graphite.exe
${{ github.workspace }}\target\artifacts\Graphite\libcef.dll
${{ github.workspace }}\target\artifacts\Graphite\chrome_elf.dll
${{ github.workspace }}\target\artifacts\Graphite\vulkan-1.dll
${{ github.workspace }}\target\artifacts\Graphite\dxcompiler.dll
${{ github.workspace }}\target\artifacts\Graphite\libEGL.dll
${{ github.workspace }}\target\artifacts\Graphite\libGLESv2.dll
${{ github.workspace }}\target\artifacts\Graphite\vk_swiftshader.dll
file-digest: SHA256
timestamp-rfc3161: http://timestamp.acs.microsoft.com
timestamp-digest: SHA256
correlation-id: ${{ github.sha }}
- name: Verify Signatures
if: github.ref == 'refs/heads/master'
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
$TargetDir = "target\artifacts\Graphite"
if (-not (Test-Path $TargetDir)) {
throw "TargetDir not found: $TargetDir"
}
$UnsignedOrBad = @()
Get-ChildItem -Path $TargetDir -Recurse -File -Include *.exe,*.dll | ForEach-Object {
$sig = Get-AuthenticodeSignature -FilePath $_.FullName
if ($sig.Status -ne 'Valid') {
$UnsignedOrBad += "$($_.FullName) (Status=$($sig.Status))"
}
}
if ($UnsignedOrBad.Count -gt 0) {
Write-Host "Unsigned or invalid binaries detected:"
$UnsignedOrBad | ForEach-Object {
Write-Host "::error::$_"
}
if ($env:GITHUB_STEP_SUMMARY) {
"### ❌ Unsigned or invalid binaries detected" |
Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
"" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
$UnsignedOrBad | ForEach-Object {
"* `$_" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
}
exit 1
}
Write-Host "All binaries are signed and valid."
if ($env:GITHUB_STEP_SUMMARY) {
"### ✅ All binaries are signed and valid" |
Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
- name: Upload Windows Bundle Signed
if: github.ref == 'refs/heads/master'
uses: actions/upload-artifact@v4
with:
name: graphite-windows-bundle-signed
path: target/artifacts
+1
View File
@@ -7,6 +7,7 @@ on:
jobs:
cargo-deny:
if: github.repository == 'GraphiteEditor/Graphite' # Don't run on forks by default
runs-on: ubuntu-latest
steps:
+31
View File
@@ -0,0 +1,31 @@
name: Provide Shaders
on:
push:
branches:
- master
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: Build graphene raster nodes shaders
run: nix build .nix#raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
- name: Upload graphene raster nodes shaders to artifacts repository
run: |
bash .github/workflows/scripts/artifact-upload.bash \
${{ vars.ARTIFACTS_REPO_OWNER }} \
${{ vars.ARTIFACTS_REPO_NAME }} \
${{ vars.ARTIFACTS_REPO_BRANCH }} \
rev/${{ github.sha }}/raster_nodes_shaders_entrypoint.wgsl \
raster_nodes_shaders_entrypoint.wgsl \
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
${{ secrets.ARTIFACTS_REPO_TOKEN }}
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: $0 <owner> <repo> <branch> <target-path> <artifact-file> <commit-message> <github-token>
Arguments:
owner : GitHub user or organization of the target repo
repo : Target repo name
branch : Branch name (e.g. main)
target-path : Full path (including folders + filename) in the target repo where to upload
artifact-file : Local file path to upload
commit-message : Commit message for creating/updating the file
github-token : GitHub token (PAT or equivalent) with write access to the target repo
This will perform a GitHub API PUT to /repos/{owner}/{repo}/contents/{target-path}.
If a file already exists at that path, it will auto-detect the SHA and update; otherwise it will create a new one.
EOF
exit 1
}
if [ $# -ne 7 ]; then
usage
fi
OWNER="$1"
REPO="$2"
BRANCH="$3"
TARGET_PATH="$4"
ARTIFACT_PATH="$5"
COMMIT_MSG="$6"
TOKEN="$7"
if [ ! -f "$ARTIFACT_PATH" ]; then
echo "Error: artifact file not found: $ARTIFACT_PATH" >&2
exit 1
fi
LOCAL_SHA=$(git hash-object "$ARTIFACT_PATH")
echo "Local blob SHA: $LOCAL_SHA"
GET_URL="https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}?ref=${BRANCH}"
GET_RESPONSE=$(curl -s -H "Authorization: token ${TOKEN}" "$GET_URL")
REMOTE_SHA=$(echo "$GET_RESPONSE" | jq -r .sha 2>/dev/null || echo "")
if [ "$REMOTE_SHA" != "null" ] && [ -n "$REMOTE_SHA" ]; then
echo "Remote blob SHA: $REMOTE_SHA"
if [ "$LOCAL_SHA" = "$REMOTE_SHA" ]; then
echo "The remote file is identical. Skipping upload."
exit 0
else
echo "Remote file differs. Preparing to upload."
fi
else
echo "No existing remote file or no SHA found. Creating."
fi
CONTENT_TMP_BASE64=$(mktemp)
if base64 --help 2>&1 | grep -q -- "-w"; then
base64 -w 0 "$ARTIFACT_PATH" > "$CONTENT_TMP_BASE64"
else
base64 "$ARTIFACT_PATH" | tr -d '\n' > "$CONTENT_TMP_BASE64"
fi
PAYLOAD_TMP=$(mktemp)
jq -n \
--arg message "$COMMIT_MSG" \
--arg branch "$BRANCH" \
--arg sha "$REMOTE_SHA" \
--rawfile content "$CONTENT_TMP_BASE64" \
'{
message: $message,
content: $content,
branch: $branch
} + (if ($sha != "" and $sha != "null") then { sha: $sha } else {} end)' \
> "$PAYLOAD_TMP"
UPLOAD_RESPONSE=$(curl -s -X PUT \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
-d @"$PAYLOAD_TMP" \
"https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}")
echo "Upload Response:"
echo "$UPLOAD_RESPONSE"
rm -f "$CONTENT_TMP_BASE64" "$PAYLOAD_TMP"
+13 -5
View File
@@ -37,7 +37,7 @@ jobs:
- name: 🕸 Install Zola
uses: taiki-e/install-action@v2
with:
tool: [email protected]0.0
tool: [email protected]2.0
- name: 🔍 Check if `website/other` directory changed
uses: dorny/paths-filter@v3
@@ -67,19 +67,27 @@ jobs:
rustup update stable
echo "🦀 Latest updated version of Rust:"
rustc --version
cargo test --package graphite-editor --lib -- messages::message::test::generate_message_tree
cd tools/editor-message-tree
cargo run
cd ../..
mkdir artifacts
mv hierarchical_message_system_tree.txt artifacts/hierarchical_message_system_tree.txt
mv website/generated/hierarchical_message_system_tree.txt artifacts/hierarchical_message_system_tree.txt
- name: 🚚 Move `artifacts` contents to the project root
- name: 🚚 Move `artifacts` contents to website/generated
run: |
mv artifacts/* .
mkdir -p website/generated
mv artifacts/* website/generated/
- name: 🔧 Build auto-generated code docs artifacts into HTML
run: |
cd website
npm run generate-editor-structure
- name: 📃 Generate node catalog documentation
run: |
cd tools/node-docs
cargo run
- name: 🌐 Build Graphite website with Zola
env:
MODE: prod
+1 -2
View File
@@ -1,6 +1,7 @@
branding/
target/
result/
.flatpak-builder/
*.spv
*.exrc
perf.data*
@@ -10,5 +11,3 @@ flamegraph.svg
.idea/
.direnv
.DS_Store
hierarchical_message_system_tree.txt
hierarchical_message_system_tree.html
+15 -16
View File
@@ -1,25 +1,24 @@
{ pkgs, inputs, ... }:
let
cef = pkgs.cef-binary.overrideAttrs (_: _: {
cefPath = pkgs.cef-binary.overrideAttrs (finalAttrs: {
postInstall = ''
strip $out/Release/*.so*
rm -r $out/* $out/.* || true
strip ./Release/*.so*
mv ./Release/* $out/
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
mv ./Resources/* $out/
mv ./include $out/
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
});
cefPath = pkgs.runCommand "cef-path" {} ''
mkdir -p $out
ln -s ${cef}/include $out/include
find ${cef}/Release -name "*" -type f -exec ln -s {} $out/ \;
find ${cef}/Resources -name "*" -maxdepth 1 -exec ln -s {} $out/ \;
echo '${builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf cef.src.url;
sha1 = "";
}}' > $out/archive.json
'';
in
{
env.CEF_PATH = cefPath;
+9 -9
View File
@@ -2,11 +2,11 @@
"nodes": {
"crane": {
"locked": {
"lastModified": 1763938834,
"narHash": "sha256-j8iB0Yr4zAvQLueCZ5abxfk6fnG/SJ5JnGUziETjwfg=",
"lastModified": 1770169865,
"narHash": "sha256-iPiy13xzDQ9GjpOez+NNIjh/qjl7i4RDf9dF2x5mF9I=",
"owner": "ipetkov",
"repo": "crane",
"rev": "d9e753122e51cee64eb8d2dddfe11148f339f5a2",
"rev": "8254ccf3b5b5131890ee073776f2e61c6d1e55d4",
"type": "github"
},
"original": {
@@ -49,11 +49,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1764242076,
"narHash": "sha256-sKoIWfnijJ0+9e4wRvIgm/HgE27bzwQxcEmo2J/gNpI=",
"lastModified": 1770197578,
"narHash": "sha256-AYqlWrX09+HvGs8zM6ebZ1pwUqjkfpnv8mewYwAo+iM=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "2fad6eac6077f03fe109c4d4eb171cf96791faa4",
"rev": "00c21e4c93d963c50d4c0c89bfa84ed6e0694df2",
"type": "github"
},
"original": {
@@ -79,11 +79,11 @@
]
},
"locked": {
"lastModified": 1764297505,
"narHash": "sha256-qrLpVu2/hA9Cu6IovMEsgh9YRyvmmWS+bSx7C1JGChA=",
"lastModified": 1770347142,
"narHash": "sha256-uz+ZSqXpXEPtdRPYwvgsum/CfNq7AUQ/0gZHqTigiPM=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "9623580f8ce09ec444b9aca107566ec5db110e62",
"rev": "2859683cd9ef7858d324c5399b0d8d6652bf4044",
"type": "github"
},
"original": {
+11 -1
View File
@@ -33,7 +33,10 @@
info = {
pname = "graphite";
version = "unstable";
src = ./..;
src = pkgs.lib.cleanSourceWith {
src = ./..;
filter = path: type: !(type == "directory" && builtins.baseNameOf path == ".nix");
};
};
pkgs = import inputs.nixpkgs {
@@ -129,6 +132,13 @@
embeddedResources = false;
dev = true;
};
graphite-bundle = import ./pkgs/graphite-bundle.nix {
inherit pkgs graphite;
};
graphite-flatpak-manifest = import ./pkgs/graphite-flatpak-manifest.nix {
inherit pkgs;
archive = graphite-bundle.tar;
};
#TODO: graphene-cli = import ./pkgs/graphene-cli.nix { inherit info pkgs inputs deps libs tools; };
raster-nodes-shaders = import ./pkgs/raster-nodes-shaders.nix {
inherit
+95
View File
@@ -0,0 +1,95 @@
{
pkgs,
graphite,
}:
let
bundle =
{
pkgs,
graphite,
archive ? false,
compression ? null,
passthru ? {},
}:
(
let
tar = if compression == null then archive else true;
nameArchiveSuffix = if tar then ".tar" else "";
nameCompressionSuffix = if compression == null then "" else "." + compression;
name = "graphite-bundle${nameArchiveSuffix}${nameCompressionSuffix}";
build = ''
mkdir -p out
mkdir -p out/bin
cp ${graphite}/bin/graphite out/bin/graphite
chmod -v +w out/bin/graphite
patchelf \
--set-rpath '$ORIGIN/../lib:$ORIGIN/../lib/cef' \
--set-interpreter '/lib64/ld-linux-x86-64.so.2' \
--remove-needed libGL.so \
out/bin/graphite
cp -r ${graphite}/share out/share
mkdir -p out/lib/cef
mkdir -p ./cef
tar -xvf ${pkgs.cef-binary.src} -C ./cef --strip-components=1
cp -r ./cef/Release/* out/lib/cef/
cp -r ./cef/Resources/* out/lib/cef/
find "out/lib/cef/locales" -type f ! -name 'en-US*' -delete
${pkgs.bintools}/bin/strip out/lib/cef/*.so*
'';
install =
if tar then
''
cd out
tar -c \
--sort=name \
--mtime='@1' --clamp-mtime \
--owner=0 --group=0 --numeric-owner \
--mode='u=rwX,go=rX' \
--format=posix \
--pax-option=delete=atime,delete=ctime \
--no-acls --no-xattrs --no-selinux \
* ${
if compression == "xz" then
"| xz "
else if compression == "gz" then
"| gzip -n "
else
""
}> $out
''
else
''
mkdir -p $out
cp -r out/* $out/
'';
in
pkgs.runCommand name
{
inherit passthru;
}
''
${build}
${install}
''
);
in
bundle {
inherit pkgs graphite;
passthru = {
tar = bundle {
inherit pkgs graphite;
archive = true;
passthru = {
gz = bundle {
inherit pkgs graphite;
compression = "gz";
};
xz = bundle {
inherit pkgs graphite;
compression = "xz";
};
};
};
};
}
+37
View File
@@ -0,0 +1,37 @@
{
pkgs,
archive,
}:
(pkgs.formats.json { }).generate "art.graphite.Graphite.json" {
app-id = "art.graphite.Graphite";
runtime = "org.freedesktop.Platform";
runtime-version = "25.08";
sdk = "org.freedesktop.Sdk";
command = "graphite";
finish-args = [
"--device=dri"
"--share=ipc"
"--socket=wayland"
"--socket=fallback-x11"
"--share=network"
];
modules = [
{
name = "app";
buildsystem = "simple";
build-commands = [
"mkdir -p /app"
"cp -r ./* /app/"
"chmod +x /app/bin/*"
];
sources = [
{
type = "archive";
path = archive;
strip-components = 0;
}
];
}
];
}
+33 -13
View File
@@ -30,32 +30,31 @@ let
mkdir -p $out
tar -xvf ${brandingTar} -C $out --strip-components 1
'';
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
resourcesCommon = {
pname = "${info.pname}-resources";
inherit (info) version src;
inherit cargoVendorDir;
strictDeps = true;
doCheck = false;
nativeBuildInputs = tools.frontend;
env.CARGO_PROFILE = if dev then "dev" else "release";
cargoExtraArgs = "--target wasm32-unknown-unknown -p graphite-wasm --no-default-features --features native";
doCheck = false;
};
resources = deps.crane.lib.buildPackage (
resourcesCommon
// {
cargoArtifacts = deps.crane.lib.buildDepsOnly resourcesCommon;
# TODO: Remove the need for this hash by using individual package resolutions and hashes from package-lock.json
npmDeps = pkgs.fetchNpmDeps {
inherit (info) pname version;
src = "${info.src}/frontend";
hash = "sha256-D8VCNK+Ca3gxO+5wriBn8FszG8/x8n/zM6/MPo9E2j4=";
npmDeps = pkgs.importNpmLock {
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
npmConfigScript = "setup";
makeCacheWritable = true;
nativeBuildInputs = tools.frontend ++ [ pkgs.npmHooks.npmConfigHook ];
nativeBuildInputs = tools.frontend ++ [ pkgs.importNpmLock.npmConfigHook pkgs.removeReferencesTo ];
prePatch = ''
mkdir branding
@@ -75,13 +74,18 @@ let
mkdir -p $out
cp -r frontend/dist/* $out/
'';
postFixup = ''
find "$out" -type f -exec remove-references-to -t "${cargoVendorDir}" '{}' +
'';
}
);
common = {
inherit (info) pname version src;
inherit cargoVendorDir;
strictDeps = true;
buildInputs = libs.desktop-all;
nativeBuildInputs = tools.desktop ++ [ pkgs.makeWrapper ];
nativeBuildInputs = tools.desktop ++ [ pkgs.makeWrapper pkgs.removeReferencesTo ];
env = deps.cef.env // {
CARGO_PROFILE = if dev then "dev" else "release";
};
@@ -109,13 +113,20 @@ deps.crane.lib.buildPackage (
}
else
{ }
);
) // {
GRAPHITE_GIT_COMMIT_HASH = inputs.self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = inputs.self.lastModified or "unknown";
};
postUnpack = ''
mkdir ./branding
cp -r ${branding}/* ./branding
'';
preBuild = if inputs.self ? rev then ''
export GRAPHITE_GIT_COMMIT_DATE="$(date -u -d "@$GRAPHITE_GIT_COMMIT_DATE" +"%Y-%m-%dT%H:%M:%SZ")"
'' else "";
installPhase = ''
mkdir -p $out/bin
cp target/${if dev then "debug" else "release"}/graphite $out/bin/graphite
@@ -124,13 +135,22 @@ deps.crane.lib.buildPackage (
cp $src/desktop/assets/*.desktop $out/share/applications/
mkdir -p $out/share/icons/hicolor/scalable/apps
cp ${branding}/app-icons/graphite.svg $out/share/icons/hicolor/scalable/apps/
cp ${branding}/app-icons/graphite.svg $out/share/icons/hicolor/scalable/apps/art.graphite.Graphite.svg
mkdir -p $out/share/icons/hicolor/512x512/apps
cp ${branding}/app-icons/graphite-512.png $out/share/icons/hicolor/512x512/apps/art.graphite.Graphite.png
mkdir -p $out/share/icons/hicolor/256x256/apps
cp ${branding}/app-icons/graphite-256.png $out/share/icons/hicolor/256x256/apps/art.graphite.Graphite.png
mkdir -p $out/share/icons/hicolor/128x128/apps
cp ${branding}/app-icons/graphite-128.png $out/share/icons/hicolor/128x128/apps/art.graphite.Graphite.png
'';
postFixup = ''
wrapProgram "$out/bin/graphite" \
--prefix LD_LIBRARY_PATH : "${pkgs.lib.makeLibraryPath libs.desktop-all}:${deps.cef.env.CEF_PATH}" \
--set CEF_PATH "${deps.cef.env.CEF_PATH}"
remove-references-to -t "${cargoVendorDir}" $out/bin/graphite
patchelf \
--set-rpath "${pkgs.lib.makeLibraryPath libs.desktop-all}:${deps.cef.env.CEF_PATH}" \
--add-needed libGL.so \
$out/bin/graphite
'';
}
)
+2 -1
View File
@@ -11,9 +11,10 @@
// Code quality
"wayou.vscode-todo-highlight",
"streetsidesoftware.code-spell-checker",
// Helpful
// Git
"mhutchie.git-graph",
"qezhu.gitlink",
// Helpful
"wmaurer.change-case"
]
}
+29 -2
View File
@@ -26,12 +26,17 @@
// Configured in `.prettierrc`
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// Website: don't format Zola/Tera-templated HTML on save
"[html]": {
"editor.formatOnSave": false
},
// Handlebars: don't save on format
// (`about.hbs` is used by Cargo About to encode license information)
"[handlebars]": {
"editor.formatOnSave": false
},
// Rust Analyzer config
"rust-analyzer.check.command": "clippy",
"rust-analyzer.cargo.allTargets": false,
"rust-analyzer.procMacro.ignored": {
"serde_derive": ["Serialize", "Deserialize"],
@@ -47,13 +52,35 @@
"vite-plugin-svelte-css-no-scopable-elements": "ignore", // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y-no-static-element-interactions": "ignore", // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y-no-noninteractive-element-interactions": "ignore", // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y-click-events-have-key-events": "ignore" // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y-click-events-have-key-events": "ignore", // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y_consider_explicit_label": "ignore", // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y_click_events_have_key_events": "ignore", // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
"a11y_no_noninteractive_element_interactions": "ignore" // NOTICE: Keep this list in sync with the list in `frontend/vite.config.ts`
},
// Git Graph config
"git-graph.repository.fetchAndPrune": true,
"git-graph.repository.showRemoteHeads": false,
"git-graph.repository.commits.fetchAvatars": true,
// VS Code Git config
"git.autofetch": true,
"git.enableStatusBarSync": false,
"git.showActionButton": {
"sync": false
},
// CSpell config
"cSpell.language": "en-US",
"cSpell.logLevel": "Information",
"cSpell.allowCompoundWords": true,
// Other extensions config
"evenBetterToml.formatter.alignComments": false,
"package-json-upgrade.ignorePatterns": ["source-sans-pro"],
// VS Code config
"html.format.wrapLineLength": 200,
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.associations": {
"*.graphite": "json"
}
},
"editor.renderWhitespace": "boundary",
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+"
}
Generated
+56 -106
View File
@@ -774,7 +774,7 @@ dependencies = [
"thiserror 2.0.16",
"tracing",
"wgpu",
"windows 0.58.0",
"windows",
"windows-sys 0.61.2",
]
@@ -1502,6 +1502,13 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "editor-message-tree"
version = "0.0.0"
dependencies = [
"graphite-editor",
]
[[package]]
name = "either"
version = "1.15.0"
@@ -1685,6 +1692,17 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "fd-lock"
version = "4.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78"
dependencies = [
"cfg-if",
"rustix",
"windows-sys 0.59.0",
]
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -1829,7 +1847,7 @@ dependencies = [
"read-fonts 0.35.0",
"roxmltree",
"smallvec",
"windows 0.58.0",
"windows",
"windows-core 0.58.0",
"yeslogic-fontconfig-sys",
]
@@ -2147,7 +2165,7 @@ dependencies = [
"log",
"presser",
"thiserror 1.0.69",
"windows 0.58.0",
"windows",
]
[[package]]
@@ -2330,6 +2348,7 @@ dependencies = [
"ctrlc",
"derivative",
"dirs",
"fd-lock",
"futures",
"glam",
"graphite-desktop-embedded-resources",
@@ -2339,18 +2358,18 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"open",
"pidlock",
"rand 0.9.2",
"rfd",
"ron",
"serde",
"thiserror 2.0.16",
"tokio",
"tracing",
"tracing-subscriber",
"vello",
"wgpu",
"window_clipboard",
"windows 0.58.0",
"windows",
"winit",
]
@@ -2392,6 +2411,14 @@ dependencies = [
"winres",
]
[[package]]
name = "graphite-desktop-update"
version = "0.0.0"
dependencies = [
"reqwest",
"serde",
]
[[package]]
name = "graphite-desktop-wrapper"
version = "0.1.0"
@@ -2470,6 +2497,7 @@ dependencies = [
"js-sys",
"log",
"math-parser",
"node-macro",
"ron",
"serde",
"serde-wasm-bindgen",
@@ -2966,9 +2994,12 @@ dependencies = [
[[package]]
name = "indoc"
version = "2.0.6"
version = "2.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c7245a08504955605670dbf141fceab975f15ca21570696aebe9d2e71576bd"
checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
dependencies = [
"rustversion",
]
[[package]]
name = "inotify"
@@ -3516,7 +3547,7 @@ dependencies = [
[[package]]
name = "muda"
version = "0.17.1"
source = "git+https://github.com/tauri-apps/muda.git?rev=3f460b8fbaed59cda6d95ceea6904f000f093f15#3f460b8fbaed59cda6d95ceea6904f000f093f15"
source = "git+https://github.com/timon-schelling/muda.git?rev=e5bc28bbd6781b18afbfc237981f9ef47eddf863#e5bc28bbd6781b18afbfc237981f9ef47eddf863"
dependencies = [
"crossbeam-channel",
"dpi",
@@ -3683,6 +3714,18 @@ dependencies = [
"spirv-std",
]
[[package]]
name = "node-docs"
version = "0.0.0"
dependencies = [
"convert_case 0.8.0",
"graph-craft",
"graphene-std",
"indoc",
"interpreted-executor",
"preprocessor",
]
[[package]]
name = "node-macro"
version = "0.0.0"
@@ -4359,17 +4402,6 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]]
name = "pidlock"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f837924d5368f9f35a1c404699de3c074311358035c77d7164f5948c08b31382"
dependencies = [
"nix",
"thiserror 1.0.69",
"windows 0.62.2",
]
[[package]]
name = "pin-project"
version = "1.1.10"
@@ -5395,9 +5427,9 @@ dependencies = [
[[package]]
name = "security-framework-sys"
version = "2.14.0"
version = "2.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32"
checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"
dependencies = [
"core-foundation-sys",
"libc",
@@ -6302,9 +6334,9 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.6"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
dependencies = [
"bitflags 2.9.3",
"bytes",
@@ -7213,7 +7245,7 @@ dependencies = [
"wasm-bindgen",
"web-sys",
"wgpu-types",
"windows 0.58.0",
"windows",
"windows-core 0.58.0",
]
@@ -7286,27 +7318,6 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core 0.62.2",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.58.0"
@@ -7333,30 +7344,6 @@ dependencies = [
"windows-strings 0.4.2",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
@@ -7413,16 +7400,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-registry"
version = "0.5.3"
@@ -7452,15 +7429,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
@@ -7480,15 +7448,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
@@ -7582,15 +7541,6 @@ dependencies = [
"windows_x86_64_msvc 0.53.0",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
+13 -7
View File
@@ -3,6 +3,7 @@ members = [
"desktop",
"desktop/wrapper",
"desktop/embedded-resources",
"desktop/update",
"desktop/bundle",
"desktop/platform/linux",
"desktop/platform/mac",
@@ -39,7 +40,9 @@ members = [
"node-graph/node-macro",
"node-graph/preprocessor",
"proc-macros",
"tools/crate-hierarchy-viz"
"tools/crate-hierarchy-viz",
"tools/editor-message-tree",
"tools/node-docs",
]
default-members = [
"editor",
@@ -137,6 +140,7 @@ log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "0.2"
convert_case = "0.8"
indoc = "2.0.5"
derivative = "2.2"
thiserror = "2"
anyhow = "1.0"
@@ -151,7 +155,7 @@ wgpu = { version = "27.0", features = [
"spirv",
"strict_asserts",
] }
once_cell = "1.13" # Remove when `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) is stabilized in Rust 1.80 and we bump our MSRV
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.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.77"
@@ -176,11 +180,17 @@ web-sys = { version = "=0.3.77", features = [
winit = { git = "https://github.com/rust-windowing/winit.git" }
keyboard-types = "0.8"
url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt"] }
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.12", features = ["serde"] }
vello = { git = "https://github.com/linebender/vello" }
vello_encoding = { git = "https://github.com/linebender/vello" }
resvg = "0.45"
usvg = "0.45"
parley = "0.6"
skrifa = "0.36"
polycool = "0.4"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.29", default-features = false, features = [
@@ -194,8 +204,6 @@ image = { version = "0.25", default-features = false, features = [
"jpeg",
"bmp",
] }
parley = "0.6"
skrifa = "0.36"
pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
@@ -217,7 +225,6 @@ syn = { version = "2.0", default-features = false, features = [
"extra-traits",
"proc-macro",
] }
kurbo = { version = "0.12", features = ["serde"] }
lyon_geom = "1.0"
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
@@ -234,7 +241,6 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.15"
open = "5.3"
polycool = "0.4"
spin = "0.10"
clap = "4.5"
spirv-std = { git = "https://github.com/Firestar99/rust-gpu-new", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
+8 -3
View File
@@ -25,9 +25,13 @@ graphite-desktop-wrapper = { path = "wrapper" }
graphite-desktop-embedded-resources = { path = "embedded-resources", optional = true }
wgpu = { workspace = true }
winit = { workspace = true, features = [ "wayland-csd-adwaita-notitlebar", "serde" ] }
winit = { workspace = true, features = [
"wayland-csd-adwaita-notitlebar",
"serde",
] }
thiserror = { workspace = true }
futures = { workspace = true }
tokio = { workspace = true }
cef = { workspace = true }
cef-dll-sys = { workspace = true }
tracing-subscriber = { workspace = true }
@@ -43,7 +47,7 @@ open = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
serde = { workspace = true }
clap = { workspace = true, features = ["derive"] }
pidlock = "0.2.2"
fd-lock = "4.0.4"
ctrlc = "3.5.1"
window_clipboard = "0.5"
@@ -55,6 +59,7 @@ windows = { version = "0.58.0", features = [
"Win32_Graphics_Gdi",
"Win32_System_LibraryLoader",
"Win32_System_Com",
"Win32_System_Console",
"Win32_UI_Controls",
"Win32_UI_WindowsAndMessaging",
"Win32_UI_HiDpi",
@@ -66,4 +71,4 @@ windows = { version = "0.58.0", features = [
objc2 = { version = "0.6.1", default-features = false }
objc2-foundation = { version = "0.3.2", default-features = false }
objc2-app-kit = { version = "0.3.2", default-features = false }
muda = { git = "https://github.com/tauri-apps/muda.git", rev = "3f460b8fbaed59cda6d95ceea6904f000f093f15", default-features = false }
muda = { git = "https://github.com/timon-schelling/muda.git", rev = "e5bc28bbd6781b18afbfc237981f9ef47eddf863", default-features = false }
+1 -1
View File
@@ -5,7 +5,7 @@ Comment=Open-source vector & raster graphics editor. Featuring node based proced
Exec=graphite
Terminal=false
Type=Application
Icon=graphite
Icon=art.graphite.Graphite
Categories=Graphics;VectorGraphics;RasterGraphics;
Keywords=graphite;editor;vector;raster;procedural;design;
StartupWMClass=art.graphite.Graphite
+25
View File
@@ -27,8 +27,33 @@ fn bundle(out_dir: &Path, app_bin: &Path) -> PathBuf {
copy_dir(&cef_path(), &app_dir);
if let Err(e) = remove_unnecessary_cef_files(&app_dir) {
eprintln!("Failed to remove unnecessary CEF files: {}", e);
}
let bin_path = app_dir.join(EXECUTABLE);
fs::copy(app_bin, &bin_path).unwrap();
bin_path
}
fn remove_unnecessary_cef_files(app_dir: &Path) -> Result<(), Box<dyn Error>> {
fs::remove_dir_all(app_dir.join("cmake"))?;
fs::remove_dir_all(app_dir.join("include"))?;
fs::remove_dir_all(app_dir.join("libcef_dll"))?;
for entry in fs::read_dir(app_dir.join("locales"))? {
let path = entry?.path();
if path.is_file() && path.file_name() != Some("en-US.pak".as_ref()) {
fs::remove_file(path)?;
}
}
fs::remove_file(app_dir.join("archive.json"))?;
fs::remove_file(app_dir.join("CMakeLists.txt"))?;
fs::remove_file(app_dir.join("bootstrapc.exe"))?;
fs::remove_file(app_dir.join("bootstrap.exe"))?;
fs::remove_file(app_dir.join("libcef.lib"))?;
Ok(())
}
+2 -1
View File
@@ -23,7 +23,8 @@ fn main() {
res.set("FileDescription", "Graphite");
res.set("ProductName", "Graphite");
res.set("LegalCopyright", "Copyright © 2025 Graphite Labs, LLC");
// TODO: Pull this year from the Git commit date
res.set("LegalCopyright", "Copyright © 2026 Graphite Labs, LLC");
res.set("CompanyName", "Graphite Labs, LLC");
res.compile().expect("Failed to compile Windows resources");
+126 -44
View File
@@ -1,22 +1,23 @@
use rand::Rng;
use rfd::AsyncFileDialog;
use std::fs;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender, SyncSender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::dpi::PhysicalSize;
use winit::event::{ButtonSource, ElementState, MouseButton, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow};
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;
use crate::cef;
use crate::cli::Cli;
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
use crate::event::{AppEvent, AppEventScheduler};
use crate::persist::PersistentData;
use crate::render::{RenderError, RenderState};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Platform};
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState};
use crate::wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
@@ -27,6 +28,8 @@ pub(crate) struct App {
window_size: PhysicalSize<u32>,
window_maximized: bool,
window_fullscreen: bool,
pointer_position: PhysicalPosition<f64>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
ui_scale: f64,
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
@@ -34,13 +37,14 @@ pub(crate) struct App {
cef_context: Box<dyn cef::CefContext>,
cef_schedule: Option<Instant>,
cef_view_info_sender: Sender<cef::ViewInfoUpdate>,
last_ui_update: Instant,
avg_frame_time: f32,
cef_init_successful: bool,
start_render_sender: SyncSender<()>,
web_communication_initialized: bool,
web_communication_startup_buffer: Vec<Vec<u8>>,
persistent_data: PersistentData,
launch_documents: Vec<PathBuf>,
cli: Cli,
startup_time: Option<Instant>,
exit_reason: ExitReason,
}
impl App {
@@ -54,20 +58,21 @@ impl App {
wgpu_context: WgpuContext,
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
launch_documents: Vec<PathBuf>,
cli: Cli,
) -> Self {
let ctrlc_app_event_scheduler = app_event_scheduler.clone();
ctrlc::set_handler(move || {
tracing::info!("Termination signal received, exiting...");
ctrlc_app_event_scheduler.schedule(AppEvent::CloseWindow);
ctrlc_app_event_scheduler.schedule(AppEvent::Exit);
})
.expect("Error setting Ctrl-C handler");
let rendering_app_event_scheduler = app_event_scheduler.clone();
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
std::thread::spawn(move || {
let runtime = tokio::runtime::Runtime::new().unwrap();
loop {
let result = futures::executor::block_on(DesktopWrapper::execute_node_graph());
let result = runtime.block_on(DesktopWrapper::execute_node_graph());
rendering_app_event_scheduler.schedule(AppEvent::NodeGraphExecutionResult(result));
let _ = start_render_receiver.recv();
}
@@ -76,6 +81,8 @@ impl App {
let mut persistent_data = PersistentData::default();
persistent_data.load_from_disk();
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
Self {
render_state: None,
wgpu_context,
@@ -84,23 +91,38 @@ impl App {
window_size: PhysicalSize { width: 0, height: 0 },
window_maximized: false,
window_fullscreen: false,
pointer_position: Default::default(),
pointer_lock_position: Default::default(),
ui_scale: 1.,
app_event_receiver,
app_event_scheduler,
desktop_wrapper: DesktopWrapper::new(),
last_ui_update: Instant::now(),
desktop_wrapper,
cef_context,
cef_schedule: Some(Instant::now()),
cef_view_info_sender,
avg_frame_time: 0.,
cef_init_successful: false,
start_render_sender,
web_communication_initialized: false,
web_communication_startup_buffer: Vec::new(),
persistent_data,
launch_documents,
cli,
exit_reason: ExitReason::Shutdown,
startup_time: None,
}
}
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
event_loop.run_app(&mut self).unwrap();
self.exit_reason
}
fn exit(&mut self, reason: Option<ExitReason>) {
if let Some(reason) = reason {
self.exit_reason = reason;
}
self.app_event_scheduler.schedule(AppEvent::Exit);
}
fn resize(&mut self) {
let Some(window) = &self.window else {
tracing::error!("Resize failed due to missing window");
@@ -173,7 +195,7 @@ impl App {
if let Some(path) = futures::executor::block_on(show_dialog)
&& let Ok(content) = fs::read(&path)
{
let message = DesktopWrapperMessage::OpenFileDialogResult { path, content, context };
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
});
@@ -238,6 +260,9 @@ impl App {
if let Some(render_state) = &mut self.render_state {
render_state.set_overlays_scene(scene);
}
if let Some(window) = &self.window {
window.request_redraw();
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document } => {
self.persistent_data.write_document(id, document);
@@ -295,11 +320,11 @@ impl App {
}
}
DesktopFrontendMessage::OpenLaunchDocuments => {
if self.launch_documents.is_empty() {
if self.cli.files.is_empty() {
return;
}
let app_event_scheduler = self.app_event_scheduler.clone();
let launch_documents = std::mem::take(&mut self.launch_documents);
let launch_documents = std::mem::take(&mut self.cli.files);
let _ = thread::spawn(move || {
for path in launch_documents {
tracing::info!("Opening file from command line: {}", path.display());
@@ -329,8 +354,14 @@ impl App {
window.clipboard_write(content);
}
}
DesktopFrontendMessage::PointerLock => {
self.pointer_lock_position = Some(self.pointer_position);
if let Some(window) = &self.window {
window.start_pointer_lock();
}
}
DesktopFrontendMessage::WindowClose => {
self.app_event_scheduler.schedule(AppEvent::CloseWindow);
self.app_event_scheduler.schedule(AppEvent::Exit);
}
DesktopFrontendMessage::WindowMinimize => {
if let Some(window) = &self.window {
@@ -342,6 +373,11 @@ impl App {
window.toggle_maximize();
}
}
DesktopFrontendMessage::WindowFullscreen => {
if let Some(window) = &mut self.window {
window.toggle_fullscreen();
}
}
DesktopFrontendMessage::WindowDrag => {
if let Some(window) = &self.window {
window.start_drag();
@@ -413,15 +449,13 @@ impl App {
AppEvent::UiUpdate(texture) => {
if let Some(render_state) = self.render_state.as_mut() {
render_state.bind_ui_texture(texture);
let elapsed = self.last_ui_update.elapsed().as_secs_f32();
self.last_ui_update = Instant::now();
if elapsed < 0.5 {
self.avg_frame_time = (self.avg_frame_time * 3. + elapsed) / 4.;
}
}
if let Some(window) = &self.window {
window.request_redraw();
}
if !self.cef_init_successful {
self.cef_init_successful = true;
}
}
AppEvent::ScheduleBrowserWork(instant) => {
if instant <= Instant::now() {
@@ -435,9 +469,7 @@ impl App {
window.set_cursor(event_loop, cursor);
}
}
AppEvent::CloseWindow => {
// TODO: Implement graceful shutdown
AppEvent::Exit => {
tracing::info!("Exiting main event loop");
event_loop.exit();
}
@@ -464,13 +496,7 @@ impl ApplicationHandler for App {
self.desktop_wrapper.init(self.wgpu_context.clone());
#[cfg(target_os = "windows")]
let platform = Platform::Windows;
#[cfg(target_os = "macos")]
let platform = Platform::Mac;
#[cfg(target_os = "linux")]
let platform = Platform::Linux;
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::UpdatePlatform(platform));
self.startup_time = Some(Instant::now());
}
fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) {
@@ -479,12 +505,32 @@ impl ApplicationHandler for App {
}
}
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
// Handle pointer lock release
if let Some(pointer_lock_position) = self.pointer_lock_position
&& let WindowEvent::PointerButton {
state: ElementState::Released,
button: ButtonSource::Mouse(MouseButton::Left),
..
} = event
{
self.pointer_lock_position = None;
if let Some(window) = &self.window {
window.end_pointer_lock();
}
self.cef_context.handle_window_event(&WindowEvent::PointerMoved {
device_id: None,
position: pointer_lock_position,
primary: true,
source: winit::event::PointerSource::Mouse,
});
}
self.cef_context.handle_window_event(&event);
match event {
WindowEvent::CloseRequested => {
self.app_event_scheduler.schedule(AppEvent::CloseWindow);
self.app_event_scheduler.schedule(AppEvent::Exit);
}
WindowEvent::SurfaceResized(_) | WindowEvent::ScaleFactorChanged { .. } => {
self.resize();
@@ -509,18 +555,28 @@ impl ApplicationHandler for App {
}
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
tracing::error!("GPU out of memory");
event_loop.exit();
self.exit(None);
}
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
}
let _ = self.start_render_sender.try_send(());
}
if !self.cef_init_successful
&& !self.cli.disable_ui_acceleration
&& self.web_communication_initialized
&& let Some(startup_time) = self.startup_time
&& startup_time.elapsed() > Duration::from_secs(3)
{
tracing::error!("UI acceleration not working, exiting.");
self.exit(Some(ExitReason::UiAccelerationFailure));
}
}
WindowEvent::DragDropped { paths, .. } => {
for path in paths {
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::OpenFile { path, content };
let message = DesktopWrapperMessage::ImportFile { path, content };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => {
@@ -556,6 +612,13 @@ impl ApplicationHandler for App {
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
}
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } | WindowEvent::PointerEntered { position, .. }
if self.pointer_lock_position.is_none() =>
{
self.pointer_position = position;
}
_ => {}
}
@@ -563,10 +626,26 @@ impl ApplicationHandler for App {
self.cef_context.work();
}
fn device_event(&mut self, _event_loop: &dyn ActiveEventLoop, _device_id: Option<winit::event::DeviceId>, event: winit::event::DeviceEvent) {
if self.pointer_lock_position.is_some()
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
{
let message = DesktopWrapperMessage::PointerLockMove { x, y };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
}
fn new_events(&mut self, _event_loop: &dyn ActiveEventLoop, cause: winit::event::StartCause) {
if let StartCause::ResumeTimeReached { .. } = cause
&& let Some(window) = &self.window
{
window.request_redraw();
}
}
fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
// Set a timeout in case we miss any cef schedule requests
let timeout = Instant::now() + Duration::from_millis(10);
let wait_until = timeout.min(self.cef_schedule.unwrap_or(timeout));
let mut wait_until = Instant::now() + Duration::from_millis(10);
if let Some(schedule) = self.cef_schedule
&& schedule < Instant::now()
{
@@ -575,11 +654,14 @@ impl ApplicationHandler for App {
for _ in 0..CEF_MESSAGE_LOOP_MAX_ITERATIONS {
self.cef_context.work();
}
} else if let Some(cef_schedule) = self.cef_schedule {
wait_until = wait_until.min(cef_schedule);
}
if let Some(window) = &self.window.as_ref() {
window.request_redraw();
}
event_loop.set_control_flow(ControlFlow::WaitUntil(wait_until));
}
}
pub(crate) enum ExitReason {
Shutdown,
UiAccelerationFailure,
}
+17 -2
View File
@@ -1,9 +1,9 @@
use std::path::{Path, PathBuf};
use cef::args::Args;
use cef::sys::{CEF_API_VERSION_LAST, cef_resultcode_t};
use cef::sys::{CEF_API_VERSION_LAST, cef_log_severity_t, cef_resultcode_t};
use cef::{
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, LogSeverity, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
browser_host_create_browser_sync, execute_process,
};
@@ -74,11 +74,24 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
}
fn common_settings(instance_dir: &Path) -> Settings {
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG") {
Ok(level) => match level.to_lowercase().as_str() {
"debug" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_VERBOSE),
"info" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_INFO),
"warn" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_WARNING),
"error" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_ERROR),
"none" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_DISABLE),
_ => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
},
Err(_) => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
};
Settings {
windowless_rendering_enabled: 1,
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
cache_path: CefString::from(""),
disable_signal_handlers: 1,
log_severity,
..Default::default()
}
}
@@ -111,6 +124,8 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
let settings = Settings {
multi_threaded_message_loop: 1,
#[cfg(target_os = "linux")]
no_sandbox: 1,
..Self::common_settings(&instance_dir)
};
+2
View File
@@ -69,6 +69,8 @@ pub(crate) fn handle_window_event(browser: &Browser, input_state: &mut InputStat
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
let Some(host) = browser.host() else { return };
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
let mut key_event = KeyEvent {
type_: match (event.state, &event.logical_key) {
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => cef_key_event_type_t::KEYEVENT_CHAR,
+27 -8
View File
@@ -3,7 +3,7 @@ use cef::sys::cef_event_flags_t;
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, MouseButton};
use winit::keyboard::{KeyLocation, ModifiersState};
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
use crate::cef::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
@@ -19,6 +19,18 @@ impl InputState {
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 {
@@ -127,25 +139,26 @@ impl ClickTracker {
let prev_time = record.time;
let prev_position = record.position;
let prev_count: ClickCount = record.down_count;
let now = Instant::now();
record.time = now;
record.position = position;
match state {
ElementState::Pressed if record.down_count == ClickCount::Double => {
ElementState::Pressed if record.down_count == ClickCount::Triple => {
*record = ClickRecord {
down_count: ClickCount::Single,
down_count: ClickCount::Double,
..*record
};
return ClickCount::Single;
return ClickCount::Double;
}
ElementState::Released if record.up_count == ClickCount::Double => {
ElementState::Released if record.up_count == ClickCount::Triple => {
*record = ClickRecord {
up_count: ClickCount::Single,
up_count: ClickCount::Double,
..*record
};
return ClickCount::Single;
return ClickCount::Double;
}
_ => {}
}
@@ -155,7 +168,11 @@ impl ClickTracker {
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let within_time = now.saturating_duration_since(prev_time) <= MULTICLICK_TIMEOUT;
let count = if within_time && within_dist { ClickCount::Double } else { ClickCount::Single };
let count = match (prev_count, within_time, within_dist) {
(ClickCount::Double, true, true) => ClickCount::Triple,
(_, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
*record = match state {
ElementState::Pressed => ClickRecord { down_count: count, ..*record },
@@ -170,12 +187,14 @@ 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,
}
}
}
@@ -34,14 +34,33 @@ impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
fn on_before_command_line_processing(&self, _process_type: Option<&cef::CefString>, command_line: Option<&mut cef::CommandLine>) {
if let Some(cmd) = command_line {
cmd.append_switch_with_value(Some(&CefString::from("renderer-process-limit")), Some(&CefString::from("1")));
cmd.append_switch_with_value(Some(&CefString::from("password-store")), Some(&CefString::from("basic")));
cmd.append_switch_with_value(Some(&CefString::from("disk-cache-size")), Some(&CefString::from("0")));
cmd.append_switch(Some(&CefString::from("incognito")));
cmd.append_switch(Some(&CefString::from("no-first-run")));
cmd.append_switch(Some(&CefString::from("no-default-browser-check")));
cmd.append_switch(Some(&CefString::from("disable-component-update")));
cmd.append_switch(Some(&CefString::from("disable-geolocation")));
cmd.append_switch(Some(&CefString::from("disable-notifications")));
cmd.append_switch(Some(&CefString::from("disable-audio-input")));
cmd.append_switch(Some(&CefString::from("disable-audio-output")));
cmd.append_switch(Some(&CefString::from("disable-sync")));
cmd.append_switch(Some(&CefString::from("disable-file-system")));
cmd.append_switch(Some(&CefString::from("disable-local-storage")));
cmd.append_switch(Some(&CefString::from("disable-background-networking")));
cmd.append_switch(Some(&CefString::from("disable-audio-input")));
cmd.append_switch(Some(&CefString::from("disable-audio-output")));
cmd.append_switch(Some(&CefString::from("disable-default-apps")));
cmd.append_switch(Some(&CefString::from("disable-breakpad")));
cmd.append_switch_with_value(Some(&CefString::from("disable-blink-features")), Some(&CefString::from("WebBluetooth,WebUSB,Serial")));
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&CefString::from("disable-features"));
let disabled_features: String = CefString::from(&cmd.switch_value(disabled_features_switch))
.to_string()
.split(',')
.chain(extra_disabled_features)
.collect::<Vec<_>>()
.join(",");
cmd.append_switch_with_value(disabled_features_switch, Some(&CefString::from(disabled_features.as_str())));
#[cfg(not(feature = "accelerated_paint"))]
{
+4 -1
View File
@@ -78,7 +78,6 @@ impl<H: CefEventHandler> ImplDisplayHandler for DisplayHandlerImpl<H> {
CT_PROGRESS => CursorIcon::Progress,
CT_NODROP => CursorIcon::NoDrop,
CT_COPY => CursorIcon::Copy,
CT_NONE => CursorIcon::Default,
CT_NOTALLOWED => CursorIcon::NotAllowed,
CT_ZOOMIN => CursorIcon::ZoomIn,
CT_ZOOMOUT => CursorIcon::ZoomOut,
@@ -91,6 +90,10 @@ impl<H: CefEventHandler> ImplDisplayHandler for DisplayHandlerImpl<H> {
CT_DND_COPY => CursorIcon::Copy,
CT_DND_LINK => CursorIcon::Alias,
CT_NUM_VALUES => CursorIcon::Default,
CT_NONE => {
self.event_handler.cursor_change(crate::window::Cursor::None);
return 1; // We handled the cursor change.
}
_ => CursorIcon::Default,
};
+3
View File
@@ -2,7 +2,10 @@ pub(crate) const APP_NAME: &str = "Graphite";
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub(crate) const APP_ID: &str = "art.graphite.Graphite";
#[cfg(target_os = "linux")]
pub(crate) const APP_DIRECTORY_NAME: &str = "graphite";
#[cfg(not(target_os = "linux"))]
pub(crate) const APP_DIRECTORY_NAME: &str = "Graphite";
pub(crate) const APP_LOCK_FILE_NAME: &str = "instance.lock";
pub(crate) const APP_STATE_FILE_NAME: &str = "state.ron";
pub(crate) const APP_PREFERENCES_FILE_NAME: &str = "preferences.ron";
+1 -1
View File
@@ -8,7 +8,7 @@ pub(crate) enum AppEvent {
WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult),
CloseWindow,
Exit,
#[cfg(target_os = "macos")]
MenuEvent {
id: String,
+53 -15
View File
@@ -1,4 +1,5 @@
use clap::Parser;
use std::io::Write;
use std::process::exit;
use tracing_subscriber::EnvFilter;
use winit::event_loop::EventLoop;
@@ -38,26 +39,36 @@ pub fn start() {
return;
}
let mut lock = pidlock::Pidlock::new_validated(dirs::app_data_dir().join(APP_LOCK_FILE_NAME)).unwrap();
match lock.acquire() {
Ok(lock) => {
let cli = Cli::parse();
let Ok(lock_file) = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(dirs::app_data_dir().join(APP_LOCK_FILE_NAME))
else {
tracing::error!("Failed to open lock file, Exiting.");
exit(1);
};
let mut lock = fd_lock::RwLock::new(lock_file);
let lock = match lock.try_write() {
Ok(mut guard) => {
tracing::info!("Acquired application lock");
lock
let _ = guard.set_len(0);
let _ = write!(guard, "{}", std::process::id());
let _ = guard.sync_all();
guard
}
Err(pidlock::PidlockError::LockExists) => {
Err(_) => {
tracing::error!("Another instance is already running, Exiting.");
exit(0);
}
Err(err) => {
tracing::error!("Failed to acquire application lock: {err}");
exit(1);
}
};
// Must be called before event loop initialization or native window integrations will break
App::init();
let cli = Cli::parse();
let wgpu_context = futures::executor::block_on(gpu_context::create_wgpu_context());
let event_loop = EventLoop::new().unwrap();
@@ -66,11 +77,15 @@ pub fn start() {
let (cef_view_info_sender, cef_view_info_receiver) = std::sync::mpsc::channel();
if cli.disable_ui_acceleration {
println!("UI acceleration is disabled");
}
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.initialize(cef_handler, cli.disable_ui_acceleration) {
Ok(c) => {
Ok(context) => {
tracing::info!("CEF initialized successfully");
c
context
}
Err(cef::InitError::AlreadyRunning) => {
tracing::error!("Another instance is already running, Exiting.");
@@ -90,9 +105,32 @@ pub fn start() {
}
};
let mut app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, cli.files);
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, cli);
event_loop.run_app(&mut app).unwrap();
let exit_reason = app.run(event_loop);
// Explicitly drop the instance lock
drop(lock);
match exit_reason {
#[cfg(target_os = "linux")]
app::ExitReason::UiAccelerationFailure => {
use std::os::unix::process::CommandExt;
tracing::error!("Restarting application without UI acceleration");
let _ = std::process::Command::new(std::env::current_exe().unwrap()).arg("--disable-ui-acceleration").exec();
tracing::error!("Failed to restart application");
}
_ => {}
}
// Workaround for a Windows-specific exception that occurs when `app` is dropped.
// The issue causes the window to hang for a few seconds before closing.
// Appears to be related to CEF object destruction order.
// Calling `exit` bypasses rust teardown and lets Windows perform process cleanup.
// TODO: Identify and fix the underlying CEF shutdown issue so this workaround can be removed.
#[cfg(target_os = "windows")]
exit(0);
}
pub fn start_helper() {
+1 -1
View File
@@ -190,7 +190,7 @@ impl DocumentStore {
fn document_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.graphite", id.0));
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
}
+30 -16
View File
@@ -1,6 +1,7 @@
use crate::window::Window;
use std::borrow::Cow;
use crate::wrapper::{Color, WgpuContext, WgpuExecutor};
use crate::window::Window;
use crate::wrapper::{TargetTexture, WgpuContext, WgpuExecutor};
#[derive(derivative::Derivative)]
#[derivative(Debug)]
@@ -17,11 +18,12 @@ pub(crate) struct RenderState {
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<wgpu::Texture>,
overlays_texture: Option<wgpu::Texture>,
overlays_texture: Option<TargetTexture>,
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
overlays_scene: Option<vello::Scene>,
surface_outdated: bool,
}
impl RenderState {
@@ -37,10 +39,13 @@ impl RenderState {
format: surface_format,
width: size.width,
height: size.height,
#[cfg(not(target_os = "macos"))]
present_mode: surface_caps.present_modes[0],
#[cfg(target_os = "macos")]
present_mode: wgpu::PresentMode::Immediate,
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
desired_maximum_frame_latency: 1,
};
surface.configure(&context.device, &config);
@@ -182,6 +187,7 @@ impl RenderState {
ui_texture: None,
bind_group: None,
overlays_scene: None,
surface_outdated: true,
}
}
@@ -192,6 +198,7 @@ impl RenderState {
self.desired_width = width;
self.desired_height = height;
self.surface_outdated = true;
if width > 0 && height > 0 && (self.config.width != width || self.config.height != height) {
self.config.width = width;
@@ -205,25 +212,23 @@ impl RenderState {
self.update_bindgroup();
}
pub(crate) fn bind_overlays_texture(&mut self, overlays_texture: wgpu::Texture) {
self.overlays_texture = Some(overlays_texture);
self.update_bindgroup();
}
pub(crate) fn bind_ui_texture(&mut self, bind_ui_texture: wgpu::Texture) {
self.ui_texture = Some(bind_ui_texture);
self.update_bindgroup();
}
pub(crate) fn set_viewport_scale(&mut self, scale: [f32; 2]) {
self.surface_outdated = true;
self.viewport_scale = scale;
}
pub(crate) fn set_viewport_offset(&mut self, offset: [f32; 2]) {
self.surface_outdated = true;
self.viewport_offset = offset;
}
pub(crate) fn set_overlays_scene(&mut self, scene: vello::Scene) {
self.surface_outdated = true;
self.overlays_scene = Some(scene);
}
@@ -233,15 +238,18 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let texture = futures::executor::block_on(self.executor.render_vello_scene_to_texture(&scene, size, &Default::default(), Color::TRANSPARENT));
let Ok(texture) = texture else {
tracing::error!("Error rendering overlays");
let result = futures::executor::block_on(self.executor.render_vello_scene_to_target_texture(&scene, size, &Default::default(), None, &mut self.overlays_texture));
if let Err(e) = result {
tracing::error!("Error rendering overlays: {:?}", e);
return;
};
self.bind_overlays_texture(texture);
}
self.update_bindgroup();
}
pub(crate) fn render(&mut self, window: &Window) -> Result<(), RenderError> {
if !self.surface_outdated {
return Ok(());
}
let ui_scale = if let Some(ui_texture) = &self.ui_texture
&& (self.desired_width != ui_texture.width() || self.desired_height != ui_texture.height())
{
@@ -303,13 +311,19 @@ impl RenderState {
if ui_scale.is_some() {
return Err(RenderError::OutdatedUITextureError);
}
self.surface_outdated = false;
Ok(())
}
fn update_bindgroup(&mut self) {
self.surface_outdated = true;
let viewport_texture_view = self.viewport_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let overlays_texture_view = self.overlays_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let overlays_texture_view = self
.overlays_texture
.as_ref()
.map(|target| Cow::Borrowed(target.view()))
.unwrap_or_else(|| Cow::Owned(self.transparent_texture.create_view(&wgpu::TextureViewDescriptor::default())));
let ui_texture_view = self.ui_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let bind_group = self.context.device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -321,7 +335,7 @@ impl RenderState {
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&overlays_texture_view),
resource: wgpu::BindingResource::TextureView(&overlays_texture_view.as_ref()),
},
wgpu::BindGroupEntry {
binding: 2,
+52 -8
View File
@@ -1,13 +1,13 @@
use crate::consts::APP_NAME;
use crate::event::AppEventScheduler;
use crate::wrapper::messages::MenuItem;
use std::collections::HashMap;
use std::sync::Arc;
use winit::cursor::{CursorIcon, CustomCursor, CustomCursorSource};
use winit::event_loop::ActiveEventLoop;
use winit::monitor::Fullscreen;
use winit::window::{Window as WinitWindow, WindowAttributes};
use crate::consts::APP_NAME;
use crate::event::AppEventScheduler;
use crate::wrapper::messages::MenuItem;
pub(crate) trait NativeWindow {
fn init() {}
fn configure(attributes: WindowAttributes, event_loop: &dyn ActiveEventLoop) -> WindowAttributes;
@@ -41,7 +41,13 @@ pub(crate) struct Window {
#[allow(dead_code)]
native_handle: native::NativeWindowImpl,
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
clipboard: window_clipboard::Clipboard,
clipboard: Option<window_clipboard::Clipboard>,
}
impl Drop for Window {
fn drop(&mut self) {
// Clipboard must be dropped before `winit_window`
drop(self.clipboard.take());
}
}
impl Window {
@@ -62,7 +68,7 @@ impl Window {
let winit_window = event_loop.create_window(attributes).unwrap();
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.expect("failed to create clipboard");
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.ok();
Self {
winit_window: winit_window.into(),
native_handle,
@@ -105,6 +111,9 @@ impl Window {
}
pub(crate) fn toggle_maximize(&self) {
if self.is_fullscreen() {
return;
}
self.winit_window.set_maximized(!self.winit_window.is_maximized());
}
@@ -112,11 +121,22 @@ impl Window {
self.winit_window.is_maximized()
}
pub(crate) fn toggle_fullscreen(&mut self) {
if self.is_fullscreen() {
self.winit_window.set_fullscreen(None);
} else {
self.winit_window.set_fullscreen(Some(Fullscreen::Borderless(None)));
}
}
pub(crate) fn is_fullscreen(&self) -> bool {
self.winit_window.fullscreen().is_some()
}
pub(crate) fn start_drag(&self) {
if self.is_fullscreen() {
return;
}
let _ = self.winit_window.drag_window();
}
@@ -149,16 +169,35 @@ impl Window {
};
custom_cursor.into()
}
Cursor::None => {
self.winit_window.set_cursor_visible(false);
return;
}
};
self.winit_window.set_cursor_visible(true);
self.winit_window.set_cursor(cursor);
}
pub(crate) fn start_pointer_lock(&self) {
let _ = self.winit_window.set_cursor_grab(winit::window::CursorGrabMode::Locked);
self.winit_window.set_cursor_visible(false);
}
pub(crate) fn end_pointer_lock(&self) {
let _ = self.winit_window.set_cursor_grab(winit::window::CursorGrabMode::None);
self.winit_window.set_cursor_visible(true);
}
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
self.native_handle.update_menu(entries);
}
pub(crate) fn clipboard_read(&self) -> Option<String> {
match self.clipboard.read() {
let Some(clipboard) = &self.clipboard else {
tracing::error!("Clipboard not available");
return None;
};
match clipboard.read() {
Ok(data) => Some(data),
Err(e) => {
tracing::error!("Failed to read from clipboard: {e}");
@@ -168,7 +207,11 @@ impl Window {
}
pub(crate) fn clipboard_write(&mut self, data: String) {
if let Err(e) = self.clipboard.write(data) {
let Some(clipboard) = &mut self.clipboard else {
tracing::error!("Clipboard not available");
return;
};
if let Err(e) = clipboard.write(data) {
tracing::error!("Failed to write to clipboard: {e}")
}
}
@@ -177,6 +220,7 @@ impl Window {
pub(crate) enum Cursor {
Icon(CursorIcon),
Custom(CustomCursorSource),
None,
}
impl From<CursorIcon> for Cursor {
fn from(icon: CursorIcon) -> Self {
+7
View File
@@ -1,4 +1,5 @@
use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
use windows::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole};
use windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID;
use windows::core::HSTRING;
use winit::event_loop::ActiveEventLoop;
@@ -13,6 +14,12 @@ pub(super) struct NativeWindowImpl {
impl super::NativeWindow for NativeWindowImpl {
fn init() {
// Attach to parent console if launched from a terminal (no-op otherwise)
unsafe {
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
}
// Set stable app ID
let app_id = HSTRING::from(APP_ID);
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok();
+36 -12
View File
@@ -61,7 +61,7 @@ impl NativeWindowHandle {
0,
0,
0,
None,
main,
None,
HINSTANCE(std::ptr::null_mut()),
// Pass the main window's HWND to WM_NCCREATE so the helper can store it.
@@ -118,7 +118,7 @@ impl NativeWindowHandle {
}
// Force window update
let _ = unsafe { SetWindowPos(main, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER) };
let _ = unsafe { SetWindowPos(main, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE) };
native_handle
}
@@ -210,10 +210,10 @@ unsafe fn ensure_helper_class() {
// Main window message handler, called on the UI thread for every message the main window receives.
unsafe extern "system" fn main_window_handle_message(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if msg == WM_NCCALCSIZE && wparam.0 != 0 {
// When maximized, shrink to visible frame so content doesn't extend beyond it.
if unsafe { IsZoomed(hwnd).as_bool() } {
let params = unsafe { &mut *(lparam.0 as *mut NCCALCSIZE_PARAMS) };
let params = unsafe { &mut *(lparam.0 as *mut NCCALCSIZE_PARAMS) };
// When maximized, shrink to visible frame so content doesn't extend beyond it.
if unsafe { IsZoomed(hwnd).as_bool() } && !is_effectively_fullscreen(params.rgrc[0]) {
let dpi = unsafe { GetDpiForWindow(hwnd) };
let size = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
let pad = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
@@ -325,20 +325,20 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
let w = (r.right - r.left) + RESIZE_BAND_THICKNESS * 2;
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
let _ = unsafe { SetWindowPos(helper, main, x, y, w, h, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING) };
let _ = unsafe { SetWindowPos(helper, main, x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
let x = (lparam.0 & 0xFFFF) as i16 as u32;
let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as u32;
let x = (lparam.0 & 0xFFFF) as i16 as i32;
let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;
let mut r = RECT::default();
let _ = unsafe { GetWindowRect(helper, &mut r) };
let on_top = y < (r.top + RESIZE_BAND_THICKNESS) as u32;
let on_right = x >= (r.right - RESIZE_BAND_THICKNESS) as u32;
let on_bottom = y >= (r.bottom - RESIZE_BAND_THICKNESS) as u32;
let on_left = x < (r.left + RESIZE_BAND_THICKNESS) as u32;
let on_top = y < (r.top + RESIZE_BAND_THICKNESS) as i32;
let on_right = x >= (r.right - RESIZE_BAND_THICKNESS) as i32;
let on_bottom = y >= (r.bottom - RESIZE_BAND_THICKNESS) as i32;
let on_left = x < (r.left + RESIZE_BAND_THICKNESS) as i32;
match (on_top, on_right, on_bottom, on_left) {
(true, _, _, true) => HTTOPLEFT,
@@ -366,3 +366,27 @@ unsafe fn calculate_resize_direction(helper: HWND, lparam: LPARAM) -> Option<u32
_ => None,
}
}
// Check if the rect is effectively fullscreen, meaning it would cover the entire monitor.
// We need to use this heuristic because Windows doesn't provide a way to check for fullscreen state.
fn is_effectively_fullscreen(rect: RECT) -> bool {
let hmon = unsafe { MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST) };
if hmon.is_invalid() {
return false;
}
let mut monitor_info = MONITORINFO {
cbSize: std::mem::size_of::<MONITORINFO>() as u32,
..Default::default()
};
if !unsafe { GetMonitorInfoW(hmon, &mut monitor_info) }.as_bool() {
return false;
}
// Allow a tiny tolerance for DPI / rounding issues
const EPS: i32 = 1;
(rect.left - monitor_info.rcMonitor.left).abs() <= EPS
&& (rect.top - monitor_info.rcMonitor.top).abs() <= EPS
&& (rect.right - monitor_info.rcMonitor.right).abs() <= EPS
&& (rect.bottom - monitor_info.rcMonitor.bottom).abs() <= EPS
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "graphite-desktop-update"
version = "0.0.0"
description = "Graphite Desktop Update"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[dependencies]
serde = { workspace = true }
reqwest = { workspace = true }
+92
View File
@@ -0,0 +1,92 @@
const UPDATE_CHECK_URL: &str = "https://localhost:8080/v1/update";
async fn check_for_update(info: Info) -> UpdateCheckResponse {
let client = reqwest::Client::new();
let response = client.post(UPDATE_CHECK_URL).json(&info).send().await;
match response {
Ok(response) if response.status().is_success() => {
if let Ok(result) = response.json::<UpdateCheckResponse>().await {
return result;
}
}
_ => {}
}
UpdateCheckResponse {
status: Status::Unknown,
prompts: Vec::new(),
}
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Info {
pub commit: Commit,
pub version: Version,
pub system: System,
pub distribution: Distribution,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Commit {
pub hash: String,
pub time: u64,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Version {
Stable { major: u32, minor: u32, patch: u32 },
Dev,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct System {
pub os: Os,
pub arch: Arch,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Os {
Linux,
Mac,
Windows,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Arch {
X86_64,
Aarch64,
Wasm32,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Distribution {
WebOfficial,
WebUnknown,
Flathub,
Nixpkgs,
Steam,
MacAppStore,
WindowsStore,
Installer,
Portable,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct UpdateCheckResponse {
status: Option<Prompt>,
prompts: Vec<Prompt>,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Prompt {
title: String,
body: String,
resolution: Option<Resolution>,
}
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Resolution {
Visit { url: String },
AutoInstall { url: String, hash: String, version: Version, commit: Commit },
PackageManager,
}
@@ -1,11 +1,8 @@
use graphene_std::Color;
use graphene_std::raster::Image;
use graphite_editor::messages::app_window::app_window_message_handler::AppWindowPlatform;
use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
use graphite_editor::messages::prelude::*;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, Platform, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
match message {
@@ -15,9 +12,9 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
DesktopWrapperMessage::Input(message) => {
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
}
DesktopWrapperMessage::OpenFileDialogResult { path, content, context } => match context {
OpenFileDialogContext::Document => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenDocument { path, content });
DesktopWrapperMessage::FileDialogResult { path, content, context } => match context {
OpenFileDialogContext::Open => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenFile { path, content });
}
OpenFileDialogContext::Import => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
@@ -36,90 +33,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
}
},
DesktopWrapperMessage::OpenFile { path, content } => {
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
match extension.as_str() {
"graphite" => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenDocument { path, content });
}
_ => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
}
}
}
DesktopWrapperMessage::OpenDocument { path, content } => {
let Ok(content) = String::from_utf8(content) else {
tracing::warn!("Document file is invalid: {}", path.display());
return;
};
let message = PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: Some(path),
document_serialized_content: content,
};
let message = PortfolioMessage::OpenFile { path, content };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::ImportFile { path, content } => {
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
match extension.as_str() {
"svg" => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportSvg { path, content });
}
_ => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportImage { path, content });
}
}
}
DesktopWrapperMessage::ImportSvg { path, content } => {
let Ok(content) = String::from_utf8(content) else {
tracing::warn!("Svg file is invalid: {}", path.display());
return;
};
let message = PortfolioMessage::PasteSvg {
name: path.file_stem().map(|s| s.to_string_lossy().to_string()),
svg: content,
mouse: None,
parent_and_insert_index: None,
};
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::ImportImage { path, content } => {
let name = path.file_stem().and_then(|s| s.to_str()).map(|s| s.to_string());
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
let Some(image_format) = image::ImageFormat::from_extension(&extension) else {
tracing::warn!("Unsupported file type: {}", path.display());
return;
};
let reader = image::ImageReader::with_format(std::io::Cursor::new(content), image_format);
let Ok(image) = reader.decode() else {
tracing::error!("Failed to decode image: {}", path.display());
return;
};
let width = image.width();
let height = image.height();
// TODO: Handle Image formats with more than 8 bits per channel
let image_data = image.to_rgba8();
let image = Image::<Color>::from_image_data(image_data.as_raw(), width, height);
let message = PortfolioMessage::PasteImage {
name,
image,
mouse: None,
parent_and_insert_index: None,
};
let message = PortfolioMessage::ImportFile { path, content };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
DesktopWrapperMessage::UpdatePlatform(platform) => {
let platform = match platform {
Platform::Windows => AppWindowPlatform::Windows,
Platform::Mac => AppWindowPlatform::Mac,
Platform::Linux => AppWindowPlatform::Linux,
};
let message = AppWindowMessage::UpdatePlatform { platform };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::UpdateMaximized { maximized } => {
let message = FrontendMessage::UpdateMaximized { maximized };
dispatcher.queue_editor_message(message);
@@ -172,5 +93,9 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
dispatcher.queue_editor_message(message);
}
}
DesktopWrapperMessage::PointerLockMove { x, y } => {
let message = AppWindowMessage::PointerLockMove { x, y };
dispatcher.queue_editor_message(message);
}
}
}
@@ -10,29 +10,17 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::RenderOverlays { context } => {
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
}
FrontendMessage::TriggerOpenDocument => {
FrontendMessage::TriggerOpen => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Open Document".to_string(),
filters: vec![FileFilter {
name: "Graphite".to_string(),
extensions: vec!["graphite".to_string()],
}],
context: OpenFileDialogContext::Document,
filters: vec![],
context: OpenFileDialogContext::Open,
});
}
FrontendMessage::TriggerImport => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters: vec![
FileFilter {
name: "Svg".to_string(),
extensions: vec!["svg".to_string()],
},
FileFilter {
name: "Image".to_string(),
extensions: vec!["png".to_string(), "jpg".to_string(), "jpeg".to_string(), "bmp".to_string()],
},
],
filters: vec![],
context: OpenFileDialogContext::Import,
});
}
@@ -136,6 +124,9 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerClipboardWrite { content } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
}
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
FrontendMessage::WindowClose => {
dispatcher.respond(DesktopFrontendMessage::WindowClose);
}
@@ -145,6 +136,9 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::WindowMaximize => {
dispatcher.respond(DesktopFrontendMessage::WindowMaximize);
}
FrontendMessage::WindowFullscreen => {
dispatcher.respond(DesktopFrontendMessage::WindowFullscreen);
}
FrontendMessage::WindowDrag => {
dispatcher.respond(DesktopFrontendMessage::WindowDrag);
}
+15 -11
View File
@@ -1,10 +1,10 @@
use graph_craft::wasm_application_io::WasmApplicationIo;
use graphite_editor::application::Editor;
use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message};
// TODO: Remove usage of this reexport in desktop create and remove this line
pub use graphene_std::Color;
pub use graphite_editor::consts::FILE_EXTENSION;
pub use wgpu_executor::TargetTexture;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
pub use wgpu_executor::WgpuExecutor;
@@ -27,8 +27,18 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new() -> Self {
Self { editor: Editor::new() }
pub fn new(uuid_random_seed: u64) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
let host = Host::Mac;
#[cfg(target_os = "linux")]
let host = Host::Linux;
let env = Environment { platform: Platform::Desktop, host };
Self {
editor: Editor::new(env, uuid_random_seed),
}
}
pub fn init(&self, wgpu_context: WgpuContext) {
@@ -51,12 +61,6 @@ impl DesktopWrapper {
}
}
impl Default for DesktopWrapper {
fn default() -> Self {
Self::new()
}
}
pub enum NodeGraphExecutionResult {
HasRun(Option<wgpu::Texture>),
NotRun,
+8 -21
View File
@@ -65,9 +65,11 @@ pub enum DesktopFrontendMessage {
ClipboardWrite {
content: String,
},
PointerLock,
WindowClose,
WindowMinimize,
WindowMaximize,
WindowFullscreen,
WindowDrag,
WindowHide,
WindowHideOthers,
@@ -77,7 +79,7 @@ pub enum DesktopFrontendMessage {
pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Input(InputMessage),
OpenFileDialogResult {
FileDialogResult {
path: PathBuf,
content: Vec<u8>,
context: OpenFileDialogContext,
@@ -86,10 +88,6 @@ pub enum DesktopWrapperMessage {
path: PathBuf,
context: SaveFileDialogContext,
},
OpenDocument {
path: PathBuf,
content: Vec<u8>,
},
OpenFile {
path: PathBuf,
content: Vec<u8>,
@@ -98,16 +96,7 @@ pub enum DesktopWrapperMessage {
path: PathBuf,
content: Vec<u8>,
},
ImportSvg {
path: PathBuf,
content: Vec<u8>,
},
ImportImage {
path: PathBuf,
content: Vec<u8>,
},
PollNodeGraphEvaluation,
UpdatePlatform(Platform),
UpdateMaximized {
maximized: bool,
},
@@ -132,6 +121,10 @@ pub enum DesktopWrapperMessage {
ClipboardReadResult {
content: Option<String>,
},
PointerLockMove {
x: f64,
y: f64,
},
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
@@ -148,7 +141,7 @@ pub struct FileFilter {
}
pub enum OpenFileDialogContext {
Document,
Open,
Import,
}
@@ -157,12 +150,6 @@ pub enum SaveFileDialogContext {
File { content: Vec<u8> },
}
pub enum Platform {
Windows,
Mac,
Linux,
}
pub enum MenuItem {
Action {
id: String,
+1 -1
View File
@@ -21,7 +21,7 @@ pub(crate) mod menu {
widgets
.into_iter()
.map(|widget| {
let text_button = match &widget.widget {
let text_button = match widget.widget.as_ref() {
Widget::TextButton(text_button) => text_button,
_ => panic!("Menu bar layout top-level widgets are supposed to be text buttons"),
};
+6 -4
View File
@@ -18,16 +18,18 @@ fn main() {
if !gh.trim().is_empty() {
gh.trim().to_string()
} else {
git_or_unknown(&["rev-parse", "--abbrev-ref", "HEAD"])
git(&["rev-parse", "--abbrev-ref", "HEAD"]).unwrap_or_default()
}
});
// Instruct Cargo to set environment variables for compile time.
// They are accessed with the `env!("GRAPHITE_*")` macro in the codebase.
println!("cargo:rustc-env=GRAPHITE_GIT_COMMIT_DATE={commit_date}");
println!("cargo:rustc-env=GRAPHITE_GIT_COMMIT_HASH={commit_hash}");
println!("cargo:rustc-env=GRAPHITE_GIT_COMMIT_BRANCH={commit_branch}");
println!("cargo:rustc-env=GRAPHITE_RELEASE_SERIES={GRAPHITE_RELEASE_SERIES}");
if !commit_branch.is_empty() {
println!("cargo:rustc-env=GRAPHITE_GIT_COMMIT_BRANCH={commit_branch}");
}
println!("cargo:rustc-env=GRAPHITE_GIT_COMMIT_HASH={commit_hash}");
println!("cargo:rustc-env=GRAPHITE_GIT_COMMIT_DATE={commit_date}");
}
/// Get an environment variable, or if it is not set or empty, use the provided fallback function. Returns a string with trimmed whitespace.
+70 -21
View File
@@ -1,24 +1,31 @@
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
pub use graphene_std::uuid::*;
use std::sync::OnceLock;
// TODO: serialize with serde to save the current editor state
pub struct Editor {
pub dispatcher: Dispatcher,
}
impl Editor {
/// Construct the editor.
/// Remember to provide a random seed with `editor::set_uuid_seed(seed)` before any editors can be used.
pub fn new() -> Self {
pub fn new(environment: Environment, uuid_random_seed: u64) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
Self { dispatcher: Dispatcher::new() }
}
#[cfg(test)]
pub(crate) fn new_local_executor() -> (Self, crate::node_graph_executor::NodeRuntime) {
let _ = ENVIRONMENT.set(*Editor::environment());
graphene_std::uuid::set_uuid_seed(0);
let (runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
let dispatcher = Dispatcher::with_executor(executor);
(Self { dispatcher }, runtime)
let editor = Self {
dispatcher: Dispatcher::with_executor(executor),
};
(editor, runtime)
}
pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Vec<FrontendMessage> {
@@ -32,26 +39,68 @@ impl Editor {
}
}
impl Default for Editor {
fn default() -> Self {
Self::new()
static ENVIRONMENT: OnceLock<Environment> = OnceLock::new();
impl Editor {
#[cfg(not(test))]
pub fn environment() -> &'static Environment {
ENVIRONMENT.get().expect("Editor environment accessed before initialization")
}
#[cfg(test)]
pub fn environment() -> &'static Environment {
&Environment {
platform: Platform::Desktop,
host: Host::Linux,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct Environment {
pub platform: Platform,
pub host: Host,
}
#[derive(Clone, Copy, Debug)]
pub enum Platform {
Desktop,
Web,
}
#[derive(Clone, Copy, Debug)]
pub enum Host {
Windows,
Mac,
Linux,
}
impl Environment {
pub fn is_desktop(&self) -> bool {
matches!(self.platform, Platform::Desktop)
}
pub fn is_web(&self) -> bool {
matches!(self.platform, Platform::Web)
}
pub fn is_windows(&self) -> bool {
matches!(self.host, Host::Windows)
}
pub fn is_mac(&self) -> bool {
matches!(self.host, Host::Mac)
}
pub fn is_linux(&self) -> bool {
matches!(self.host, Host::Linux)
}
}
pub const GRAPHITE_RELEASE_SERIES: &str = env!("GRAPHITE_RELEASE_SERIES");
pub const GRAPHITE_GIT_COMMIT_DATE: &str = env!("GRAPHITE_GIT_COMMIT_DATE");
pub const GRAPHITE_GIT_COMMIT_BRANCH: Option<&str> = option_env!("GRAPHITE_GIT_COMMIT_BRANCH");
pub const GRAPHITE_GIT_COMMIT_HASH: &str = env!("GRAPHITE_GIT_COMMIT_HASH");
pub const GRAPHITE_GIT_COMMIT_BRANCH: &str = env!("GRAPHITE_GIT_COMMIT_BRANCH");
pub const GRAPHITE_GIT_COMMIT_DATE: &str = env!("GRAPHITE_GIT_COMMIT_DATE");
pub fn commit_info_localized(localized_commit_date: &str) -> String {
format!(
"Release Series: {}\n\
Branch: {}\n\
Commit: {}\n\
{}",
GRAPHITE_RELEASE_SERIES,
GRAPHITE_GIT_COMMIT_BRANCH,
GRAPHITE_GIT_COMMIT_HASH.get(..8).unwrap_or(GRAPHITE_GIT_COMMIT_HASH),
localized_commit_date
)
let mut info = String::new();
info.push_str(&format!("Release Series: {GRAPHITE_RELEASE_SERIES}\n"));
if let Some(branch) = GRAPHITE_GIT_COMMIT_BRANCH {
info.push_str(&format!("Branch: {branch}\n"));
}
info.push_str(&format!("Commit: {}\n", GRAPHITE_GIT_COMMIT_HASH.get(..8).unwrap_or(GRAPHITE_GIT_COMMIT_HASH)));
info.push_str(localized_commit_date);
info
}
+6
View File
@@ -56,6 +56,8 @@ pub const DEFAULT_STROKE_WIDTH: f64 = 2.;
pub const SELECTION_TOLERANCE: f64 = 5.;
pub const DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD: f64 = 15.;
pub const SELECTION_DRAG_ANGLE: f64 = 90.;
pub const LAYER_ORIGIN_CROSS_DIAMETER: f64 = 10.;
pub const LAYER_ORIGIN_CROSS_THICKNESS: f64 = 1.;
// PIVOT
pub const PIVOT_CROSSHAIR_THICKNESS: f64 = 1.;
@@ -122,6 +124,9 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
// EYEDROPPER TOOL
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
// GIZMOS
pub const POINT_RADIUS_HANDLE_SNAP_THRESHOLD: f64 = 8.;
pub const POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD: f64 = 7.9;
@@ -148,6 +153,7 @@ pub const COLOR_OVERLAY_RED: &str = "#ef5454";
pub const COLOR_OVERLAY_GRAY: &str = "#cccccc";
pub const COLOR_OVERLAY_GRAY_25: &str = "#cccccc40";
pub const COLOR_OVERLAY_WHITE: &str = "#ffffff";
pub const COLOR_OVERLAY_BLACK: &str = "#000000";
pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
// DOCUMENT
+6 -13
View File
@@ -23,12 +23,11 @@ pub struct DispatcherMessageHandlers {
debug_message_handler: DebugMessageHandler,
defer_message_handler: DeferMessageHandler,
dialog_message_handler: DialogMessageHandler,
globals_message_handler: GlobalsMessageHandler,
input_preprocessor_message_handler: InputPreprocessorMessageHandler,
key_mapping_message_handler: KeyMappingMessageHandler,
layout_message_handler: LayoutMessageHandler,
menu_bar_message_handler: MenuBarMessageHandler,
pub portfolio_message_handler: PortfolioMessageHandler,
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
preferences_message_handler: PreferencesMessageHandler,
tool_message_handler: ToolMessageHandler,
viewport_message_handler: ViewportMessageHandler,
@@ -192,17 +191,11 @@ impl Dispatcher {
self.responses.push(message);
}
}
Message::Globals(message) => {
self.message_handlers.globals_message_handler.process_message(message, &mut queue, ());
}
Message::InputPreprocessor(message) => {
let keyboard_platform = GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
self.message_handlers.input_preprocessor_message_handler.process_message(
message,
&mut queue,
InputPreprocessorMessageContext {
keyboard_platform,
viewport: &self.message_handlers.viewport_message_handler,
},
);
@@ -239,6 +232,7 @@ impl Dispatcher {
Message::MenuBar(message) => {
let menu_bar_message_handler = &mut self.message_handlers.menu_bar_message_handler;
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.focus_document;
menu_bar_message_handler.data_panel_open = self.message_handlers.portfolio_message_handler.data_panel_open;
menu_bar_message_handler.layers_panel_open = self.message_handlers.portfolio_message_handler.layers_panel_open;
menu_bar_message_handler.properties_panel_open = self.message_handlers.portfolio_message_handler.properties_panel_open;
@@ -578,10 +572,9 @@ mod test {
"Demo artwork '{document_name}' has more than 1 line (remember to open and re-save it in Graphite)",
);
let responses = editor.editor.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: Some(document_name.to_string()),
document_path: None,
document_serialized_content,
let responses = editor.editor.handle_message(PortfolioMessage::OpenFile {
path: file_name.into(),
content: document_serialized_content.bytes().collect(),
});
// Check if the graph renders
@@ -594,7 +587,7 @@ mod test {
if let FrontendMessage::UpdateDialogColumn1 { diff } = response {
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
if let LayoutGroup::Row { widgets } = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &widgets[0].widget {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
@@ -1,14 +1,14 @@
use crate::messages::prelude::*;
use super::app_window_message_handler::AppWindowPlatform;
#[impl_message(Message, AppWindow)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum AppWindowMessage {
UpdatePlatform { platform: AppWindowPlatform },
PointerLock,
PointerLockMove { x: f64, y: f64 },
Close,
Minimize,
Maximize,
Fullscreen,
Drag,
Hide,
HideOthers,
@@ -1,19 +1,20 @@
use crate::messages::app_window::AppWindowMessage;
use crate::application::{Environment, Platform};
use crate::messages::prelude::*;
use crate::{application::Host, messages::app_window::AppWindowMessage};
use graphite_proc_macros::{ExtractField, message_handler_data};
#[derive(Debug, Clone, Default, ExtractField)]
pub struct AppWindowMessageHandler {
platform: AppWindowPlatform,
}
pub struct AppWindowMessageHandler {}
#[message_handler_data]
impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
fn process_message(&mut self, message: AppWindowMessage, responses: &mut std::collections::VecDeque<Message>, _: ()) {
match message {
AppWindowMessage::UpdatePlatform { platform } => {
self.platform = platform;
responses.add(FrontendMessage::UpdatePlatform { platform: self.platform });
AppWindowMessage::PointerLock => {
responses.add(FrontendMessage::WindowPointerLock);
}
AppWindowMessage::PointerLockMove { x, y } => {
responses.add(FrontendMessage::WindowPointerLockMove { x, y });
}
AppWindowMessage::Close => {
responses.add(FrontendMessage::WindowClose);
@@ -24,6 +25,9 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
AppWindowMessage::Maximize => {
responses.add(FrontendMessage::WindowMaximize);
}
AppWindowMessage::Fullscreen => {
responses.add(FrontendMessage::WindowFullscreen);
}
AppWindowMessage::Drag => {
responses.add(FrontendMessage::WindowDrag);
}
@@ -42,6 +46,7 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
Close,
Minimize,
Maximize,
Fullscreen,
Drag,
Hide,
HideOthers,
@@ -56,3 +61,14 @@ pub enum AppWindowPlatform {
Mac,
Linux,
}
impl From<&Environment> for AppWindowPlatform {
fn from(environment: &Environment) -> Self {
match (environment.platform, environment.host) {
(Platform::Web, _) => AppWindowPlatform::Web,
(Platform::Desktop, Host::Linux) => AppWindowPlatform::Linux,
(Platform::Desktop, Host::Mac) => AppWindowPlatform::Mac,
(Platform::Desktop, Host::Windows) => AppWindowPlatform::Windows,
}
}
}
@@ -1,4 +1,5 @@
use super::simple_dialogs::{self, AboutGraphiteDialog, DemoArtworkDialog, LicensesDialog};
use crate::application::GRAPHITE_GIT_COMMIT_DATE;
use crate::messages::dialog::simple_dialogs::LicensesThirdPartyDialog;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
@@ -48,7 +49,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
}
DialogMessage::RequestAboutGraphiteDialog => {
responses.add(FrontendMessage::TriggerAboutGraphiteLocalizedCommitDate {
commit_date: env!("GRAPHITE_GIT_COMMIT_DATE").into(),
commit_date: GRAPHITE_GIT_COMMIT_DATE.into(),
});
}
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
@@ -43,13 +43,21 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
ExportDialogMessage::TransparentBackground { transparent } => self.transparent_background = transparent,
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
ExportDialogMessage::Submit => responses.add_front(PortfolioMessage::SubmitDocumentExport {
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
file_type: self.file_type,
scale_factor: self.scale_factor,
bounds: self.bounds,
transparent_background: self.file_type != FileType::Jpg && self.transparent_background,
}),
ExportDialogMessage::Submit => {
let artboard_name = match self.bounds {
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
_ => None,
};
responses.add_front(PortfolioMessage::SubmitDocumentExport {
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
file_type: self.file_type,
scale_factor: self.scale_factor,
bounds: self.bounds,
transparent_background: self.file_type != FileType::Jpg && self.transparent_background,
artboard_name,
artboard_count: self.artboards.len(),
})
}
}
self.send_dialog_to_frontend(responses);
@@ -92,14 +100,14 @@ impl LayoutHolder for ExportDialogMessageHandler {
.collect();
let export_type = vec![
TextLabel::new("File Type").table_align(true).min_width("100px").widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("File Type").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(self.file_type as u32)).widget_instance(),
];
let resolution = vec![
TextLabel::new("Scale Factor").table_align(true).min_width("100px").widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("Scale Factor").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.scale_factor))
.unit("")
.min(0.)
@@ -144,15 +152,15 @@ impl LayoutHolder for ExportDialogMessageHandler {
}
let export_area = vec![
TextLabel::new("Bounds").table_align(true).min_width("100px").widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("Bounds").table_align(true).min_width(100).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
];
let checkbox_id = CheckboxId::new();
let transparent_background = vec![
TextLabel::new("Transparency").table_align(true).min_width("100px").for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("Transparency").table_align(true).min_width(100).for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.transparent_background)
.disabled(self.file_type == FileType::Jpg)
.on_update(move |value: &CheckboxInput| ExportDialogMessage::TransparentBackground { transparent: value.checked }.into())
@@ -73,8 +73,8 @@ impl DialogLayoutHolder for NewDocumentDialogMessageHandler {
impl LayoutHolder for NewDocumentDialogMessageHandler {
fn layout(&self) -> Layout {
let name = vec![
TextLabel::new("Name").table_align(true).min_width("90px").widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("Name").table_align(true).min_width(90).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(&self.name)
.on_update(|text_input: &TextInput| NewDocumentDialogMessage::Name { name: text_input.value.clone() }.into())
.min_width(204) // Matches the 100px of both NumberInputs below + the 4px of the Unrelated-type separator
@@ -83,8 +83,8 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
let checkbox_id = CheckboxId::new();
let infinite = vec![
TextLabel::new("Infinite Canvas").table_align(true).min_width("90px").for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("Infinite Canvas").table_align(true).min_width(90).for_checkbox(checkbox_id).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.infinite)
.on_update(|checkbox_input: &CheckboxInput| NewDocumentDialogMessage::Infinite { infinite: checkbox_input.checked }.into())
.for_label(checkbox_id)
@@ -92,8 +92,8 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
];
let scale = vec![
TextLabel::new("Dimensions").table_align(true).min_width("90px").widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
TextLabel::new("Dimensions").table_align(true).min_width(90).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.dimensions.x as f64))
.label("W")
.unit(" px")
@@ -104,7 +104,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
.min_width(100)
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(self.dimensions.y as f64))
.label("H")
.unit(" px")
@@ -46,13 +46,13 @@ impl PreferencesDialogMessageHandler {
let zoom_rate_description = "Adjust how fast zooming occurs when using the scroll wheel or pinch gesture (relative to a default of 50).";
let zoom_rate_label = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Zoom Rate").tooltip_label("Zoom Rate").tooltip_description(zoom_rate_description).widget_instance(),
];
let zoom_rate = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(map_zoom_rate_to_display(preferences.viewport_zoom_wheel_rate)))
.tooltip_label("Zoom Rate")
.tooltip_description(zoom_rate_description)
@@ -74,8 +74,8 @@ impl PreferencesDialogMessageHandler {
let checkbox_id = CheckboxId::new();
let zoom_with_scroll_description = "Use the scroll wheel for zooming instead of vertically panning (not recommended for trackpads).";
let zoom_with_scroll = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.zoom_with_scroll)
.tooltip_label("Zoom with Scroll")
.tooltip_description(zoom_with_scroll_description)
@@ -104,8 +104,8 @@ impl PreferencesDialogMessageHandler {
let header = vec![TextLabel::new("Editing").italic(true).widget_instance()];
let selection_label = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Selection")
.tooltip_label("Selection")
.tooltip_description("Choose how targets are selected within dragged rectangular and lasso areas.")
@@ -147,8 +147,8 @@ impl PreferencesDialogMessageHandler {
.selected_index(Some(preferences.selection_mode as u32))
.widget_instance();
let selection_mode = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
selection_mode,
];
@@ -164,13 +164,13 @@ impl PreferencesDialogMessageHandler {
let scale_description = "Adjust the scale of the entire user interface (100% is default).";
let scale_label = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Scale").tooltip_label("Scale").tooltip_description(scale_description).widget_instance(),
];
let scale = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(ui_scale_to_display(preferences.ui_scale)))
.tooltip_label("Scale")
.tooltip_description(scale_description)
@@ -204,8 +204,8 @@ impl PreferencesDialogMessageHandler {
let node_graph_section_description = "Configure the appearance of the wires running between node connections in the graph.";
let node_graph_wires_label = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Node Graph Wires")
.tooltip_label("Node Graph Wires")
.tooltip_description(node_graph_section_description)
@@ -226,8 +226,8 @@ impl PreferencesDialogMessageHandler {
.selected_index(Some(preferences.graph_wire_style as u32))
.widget_instance();
let graph_wire_style = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
graph_wire_style,
];
@@ -239,8 +239,8 @@ impl PreferencesDialogMessageHandler {
vello_description.push_str("\n\n(Your browser must support WebGPU.)");
let use_vello = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.use_vello && preferences.supports_wgpu())
.tooltip_label("Vello Renderer")
.tooltip_description(vello_description.clone())
@@ -256,29 +256,6 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
let checkbox_id = CheckboxId::new();
let vector_mesh_description = "
Allow the Pen tool to produce branching geometry, where more than two segments may be connected to one anchor point.\n\
\n\
Currently, vector meshes do not properly render strokes (branching joins) and fills (multiple regions).
"
.trim();
let vector_meshes = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
CheckboxInput::new(preferences.vector_meshes)
.tooltip_label("Vector Meshes")
.tooltip_description(vector_mesh_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::VectorMeshes { enabled: checkbox_input.checked }.into())
.for_label(checkbox_id)
.widget_instance(),
TextLabel::new("Vector Meshes")
.tooltip_label("Vector Meshes")
.tooltip_description(vector_mesh_description)
.for_checkbox(checkbox_id)
.widget_instance(),
];
let checkbox_id = CheckboxId::new();
let brush_tool_description = "
Enable the Brush tool to support basic raster-based layer painting.\n\
@@ -289,8 +266,8 @@ impl PreferencesDialogMessageHandler {
"
.trim();
let brush_tool = vec![
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.brush_tool)
.tooltip_label("Brush Tool")
.tooltip_description(brush_tool_description)
@@ -304,7 +281,7 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
rows.extend_from_slice(&[header, node_graph_wires_label, graph_wire_style, use_vello, vector_meshes, brush_tool]);
rows.extend_from_slice(&[header, node_graph_wires_label, graph_wire_style, use_vello, brush_tool]);
}
Layout(rows.into_iter().map(|r| LayoutGroup::Row { widgets: r }).collect())
@@ -18,25 +18,19 @@ impl DialogLayoutHolder for LicensesDialog {
fn layout_column_2(&self) -> Layout {
#[allow(clippy::type_complexity)]
let button_definitions: &[(&str, &str, fn() -> Message)] = &[
("GraphiteLogo", "Graphite Logo", || {
("Code", "Source Code License", || {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.art/logo/".into(),
url: "https://graphite.art/license#source-code".into(),
}
.into()
}),
("IconsGrid", "Graphite Icons", || {
("GraphiteLogo", "Branding License", || {
FrontendMessage::TriggerVisitLink {
url: "https://raw.githubusercontent.com/GraphiteEditor/Graphite/master/frontend/assets/LICENSE.md".into(),
url: "https://graphite.art/license#branding".into(),
}
.into()
}),
("License", "Graphite License", || {
FrontendMessage::TriggerVisitLink {
url: "https://graphite.art/license/".into(),
}
.into()
}),
("License", "Other Licenses", || FrontendMessage::TriggerDisplayThirdPartyLicensesDialog.into()),
("IconsGrid", "Dependency Licenses", || FrontendMessage::TriggerDisplayThirdPartyLicensesDialog.into()),
];
let widgets = button_definitions
.iter()
@@ -52,13 +46,11 @@ impl LayoutHolder for LicensesDialog {
let year = &self.localized_commit_year;
let description = format!(
"
The Graphite logo and brand identity are copyright © {year}\nGraphite Labs, LLC. See \"Graphite Logo\" for usage policy.\n\
Graphite source code is copyright © {year} Graphite contrib-\nutors and is available under the Apache License 2.0. See\n\"Source Code License\" for details.\n\
\n\
The Graphite editor's icons and design assets are copyright\n© {year} Graphite Labs, LLC. See \"Graphite Icons\" 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 code is copyright © {year} Graphite contributors\nand is made available under the Apache 2.0 license. See\n\"Graphite License\" for details.\n\
\n\
Graphite is distributed with third-party open source code\ndependencies. See \"Other Licenses\" for details.
Graphite is distributed with third-party open source code\ndependencies. See \"Dependency Licenses\" for details.
"
);
let description = description.trim();
@@ -29,14 +29,14 @@ impl LayoutHolder for LicensesThirdPartyDialog {
};
// Two characters (one before, one after) the sequence of underscore characters, plus one additional column to provide a space between the text and the scrollbar
let non_wrapping_column_width = license_text.split('\n').map(|line| line.chars().filter(|&c| c == '_').count()).max().unwrap_or(0) + 2 + 1;
let non_wrapping_column_width = license_text.split('\n').map(|line| line.chars().filter(|&c| c == '_').count() as u32).max().unwrap_or(0) + 2 + 1;
Layout(vec![LayoutGroup::Row {
widgets: vec![
TextLabel::new(license_text)
.monospace(true)
.multiline(true)
.min_width(format!("{non_wrapping_column_width}ch"))
.min_width_characters(non_wrapping_column_width)
.widget_instance(),
],
}])
@@ -1,11 +1,12 @@
use super::utility_types::{DocumentDetails, MouseCursorIcon, OpenDocument};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::EyedropperPreviewImage;
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::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic, Transform,
};
use crate::messages::portfolio::document::utility_types::nodes::{JsRawBuffer, LayerPanelEntry, RawBuffer};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::prelude::*;
use glam::IVec2;
@@ -64,8 +65,10 @@ pub enum FrontendMessage {
#[serde(rename = "nodeTypes")]
node_types: Vec<FrontendNodeType>,
},
SendShortcutF11 {
SendShortcutFullscreen {
shortcut: Option<ActionShortcut>,
#[serde(rename = "shortcutMac")]
shortcut_mac: Option<ActionShortcut>,
},
SendShortcutAltClick {
shortcut: Option<ActionShortcut>,
@@ -105,7 +108,6 @@ pub enum FrontendMessage {
font: Font,
url: String,
},
TriggerImport,
TriggerPersistenceRemoveDocument {
#[serde(rename = "documentId")]
document_id: DocumentId,
@@ -120,7 +122,8 @@ pub enum FrontendMessage {
TriggerLoadRestAutoSaveDocuments,
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpenDocument,
TriggerOpen,
TriggerImport,
TriggerSavePreferences {
preferences: PreferencesMessageHandler,
},
@@ -232,12 +235,8 @@ pub enum FrontendMessage {
data: LayerPanelEntry,
},
UpdateDocumentLayerStructure {
#[serde(rename = "dataBuffer")]
data_buffer: RawBuffer,
},
UpdateDocumentLayerStructureJs {
#[serde(rename = "dataBuffer")]
data_buffer: JsRawBuffer,
#[serde(rename = "layerStructure")]
layer_structure: Vec<LayerStructureEntry>,
},
UpdateDocumentRulers {
origin: (f64, f64),
@@ -251,6 +250,7 @@ pub enum FrontendMessage {
multiplier: (f64, f64),
},
UpdateEyedropperSamplingState {
image: Option<EyedropperPreviewImage>,
#[serde(rename = "mousePosition")]
mouse_position: Option<(f64, f64)>,
#[serde(rename = "primaryColor")]
@@ -327,6 +327,9 @@ pub enum FrontendMessage {
UpdateStatusBarHintsLayout {
diff: Vec<WidgetDiff>,
},
UpdateStatusBarInfoLayout {
diff: Vec<WidgetDiff>,
},
UpdateWorkingColorsLayout {
diff: Vec<WidgetDiff>,
},
@@ -360,9 +363,15 @@ pub enum FrontendMessage {
},
// Window prefix: cause the application window to do something
WindowPointerLock,
WindowPointerLockMove {
x: f64,
y: f64,
},
WindowClose,
WindowMinimize,
WindowMaximize,
WindowFullscreen,
WindowDrag,
WindowHide,
WindowHideOthers,
@@ -62,3 +62,10 @@ pub enum ExportBounds {
Selection,
Artboard(LayerNodeIdentifier),
}
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct EyedropperPreviewImage {
pub data: Vec<u8>,
pub width: u32,
pub height: u32,
}
@@ -1,4 +0,0 @@
use crate::messages::portfolio::utility_types::Platform;
use std::sync::OnceLock;
pub static GLOBAL_PLATFORM: OnceLock<Platform> = OnceLock::new();
@@ -1,8 +0,0 @@
use crate::messages::portfolio::utility_types::Platform;
use crate::messages::prelude::*;
#[impl_message(Message, Globals)]
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum GlobalsMessage {
SetPlatform { platform: Platform },
}
@@ -1,20 +0,0 @@
use crate::messages::prelude::*;
#[derive(Debug, Default, ExtractField)]
pub struct GlobalsMessageHandler {}
#[message_handler_data]
impl MessageHandler<GlobalsMessage, ()> for GlobalsMessageHandler {
fn process_message(&mut self, message: GlobalsMessage, _responses: &mut VecDeque<Message>, _: ()) {
match message {
GlobalsMessage::SetPlatform { platform } => {
if GLOBAL_PLATFORM.get() != Some(&platform) {
GLOBAL_PLATFORM.set(platform).expect("Failed to set GLOBAL_PLATFORM");
}
}
}
}
advertise_actions!(GlobalsMessageDiscriminant;
);
}
-9
View File
@@ -1,9 +0,0 @@
mod globals_message;
mod globals_message_handler;
pub mod global_variables;
#[doc(inline)]
pub use globals_message::{GlobalsMessage, GlobalsMessageDiscriminant};
#[doc(inline)]
pub use globals_message_handler::GlobalsMessageHandler;
@@ -1,10 +1,9 @@
use super::utility_types::input_keyboard::KeysGroup;
use super::utility_types::misc::Mapping;
use crate::application::Editor;
use crate::messages::input_mapper::utility_types::input_keyboard::{self, Key};
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
use std::fmt::Write;
#[derive(ExtractField)]
pub struct InputMapperMessageContext<'a> {
@@ -34,27 +33,6 @@ impl InputMapperMessageHandler {
self.mapping = mapping;
}
pub fn hints(&self, actions: ActionList) -> String {
let mut output = String::new();
let mut actions = actions
.into_iter()
.flatten()
.filter(|a| !matches!(*a, MessageDiscriminant::Tool(ToolMessageDiscriminant::ActivateTool) | MessageDiscriminant::Debug(_)));
self.mapping
.key_down
.iter()
.enumerate()
.filter_map(|(i, m)| {
let ma = m.0.iter().find_map(|m| actions.find_map(|a| (a == m.action.to_discriminant()).then(|| m.action.to_discriminant())));
ma.map(|a| ((i as u8).try_into().unwrap(), a))
})
.for_each(|(k, a): (Key, _)| {
let _ = write!(output, "{}: {}, ", k.to_discriminant().local_name(), a.local_name().split('.').next_back().unwrap());
});
output.replace("Key", "")
}
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option<KeysGroup> {
let all_key_mapping_entries = std::iter::empty()
.chain(self.mapping.key_up.iter())
@@ -70,11 +48,7 @@ impl InputMapperMessageHandler {
let found_actions = all_mapping_entries.filter(|entry| entry.action.to_discriminant() == *action_to_find);
// Get the `Key` for this platform's accelerator key
let keyboard_layout = || GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
let platform_accel_key = match keyboard_layout() {
KeyboardPlatformLayout::Standard => Key::Control,
KeyboardPlatformLayout::Mac => Key::Command,
};
let platform_accel_key = if Editor::environment().is_mac() { Key::Command } else { Key::Control };
let entry_to_key = |entry: &MappingEntry| {
// Get the modifier keys for the entry (and convert them to Key)
@@ -1,3 +1,4 @@
use crate::application::Editor;
use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT};
use crate::messages::input_mapper::key_mapping::MappingVariant;
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates};
@@ -8,7 +9,6 @@ use crate::messages::input_mapper::utility_types::misc::{KeyMappingEntries, Mapp
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpdate;
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
@@ -17,16 +17,18 @@ use glam::DVec2;
impl From<MappingVariant> for Mapping {
fn from(value: MappingVariant) -> Self {
match value {
MappingVariant::Default => input_mappings(),
MappingVariant::ZoomWithScroll => zoom_with_scroll(),
MappingVariant::Default => input_mappings(false),
MappingVariant::ZoomWithScroll => input_mappings(true),
}
}
}
pub fn input_mappings() -> Mapping {
pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
use InputMapperMessage::*;
use Key::*;
let is_mac = Editor::environment().is_mac();
// NOTICE:
// If a new mapping you added here isn't working (and perhaps another lower-precedence one is instead), make sure to advertise
// it as an available action in the respective message handler file (such as the bottom of `document_message_handler.rs`).
@@ -54,6 +56,11 @@ pub fn input_mappings() -> Mapping {
// Hack to prevent Left Click + Accel + Z combo (this effectively blocks you from making a double undo with AbortTransaction)
entry!(KeyDown(KeyZ); modifiers=[Accel, MouseLeft], action_dispatch=DocumentMessage::Noop),
//
// AppWindowMessage
entry!(KeyDown(F11); disabled=is_mac, action_dispatch=AppWindowMessage::Fullscreen),
entry!(KeyDown(KeyF); modifiers=[Command, Control], disabled=!is_mac, action_dispatch=AppWindowMessage::Fullscreen),
entry!(KeyDown(KeyQ); modifiers=[Command], disabled=cfg!(not(target_os = "macos")), action_dispatch=AppWindowMessage::Close),
//
// ClipboardMessage
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=ClipboardMessage::Cut),
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=ClipboardMessage::Copy),
@@ -171,7 +178,6 @@ pub fn input_mappings() -> Mapping {
entry!(KeyDown(MouseLeft); action_dispatch=GradientToolMessage::PointerDown),
entry!(PointerMove; refresh_keys=[Shift], action_dispatch=GradientToolMessage::PointerMove { constrain_axis: Shift }),
entry!(KeyUp(MouseLeft); action_dispatch=GradientToolMessage::PointerUp),
entry!(DoubleClick(MouseButton::Left); action_dispatch=GradientToolMessage::InsertStop),
entry!(KeyDown(Delete); action_dispatch=GradientToolMessage::DeleteStop),
entry!(KeyDown(Backspace); action_dispatch=GradientToolMessage::DeleteStop),
entry!(KeyDown(MouseRight); action_dispatch=GradientToolMessage::Abort),
@@ -327,7 +333,8 @@ pub fn input_mappings() -> Mapping {
entry!(KeyDown(KeyX); modifiers=[Shift], action_dispatch=ToolMessage::SwapColors),
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=ToolMessage::SelectRandomWorkingColor { primary: true }),
entry!(KeyDown(KeyC); modifiers=[Alt, Shift], action_dispatch=ToolMessage::SelectRandomWorkingColor { primary: false }),
entry!(KeyDownNoRepeat(Tab); action_dispatch=ToolMessage::ToggleSelectVsPath),
// TODO: Change to KeyDownNoRepeat when https://github.com/GraphiteEditor/Graphite/issues/2266 is resolved
entry!(KeyDown(Tab); action_dispatch=ToolMessage::ToggleSelectVsPath),
//
// DocumentMessage
entry!(KeyDown(Space); modifiers=[Control], action_dispatch=DocumentMessage::GraphViewOverlayToggle),
@@ -416,10 +423,14 @@ pub fn input_mappings() -> Mapping {
entry!(KeyDown(FakeKeyPlus); modifiers=[Accel], canonical, action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
entry!(KeyDown(Equal); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }),
entry!(KeyDown(Minus); modifiers=[Accel], action_dispatch=NavigationMessage::CanvasZoomDecrease { center_on_mouse: false }),
entry!(WheelScroll; modifiers=[Control], action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(WheelScroll; modifiers=[Command], action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(WheelScroll; modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
entry!(WheelScroll; action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
entry!(WheelScroll; modifiers=[Control], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(WheelScroll; modifiers=[Command], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(WheelScroll; modifiers=[Shift], disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
entry!(WheelScroll; disabled=zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
// On Mac, the OS already converts Shift+scroll into horizontal scrolling so we have to reverse the behavior from normal to produce the same outcome
entry!(WheelScroll; modifiers=[Control], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: is_mac }),
entry!(WheelScroll; modifiers=[Shift], disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: !is_mac }),
entry!(WheelScroll; disabled=!zoom_with_scroll, action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(KeyDown(PageUp); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(1., 0.) }),
entry!(KeyDown(PageDown); modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(-1., 0.) }),
entry!(KeyDown(PageUp); action_dispatch=NavigationMessage::CanvasPanByViewportFraction { delta: DVec2::new(0., 1.) }),
@@ -431,12 +442,13 @@ pub fn input_mappings() -> Mapping {
entry!(KeyDown(Tab); modifiers=[Control, Shift], action_dispatch=PortfolioMessage::PrevDocument),
entry!(KeyDown(KeyW); modifiers=[Accel], action_dispatch=PortfolioMessage::CloseActiveDocumentWithConfirmation),
entry!(KeyDown(KeyW); modifiers=[Accel, Alt], action_dispatch=PortfolioMessage::CloseAllDocumentsWithConfirmation),
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=PortfolioMessage::OpenDocument),
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=PortfolioMessage::Open),
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=PortfolioMessage::Import),
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PortfolioMessage::Cut { clipboard: Clipboard::Device }),
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PortfolioMessage::Copy { clipboard: Clipboard::Device }),
entry!(KeyDown(KeyR); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleRulers),
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleDataPanelOpen),
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleFocusDocument),
//
// DialogMessage
entry!(KeyDown(KeyE); modifiers=[Accel], action_dispatch=DialogMessage::RequestExportDialog),
@@ -471,7 +483,7 @@ pub fn input_mappings() -> Mapping {
// Sort `pointer_shake`
sort(&mut pointer_shake);
let mut mapping = Mapping {
Mapping {
key_up,
key_down,
key_up_no_repeat,
@@ -480,54 +492,5 @@ pub fn input_mappings() -> Mapping {
wheel_scroll,
pointer_move,
pointer_shake,
};
if cfg!(target_os = "macos") {
let remove: [&[&[MappingEntry; 0]; 0]; 0] = [];
let add = [entry!(KeyDown(KeyQ); modifiers=[Accel], action_dispatch=AppWindowMessage::Close)];
apply_mapping_patch(&mut mapping, remove, add);
}
mapping
}
/// Default mappings except that scrolling without modifier keys held down is bound to zooming instead of vertical panning
pub fn zoom_with_scroll() -> Mapping {
use InputMapperMessage::*;
// On Mac, the OS already converts Shift+scroll into horizontal scrolling so we have to reverse the behavior from normal to produce the same outcome
let keyboard_platform = GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
let mut mapping = input_mappings();
let remove = [
entry!(WheelScroll; modifiers=[Control], action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(WheelScroll; modifiers=[Command], action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
entry!(WheelScroll; modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: true }),
entry!(WheelScroll; action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: false }),
];
let add = [
entry!(WheelScroll; modifiers=[Control], action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: keyboard_platform == KeyboardPlatformLayout::Mac }),
entry!(WheelScroll; modifiers=[Shift], action_dispatch=NavigationMessage::CanvasPanMouseWheel { use_y_as_x: keyboard_platform != KeyboardPlatformLayout::Mac }),
entry!(WheelScroll; action_dispatch=NavigationMessage::CanvasZoomMouseWheel),
];
apply_mapping_patch(&mut mapping, remove, add);
mapping
}
fn apply_mapping_patch<'a, const N: usize, const M: usize, const X: usize, const Y: usize>(
mapping: &mut Mapping,
remove: impl IntoIterator<Item = &'a [&'a [MappingEntry; N]; M]>,
add: impl IntoIterator<Item = &'a [&'a [MappingEntry; X]; Y]>,
) {
for entry in remove.into_iter().flat_map(|inner| inner.iter()).flat_map(|inner| inner.iter()) {
mapping.remove(entry);
}
for entry in add.into_iter().flat_map(|inner| inner.iter()).flat_map(|inner| inner.iter()) {
mapping.add(entry.clone());
}
}
@@ -1,4 +1,4 @@
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::application::Editor;
use crate::messages::prelude::*;
use bitflags::bitflags;
use std::fmt::{self, Display, Formatter};
@@ -258,7 +258,7 @@ impl fmt::Display for Key {
return write!(f, "{}", key_name.chars().skip(KEY_PREFIX.len()).collect::<String>());
}
let keyboard_layout = || GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
let is_mac = Editor::environment().is_mac();
let name = match self {
// Writing system keys
@@ -275,21 +275,21 @@ impl fmt::Display for Key {
Self::Slash => "/",
// Functional keys
Self::Alt => match keyboard_layout() {
KeyboardPlatformLayout::Standard => "Alt",
KeyboardPlatformLayout::Mac => "⌥",
Self::Alt => match is_mac {
true => "⌥",
false => "Alt",
},
Self::Meta => match keyboard_layout() {
KeyboardPlatformLayout::Standard => "⊞",
KeyboardPlatformLayout::Mac => "⌘",
Self::Meta => match is_mac {
true => "⌘",
false => "⊞",
},
Self::Shift => match keyboard_layout() {
KeyboardPlatformLayout::Standard => "Shift",
KeyboardPlatformLayout::Mac => "⇧",
Self::Shift => match is_mac {
true => "⇧",
false => "Shift",
},
Self::Control => match keyboard_layout() {
KeyboardPlatformLayout::Standard => "Ctrl",
KeyboardPlatformLayout::Mac => "⌃",
Self::Control => match is_mac {
true => "⌃",
false => "Ctrl",
},
Self::Backspace => "⌫",
@@ -317,9 +317,9 @@ impl fmt::Display for Key {
// Other keys that aren't part of the W3C spec
Self::Command => "⌘",
Self::Accel => match keyboard_layout() {
KeyboardPlatformLayout::Standard => "Ctrl",
KeyboardPlatformLayout::Mac => "⌘",
Self::Accel => match is_mac {
true => "⌘",
false => "Ctrl",
},
Self::MouseLeft => "Click",
Self::MouseRight => "R.Click",
@@ -356,10 +356,9 @@ impl fmt::Display for KeysGroup {
.0
.iter()
.map(|key| {
let keyboard_layout = GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
let key_is_modifier = matches!(*key, Key::Control | Key::Command | Key::Alt | Key::Shift | Key::Meta | Key::Accel);
if keyboard_layout == KeyboardPlatformLayout::Mac && key_is_modifier {
if Editor::environment().is_mac() && key_is_modifier {
key.to_string()
} else {
key.to_string() + JOINER_MARK
@@ -76,7 +76,8 @@ pub struct EditorMouseState {
impl EditorMouseState {
pub fn from_keys_and_editor_position(keys: u8, editor_position: EditorPosition) -> Self {
let mouse_keys = MouseKeys::from_bits(keys).expect("Invalid decoding of MouseKeys");
// TODO: Some graphic tablets send key codes not mentioned in the spec. In the future we would like to support these as well.
let mouse_keys = MouseKeys::from_bits_truncate(keys);
Self {
editor_position,
@@ -25,17 +25,44 @@ macro_rules! modifiers {
/// When an action is currently available, and the user enters that input, the action's message is dispatched on the message bus.
macro_rules! entry {
// Pattern with canonical parameter
($input:expr_2021; $(modifiers=[$($modifier:ident),*],)? $(refresh_keys=[$($refresh:ident),* $(,)?],)? canonical, action_dispatch=$action_dispatch:expr_2021$(,)?) => {
entry!($input; $($($modifier),*)?; $($($refresh),*)?; $action_dispatch; true)
(
$input:expr_2021;
$(modifiers=[$($modifier:ident),*],)?
$(refresh_keys=[$($refresh:ident),* $(,)?],)?
canonical,
$(disabled=$disabled:expr,)?
action_dispatch=$action_dispatch:expr_2021$(,)?
) => {
entry!(
$input;
$($($modifier),*)?;
$($($refresh),*)?;
$action_dispatch;
true;
false $( || $disabled )?
)
};
// Pattern without canonical parameter
($input:expr_2021; $(modifiers=[$($modifier:ident),*],)? $(refresh_keys=[$($refresh:ident),* $(,)?],)? action_dispatch=$action_dispatch:expr_2021$(,)?) => {
entry!($input; $($($modifier),*)?; $($($refresh),*)?; $action_dispatch; false)
(
$input:expr_2021;
$(modifiers=[$($modifier:ident),*],)?
$(refresh_keys=[$($refresh:ident),* $(,)?],)?
$(disabled=$disabled:expr,)?
action_dispatch=$action_dispatch:expr_2021$(,)?
) => {
entry!(
$input;
$($($modifier),*)?;
$($($refresh),*)?;
$action_dispatch;
false;
false $( || $disabled )?
)
};
// Implementation macro to avoid code duplication
($input:expr; $($modifier:ident),*; $($refresh:ident),*; $action_dispatch:expr; $canonical:expr) => {
($input:expr; $($modifier:ident),*; $($refresh:ident),*; $action_dispatch:expr; $canonical:expr; $disabled:expr) => {
&[&[
// Cause the `action_dispatch` message to be sent when the specified input occurs.
MappingEntry {
@@ -43,33 +70,37 @@ macro_rules! entry {
input: $input,
modifiers: modifiers!($($modifier),*),
canonical: $canonical,
disabled: $disabled,
},
// Also cause the `action_dispatch` message to be sent when any of the specified refresh keys change.
$(
MappingEntry {
action: $action_dispatch.into(),
input: InputMapperMessage::KeyDown(Key::$refresh),
modifiers: modifiers!(),
canonical: $canonical,
disabled: $disabled,
},
MappingEntry {
action: $action_dispatch.into(),
input: InputMapperMessage::KeyUp(Key::$refresh),
modifiers: modifiers!(),
canonical: $canonical,
disabled: $disabled,
},
MappingEntry {
action: $action_dispatch.into(),
input: InputMapperMessage::KeyDownNoRepeat(Key::$refresh),
modifiers: modifiers!(),
canonical: $canonical,
disabled: $disabled,
},
MappingEntry {
action: $action_dispatch.into(),
input: InputMapperMessage::KeyUpNoRepeat(Key::$refresh),
modifiers: modifiers!(),
canonical: $canonical,
disabled: $disabled,
},
)*
]]
@@ -97,6 +128,10 @@ macro_rules! mapping {
for entry_slice in $entry {
// Each entry in the slice (usually just one, except when `refresh_keys` adds additional key entries)
for entry in entry_slice.into_iter() {
if entry.disabled {
continue;
}
let corresponding_list = match entry.input {
InputMapperMessage::KeyDown(key) => &mut key_down[key as usize],
InputMapperMessage::KeyUp(key) => &mut key_up[key as usize],
@@ -29,16 +29,6 @@ impl Mapping {
list.match_mapping(keyboard_state, actions)
}
pub fn remove(&mut self, target_entry: &MappingEntry) {
let list = self.associated_entries_mut(&target_entry.input);
list.remove(target_entry);
}
pub fn add(&mut self, new_entry: MappingEntry) {
let list = self.associated_entries_mut(&new_entry.input);
list.push(new_entry);
}
fn associated_entries(&self, message: &InputMapperMessage) -> &KeyMappingEntries {
match message {
InputMapperMessage::KeyDown(key) => &self.key_down[*key as usize],
@@ -51,19 +41,6 @@ impl Mapping {
InputMapperMessage::PointerShake => &self.pointer_shake,
}
}
fn associated_entries_mut(&mut self, message: &InputMapperMessage) -> &mut KeyMappingEntries {
match message {
InputMapperMessage::KeyDown(key) => &mut self.key_down[*key as usize],
InputMapperMessage::KeyUp(key) => &mut self.key_up[*key as usize],
InputMapperMessage::KeyDownNoRepeat(key) => &mut self.key_down_no_repeat[*key as usize],
InputMapperMessage::KeyUpNoRepeat(key) => &mut self.key_up_no_repeat[*key as usize],
InputMapperMessage::DoubleClick(key) => &mut self.double_click[*key as usize],
InputMapperMessage::WheelScroll => &mut self.wheel_scroll,
InputMapperMessage::PointerMove => &mut self.pointer_move,
InputMapperMessage::PointerShake => &mut self.pointer_shake,
}
}
}
#[derive(Debug, Clone)]
@@ -125,6 +102,8 @@ pub struct MappingEntry {
pub modifiers: KeyStates,
/// True indicates that this takes priority as the labeled hotkey shown in UI menus and tooltips instead of an alternate binding for the same action
pub canonical: bool,
/// Whether this mapping is disabled
pub disabled: bool,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
@@ -1,13 +1,12 @@
use crate::application::Editor;
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState};
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
use std::time::Duration;
#[derive(ExtractField)]
pub struct InputPreprocessorMessageContext<'a> {
pub keyboard_platform: KeyboardPlatformLayout,
pub viewport: &'a ViewportMessageHandler,
}
@@ -22,11 +21,11 @@ pub struct InputPreprocessorMessageHandler {
#[message_handler_data]
impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext<'a>> for InputPreprocessorMessageHandler {
fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>, context: InputPreprocessorMessageContext<'a>) {
let InputPreprocessorMessageContext { keyboard_platform, viewport } = context;
let InputPreprocessorMessageContext { viewport } = context;
match message {
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
@@ -43,7 +42,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
}
}
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
self.keyboard.set(key as usize);
if !key_repeat {
responses.add(InputMapperMessage::KeyDownNoRepeat(key));
@@ -51,7 +50,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
responses.add(InputMapperMessage::KeyDown(key));
}
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
self.keyboard.unset(key as usize);
if !key_repeat {
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
@@ -59,7 +58,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
responses.add(InputMapperMessage::KeyUp(key));
}
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
@@ -67,7 +66,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
self.translate_mouse_event(mouse_state, true, responses);
}
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
@@ -78,7 +77,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
self.translate_mouse_event(mouse_state, false, responses);
}
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
@@ -86,7 +85,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
self.translate_mouse_event(mouse_state, false, responses);
}
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
@@ -99,7 +98,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
self.frame_time.advance_timestamp(Duration::from_millis(timestamp));
}
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
@@ -148,7 +147,7 @@ impl InputPreprocessorMessageHandler {
self.mouse = new_state;
}
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, keyboard_platform: KeyboardPlatformLayout, responses: &mut VecDeque<Message>) {
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, responses: &mut VecDeque<Message>) {
let is_key_pressed = |key_to_check: ModifierKeys| pressed_modifier_keys.contains(key_to_check);
// Update the state of the concrete modifier keys based on the source state
@@ -157,16 +156,16 @@ impl InputPreprocessorMessageHandler {
self.update_modifier_key(Key::Control, is_key_pressed(ModifierKeys::CONTROL), responses);
// Update the state of either the concrete Meta or the Command keys based on which one is applicable for this platform
let meta_or_command = match keyboard_platform {
KeyboardPlatformLayout::Mac => Key::Command,
KeyboardPlatformLayout::Standard => Key::Meta,
let meta_or_command = match Editor::environment().is_mac() {
true => Key::Command,
false => Key::Meta,
};
self.update_modifier_key(meta_or_command, is_key_pressed(ModifierKeys::META_OR_COMMAND), responses);
// Update the state of the virtual Accel key (the primary accelerator key) based on the source state of the Control or Command key, whichever is relevant on this platform
let accel_virtual_key_state = match keyboard_platform {
KeyboardPlatformLayout::Mac => is_key_pressed(ModifierKeys::META_OR_COMMAND),
KeyboardPlatformLayout::Standard => is_key_pressed(ModifierKeys::CONTROL),
let accel_virtual_key_state = match Editor::environment().is_mac() {
true => is_key_pressed(ModifierKeys::META_OR_COMMAND),
false => is_key_pressed(ModifierKeys::CONTROL),
};
self.update_modifier_key(Key::Accel, accel_virtual_key_state, responses);
}
@@ -188,7 +187,6 @@ impl InputPreprocessorMessageHandler {
mod test {
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
#[test]
@@ -206,7 +204,6 @@ mod test {
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
@@ -226,7 +223,6 @@ mod test {
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
@@ -246,7 +242,6 @@ mod test {
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
@@ -268,7 +263,6 @@ mod test {
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
@@ -289,7 +283,6 @@ mod test {
let mut responses = VecDeque::new();
let context = InputPreprocessorMessageContext {
keyboard_platform: KeyboardPlatformLayout::Standard,
viewport: &ViewportMessageHandler::default(),
};
input_preprocessor.process_message(message, &mut responses, context);
@@ -71,7 +71,7 @@ impl LayoutMessageHandler {
return Some((widget, widget_path));
}
if let Widget::PopoverButton(popover) = &widget.widget {
if let Widget::PopoverButton(popover) = &*widget.widget {
stack.extend(
popover
.popover_layout
@@ -97,7 +97,7 @@ impl LayoutMessageHandler {
return Some((cell, widget_path));
}
if let Widget::PopoverButton(popover) = &cell.widget {
if let Widget::PopoverButton(popover) = &*cell.widget {
stack.extend(
popover
.popover_layout
@@ -126,7 +126,7 @@ impl LayoutMessageHandler {
return;
};
match &mut widget_instance.widget {
match &mut *widget_instance.widget {
Widget::BreadcrumbTrailButtons(breadcrumb_trail_buttons) => {
let callback_message = match action {
WidgetValueAction::Commit => (breadcrumb_trail_buttons.on_commit.callback)(&()),
@@ -287,11 +287,7 @@ impl LayoutMessageHandler {
responses.add(callback_message);
}
WidgetValueAction::Update => {
let Some(value) = value.as_str().map(|s| s.to_string()) else {
error!("NodeCatalog update was not of type String");
return;
};
let callback_message = (node_type_input.on_update.callback)(&value);
let callback_message = (node_type_input.on_update.callback)(&value.into());
responses.add(callback_message);
}
},
@@ -481,6 +477,7 @@ impl LayoutMessageHandler {
LayoutTarget::NodeGraphControlBar => FrontendMessage::UpdateNodeGraphControlBarLayout { diff },
LayoutTarget::PropertiesPanel => FrontendMessage::UpdatePropertiesPanelLayout { diff },
LayoutTarget::StatusBarHints => FrontendMessage::UpdateStatusBarHintsLayout { diff },
LayoutTarget::StatusBarInfo => FrontendMessage::UpdateStatusBarInfoLayout { diff },
LayoutTarget::ToolOptions => FrontendMessage::UpdateToolOptionsLayout { diff },
LayoutTarget::ToolShelf => FrontendMessage::UpdateToolShelfLayout { diff },
LayoutTarget::WelcomeScreenButtons => FrontendMessage::UpdateWelcomeScreenButtonsLayout { diff },
@@ -46,6 +46,8 @@ pub enum LayoutTarget {
PropertiesPanel,
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
StatusBarHints,
/// The version information shown in the status bar at the bottom right of the window.
StatusBarInfo,
/// The left side of the control bar directly above the canvas.
ToolOptions,
/// The vertical buttons for all of the tools on the left of the canvas.
@@ -229,13 +231,13 @@ impl<'a> Iterator for WidgetIter<'a> {
Some(first)
});
if let Some(item) = widget {
if let WidgetInstance { widget: Widget::PopoverButton(p), .. } = item {
self.stack.extend(p.popover_layout.0.iter());
if let Some(instance) = widget {
if let Widget::PopoverButton(popover_button) = &*instance.widget {
self.stack.extend(popover_button.popover_layout.0.iter());
return self.next();
}
return Some(item);
return Some(instance);
}
match self.stack.pop() {
@@ -279,13 +281,15 @@ impl<'a> Iterator for WidgetIterMut<'a> {
Some(first)
});
if let Some(widget) = widget {
if let WidgetInstance { widget: Widget::PopoverButton(p), .. } = widget {
self.stack.extend(p.popover_layout.0.iter_mut());
return self.next();
if let Some(instance) = widget {
// We have to check that we're not a popover and return first, then extract the popover with an unreachable else condition second, to satisfy the borrow checker.
// After Rust's Polonius is stable, we can reverse that order of steps to avoid the redundancy and unreachable statement.
if !matches!(*instance.widget, Widget::PopoverButton(_)) {
return Some(instance);
}
return Some(widget);
let Widget::PopoverButton(popover_button) = &mut *instance.widget else { unreachable!() };
self.stack.extend(popover_button.popover_layout.0.iter_mut());
return self.next();
}
match self.stack.pop() {
@@ -362,7 +366,7 @@ impl LayoutGroup {
};
let description = description.into();
for widget in &mut widgets {
let val = match &mut widget.widget {
let val = match &mut *widget.widget {
Widget::CheckboxInput(x) => &mut x.tooltip_description,
Widget::ColorInput(x) => &mut x.tooltip_description,
Widget::CurveInput(x) => &mut x.tooltip_description,
@@ -552,7 +556,7 @@ impl Diffable for LayoutGroup {
pub struct WidgetInstance {
#[serde(rename = "widgetId")]
pub widget_id: WidgetId,
pub widget: Widget,
pub widget: Box<Widget>,
}
impl PartialEq for WidgetInstance {
@@ -566,7 +570,7 @@ impl WidgetInstance {
pub fn new(widget: Widget) -> Self {
Self {
widget_id: WidgetId(generate_uuid()),
widget,
widget: Box::new(widget),
}
}
}
@@ -584,7 +588,7 @@ impl Diffable for WidgetInstance {
}
// Special handling for PopoverButton: recursively diff nested layout if only the layout changed
if let (Widget::PopoverButton(button1), Widget::PopoverButton(button2)) = (&mut self.widget, &new.widget) {
if let (Widget::PopoverButton(button1), Widget::PopoverButton(button2)) = (&mut *self.widget, &*new.widget) {
// Check if only the popover layout changed (all other fields are the same)
if self.widget_id == new.widget_id
&& button1.disabled == button2.disabled
@@ -614,7 +618,7 @@ impl Diffable for WidgetInstance {
}
fn collect_checkbox_ids(&self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &mut HashMap<CheckboxId, CheckboxId>) {
match &self.widget {
match &*self.widget {
Widget::CheckboxInput(checkbox) => {
// Compute stable ID based on position and insert mapping
let checkbox_id = checkbox.for_label;
@@ -644,7 +648,7 @@ impl Diffable for WidgetInstance {
self.widget_id = compute_widget_id(layout_target, widget_path, &self.widget);
// 2. Replace CheckboxIds if present
match &mut self.widget {
match &mut *self.widget {
Widget::CheckboxInput(checkbox) => {
let old_id = checkbox.for_label;
if let Some(&new_id) = checkbox_map.get(&old_id) {
@@ -744,7 +748,7 @@ impl DiffUpdate {
// Go through each widget to convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` and append the key combination to the widget tooltip
let convert_tooltip = |widget_instance: &mut WidgetInstance| {
// Handle all the widgets that have tooltips
let tooltip_shortcut = match &mut widget_instance.widget {
let tooltip_shortcut = match &mut *widget_instance.widget {
Widget::BreadcrumbTrailButtons(widget) => widget.tooltip_shortcut.as_mut(),
Widget::CheckboxInput(widget) => widget.tooltip_shortcut.as_mut(),
Widget::ColorInput(widget) => widget.tooltip_shortcut.as_mut(),
@@ -775,7 +779,7 @@ impl DiffUpdate {
}
// Handle RadioInput separately because its tooltips are children of the widget
if let Widget::RadioInput(radio_input) = &mut widget_instance.widget {
if let Widget::RadioInput(radio_input) = &mut *widget_instance.widget {
for radio_entry_data in &mut radio_input.entries {
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
if let Some(tooltip_shortcut) = radio_entry_data.tooltip_shortcut.as_mut() {
@@ -786,23 +790,19 @@ impl DiffUpdate {
};
// Recursively fill menu list entries with their realized shortcut keys specific to the current bindings and platform
let apply_action_shortcut_to_menu_lists = |entry_sections: &mut MenuListEntrySections| {
struct RecursiveWrapper<'a>(&'a dyn Fn(&mut MenuListEntrySections, &RecursiveWrapper));
let recursive_wrapper = RecursiveWrapper(&|entry_sections: &mut MenuListEntrySections, recursive_wrapper| {
for entries in entry_sections {
for entry in entries {
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
if let Some(tooltip_shortcut) = &mut entry.tooltip_shortcut {
tooltip_shortcut.realize_shortcut(action_input_mapping);
}
// Recursively call this inner closure on the menu's children
(recursive_wrapper.0)(&mut entry.children, recursive_wrapper);
fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
for entries in entry_sections {
for entry in entries {
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
if let Some(tooltip_shortcut) = &mut entry.tooltip_shortcut {
tooltip_shortcut.realize_shortcut(action_input_mapping);
}
// Recursively call this function on the menu's children
apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping);
}
});
(recursive_wrapper.0)(entry_sections, &recursive_wrapper)
};
}
}
// Hash the menu list entry sections for caching purposes
let hash_menu_list_entry_sections = |entry_sections: &MenuListEntrySections| {
@@ -827,13 +827,13 @@ impl DiffUpdate {
};
// Apply shortcut conversions to all widgets that have menu lists
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut widget_instance.widget {
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
Widget::DropdownInput(dropdown_input) => {
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries);
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping);
dropdown_input.entries_hash = hash_menu_list_entry_sections(&dropdown_input.entries);
}
Widget::TextButton(text_button) => {
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children);
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping);
text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children);
}
_ => {}
@@ -9,25 +9,23 @@ use graphite_proc_macros::WidgetBuilder;
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct IconButton {
// Content
#[widget_builder(constructor)]
pub icon: String,
#[serde(rename = "hoverIcon")]
pub hover_icon: Option<String>,
#[widget_builder(constructor)]
pub size: u32, // TODO: Convert to an `IconSize` enum
pub disabled: bool,
pub active: bool,
// Styling
pub emphasized: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -35,7 +33,6 @@ pub struct IconButton {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<IconButton>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -44,29 +41,26 @@ pub struct IconButton {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct PopoverButton {
// Content
pub style: Option<String>,
pub icon: Option<String>,
pub disabled: bool,
// Children
#[serde(rename = "popoverLayout")]
pub popover_layout: Layout,
#[serde(rename = "popoverMinWidth")]
pub popover_min_width: Option<u32>,
#[serde(rename = "menuDirection")]
pub menu_direction: Option<MenuDirection>,
pub icon: Option<String>,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
#[serde(rename = "popoverLayout")]
pub popover_layout: Layout,
#[serde(rename = "popoverMinWidth")]
pub popover_min_width: Option<u32>,
}
#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
@@ -86,17 +80,16 @@ pub enum MenuDirection {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ParameterExposeButton {
// Content
pub exposed: bool,
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -104,7 +97,6 @@ pub struct ParameterExposeButton {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<ParameterExposeButton>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -113,46 +105,42 @@ pub struct ParameterExposeButton {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct TextButton {
// Content
#[widget_builder(constructor)]
pub label: String,
pub icon: Option<String>,
#[serde(rename = "hoverIcon")]
pub hover_icon: Option<String>,
pub flush: bool,
pub emphasized: bool,
#[serde(rename = "minWidth")]
pub min_width: u32,
pub disabled: bool,
pub narrow: bool,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Children
#[serde(rename = "menuListChildren")]
pub menu_list_children: MenuListEntrySections,
#[serde(rename = "menuListChildrenHash")]
#[widget_builder(skip)]
pub menu_list_children_hash: u64,
// Styling
pub emphasized: bool,
pub flush: bool,
pub narrow: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<TextButton>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -161,19 +149,17 @@ pub struct TextButton {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ImageButton {
// Content
#[widget_builder(constructor)]
pub image: String,
pub width: Option<String>,
pub height: Option<String>,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -181,7 +167,6 @@ pub struct ImageButton {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -190,32 +175,26 @@ pub struct ImageButton {
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct ColorInput {
// Content
/// WARNING: The colors are gamma, not linear!
#[widget_builder(constructor)]
pub value: FillChoice,
// TODO: Implement
// #[serde(rename = "allowTransparency")]
// #[derivative(Default(value = "false"))]
// pub allow_transparency: bool,
//
#[serde(rename = "allowNone")]
#[derivative(Default(value = "true"))]
pub allow_none: bool,
pub disabled: bool,
pub narrow: bool,
// #[serde(rename = "allowTransparency")] pub allow_transparency: bool, // TODO: Implement
#[serde(rename = "menuDirection")]
pub menu_direction: Option<MenuDirection>,
pub disabled: bool,
// Styling
pub narrow: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -223,7 +202,6 @@ pub struct ColorInput {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<ColorInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -232,17 +210,16 @@ pub struct ColorInput {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct BreadcrumbTrailButtons {
// Content
#[widget_builder(constructor)]
pub labels: Vec<String>,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -250,7 +227,6 @@ pub struct BreadcrumbTrailButtons {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<u64>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -1,5 +1,6 @@
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use derivative::*;
use graphene_std::Color;
use graphene_std::raster::curve::Curve;
@@ -7,53 +8,34 @@ use graphene_std::transform::ReferencePoint;
use graphite_proc_macros::WidgetBuilder;
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[derivative(Debug, Default, PartialEq)]
pub struct CheckboxInput {
// Content
#[widget_builder(constructor)]
pub checked: bool,
pub disabled: bool,
#[derivative(Default(value = "\"Checkmark\".to_string()"))]
pub icon: String,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
#[serde(rename = "forLabel")]
pub for_label: CheckboxId,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<CheckboxInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
impl Default for CheckboxInput {
fn default() -> Self {
Self {
icon: "Checkmark".into(),
checked: Default::default(),
disabled: Default::default(),
tooltip_label: Default::default(),
tooltip_description: Default::default(),
tooltip_shortcut: Default::default(),
for_label: CheckboxId::new(),
on_update: Default::default(),
on_commit: Default::default(),
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct CheckboxId(pub u64);
@@ -77,48 +59,45 @@ impl specta::Type for CheckboxId {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct DropdownInput {
// Content
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (we can replace this with `usize` if we switch to a Rust-based GUI)
#[serde(rename = "selectedIndex")]
pub selected_index: Option<u32>,
#[serde(rename = "drawIcon")]
pub draw_icon: bool,
pub disabled: bool,
// Children
#[widget_builder(constructor)]
pub entries: MenuListEntrySections,
#[serde(rename = "entriesHash")]
#[widget_builder(skip)]
pub entries_hash: u64,
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (replace this with `usize` after switching to a Rust-based GUI)
#[serde(rename = "selectedIndex")]
pub selected_index: Option<u32>,
#[serde(rename = "drawIcon")]
pub draw_icon: bool,
// Styling
pub narrow: bool,
// Behavior
#[serde(rename = "virtualScrolling")]
pub virtual_scrolling: bool,
#[derivative(Default(value = "true"))]
pub interactive: bool,
pub disabled: bool,
pub narrow: bool,
#[serde(rename = "virtualScrolling")]
pub virtual_scrolling: bool,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Styling
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
//
// Callbacks
// `on_update` exists on the `MenuListEntry`, not this parent `DropdownInput`
// Callbacks exists on the `MenuListEntry` children, not this parent `DropdownInput`
}
pub type MenuListEntrySections = Vec<Vec<MenuListEntry>>;
@@ -127,37 +106,34 @@ pub type MenuListEntrySections = Vec<Vec<MenuListEntry>>;
#[derivative(Debug, PartialEq)]
#[widget_builder(not_widget_instance)]
pub struct MenuListEntry {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: String,
pub font: String,
pub icon: String,
pub disabled: bool,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Children
pub children: MenuListEntrySections,
#[serde(rename = "childrenHash")]
#[widget_builder(skip)]
pub children_hash: u64,
// Styling
pub font: String,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -175,83 +151,64 @@ impl std::hash::Hash for MenuListEntry {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct NumberInput {
// Label
pub label: String,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Disabled
pub disabled: bool,
pub narrow: bool,
// Value
// Content
#[widget_builder(constructor)]
pub value: Option<f64>,
pub label: String,
pub disabled: bool,
// Styling
pub narrow: bool,
// Behavior
pub mode: NumberInputMode,
#[widget_builder(skip)]
pub min: Option<f64>,
#[widget_builder(skip)]
pub max: Option<f64>,
// TODO: Make this (and range_max) apply to both Range and Increment modes when dragging with the mouse
#[serde(rename = "rangeMin")]
pub range_min: Option<f64>,
#[serde(rename = "rangeMax")]
pub range_max: Option<f64>,
#[derivative(Default(value = "1."))]
pub step: f64,
#[serde(rename = "isInteger")]
pub is_integer: bool,
// Number presentation
#[serde(rename = "incrementBehavior")]
pub increment_behavior: NumberInputIncrementBehavior,
#[serde(rename = "displayDecimalPlaces")]
#[derivative(Default(value = "2"))]
pub display_decimal_places: u32,
pub unit: String,
#[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))]
pub unit_is_hidden_when_editing: bool,
// Mode behavior
pub mode: NumberInputMode,
#[serde(rename = "incrementBehavior")]
pub increment_behavior: NumberInputIncrementBehavior,
#[derivative(Default(value = "1."))]
pub step: f64,
// TODO: Make this (and range_max) apply to both Range and Increment modes when dragging with the mouse
#[serde(rename = "rangeMin")]
pub range_min: Option<f64>,
#[serde(rename = "rangeMax")]
pub range_max: Option<f64>,
// Styling
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub increment_callback_increase: WidgetCallback<NumberInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub increment_callback_decrease: WidgetCallback<NumberInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<NumberInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -307,16 +264,17 @@ pub enum NumberInputMode {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct NodeCatalog {
// Content
pub disabled: bool,
// Behavior
#[serde(rename = "initialSearchTerm")]
pub intial_search: String,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<String>,
pub on_update: WidgetCallback<DefinitionIdentifier>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -325,38 +283,41 @@ pub struct NodeCatalog {
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct RadioInput {
#[widget_builder(constructor)]
pub entries: Vec<RadioEntryData>,
pub disabled: bool,
pub narrow: bool,
// Content
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (replace this with `usize` after switching to a Rust-based GUI)
#[serde(rename = "selectedIndex")]
pub selected_index: Option<u32>,
pub disabled: bool,
// Children
#[widget_builder(constructor)]
pub entries: Vec<RadioEntryData>,
// Styling
pub narrow: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
//
// Callbacks exists on the `RadioEntryData` children, not this parent `RadioInput`
}
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
#[widget_builder(not_widget_instance)]
pub struct RadioEntryData {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: String,
pub icon: String,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -364,7 +325,6 @@ pub struct RadioEntryData {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<()>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -373,9 +333,9 @@ pub struct RadioEntryData {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct WorkingColorsInput {
// Content
#[widget_builder(constructor)]
pub primary: Color,
#[widget_builder(constructor)]
pub secondary: Color,
}
@@ -383,19 +343,17 @@ pub struct WorkingColorsInput {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct TextAreaInput {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: Option<String>,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -403,7 +361,6 @@ pub struct TextAreaInput {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<TextAreaInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -412,37 +369,35 @@ pub struct TextAreaInput {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct TextInput {
// Content
#[widget_builder(constructor)]
pub value: String,
pub label: Option<String>,
pub placeholder: Option<String>,
pub disabled: bool,
// Styling
pub narrow: bool,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
pub centered: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "maxWidth")]
pub max_width: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<TextInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -451,17 +406,15 @@ pub struct TextInput {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq, Default)]
pub struct CurveInput {
// Content
#[widget_builder(constructor)]
pub value: Curve,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -469,7 +422,6 @@ pub struct CurveInput {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<CurveInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -478,17 +430,16 @@ pub struct CurveInput {
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ReferencePointInput {
// Content
#[widget_builder(constructor)]
pub value: ReferencePoint,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
@@ -496,7 +447,6 @@ pub struct ReferencePointInput {
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<ReferencePointInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
@@ -5,28 +5,26 @@ use graphite_proc_macros::WidgetBuilder;
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Debug, Default, PartialEq, Eq, WidgetBuilder, specta::Type)]
pub struct IconLabel {
// Content
#[widget_builder(constructor)]
pub icon: String,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, WidgetBuilder, specta::Type)]
pub struct Separator {
// Content
pub direction: SeparatorDirection,
#[serde(rename = "type")]
#[widget_builder(constructor)]
pub separator_type: SeparatorType,
pub style: SeparatorStyle,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
@@ -37,7 +35,7 @@ pub enum SeparatorDirection {
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum SeparatorType {
pub enum SeparatorStyle {
Related,
#[default]
Unrelated,
@@ -47,60 +45,53 @@ pub enum SeparatorType {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Debug, Eq, Default, WidgetBuilder, specta::Type)]
#[derivative(PartialEq)]
pub struct TextLabel {
// Content
#[widget_builder(constructor)]
pub value: String,
pub disabled: bool,
pub narrow: bool,
pub bold: bool,
pub italic: bool,
pub monospace: bool,
pub multiline: bool,
#[serde(rename = "centerAlign")]
pub center_align: bool,
#[serde(rename = "tableAlign")]
pub table_align: bool,
#[serde(rename = "minWidth")]
pub min_width: String,
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
#[serde(rename = "forCheckbox")]
pub for_checkbox: CheckboxId,
// Body
#[widget_builder(constructor)]
pub value: String,
// Styling
pub narrow: bool,
pub bold: bool,
pub italic: bool,
pub monospace: bool,
pub multiline: bool,
#[serde(rename = "centerAlign")]
pub center_align: bool,
#[serde(rename = "tableAlign")]
pub table_align: bool,
// Sizing
#[serde(rename = "minWidth")]
pub min_width: u32,
#[serde(rename = "minWidthCharacters")]
pub min_width_characters: u32,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ImageLabel {
// Content
#[widget_builder(constructor)]
pub url: String,
pub width: Option<String>,
pub height: Option<String>,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
@@ -108,6 +99,7 @@ pub struct ImageLabel {
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder, specta::Type)]
#[derivative(Debug, PartialEq)]
pub struct ShortcutLabel {
// Content
// This is wrapped in an Option to satisfy the requirement that widgets implement Default
#[widget_builder(constructor)]
pub shortcut: Option<ActionShortcut>,
@@ -21,6 +21,7 @@ pub struct MenuBarMessageHandler {
pub data_panel_open: bool,
pub layers_panel_open: bool,
pub properties_panel_open: bool,
pub focus_document: bool,
}
#[message_handler_data]
@@ -120,8 +121,8 @@ impl LayoutHolder for MenuBarMessageHandler {
MenuListEntry::new("Open…")
.label("Open…")
.icon("Folder")
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::OpenDocument))
.on_commit(|_| PortfolioMessage::OpenDocument.into()),
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Open))
.on_commit(|_| PortfolioMessage::Open.into()),
MenuListEntry::new("Open Demo Artwork…")
.label("Open Demo Artwork…")
.icon("Image")
@@ -161,7 +162,8 @@ impl LayoutHolder for MenuBarMessageHandler {
.label("Import…")
.icon("FileImport")
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Import))
.on_commit(|_| PortfolioMessage::Import.into()),
.on_commit(|_| PortfolioMessage::Import.into())
.disabled(no_active_document),
MenuListEntry::new("Export…")
.label("Export…")
.icon("FileExport")
@@ -621,24 +623,37 @@ impl LayoutHolder for MenuBarMessageHandler {
.label("Window")
.flush(true)
.menu_list_children(vec![
vec![
MenuListEntry::new("Fullscreen")
.label("Fullscreen")
.icon("FullscreenEnter")
.tooltip_shortcut(action_shortcut!(AppWindowMessageDiscriminant::Fullscreen))
.on_commit(|_| AppWindowMessage::Fullscreen.into()),
MenuListEntry::new("Focus Document")
.label("Focus Document")
.icon(if self.focus_document { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleFocusDocument))
.on_commit(|_| PortfolioMessage::ToggleFocusDocument.into()),
],
vec![
MenuListEntry::new("Properties")
.label("Properties")
.icon(if self.properties_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::TogglePropertiesPanelOpen))
.on_commit(|_| PortfolioMessage::TogglePropertiesPanelOpen.into()),
.on_commit(|_| PortfolioMessage::TogglePropertiesPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("Layers")
.label("Layers")
.icon(if self.layers_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleLayersPanelOpen))
.on_commit(|_| PortfolioMessage::ToggleLayersPanelOpen.into()),
],
vec![
.on_commit(|_| PortfolioMessage::ToggleLayersPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("Data")
.label("Data")
.icon(if self.data_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleDataPanelOpen))
.on_commit(|_| PortfolioMessage::ToggleDataPanelOpen.into()),
.on_commit(|_| PortfolioMessage::ToggleDataPanelOpen.into())
.disabled(self.focus_document),
],
])
.widget_instance(),
+3 -94
View File
@@ -22,8 +22,6 @@ pub enum Message {
#[child]
Frontend(FrontendMessage),
#[child]
Globals(GlobalsMessage),
#[child]
InputPreprocessor(InputPreprocessorMessage),
#[child]
KeyMapping(KeyMappingMessage),
@@ -55,97 +53,8 @@ impl specta::Type for MessageDiscriminant {
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Write;
#[test]
fn generate_message_tree() {
let result = Message::build_message_tree();
let mut file = std::fs::File::create("../hierarchical_message_system_tree.txt").unwrap();
file.write_all(format!("{} `{}`\n", result.name(), result.path()).as_bytes()).unwrap();
if let Some(variants) = result.variants() {
for (i, variant) in variants.iter().enumerate() {
let is_last = i == variants.len() - 1;
print_tree_node(variant, "", is_last, &mut file);
}
}
}
fn print_tree_node(tree: &DebugMessageTree, prefix: &str, is_last: bool, file: &mut std::fs::File) {
// Print the current node
let (branch, child_prefix) = if tree.message_handler_data_fields().is_some() || tree.message_handler_fields().is_some() {
("├── ", format!("{prefix}│ "))
} else if is_last {
("└── ", format!("{prefix} "))
} else {
("├── ", format!("{prefix}│ "))
};
if tree.path().is_empty() {
file.write_all(format!("{}{}{}\n", prefix, branch, tree.name()).as_bytes()).unwrap();
} else {
file.write_all(format!("{}{}{} `{}`\n", prefix, branch, tree.name(), tree.path()).as_bytes()).unwrap();
}
// Print children if any
if let Some(variants) = tree.variants() {
let len = variants.len();
for (i, variant) in variants.iter().enumerate() {
let is_last_child = i == len - 1;
print_tree_node(variant, &child_prefix, is_last_child, file);
}
}
// Print message field if any
if let Some(fields) = tree.fields() {
let len = fields.len();
for (i, field) in fields.iter().enumerate() {
let is_last_field = i == len - 1;
let branch = if is_last_field { "└── " } else { "├── " };
file.write_all(format!("{child_prefix}{branch}{field}\n").as_bytes()).unwrap();
}
}
// Print handler field if any
if let Some(data) = tree.message_handler_fields() {
let len = data.fields().len();
let (branch, child_prefix) = if tree.message_handler_data_fields().is_some() {
("├── ", format!("{prefix}│ "))
} else {
("└── ", format!("{prefix} "))
};
const FRONTEND_MESSAGE_STR: &str = "FrontendMessage";
if data.name().is_empty() && tree.name() != FRONTEND_MESSAGE_STR {
panic!("{}'s MessageHandler is missing #[message_handler_data]", tree.name());
} else if tree.name() != FRONTEND_MESSAGE_STR {
file.write_all(format!("{}{}{} `{}`\n", prefix, branch, data.name(), data.path()).as_bytes()).unwrap();
for (i, field) in data.fields().iter().enumerate() {
let is_last_field = i == len - 1;
let branch = if is_last_field { "└── " } else { "├── " };
file.write_all(format!("{}{}{}\n", child_prefix, branch, field.0).as_bytes()).unwrap();
}
}
}
// Print data field if any
if let Some(data) = tree.message_handler_data_fields() {
let len = data.fields().len();
if data.path().is_empty() {
file.write_all(format!("{}{}{}\n", prefix, "└── ", data.name()).as_bytes()).unwrap();
} else {
file.write_all(format!("{}{}{} `{}`\n", prefix, "└── ", data.name(), data.path()).as_bytes()).unwrap();
}
for (i, field) in data.fields().iter().enumerate() {
let is_last_field = i == len - 1;
let branch = if is_last_field { "└── " } else { "├── " };
file.write_all(format!("{}{}{}\n", format!("{} ", prefix), branch, field.0).as_bytes()).unwrap();
}
}
impl Message {
pub fn message_tree() -> DebugMessageTree {
Self::build_message_tree()
}
}
-1
View File
@@ -8,7 +8,6 @@ pub mod debug;
pub mod defer;
pub mod dialog;
pub mod frontend;
pub mod globals;
pub mod input_mapper;
pub mod input_preprocessor;
pub mod layout;
@@ -102,7 +102,7 @@ impl DataPanelMessageHandler {
} else {
IconLabel::new("Node").tooltip_description("Name of the selected node.").widget_instance()
},
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(network_interface.display_name(&node_id, &[]))
.tooltip_description(if is_layer { "Name of the selected layer." } else { "Name of the selected node." })
.on_update(move |text_input| {
@@ -115,7 +115,7 @@ impl DataPanelMessageHandler {
})
.max_width(200)
.widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
]);
}
@@ -1,4 +1,5 @@
use std::path::PathBuf;
use std::sync::Arc;
use super::utility_types::misc::{GroupFolderType, SnappingState};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
@@ -203,7 +204,7 @@ pub enum DocumentMessage {
first_element_source_id: HashMap<NodeId, Option<NodeId>>,
},
UpdateClickTargets {
click_targets: HashMap<NodeId, Vec<ClickTarget>>,
click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
},
UpdateClipTargets {
clip_targets: HashSet<NodeId>,
@@ -3,7 +3,7 @@ use super::node_graph::utility_types::Transform;
use super::utility_types::error::EditorError;
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
use super::utility_types::nodes::{CollapsedLayers, SelectedNodes};
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{ASYMPTOTIC_EFFECT, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, SCALE_EFFECT, SCROLLBAR_SPACING, VIEWPORT_ROTATE_SNAP_INTERVAL};
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
@@ -11,6 +11,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay, overlay_options};
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
@@ -18,8 +19,7 @@ use crate::messages::portfolio::document::properties_panel::properties_panel_mes
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
use crate::messages::portfolio::document::utility_types::nodes::RawBuffer;
use crate::messages::portfolio::utility_types::{FontCatalog, PanelType, PersistentData};
use crate::messages::portfolio::utility_types::{PanelType, PersistentData};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
@@ -35,13 +35,13 @@ use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Raster;
use graphene_std::subpath::Subpath;
use graphene_std::table::Table;
use graphene_std::text::Font;
use graphene_std::vector::PointId;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2};
use graphene_std::vector::style::RenderMode;
use kurbo::{Affine, CubicBez, Line, ParamCurve, PathSeg, QuadBez};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
#[derive(ExtractField)]
@@ -315,8 +315,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
DocumentMessage::ClearLayersPanel => {
// Send an empty layer list
let data_buffer: RawBuffer = Self::default().serialize_root();
responses.add(FrontendMessage::UpdateDocumentLayerStructure { data_buffer });
if layers_panel_open {
let layer_structure = Self::default().build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
responses.add(FrontendMessage::UpdateDocumentLayerStructure { layer_structure });
}
// Clear the control bar
responses.add(LayoutMessage::SendLayout {
@@ -377,12 +379,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
let data_buffer: RawBuffer = self.serialize_root();
let layer_structure = self.build_layer_structure(LayerNodeIdentifier::ROOT_PARENT);
self.update_layers_panel_control_bar_widgets(layers_panel_open, responses);
self.update_layers_panel_bottom_bar_widgets(layers_panel_open, responses);
responses.add(FrontendMessage::UpdateDocumentLayerStructure { data_buffer });
responses.add(FrontendMessage::UpdateDocumentLayerStructure { layer_structure });
}
}
DocumentMessage::DrawArtboardOverlays { context: overlay_context } => {
@@ -477,6 +479,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
if self.node_graph_handler.drag_start.is_some() {
responses.add(DocumentMessage::AbortTransaction);
self.node_graph_handler.drag_start = None;
self.node_graph_handler.select_if_not_dragged = None;
}
// Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() {
@@ -961,6 +964,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(DocumentMessage::DocumentHistoryForward);
responses.add(ToolMessage::Redo);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
DocumentMessage::RenameDocument { new_name } => {
self.name = new_name.clone();
@@ -1261,6 +1265,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
OverlaysType::TransformCage => visibility_settings.transform_cage = visible,
OverlaysType::HoverOutline => visibility_settings.hover_outline = visible,
OverlaysType::SelectionOutline => visibility_settings.selection_outline = visible,
OverlaysType::LayerOriginCross => visibility_settings.layer_origin_cross = visible,
OverlaysType::Pivot => visibility_settings.pivot = visible,
OverlaysType::Origin => visibility_settings.origin = visible,
OverlaysType::Path => visibility_settings.path = visible,
@@ -1427,6 +1432,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(DocumentMessage::DocumentHistoryBackward);
responses.add(OverlaysMessage::Draw);
responses.add(ToolMessage::Undo);
responses.add(EventMessage::SelectionChanged);
}
DocumentMessage::UngroupSelectedLayers => {
if !self.selection_network_path.is_empty() {
@@ -1548,7 +1554,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
// Create an artboard and set its dimensions to the bounding box size and location
let node_id = NodeId::new();
let node_layer_id = LayerNodeIdentifier::new_unchecked(node_id);
let new_artboard_node = document_node_definitions::resolve_document_node_type("Artboard")
let new_artboard_node = document_node_definitions::resolve_network_node_type("Artboard")
.expect("Failed to create artboard node")
.default_node_template();
responses.add(NodeGraphMessage::InsertNode {
@@ -1886,70 +1892,22 @@ impl DocumentMessageHandler {
Ok(document_message_handler)
}
/// Called recursively by the entry function [`serialize_root`].
fn serialize_structure(&self, folder: LayerNodeIdentifier, structure_section: &mut Vec<u64>, data_section: &mut Vec<u64>, path: &mut Vec<LayerNodeIdentifier>) {
let mut space = 0;
for layer_node in folder.children(self.metadata()) {
data_section.push(layer_node.to_node().0);
space += 1;
if layer_node.has_children(self.metadata()) && !self.collapsed.0.contains(&layer_node) {
path.push(layer_node);
// TODO: Skip if folder is not expanded.
structure_section.push(space);
self.serialize_structure(layer_node, structure_section, data_section, path);
space = 0;
path.pop();
}
}
structure_section.push(space | (1 << 63));
}
/// Serializes the layer structure into a condensed 1D structure.
///
/// # Format
/// It is a string of numbers broken into three sections:
///
/// | Data | Description | Length |
/// |------------------------------------------------------------------------------------------------------------------------------ |---------------------------------------------------------------|------------------|
/// | `4,` `2, 1, -2, -0,` `16533113728871998040,3427872634365736244,18115028555707261608,15878401910454357952,449479075714955186` | Encoded example data | |
/// | _____________________________________________________________________________________________________________________________ | _____________________________________________________________ | ________________ |
/// | **Length** section: `4` | Length of the **Structure** section (`L` = `structure.len()`) | First value |
/// | **Structure** section: `2, 1, -2, -0` | The **Structure** section | Next `L` values |
/// | **Data** section: `16533113728871998040, 3427872634365736244, 18115028555707261608, 15878401910454357952, 449479075714955186` | The **Data** section (layer IDs) | Remaining values |
///
/// The data section lists the layer IDs for all folders/layers in the tree as read from top to bottom.
/// The structure section lists signed numbers. The sign indicates a folder indentation change (`+` is down a level, `-` is up a level).
/// The numbers in the structure block encode the indentation. For example:
/// - `2` means read two elements from the data section, then place a `[`.
/// - `-x` means read `x` elements from the data section and then insert a `]`.
///
/// ```text
/// 2 V 1 V -2 A -0 A
/// 16533113728871998040,3427872634365736244, 18115028555707261608, 15878401910454357952,449479075714955186
/// 16533113728871998040,3427872634365736244,[ 18115028555707261608,[15878401910454357952,449479075714955186] ]
/// ```
///
/// Resulting layer panel:
/// ```text
/// 16533113728871998040
/// 3427872634365736244
/// [3427872634365736244,18115028555707261608]
/// [3427872634365736244,18115028555707261608,15878401910454357952]
/// [3427872634365736244,18115028555707261608,449479075714955186]
/// ```
pub fn serialize_root(&self) -> RawBuffer {
let mut structure_section = vec![NodeId(0).0];
let mut data_section = Vec::new();
self.serialize_structure(LayerNodeIdentifier::ROOT_PARENT, &mut structure_section, &mut data_section, &mut vec![]);
// Remove the ROOT element. Prepend `L`, the length (excluding the ROOT) of the structure section (which happens to be where the ROOT element was).
structure_section[0] = structure_section.len() as u64 - 1;
// Append the data section to the end.
structure_section.extend(data_section);
structure_section.as_slice().into()
/// Recursively builds the layer structure tree for a folder.
fn build_layer_structure(&self, folder: LayerNodeIdentifier) -> Vec<LayerStructureEntry> {
folder
.children(self.metadata())
.map(|layer_node| {
let children = if layer_node.has_children(self.metadata()) && !self.collapsed.0.contains(&layer_node) {
self.build_layer_structure(layer_node)
} else {
Vec::new()
};
LayerStructureEntry {
layer_id: layer_node.to_node(),
children,
}
})
.collect()
}
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
@@ -2133,8 +2091,7 @@ impl DocumentMessageHandler {
network_interface.upstream_flow_back_from_nodes(vec![selected_id.to_node()], &[], FlowType::HorizontalFlow).find(|id| {
network_interface
.reference(id, &[])
.map(|name| name.as_deref().unwrap_or_default() == "Boolean Operation")
.unwrap_or_default()
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Boolean Operation".into()))
})
});
@@ -2171,7 +2128,7 @@ impl DocumentMessageHandler {
}
/// Loads all of the fonts in the document.
pub fn load_layer_resources(&self, responses: &mut VecDeque<Message>, font_catalog: &FontCatalog) {
pub fn load_layer_resources(&self, responses: &mut VecDeque<Message>) {
let mut fonts_to_load = HashSet::new();
for (_, node, _) in self.document_network().recursive_nodes() {
@@ -2183,12 +2140,7 @@ impl DocumentMessageHandler {
}
for font in fonts_to_load {
if let Some(style) = font_catalog.find_font_style_in_catalog(&font) {
responses.add_front(FrontendMessage::TriggerFontDataLoad {
font: Font::new(font.font_family, style.to_named_style()),
url: style.url,
});
}
responses.add(PortfolioMessage::LoadFontData { font });
}
}
@@ -2208,7 +2160,7 @@ impl DocumentMessageHandler {
.tooltip_shortcut(action_shortcut!(AnimationMessageDiscriminant::ToggleLivePreview))
.on_update(|_| AnimationMessage::ToggleLivePreview.into())
.widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.overlays_visibility_settings.all)
.icon("Overlays")
.tooltip_label("Overlays")
@@ -2394,6 +2346,24 @@ impl DocumentMessageHandler {
]
},
},
LayoutGroup::Row {
widgets: {
let checkbox_id = CheckboxId::new();
vec![
CheckboxInput::new(self.overlays_visibility_settings.layer_origin_cross)
.on_update(|optional_input: &CheckboxInput| {
DocumentMessage::SetOverlaysVisibility {
visible: optional_input.checked,
overlays_type: Some(OverlaysType::LayerOriginCross),
}
.into()
})
.for_label(checkbox_id)
.widget_instance(),
TextLabel::new("Layer Origin".to_string()).for_checkbox(checkbox_id).widget_instance(),
]
},
},
LayoutGroup::Row {
widgets: vec![TextLabel::new("Pen & Path Tools").widget_instance()],
},
@@ -2457,7 +2427,7 @@ impl DocumentMessageHandler {
},
]))
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
CheckboxInput::new(snapping_state.snapping_enabled)
.icon("Snapping")
.tooltip_label("Snapping")
@@ -2527,7 +2497,7 @@ impl DocumentMessageHandler {
.collect(),
))
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
CheckboxInput::new(self.snapping_state.grid_snapping)
.icon("Grid")
.tooltip_label("Grid")
@@ -2538,7 +2508,7 @@ impl DocumentMessageHandler {
.popover_layout(Layout(overlay_options(&self.snapping_state.grid)))
.popover_min_width(Some(320))
.widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(vec![
RadioEntryData::new("Normal")
.icon("RenderModeNormal")
@@ -2562,7 +2532,7 @@ impl DocumentMessageHandler {
.selected_index(Some(self.render_mode as u32))
.narrow(true)
.widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
];
widgets.extend(navigation_controls(&self.document_ptz, &self.navigation_handler, false));
@@ -2570,7 +2540,7 @@ impl DocumentMessageHandler {
let tilt_value = self.navigation_handler.snapped_tilt(self.document_ptz.tilt()) / (std::f64::consts::PI / 180.);
if tilt_value.abs() > 0.00001 {
widgets.extend([
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(tilt_value))
.unit("°")
.increment_behavior(NumberInputIncrementBehavior::Callback)
@@ -2600,7 +2570,7 @@ impl DocumentMessageHandler {
}
widgets.extend([
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextButton::new("Node Graph")
.icon(Some((if self.graph_view_overlay_open { "GraphViewOpen" } else { "GraphViewClosed" }).into()))
.hover_icon(Some((if self.graph_view_overlay_open { "GraphViewClosed" } else { "GraphViewOpen" }).into()))
@@ -2704,7 +2674,7 @@ impl DocumentMessageHandler {
.max_width(100)
.tooltip_label("Blend Mode")
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(opacity)
.label("Opacity")
.unit("%")
@@ -2726,7 +2696,7 @@ impl DocumentMessageHandler {
.max_width(100)
.tooltip_label("Opacity")
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(fill)
.label("Fill")
.unit("%")
@@ -2824,7 +2794,7 @@ impl DocumentMessageHandler {
Layout(vec![LayoutGroup::Row { widgets: vec![node_chooser] }])
})
.widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
IconButton::new("Folder", 24)
.tooltip_label("Group Selected")
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::GroupSelectedLayers))
@@ -3055,7 +3025,14 @@ impl<'a> ClickXRayIter<'a> {
}
/// Handles the checking of the layer where the target is a rect or path
fn check_layer_area_target(&mut self, click_targets: Option<&Vec<ClickTarget>>, clip: bool, layer: LayerNodeIdentifier, path: Vec<path_bool_lib::PathSegment>, transform: DAffine2) -> XRayResult {
fn check_layer_area_target(
&mut self,
click_targets: Option<&[Arc<ClickTarget>]>,
clip: bool,
layer: LayerNodeIdentifier,
path: Vec<path_bool_lib::PathSegment>,
transform: DAffine2,
) -> XRayResult {
// Convert back to Kurbo types for intersections
let segment = |bezier: &path_bool_lib::PathSegment| match *bezier {
path_bool_lib::PathSegment::Line(start, end) => PathSeg::Line(Line::new(dvec2_to_point(start), dvec2_to_point(end))),
@@ -3072,7 +3049,7 @@ impl<'a> ClickXRayIter<'a> {
// In the case of a clip path where the area partially intersects, it is necessary to do a boolean operation.
// We do this on this using the target area to reduce computation (as the target area is usually very simple).
if clip && intersects {
let clip_path = click_targets_to_path_lib_segments(click_targets.iter().flat_map(|x| x.iter()), transform);
let clip_path = click_targets_to_path_lib_segments(click_targets.iter().flat_map(|x| x.iter()).map(|x| x.as_ref()), transform);
let subtracted = boolean_intersect(path, clip_path).into_iter().flatten().collect::<Vec<_>>();
if subtracted.is_empty() {
use_children = false;
@@ -3149,7 +3126,7 @@ pub fn navigation_controls(ptz: &PTZ, navigation_handler: &NavigationMessageHand
);
}
list.extend([
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(navigation_handler.snapped_zoom(ptz.zoom()) * 100.))
.unit("%")
.min(0.000001)
@@ -382,7 +382,7 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
modify_inputs.insert_vector(subpaths, layer, true, path.fill().is_some(), path.stroke().is_some());
if let Some(transform_node_id) = modify_inputs.existing_node_id("Transform", true) {
if let Some(transform_node_id) = modify_inputs.existing_network_node_id("Transform", true) {
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, transform * usvg_transform(node.abs_transform()));
}
@@ -1,12 +1,12 @@
use super::transform_utils;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
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::{self, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use glam::{DAffine2, IVec2};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::Artboard;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
@@ -123,14 +123,14 @@ impl<'a> ModifyInputsContext<'a> {
/// Creates a new layer and adds it to the document network. network_interface.move_layer_to_stack should be called after
pub fn create_layer(&mut self, new_id: NodeId) -> LayerNodeIdentifier {
let new_merge_node = resolve_document_node_type("Merge").expect("Merge node").default_node_template();
let new_merge_node = resolve_network_node_type("Merge").expect("Merge node").default_node_template();
self.network_interface.insert_node(new_id, new_merge_node, &[]);
LayerNodeIdentifier::new(new_id, self.network_interface)
}
/// Creates an artboard as the primary export for the document network
pub fn create_artboard(&mut self, new_id: NodeId, artboard: Artboard) -> LayerNodeIdentifier {
let artboard_node_template = resolve_document_node_type("Artboard").expect("Node").node_template_input_override([
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
Some(NodeInput::value(TaggedValue::Artboard(Default::default()), true)),
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
Some(NodeInput::value(TaggedValue::DVec2(artboard.location.into()), false)),
@@ -143,7 +143,7 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn insert_boolean_data(&mut self, operation: graphene_std::path_bool::BooleanOperation, layer: LayerNodeIdentifier) {
let boolean = resolve_document_node_type("Boolean Operation").expect("Boolean node does not exist").node_template_input_override([
let boolean = resolve_network_node_type("Boolean Operation").expect("Boolean node does not exist").node_template_input_override([
Some(NodeInput::value(TaggedValue::Graphic(Default::default()), true)),
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
]);
@@ -156,7 +156,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
let vector = Table::new_from_element(Vector::from_subpaths(subpaths, true));
let shape = resolve_document_node_type("Path")
let shape = resolve_network_node_type("Path")
.expect("Path node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::Vector(vector), false))]);
let shape_id = NodeId::new();
@@ -164,21 +164,25 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&shape_id, layer, &[]);
if include_transform {
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[]);
}
if include_fill {
let fill = resolve_document_node_type("Fill").expect("Fill node does not exist").default_node_template();
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
.default_node_template();
let fill_id = NodeId::new();
self.network_interface.insert_node(fill_id, fill, &[]);
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[]);
}
if include_stroke {
let stroke = resolve_document_node_type("Stroke").expect("Stroke node does not exist").default_node_template();
let stroke = resolve_proto_node_type(graphene_std::vector_nodes::stroke::IDENTIFIER)
.expect("Stroke node does not exist")
.default_node_template();
let stroke_id = NodeId::new();
self.network_interface.insert_node(stroke_id, stroke, &[]);
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[]);
@@ -186,21 +190,29 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn insert_text(&mut self, text: String, font: Font, typesetting: TypesettingConfig, layer: LayerNodeIdentifier) {
let stroke = resolve_document_node_type("Stroke").expect("Stroke node does not exist").default_node_template();
let fill = resolve_document_node_type("Fill").expect("Fill node does not exist").default_node_template();
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
let text = resolve_document_node_type("Text").expect("Text node does not exist").node_template_input_override([
Some(NodeInput::scope("editor-api")),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Font(font), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
Some(NodeInput::value(TaggedValue::OptionalF64(typesetting.max_width), false)),
Some(NodeInput::value(TaggedValue::OptionalF64(typesetting.max_height), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let stroke = resolve_proto_node_type(graphene_std::vector_nodes::stroke::IDENTIFIER)
.expect("Stroke node does not exist")
.default_node_template();
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
.expect("Fill node does not exist")
.default_node_template();
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
let text = resolve_proto_node_type(graphene_std::text::text::IDENTIFIER)
.expect("Text node does not exist")
.node_template_input_override([
Some(NodeInput::scope("editor-api")),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Font(font), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_id = NodeId::new();
self.network_interface.insert_node(text_id, text, &[]);
@@ -220,8 +232,8 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn insert_image_data(&mut self, image_frame: Table<Raster<CPU>>, layer: LayerNodeIdentifier) {
let transform = resolve_document_node_type("Transform").expect("Transform node does not exist").default_node_template();
let image = resolve_document_node_type("Image Value")
let transform = resolve_network_node_type("Transform").expect("Transform node does not exist").default_node_template();
let image = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image_value::IDENTIFIER)
.expect("ImageValue node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Raster(image_frame), false))]);
@@ -245,18 +257,26 @@ impl<'a> ModifyInputsContext<'a> {
})
}
/// Gets the node id of a node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
/// The returned node is based on the selection dots in the layer. The right most dot will always insert/access the path that flows directly into the layer.
/// Each dot after that represents an existing path node. If there is an existing upstream node, then it will always be returned first.
pub fn existing_node_id(&mut self, reference_name: &'static str, create_if_nonexistent: bool) -> Option<NodeId> {
/// Gets the node id of a network node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
pub fn existing_network_node_id(&mut self, reference: &str, create_if_nonexistent: bool) -> Option<NodeId> {
self.existing_node_id(&DefinitionIdentifier::Network(reference.into()), create_if_nonexistent)
}
/// Gets the node id of a proto node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
pub fn existing_proto_node_id(&mut self, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
self.existing_node_id(&DefinitionIdentifier::ProtoNode(reference), create_if_nonexistent)
}
/// Gets the node id of a document node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
fn existing_node_id(&mut self, reference: &DefinitionIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
// Start from the layer node or export
let output_layer = self.get_output_layer()?;
let existing_node_id = Self::locate_node_in_layer_chain(reference_name, output_layer, self.network_interface);
let existing_node_id = Self::locate_node_in_layer_chain(reference, output_layer, self.network_interface);
// Create a new node if the node does not exist and update its inputs
if create_if_nonexistent {
return existing_node_id.or_else(|| self.create_node(reference_name));
return existing_node_id.or_else(|| self.create_node(reference));
}
existing_node_id
@@ -265,16 +285,13 @@ impl<'a> ModifyInputsContext<'a> {
/// Gets the node id of a node with a specific reference (name) that is upstream (leftward) from the layer node, but before reaching another upstream layer stack.
/// For example, if given a parent layer, this would find a requested "Transform" or "Boolean Operation" node in its chain, between the parent layer and its layer stack child contents.
/// It would also travel up an entire layer that's not fed by a stack until reaching the generator node, such as a "Rectangle" or "Path" layer.
pub fn locate_node_in_layer_chain(reference_name: &str, left_of_layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
pub fn locate_node_in_layer_chain(reference: &DefinitionIdentifier, left_of_layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let upstream = network_interface.upstream_flow_back_from_nodes(vec![left_of_layer.to_node()], &[], network_interface::FlowType::HorizontalFlow);
// Look at all of the upstream nodes
for upstream_node in upstream {
// Check if this is the node we have been searching for.
if network_interface
.reference(&upstream_node, &[])
.is_some_and(|node_reference| *node_reference == Some(reference_name.to_string()))
{
if network_interface.reference(&upstream_node, &[]).is_some_and(|node_reference| node_reference == *reference) {
if !network_interface.is_visible(&upstream_node, &[]) {
continue;
}
@@ -293,10 +310,10 @@ impl<'a> ModifyInputsContext<'a> {
}
/// Create a new node inside the layer
pub fn create_node(&mut self, reference: &str) -> Option<NodeId> {
pub fn create_node(&mut self, reference: &DefinitionIdentifier) -> Option<NodeId> {
let output_layer = self.get_output_layer()?;
let Some(node_definition) = resolve_document_node_type(reference) else {
log::error!("Node type {reference} does not exist in ModifyInputsContext::existing_node_id");
log::error!("Node {reference:?} does not exist in ModifyInputsContext::existing_node_id");
return None;
};
@@ -305,7 +322,7 @@ impl<'a> ModifyInputsContext<'a> {
if node_definition.identifier == "Path" {
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
if layer_input_type.compiled_nested_type() == Some(&concrete!(Table<Graphic>)) {
let Some(flatten_path_definition) = resolve_document_node_type("Flatten Path") else {
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
return None;
};
@@ -325,7 +342,9 @@ impl<'a> ModifyInputsContext<'a> {
let backup_color_index = 2;
let backup_gradient_index = 3;
let Some(fill_node_id) = self.existing_node_id("Fill", true) else { return };
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
match &fill {
Fill::None => {
let input_connector = InputConnector::node(fill_node_id, backup_color_index);
@@ -345,32 +364,42 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(blend_node_id, 1);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
}
pub fn opacity_set(&mut self, opacity: f64) {
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(blend_node_id, 2);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(opacity * 100.), false), false);
}
pub fn blending_fill_set(&mut self, fill: f64) {
let Some(blend_node_id) = self.existing_node_id("Blending", true) else { return };
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(blend_node_id, 3);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(fill * 100.), false), false);
}
pub fn clip_mode_toggle(&mut self, clip_mode: Option<bool>) {
let clip = !clip_mode.unwrap_or(false);
let Some(clip_node_id) = self.existing_node_id("Blending", true) else { return };
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blending::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(clip_node_id, 4);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
}
pub fn stroke_set(&mut self, stroke: Stroke) {
let Some(stroke_node_id) = self.existing_node_id("Stroke", true) else { return };
let Some(stroke_node_id) = self.existing_proto_node_id(graphene_std::vector::stroke::IDENTIFIER, true) else {
return;
};
let stroke_color = if let Some(color) = stroke.color { Table::new_from_element(color) } else { Table::new() };
@@ -399,7 +428,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn transform_change_with_parent(&mut self, transform: DAffine2, transform_in: TransformIn, parent_transform: DAffine2, skip_rerender: bool) {
// Get the existing upstream Transform node and its transform, if present, otherwise use the identity transform
let (layer_transform, transform_node_id) = self
.existing_node_id("Transform", false)
.existing_network_node_id("Transform", false)
.and_then(|transform_node_id| {
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
@@ -423,7 +452,7 @@ impl<'a> ModifyInputsContext<'a> {
/// A new Transform node is created if one does not exist, unless it would be given the identity transform.
pub fn transform_set(&mut self, transform: DAffine2, transform_in: TransformIn, skip_rerender: bool) {
// Get the existing upstream Transform node, if present
let transform_node_id = self.existing_node_id("Transform", false);
let transform_node_id = self.existing_network_node_id("Transform", false);
// Get a transform appropriate for the requested space
let to_transform = match transform_in {
@@ -448,7 +477,7 @@ impl<'a> ModifyInputsContext<'a> {
}
// Create the Transform node
self.existing_node_id("Transform", true)
self.existing_network_node_id("Transform", true)
}) else {
return;
};
@@ -464,19 +493,23 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn vector_modify(&mut self, modification_type: VectorModificationType) {
let Some(path_node_id) = self.existing_node_id("Path", true) else { return };
let Some(path_node_id) = self.existing_network_node_id("Path", true) else {
return;
};
self.network_interface.vector_modify(&path_node_id, modification_type);
self.responses.add(PropertiesPanelMessage::Refresh);
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
pub fn brush_modify(&mut self, strokes: Vec<BrushStroke>) {
let Some(brush_node_id) = self.existing_node_id("Brush", true) else { return };
let Some(brush_node_id) = self.existing_network_node_id("Brush", true) else {
return;
};
self.set_input_with_refresh(InputConnector::node(brush_node_id, 1), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
}
pub fn resize_artboard(&mut self, location: IVec2, dimensions: IVec2) {
let Some(artboard_node_id) = self.existing_node_id("Artboard", true) else {
let Some(artboard_node_id) = self.existing_network_node_id("Artboard", true) else {
return;
};
@@ -1,3 +1,4 @@
use crate::application::Editor;
use crate::consts::{
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
@@ -8,7 +9,6 @@ use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
use crate::messages::prelude::*;
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use glam::{DAffine2, DVec2};
@@ -176,9 +176,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
}
NavigationMessage::CanvasPanMouseWheel { use_y_as_x } => {
// On Mac, the OS already converts Shift+scroll into horizontal scrolling
let keyboard_platform = GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
let delta = if use_y_as_x && keyboard_platform == KeyboardPlatformLayout::Standard {
let delta = if use_y_as_x && !Editor::environment().is_mac() {
(ipp.mouse.scroll_delta.y, 0.).into()
} else {
ipp.mouse.scroll_delta.as_dvec2()
@@ -21,12 +21,12 @@ use graphene_std::extract_xy::XY;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::table::Table;
use graphene_std::text::{Font, TypesettingConfig};
#[allow(unused_imports)]
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::*;
use std::collections::{HashMap, HashSet, VecDeque};
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> {
pub persistent_data: &'a PersistentData,
@@ -54,10 +54,57 @@ impl NodePropertiesContext<'_> {
}
}
/// The key used to access definitions for a network node or proto node.
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
/// For network nodes, it doesn't necessarily have to be the same as the network's display name, but it often is.
#[derive(Debug, Clone, Hash, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(tag = "type", content = "data")]
pub enum DefinitionIdentifier {
ProtoNode(ProtoNodeIdentifier),
Network(String),
}
impl DefinitionIdentifier {
pub fn implementation_name_from_identifier(&self) -> String {
match self {
DefinitionIdentifier::Network(name) => name.clone(),
DefinitionIdentifier::ProtoNode(proto_node_identifier) => registry::NODE_METADATA
.lock()
.unwrap()
.get(proto_node_identifier)
.map(|metadata| metadata.display_name.to_string())
.unwrap_or_else(|| {
let mut last_segment = proto_node_identifier.as_str().split("::").last().unwrap_or_default().to_string();
last_segment = last_segment.strip_suffix("Node").unwrap_or(&last_segment).to_string();
last_segment
}),
}
}
pub fn serialized(&self) -> String {
match self {
DefinitionIdentifier::ProtoNode(id) => format!("PROTONODE:{}", id.as_str()),
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
}
}
}
impl From<Value> for DefinitionIdentifier {
fn from(value: Value) -> Self {
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
match s.split_once(':') {
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
other => panic!("Unknown `DefinitionIdentifier` type. Found `{other:?}`."),
}
}
}
/// Acts as a description for a [DocumentNode] before it gets instantiated as one.
#[derive(Clone)]
#[derive(Debug, Clone)]
pub struct DocumentNodeDefinition {
/// Used by the reference field in [`DocumentNodeMetadata`] to prevent storing a copy of the implementation, if it is unchanged from the definition.
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
pub identifier: &'static str,
/// All data required to construct a [`DocumentNode`] and [`DocumentNodeMetadata`]
@@ -75,14 +122,15 @@ pub struct DocumentNodeDefinition {
pub properties: Option<&'static str>,
}
// We use the once cell for lazy initialization to avoid the overhead of reconstructing the node list every time.
// TODO: make document nodes not require a `'static` lifetime to avoid having to split the construction into const and non-const parts.
static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<Vec<DocumentNodeDefinition>> = once_cell::sync::Lazy::new(static_nodes);
// We use the once_cell to use the document node definitions throughout the editor without passing a reference
// TODO: If dynamic node library is required, use a Mutex as well
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier, DocumentNodeDefinition>> = once_cell::sync::Lazy::new(document_node_definitions);
// TODO: Dynamic node library
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
fn static_nodes() -> Vec<DocumentNodeDefinition> {
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
@@ -100,7 +148,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
..Default::default()
},
},
description: Cow::Borrowed("Returns the input value without changing it. This is useful for rerouting wires for organization purposes."),
description: Cow::Borrowed("Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes."),
properties: None,
},
// TODO: Auto-generate this from its proto node macro
@@ -140,6 +188,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
properties: None,
},
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
identifier: "Cache",
category: "General",
@@ -224,7 +273,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "To Graphic".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default()
},
@@ -232,7 +280,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Wrap Graphic".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -1)),
..Default::default()
},
@@ -240,7 +287,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Source Node ID".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
..Default::default()
},
@@ -248,7 +294,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Monitor".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
..Default::default()
},
@@ -256,7 +301,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extend".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -3)),
..Default::default()
},
@@ -375,7 +419,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Create Artboard".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default()
},
@@ -383,7 +426,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Source Node ID".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
..Default::default()
},
@@ -391,7 +433,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Monitor".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
..Default::default()
},
@@ -399,7 +440,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extend".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default()
},
@@ -989,7 +1029,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Load Resource".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -997,7 +1036,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Decode Image".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
@@ -1071,7 +1109,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Create Surface".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
..Default::default()
},
@@ -1079,7 +1116,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Cache".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 2)),
..Default::default()
},
@@ -1087,7 +1123,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Rasterize".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
},
@@ -1108,12 +1143,13 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
description: Cow::Borrowed("TODO"),
properties: None,
},
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
identifier: "Noise Pattern",
category: "Raster: Pattern",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(raster_nodes::std_nodes::noise_pattern::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER),
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::Bool(true), false),
@@ -1228,7 +1264,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract Channel".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1236,7 +1271,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract Channel".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
..Default::default()
},
@@ -1244,7 +1278,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract Channel".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 4)),
..Default::default()
},
@@ -1252,7 +1285,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract Channel".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 6)),
..Default::default()
},
@@ -1312,7 +1344,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract XY".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1320,7 +1351,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract XY".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
..Default::default()
},
@@ -1382,7 +1412,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
persistent_metadata: NodeNetworkPersistentMetadata {
node_metadata: [DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Brush".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1402,6 +1431,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
description: Cow::Borrowed("TODO"),
properties: None,
},
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
identifier: "Memoize",
category: "Debug",
@@ -1423,7 +1453,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
#[cfg(feature = "gpu")]
DocumentNodeDefinition {
identifier: "Upload Texture",
category: "Debug: GPU",
category: "Debug",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
@@ -1463,7 +1493,13 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Extract Executor".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1471,20 +1507,11 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Upload Texture".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
..Default::default()
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Cache".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
},
..Default::default()
},
]
.into_iter()
.enumerate()
@@ -1592,7 +1619,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Monitor".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1600,7 +1626,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Path Modify".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
@@ -1621,103 +1646,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
description: Cow::Borrowed("TODO"),
properties: None,
},
DocumentNodeDefinition {
identifier: "Text",
category: "Text",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(text::text::IDENTIFIER),
inputs: vec![
NodeInput::scope("editor-api"),
NodeInput::value(TaggedValue::String("Lorem ipsum".to_string()), false),
NodeInput::value(
TaggedValue::Font(Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into())),
false,
),
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().font_size), false),
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().line_height_ratio), false),
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().character_spacing), false),
NodeInput::value(TaggedValue::OptionalF64(TypesettingConfig::default().max_width), false),
NodeInput::value(TaggedValue::OptionalF64(TypesettingConfig::default().max_height), false),
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().tilt), false),
NodeInput::value(TaggedValue::TextAlign(text::TextAlign::default()), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
input_metadata: vec![
("Editor API", "TODO").into(),
InputMetadata::with_name_description_override("Text", "TODO", WidgetOverride::Custom("text_area".to_string())),
InputMetadata::with_name_description_override("Font", "TODO", WidgetOverride::Custom("text_font".to_string())),
InputMetadata::with_name_description_override(
"Size",
"TODO",
WidgetOverride::Number(NumberInputSettings {
unit: Some(" px".to_string()),
min: Some(1.),
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Line Height",
"TODO",
WidgetOverride::Number(NumberInputSettings {
unit: Some("x".to_string()),
min: Some(0.),
step: Some(0.1),
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Character Spacing",
"TODO",
WidgetOverride::Number(NumberInputSettings {
unit: Some(" px".to_string()),
step: Some(0.1),
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Max Width",
"TODO",
WidgetOverride::Number(NumberInputSettings {
unit: Some(" px".to_string()),
min: Some(1.),
blank_assist: false,
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Max Height",
"TODO",
WidgetOverride::Number(NumberInputSettings {
unit: Some(" px".to_string()),
min: Some(1.),
blank_assist: false,
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Tilt",
"Faux italic.",
WidgetOverride::Number(NumberInputSettings {
min: Some(-85.),
max: Some(85.),
unit: Some("°".to_string()),
..Default::default()
}),
),
InputMetadata::with_name_description_override("Align", "TODO", WidgetOverride::Custom("text_align".to_string())),
("Per-Glyph Instances", "Splits each text glyph into its own row in the table of vector geometry.").into(),
],
output_names: vec!["Vector".to_string()],
..Default::default()
},
},
description: Cow::Borrowed("TODO"),
properties: None,
},
// TODO: Auto-generate this from its proto node macro
DocumentNodeDefinition {
identifier: "Transform",
category: "Math: Transform",
@@ -1788,7 +1717,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Monitor".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1796,15 +1724,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Transform".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
input_metadata: vec![
("Value", "TODO").into(),
("Translation", "TODO").into(),
("Rotation", "TODO").into(),
("Scale", "TODO").into(),
("Skew", "TODO").into(),
],
..Default::default()
},
..Default::default()
@@ -1854,7 +1774,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeDefinition {
identifier: "Boolean Operation",
category: "Vector",
category: "Vector: Modifier",
node_template: NodeTemplate {
document_node: DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
@@ -1891,7 +1811,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Boolean Operation".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -1899,7 +1818,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Memoize".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
@@ -1981,7 +1899,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Subpath Segment Lengths".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 7)),
..Default::default()
},
@@ -1989,7 +1906,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Sample Polyline".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
@@ -1997,7 +1913,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Memoize".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
},
@@ -2104,7 +2019,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
node_metadata: [
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Poisson-Disk Points".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
@@ -2112,7 +2026,6 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
},
DocumentNodeMetadata {
persistent_metadata: DocumentNodePersistentMetadata {
display_name: "Memoize".to_string(),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
@@ -2164,6 +2077,7 @@ fn static_nodes() -> Vec<DocumentNodeDefinition> {
type NodeProperties = HashMap<String, Box<dyn Fn(NodeId, &mut NodePropertiesContext) -> Vec<LayoutGroup> + Send + Sync>>;
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
pub static NODE_OVERRIDES: once_cell::sync::Lazy<NodeProperties> = once_cell::sync::Lazy::new(static_node_properties);
/// Defines the logic for inputs to display a custom properties panel widget.
@@ -2190,6 +2104,7 @@ fn static_node_properties() -> NodeProperties {
type InputProperties = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, String> + Send + Sync>>;
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputProperties> = once_cell::sync::Lazy::new(static_input_properties);
/// Defines the logic for inputs to display a custom properties panel widget.
@@ -2281,6 +2196,43 @@ fn static_input_properties() -> InputProperties {
}])
}),
);
map.insert(
// The custom number input settings are only available on proto nodes
"optional_f64".to_string(),
Box::new(|node_id, index, context| {
let node_metadata = registry::NODE_METADATA.lock().unwrap();
let mut number_input = NumberInput::default();
if let Some(field) = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| node_metadata.get(proto_node_identifier))
.and_then(|metadata| metadata.fields.get(index))
{
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
if let Some(number_min) = field.number_min {
number_input = number_input.min(number_min);
}
if let Some(number_max) = field.number_max {
number_input = number_input.max(number_max);
}
if let Some((range_min, range_max)) = field.number_mode_range {
number_input = number_input.range_min(Some(range_min));
number_input = number_input.range_max(Some(range_max));
}
number_input = number_input.is_integer(false);
if let Some(number_step) = field.number_step {
number_input = number_input.step(number_step);
}
};
Ok(vec![LayoutGroup::Row {
// NOTE: The bool input MUST be at the input index directly before the f64 input!
widgets: node_properties::optional_f64_widget(ParameterWidgetsInfo::new(node_id, index, false, context), index - 1, number_input),
}])
}),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
@@ -2536,7 +2488,7 @@ fn static_input_properties() -> InputProperties {
};
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
.unit("°")
.mode(NumberInputMode::Range)
@@ -2567,7 +2519,7 @@ fn static_input_properties() -> InputProperties {
};
if let Some(&TaggedValue::DVec2(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val.x))
.label("X")
.unit("°")
@@ -2580,7 +2532,7 @@ fn static_input_properties() -> InputProperties {
))
.on_commit(node_properties::commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(val.y))
.label("Y")
.unit("°")
@@ -2637,99 +2589,50 @@ fn static_input_properties() -> InputProperties {
map
}
pub fn resolve_document_node_type(identifier: &str) -> Option<&DocumentNodeDefinition> {
DOCUMENT_NODE_TYPES.iter().find(|definition| definition.identifier == identifier)
pub fn resolve_network_node_type(identifier: &str) -> Option<&'static DocumentNodeDefinition> {
resolve_document_node_type(&DefinitionIdentifier::Network(identifier.into()))
}
pub fn resolve_proto_node_type(identifier: ProtoNodeIdentifier) -> Option<&'static DocumentNodeDefinition> {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
}
pub fn resolve_document_node_type(identifier: &DefinitionIdentifier) -> Option<&'static DocumentNodeDefinition> {
DOCUMENT_NODE_TYPES.get(identifier)
}
pub fn collect_node_types() -> Vec<FrontendNodeType> {
// Create a mapping from registry ID to document node identifier
let id_to_identifier_map: HashMap<ProtoNodeIdentifier, &'static str> = DOCUMENT_NODE_TYPES
DOCUMENT_NODE_TYPES
.iter()
.filter_map(|definition| {
if let DocumentNodeImplementation::ProtoNode(name) = &definition.node_template.document_node.implementation {
Some((name.clone(), definition.identifier))
} else {
None
}
})
.collect();
let mut extracted_node_types = Vec::new();
let node_registry = registry::NODE_REGISTRY.lock().unwrap();
let node_metadata = registry::NODE_METADATA.lock().unwrap();
for (id, metadata) in node_metadata.iter() {
if let Some(implementations) = node_registry.get(id) {
let identifier = match id_to_identifier_map.get(id) {
Some(&id) => id,
None => continue,
};
// Extract category from metadata (already creates an owned String)
let category = metadata.category.unwrap_or_default();
// Extract input types (already creates owned Strings)
let input_types = implementations
.iter()
.flat_map(|(_, node_io)| node_io.inputs.iter().map(|ty| ty.nested_type().to_cow_string()))
.collect::<HashSet<Cow<'static, str>>>()
.into_iter()
.collect::<Vec<Cow<'static, str>>>();
// Create a FrontendNodeType
let node_type = FrontendNodeType::with_input_types(identifier, category, input_types);
// Store the created node_type
extracted_node_types.push(node_type);
}
}
let node_types: Vec<FrontendNodeType> = DOCUMENT_NODE_TYPES
.iter()
.filter(|definition| !definition.category.is_empty())
.map(|definition| {
.filter(|(_, definition)| !definition.category.is_empty())
.map(|(identifier, definition)| {
let input_types = definition
.node_template
.document_node
.inputs
.iter()
.filter_map(|node_input| node_input.as_value().map(|node_value| node_value.ty().nested_type().to_cow_string()))
.collect::<Vec<Cow<'static, str>>>();
FrontendNodeType::with_input_types(definition.identifier, definition.category, input_types)
})
.collect();
// Update categories in extracted_node_types from node_types
for extracted_node in &mut extracted_node_types {
if extracted_node.category.is_empty() {
// Find matching node in node_types and update category if found
if let Some(matching_node) = node_types.iter().find(|node_type| node_type.name == extracted_node.name) {
extracted_node.category = matching_node.category.clone();
.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.persistent_node_metadata.display_name.clone();
if name.is_empty() {
name = identifier.implementation_name_from_identifier()
}
}
}
let missing_nodes: Vec<FrontendNodeType> = node_types
.iter()
.filter(|node| !extracted_node_types.iter().any(|extracted| extracted.name == node.name))
.cloned()
.collect();
// Add the missing nodes to extracted_node_types
for node in missing_nodes {
extracted_node_types.push(node);
}
// Remove entries with empty categories
extracted_node_types.retain(|node| !node.category.is_empty());
extracted_node_types
FrontendNodeType {
identifier: identifier.serialized(),
name,
category: definition.category.to_string(),
input_types,
}
})
.collect()
}
pub fn collect_node_descriptions() -> Vec<(String, String)> {
DOCUMENT_NODE_TYPES
.iter()
.map(|definition| {
.map(|(identifier, definition)| {
(
definition.identifier.to_string(),
identifier.serialized(),
if definition.description != "TODO" { definition.description.to_string() } else { String::new() },
)
})
@@ -2744,8 +2647,9 @@ impl DocumentNodeDefinition {
// TODO: Replace the .enumerate() with changing the iterator to take a tuple of (index, input) so the user is forced to provide the correct index
input_override.into_iter().enumerate().for_each(|(index, input_override)| {
if let Some(input_override) = input_override {
// Only value inputs can be overridden, since node inputs change graph structure and must be handled by the network interface
// assert!(matches!(input_override, NodeInput::Value { .. }), "Only value inputs are supported for input overrides");
// Only value inputs should be overridden, since node inputs change graph structure and must be handled by the network interface.
// However, this would require changing some tooling which creates multiple nodes at once, before they are inserted into the network.
// debug_assert!(input_override.as_node().is_none(), "Node inputs are not supported in input overrides");
template.document_node.inputs[index] = input_override;
}
});
@@ -2806,12 +2710,6 @@ impl DocumentNodeDefinition {
}
populate_input_properties(&mut template, Vec::new());
// Set the reference to the node definition
template.persistent_node_metadata.reference = Some(self.identifier.to_string());
// If the display name is empty and it is not a merge node, then set it to the reference
if template.persistent_node_metadata.display_name.is_empty() && self.identifier != "Merge" {
template.persistent_node_metadata.display_name = self.identifier.to_string();
}
template
}
@@ -1,72 +1,34 @@
use super::DocumentNodeDefinition;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{DocumentNodePersistentMetadata, InputMetadata, NodeTemplate, WidgetOverride};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::*;
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
/// Traverses a document node template and metadata in parallel to link the protonodes to their reference
fn traverse_node(node: &DocumentNode, node_metadata: &mut DocumentNodePersistentMetadata) {
match &node.implementation {
DocumentNodeImplementation::Network(node_network) => {
for (nested_node_id, nested_node) in node_network.nodes.iter() {
let nested_metadata = node_metadata
.network_metadata
.as_mut()
.expect("Network node must have network metadata")
.persistent_metadata
.node_metadata
.get_mut(nested_node_id)
.expect("Network metadata must have corresponding node id");
traverse_node(nested_node, &mut nested_metadata.persistent_metadata);
}
}
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
if let Some(metadata) = NODE_METADATA.lock().unwrap().get(proto_node_identifier) {
node_metadata.reference = Some(metadata.display_name.to_string());
}
}
DocumentNodeImplementation::Extract => {}
}
}
pub(super) fn post_process_nodes(mut custom: Vec<DocumentNodeDefinition>) -> Vec<DocumentNodeDefinition> {
// Link the protonodes with custom networks to their reference
for node in custom.iter_mut() {
traverse_node(&node.node_template.document_node, &mut node.node_template.persistent_node_metadata);
}
// Remove struct generics
for DocumentNodeDefinition { node_template, .. } in custom.iter_mut() {
let NodeTemplate {
document_node: DocumentNode { implementation, .. },
..
} = node_template;
if let DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier { name }) = implementation
&& let Some((new_name, _suffix)) = name.rsplit_once("<")
{
*name = Cow::Owned(new_name.to_string())
};
}
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
// Create hashmap for the protonodes added by the macro.
let mut definitions_map = HashMap::new();
// First remove the custom protonodes and add them to the definitions map since they contain different metadata
// from the macro and must be inserted first so that network nodes which reference them use the correct metadata.
let network_nodes = custom
.into_iter()
.filter_map(|definition| {
if let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = &definition.node_template.document_node.implementation {
definitions_map.insert(DefinitionIdentifier::ProtoNode(proto_node_identifier.clone()), definition);
return None;
};
Some(definition)
})
.collect::<Vec<_>>();
// Add the rest of the protonodes from the macro
let node_registry = NODE_REGISTRY.lock().unwrap();
'outer: for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
for node in custom.iter() {
let DocumentNodeDefinition {
node_template: NodeTemplate {
document_node: DocumentNode { implementation, .. },
..
},
..
} = node;
match implementation {
DocumentNodeImplementation::ProtoNode(name) if name == id => continue 'outer,
_ => (),
}
}
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
if definitions_map.contains_key(&identifier) {
continue;
};
let NodeMetadata {
display_name,
category,
@@ -78,48 +40,96 @@ pub(super) fn post_process_nodes(mut custom: Vec<DocumentNodeDefinition>) -> Vec
let Some(implementations) = &node_registry.get(id) else { continue };
let valid_inputs: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.call_argument.clone()).collect();
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
let valid_inputs: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.call_argument.clone()).collect();
let input_type = if valid_inputs.len() > 1 { &const { generic!(D) } } else { &first_node_io.call_argument };
let output_type = &first_node_io.return_value;
let inputs = preprocessor::node_inputs(fields, first_node_io);
let node = DocumentNodeDefinition {
identifier: display_name,
node_template: NodeTemplate {
document_node: DocumentNode {
inputs,
call_argument: input_type.clone(),
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
visible: true,
skip_deduplication: false,
context_features: ContextDependencies::from(context_features.as_slice()),
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
output_names: vec![output_type.to_string()],
locked: false,
..Default::default()
definitions_map.insert(
identifier,
DocumentNodeDefinition {
identifier: display_name,
node_template: NodeTemplate {
document_node: DocumentNode {
inputs,
call_argument: input_type.clone(),
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
visible: true,
skip_deduplication: false,
context_features: ContextDependencies::from(context_features.as_slice()),
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
locked: false,
..Default::default()
},
},
category,
description: Cow::Borrowed(description),
properties: *properties,
},
category: category.unwrap_or("UNCATEGORIZED"),
description: Cow::Borrowed(description),
properties: *properties,
};
custom.push(node);
);
}
custom
// If any protonode does not have metadata then set its display name to its identifier string
for definition in definitions_map.values_mut() {
let metadata = NODE_METADATA.lock().unwrap();
if let DocumentNodeImplementation::ProtoNode(id) = &definition.node_template.document_node.implementation
&& !metadata.contains_key(id)
{
definition.node_template.persistent_node_metadata.display_name = definition.identifier.to_string();
}
}
// Add the rest of the network nodes to the map and add the metadata for their internal protonodes
for mut network_node in network_nodes {
traverse_node(&network_node.node_template.document_node, &mut network_node.node_template.persistent_node_metadata, &definitions_map);
// Set the reference to the node identifier
if let Some(nested_metadata) = network_node.node_template.persistent_node_metadata.network_metadata.as_mut() {
nested_metadata.persistent_metadata.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.persistent_node_metadata.display_name = network_node.identifier.to_string();
}
}
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
}
definitions_map
}
/// Traverses a document node template and metadata in parallel to add metadata to the protonodes
fn traverse_node(node: &DocumentNode, node_metadata: &mut DocumentNodePersistentMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &node.implementation {
DocumentNodeImplementation::Network(node_network) => {
for (nested_node_id, nested_node) in node_network.nodes.iter() {
let nested_metadata = node_metadata.network_metadata.as_mut().unwrap().persistent_metadata.node_metadata.get_mut(nested_node_id).unwrap();
traverse_node(nested_node, &mut nested_metadata.persistent_metadata, definitions_map);
}
}
DocumentNodeImplementation::ProtoNode(id) => {
// Set all the metadata except the position to the proto node information from the macro
// TODO: Use options in the template to specify what you want to default and what you want to override
// If this fails then the proto node id in the definition doesn't match what is generated by the macro
let Some(definition) = definitions_map.get(&DefinitionIdentifier::ProtoNode(id.clone())) else {
// log::error!("Could not get definition for id {} when filling in protonode metadata for a custom node", id.clone());
return;
};
let mut new_metadata = definition.node_template.persistent_node_metadata.clone();
new_metadata.node_type_metadata = node_metadata.node_type_metadata.clone();
*node_metadata = new_metadata
}
DocumentNodeImplementation::Extract => {}
}
}
@@ -1,5 +1,6 @@
use super::utility_types::Direction;
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::prelude::*;
@@ -27,16 +28,16 @@ pub enum NodeGraphMessage {
SelectedNodesUpdated,
Copy,
CreateNodeInLayerNoTransaction {
node_type: String,
node_type: DefinitionIdentifier,
layer: LayerNodeIdentifier,
},
CreateNodeInLayerWithTransaction {
node_type: String,
node_type: DefinitionIdentifier,
layer: LayerNodeIdentifier,
},
CreateNodeFromContextMenu {
node_id: Option<NodeId>,
node_type: String,
node_type: DefinitionIdentifier,
xy: Option<(i32, i32)>,
add_transaction: bool,
},
@@ -1,12 +1,14 @@
use super::node_properties;
use super::utility_types::{BoxSelection, ContextMenuInformation, DragStart, FrontendNode};
use super::{document_node_definitions, node_properties};
use crate::consts::GRID_SIZE;
use crate::messages::clipboard::utility_types::ClipboardContent;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::NodePropertiesContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{
DefinitionIdentifier, NodePropertiesContext, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type,
};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
@@ -23,6 +25,7 @@ use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
@@ -72,7 +75,7 @@ pub struct NodeGraphMessageHandler {
disconnecting: Option<InputConnector>,
initial_disconnecting: bool,
/// Node to select on pointer up if multiple nodes are selected and they were not dragged.
select_if_not_dragged: Option<NodeId>,
pub select_if_not_dragged: Option<NodeId>,
/// The start of the dragged line (cannot be moved), stored in node graph coordinates.
pub wire_in_progress_from_connector: Option<DVec2>,
/// The end point of the dragged line (cannot be moved), stored in node graph coordinates.
@@ -131,7 +134,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
NodeGraphMessage::AddPathNode => {
if let Some(layer) = make_path_editable_is_allowed(network_interface) {
responses.add(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type: "Path".to_string(), layer });
responses.add(NodeGraphMessage::CreateNodeInLayerWithTransaction {
node_type: DefinitionIdentifier::Network("Path".into()),
layer,
});
responses.add(EventMessage::SelectionChanged);
}
}
@@ -208,7 +214,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let mid_point = (network_interface.get_output_center(&output_connector, breadcrumb_network_path).unwrap()
+ network_interface.get_input_center(&input_connector, breadcrumb_network_path).unwrap())
/ 2.;
let node_template = Box::new(document_node_definitions::resolve_document_node_type("Passthrough").unwrap().default_node_template());
let node_template = Box::new(resolve_proto_node_type(graphene_core::ops::identity::IDENTIFIER).unwrap().default_node_template());
let node_id = NodeId::new();
responses.add(NodeGraphMessage::InsertNode { node_id, node_template });
@@ -274,10 +280,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let node_id = node_id.unwrap_or_else(NodeId::new);
let Some(document_node_type) = document_node_definitions::resolve_document_node_type(&node_type) else {
let Some(document_node_type) = resolve_document_node_type(&node_type) else {
responses.add(DialogMessage::DisplayDialogError {
title: "Cannot insert node".to_string(),
description: format!("The document node '{node_type}' does not exist in the document node list"),
description: format!("The document node '{node_type:?}' does not exist in the document node list"),
});
return;
};
@@ -639,9 +645,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
let encapsulating_node_id = NodeId::new();
let mut default_node_template = document_node_definitions::resolve_document_node_type("Default Network")
.expect("Default Network node should exist")
.default_node_template();
let mut default_node_template = resolve_network_node_type("Default Network").expect("Default Network node should exist").default_node_template();
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
log::error!("Could not get center of selected_nodes");
return;
@@ -775,6 +779,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Abort dragging a node
if self.drag_start.is_some() {
self.drag_start = None;
self.select_if_not_dragged = None;
responses.add(DocumentMessage::AbortTransaction);
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.selection_before_pointer_down.clone(),
@@ -1695,13 +1700,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
let is_fill = matches!(value, TaggedValue::Fill(_));
let input = NodeInput::value(value, false);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, input_index),
input,
});
responses.add(PropertiesPanelMessage::Refresh);
if !(network_interface.reference(&node_id, selection_network_path).is_none() || input_index == 0) && network_interface.connected_to_output(&node_id, selection_network_path) {
if is_fill {
responses.add(OverlaysMessage::Draw);
}
if network_interface.connected_to_output(&node_id, selection_network_path) {
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
@@ -1954,6 +1963,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let shift = ipp.keyboard.get(Key::Shift as usize);
let alt = ipp.keyboard.get(Key::Alt as usize);
let control = ipp.keyboard.get(Key::Control as usize);
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
log::error!("Could not get selected nodes in UpdateBoxSelection");
return;
@@ -1979,6 +1989,33 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
if control {
let mut non_layer_nodes = HashSet::new();
let layer_nodes = nodes.iter().filter(|node_id| network_interface.is_layer(node_id, selection_network_path));
for &layer_id in layer_nodes {
for child_id in network_interface.upstream_flow_back_from_nodes(vec![layer_id], selection_network_path, FlowType::LayerChildrenUpstreamFlow) {
if nodes.contains(&child_id) && child_id != layer_id {
non_layer_nodes.insert(child_id);
}
}
}
// Remove non-layer nodes from selection
if alt {
nodes = previous_selection.difference(&non_layer_nodes).cloned().collect();
}
// Add non-layer nodes to selection
else if shift {
nodes = previous_selection.union(&non_layer_nodes).cloned().collect();
}
// Replace selection with non-layer nodes
else {
nodes = non_layer_nodes;
}
}
if nodes != previous_selection {
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: nodes.into_iter().collect::<Vec<_>>(),
@@ -2180,7 +2217,7 @@ impl NodeGraphMessageHandler {
})
.widget_instance(),
//
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
//
IconButton::new("Folder", 24)
.tooltip_label("Group Selected")
@@ -2203,7 +2240,7 @@ impl NodeGraphMessageHandler {
.disabled(!has_selection)
.widget_instance(),
//
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
//
IconButton::new(if selection_all_locked { "PadlockLocked" } else { "PadlockUnlocked" }, 24)
.hover_icon(Some((if selection_all_locked { "PadlockUnlocked" } else { "PadlockLocked" }).into()))
@@ -2244,7 +2281,7 @@ impl NodeGraphMessageHandler {
.tooltip_description("Restore preview to the graph output.")
.on_update(move |_| NodeGraphMessage::TogglePreview { node_id }.into())
.widget_instance();
widgets.extend([Separator::new(SeparatorType::Unrelated).widget_instance(), button]);
widgets.extend([Separator::new(SeparatorStyle::Unrelated).widget_instance(), button]);
} else if let Some(&node_id) = selection {
let selection_is_not_already_the_output = !network
.exports
@@ -2258,14 +2295,14 @@ impl NodeGraphMessageHandler {
.tooltip_shortcut(action_shortcut_manual!(Key::Alt, Key::MouseLeft))
.on_update(move |_| NodeGraphMessage::TogglePreview { node_id }.into())
.widget_instance();
widgets.extend([Separator::new(SeparatorType::Unrelated).widget_instance(), button]);
widgets.extend([Separator::new(SeparatorStyle::Unrelated).widget_instance(), button]);
}
}
let subgraph_path_names_length = subgraph_path_names.len();
if subgraph_path_names_length >= 2 {
widgets.extend([
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
BreadcrumbTrailButtons::new(subgraph_path_names)
.on_update(move |index| {
DocumentMessage::ExitNestedNetwork {
@@ -2305,11 +2342,11 @@ impl NodeGraphMessageHandler {
.into()
})
.widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
];
widgets.extend(navigation_controls(node_graph_ptz, navigation_handler, true));
widgets.extend([
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextButton::new("Node Graph")
.icon(Some("GraphViewOpen".into()))
.hover_icon(Some("GraphViewClosed".into()))
@@ -2363,9 +2400,9 @@ impl NodeGraphMessageHandler {
if let [node_id] = *nodes.as_slice() {
properties.push(LayoutGroup::Row {
widgets: vec![
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("Node").tooltip_description("Name of the selected node.").widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(context.network_interface.display_name(&node_id, context.selection_network_path))
.tooltip_description("Name of the selected node.")
.on_update(move |text_input| {
@@ -2377,7 +2414,7 @@ impl NodeGraphMessageHandler {
.into()
})
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
],
});
}
@@ -2391,14 +2428,14 @@ impl NodeGraphMessageHandler {
// This may require store a separate path for the properties panel
let mut properties = vec![LayoutGroup::Row {
widgets: vec![
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("File").tooltip_description("Name of the current document.").widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(context.document_name)
.tooltip_description("Name of the current document.")
.on_update(|text_input| DocumentMessage::RenameDocument { new_name: text_input.value.clone() }.into())
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
],
}];
@@ -2438,9 +2475,9 @@ impl NodeGraphMessageHandler {
let mut layer_properties = vec![LayoutGroup::Row {
widgets: vec![
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("Layer").tooltip_description("Name of the selected layer.").widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(context.network_interface.display_name(&layer, context.selection_network_path))
.tooltip_description("Name of the selected layer.")
.on_update(move |text_input| {
@@ -2452,7 +2489,7 @@ impl NodeGraphMessageHandler {
.into()
})
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
PopoverButton::new()
.icon(Some("Node".to_string()))
.tooltip_description("Add an operation to the end of this layer's chain of nodes.")
@@ -2477,7 +2514,7 @@ impl NodeGraphMessageHandler {
Layout(vec![LayoutGroup::Row { widgets: vec![node_chooser] }])
})
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
],
}];
@@ -2596,8 +2633,9 @@ impl NodeGraphMessageHandler {
.node_metadata(&node_id, breadcrumb_network_path)
.is_some_and(|node_metadata| node_metadata.persistent_metadata.is_layer()),
can_be_layer: network_interface.is_eligible_to_be_layer(&node_id, breadcrumb_network_path),
reference: network_interface.reference(&node_id, breadcrumb_network_path).cloned().unwrap_or_default(),
reference: network_interface.reference(&node_id, breadcrumb_network_path).map(|reference| reference.serialized()),
display_name: network_interface.display_name(&node_id, breadcrumb_network_path),
implementation_name: network_interface.implementation_name(&node_id, breadcrumb_network_path),
primary_input,
exposed_inputs,
primary_output,
@@ -2712,8 +2750,11 @@ impl NodeGraphMessageHandler {
});
let clippable = layer.can_be_clipped(network_interface.document_metadata());
let data = LayerPanelEntry {
id: node_id,
implementation_name: network_interface.implementation_name(&node_id, &[]),
icon_name: network_interface.is_artboard(&node_id, &[]).then(|| "Artboard".to_string()),
alias: network_interface.display_name(&node_id, &[]),
in_selected_network: selection_network_path.is_empty(),
children_allowed,
@@ -2762,6 +2803,7 @@ impl NodeGraphMessageHandler {
HintInfo::mouse(MouseMotion::LmbDrag, "Select Area"),
HintInfo::keys([Key::Shift], "Extend").prepend_plus(),
HintInfo::keys([Key::Alt], "Subtract").prepend_plus(),
HintInfo::keys([Key::Control], "Exclude Layers").prepend_plus(),
]),
]);
if self.has_selection {
@@ -3,6 +3,7 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::utility_types::{FontCatalogStyle, PersistentData};
use crate::messages::prelude::*;
@@ -71,9 +72,9 @@ pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphData
pub fn add_blank_assist(widgets: &mut Vec<WidgetInstance>) {
widgets.extend_from_slice(&[
// Custom CSS specific to the Properties panel converts this Section separator into the width of an assist (24px).
Separator::new(SeparatorType::Section).widget_instance(),
Separator::new(SeparatorStyle::Section).widget_instance(),
// This last one is the separator after the 24px assist.
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
]);
}
@@ -231,17 +232,9 @@ pub(crate) fn property_from_type(
_ => {
let mut widgets = start_widgets(default_info);
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("-")
.tooltip_label(format!(
"Data Type: {}",
concrete_type
.alias
.as_deref()
// TODO: Avoid needing to remove spaces here by fixing how `alias` is generated
.map(|s| s.to_string().replace(" ", ""))
.unwrap_or_else(|| graphene_std::format_type(concrete_type.name.as_ref())),
))
.tooltip_label(format!("Data Type: {concrete_type}"))
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
.widget_instance(),
]);
@@ -251,7 +244,7 @@ pub(crate) fn property_from_type(
}
}
}
Type::Generic(_) => vec![TextLabel::new("Generic type (not supported)").widget_instance()].into(),
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),
};
@@ -273,7 +266,7 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
};
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(x.clone())
.on_update(update_value(|x: &TextInput| TaggedValue::String(x.value.clone()), node_id, index))
.on_commit(commit_value)
@@ -295,7 +288,7 @@ pub fn text_area_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Wid
};
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextAreaInput::new(x.clone())
.on_update(update_value(|x: &TextAreaInput| TaggedValue::String(x.value.clone()), node_id, index))
.on_commit(commit_value)
@@ -317,7 +310,7 @@ pub fn bool_widget(parameter_widgets_info: ParameterWidgetsInfo, checkbox_input:
};
if let Some(&TaggedValue::Bool(x)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
checkbox_input
.checked(x)
.on_update(update_value(|x: &CheckboxInput| TaggedValue::Bool(x.checked), node_id, index))
@@ -340,7 +333,7 @@ pub fn reference_point_widget(parameter_widgets_info: ParameterWidgetsInfo, disa
};
if let Some(&TaggedValue::ReferencePoint(reference_point)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(reference_point != ReferencePoint::None)
.on_update(update_value(
move |x: &CheckboxInput| TaggedValue::ReferencePoint(if x.checked { ReferencePoint::Center } else { ReferencePoint::None }),
@@ -349,7 +342,7 @@ pub fn reference_point_widget(parameter_widgets_info: ParameterWidgetsInfo, disa
))
.disabled(disabled)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
ReferencePointInput::new(reference_point)
.on_update(update_value(move |x: &ReferencePointInput| TaggedValue::ReferencePoint(x.value), node_id, index))
.disabled(disabled)
@@ -363,15 +356,15 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
let mut location_widgets = start_widgets(parameter_widgets_info);
location_widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut scale_widgets);
scale_widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut resolution_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut resolution_widgets);
resolution_widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let Some(document_node) = document_node else { return LayoutGroup::default() };
let Some(input) = document_node.inputs.get(index) else {
@@ -408,7 +401,7 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(top_left.y))
.label("Y")
.unit(" px")
@@ -455,7 +448,7 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(bounds.y))
.label("H")
.unit(" px")
@@ -515,15 +508,15 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
let mut location_widgets = start_widgets(parameter_widgets_info);
location_widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut rotation_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut rotation_widgets);
rotation_widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
rotation_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut scale_widgets);
scale_widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let Some(document_node) = document_node else { return LayoutGroup::default() };
let Some(input) = document_node.inputs.get(index) else {
@@ -551,7 +544,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(translation.y))
.label("Y")
.unit(" px")
@@ -598,7 +591,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(scale.y))
.label("H")
.unit("x")
@@ -644,7 +637,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
match input.as_non_exposed_value() {
Some(&TaggedValue::DVec2(dvec2)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(dvec2.x))
.label(x)
.unit(unit)
@@ -654,7 +647,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.on_update(update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y)), node_id, index))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(dvec2.y))
.label(y)
.unit(unit)
@@ -668,7 +661,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
}
Some(&TaggedValue::F64(value)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(value))
.label(x)
.unit(unit)
@@ -678,7 +671,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.on_update(update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value)), node_id, index))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(value))
.label(y)
.unit(unit)
@@ -718,7 +711,7 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
};
if let Some(TaggedValue::VecF64(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
.value(x.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, index))
@@ -750,7 +743,7 @@ pub fn array_of_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, text_p
};
if let Some(TaggedValue::VecDVec2(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_props
.value(x.iter().map(|v| format!("({}, {})", v.x, v.y)).collect::<Vec<_>>().join(", "))
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, index))
@@ -780,7 +773,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
if let Some(TaggedValue::Font(font)) = &input.as_non_exposed_value() {
first_widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(vec![
persistent_data
.font_catalog
@@ -843,7 +836,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
let mut second_row = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut second_row);
second_row.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new({
persistent_data
.font_catalog
@@ -918,7 +911,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
let fractional_part = x.fract();
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.clone()
.label("Progress")
@@ -929,9 +922,9 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.on_update(update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap()), node_id, index))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextLabel::new("+").widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
number_props
.label("Element #")
.mode_increment()
@@ -946,6 +939,49 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
widgets
}
/// `parameter_widgets_info` is for the f64 parameter. `bool_input_index` is the input index of the bool parameter for the checkbox.
pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput) -> Vec<WidgetInstance> {
let ParameterWidgetsInfo {
document_node,
node_id,
index: number_input_index,
..
} = parameter_widgets_info;
let mut widgets = start_widgets(parameter_widgets_info);
let Some(document_node) = document_node else { return Vec::new() };
let Some(number_input) = document_node.inputs.get(number_input_index) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let Some(bool_input) = document_node.inputs.get(bool_input_index) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let (Some(&TaggedValue::Bool(enabled)), Some(&TaggedValue::F64(number))) = (bool_input.as_non_exposed_value(), number_input.as_non_exposed_value()) {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
// The checkbox toggles if the value is Some or None
CheckboxInput::new(enabled)
.on_update(update_value(|x: &CheckboxInput| TaggedValue::Bool(x.checked), node_id, bool_input_index))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(number))
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap_or_default()), node_id, number_input_index))
.disabled(!enabled)
.on_commit(commit_value)
.widget_instance(),
]);
}
widgets
}
pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
@@ -958,7 +994,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
};
match input.as_non_exposed_value() {
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x))
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, index))
@@ -966,7 +1002,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
.widget_instance(),
]),
Some(&TaggedValue::F32(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(update_value(move |x: &NumberInput| TaggedValue::F32(x.value.unwrap() as f32), node_id, index))
@@ -974,7 +1010,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
.widget_instance(),
]),
Some(&TaggedValue::U32(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(update_value(move |x: &NumberInput| TaggedValue::U32((x.value.unwrap()) as u32), node_id, index))
@@ -982,36 +1018,15 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
.widget_instance(),
]),
Some(&TaggedValue::U64(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(update_value(move |x: &NumberInput| TaggedValue::U64((x.value.unwrap()) as u64), node_id, index))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::OptionalF64(x)) => {
// TODO: Don't wipe out the previously set value (setting it back to the default of 100) when reenabling this checkbox back to Some from None
let toggle_enabled = move |checkbox_input: &CheckboxInput| TaggedValue::OptionalF64(if checkbox_input.checked { Some(100.) } else { None });
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
// The checkbox toggles if the value is Some or None
CheckboxInput::new(x.is_some())
.on_update(update_value(toggle_enabled, node_id, index))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
number_props
.value(x)
.on_update(update_value(move |x: &NumberInput| TaggedValue::OptionalF64(x.value), node_id, index))
.disabled(x.is_none())
.on_commit(commit_value)
.widget_instance(),
]);
}
Some(&TaggedValue::DVec2(dvec2)) => widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
.value(Some(dvec2.y))
@@ -1020,7 +1035,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
.widget_instance(),
]),
Some(&TaggedValue::FVec2(vec2)) => widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
.value(Some(vec2.y as f64))
@@ -1061,7 +1076,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
.collect();
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries)
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
.widget_instance(),
@@ -1082,7 +1097,7 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
};
// Add a separator
widgets.push(Separator::new(SeparatorType::Unrelated).widget_instance());
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
// Add the color input
match &**tagged_value {
@@ -1094,14 +1109,6 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
.on_commit(commit_value)
.widget_instance(),
),
TaggedValue::OptionalColorNotInTable(color) => widgets.push(
color_button
.value(color.map_or(FillChoice::None, FillChoice::Solid))
.allow_none(true)
.on_update(update_value(|input: &ColorInput| TaggedValue::OptionalColorNotInTable(input.value.as_solid()), node_id, index))
.on_commit(commit_value)
.widget_instance(),
),
TaggedValue::Color(color_table) => widgets.push(
color_button
.value(match color_table.iter().next() {
@@ -1164,7 +1171,7 @@ pub fn curve_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup
};
if let Some(TaggedValue::Curve(curve)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CurveInput::new(curve.clone())
.on_update(update_value(|x: &CurveInput| TaggedValue::Curve(x.value.clone()), node_id, index))
.on_commit(commit_value)
@@ -1574,9 +1581,9 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
// Corner Radius
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::<f64>::INDEX, true, context));
corner_radius_row_1.push(Separator::new(SeparatorType::Unrelated).widget_instance());
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut corner_radius_row_2 = vec![Separator::new(SeparatorType::Unrelated).widget_instance()];
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
corner_radius_row_2.push(TextLabel::new("").widget_instance());
add_blank_assist(&mut corner_radius_row_2);
@@ -1713,10 +1720,8 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
if let Some(properties_override) = context
.network_interface
.reference(&node_id, context.selection_network_path)
.cloned()
.unwrap_or_default()
.as_ref()
.and_then(|reference| super::document_node_definitions::resolve_document_node_type(reference))
.and_then(|identifier| resolve_document_node_type(identifier))
.and_then(|definition| definition.properties)
.and_then(|properties| NODE_OVERRIDES.get(properties))
{
@@ -1781,25 +1786,20 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
if layout.is_empty() {
layout = node_no_properties(node_id, context);
}
let name = context
let name = context.network_interface.implementation_name(&node_id, context.selection_network_path);
let description = context
.network_interface
.reference(&node_id, context.selection_network_path)
.cloned()
.unwrap_or_default() // If there is an error getting the reference, default to empty string
.or_else(|| {
// If there is no reference, try to get the proto node name
context.network_interface.implementation(&node_id, context.selection_network_path).and_then(|implementation|{
if let DocumentNodeImplementation::ProtoNode(protonode) = implementation {
Some(protonode.name.clone().into_owned())
} else {
None
}
})
})
.unwrap_or("Custom Node".to_string());
let description = context.network_interface.description(&node_id, context.selection_network_path);
.as_ref()
.and_then(|identifier| resolve_document_node_type(identifier))
.map(|definition| definition.description.to_string())
.filter(|string| string != "TODO")
.unwrap_or_default();
let visible = context.network_interface.is_visible(&node_id, context.selection_network_path);
let pinned = context.network_interface.is_pinned(&node_id, context.selection_network_path);
LayoutGroup::Section {
name,
description,
@@ -1837,7 +1837,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
let backup_color_fill: Fill = backup_color.clone().into();
let backup_gradient_fill: Fill = backup_gradient.clone().into();
widgets_first_row.push(Separator::new(SeparatorType::Unrelated).widget_instance());
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
widgets_first_row.push(
ColorInput::default()
.value(fill.clone().into())
@@ -1896,7 +1896,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
FillInput::<Color>::INDEX,
))
.widget_instance();
row.push(Separator::new(SeparatorType::Unrelated).widget_instance());
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(reverse_button);
}
}
@@ -1913,7 +1913,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
];
row.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(if fill.as_gradient().is_some() { 1 } else { 0 })).widget_instance(),
]);
@@ -1946,43 +1946,43 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
FillInput::<Color>::INDEX,
))
.widget_instance();
row.push(Separator::new(SeparatorType::Unrelated).widget_instance());
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(reverse_radial_gradient_button);
}
}
let new_gradient1 = gradient.clone();
let new_gradient2 = gradient.clone();
let gradient_for_closure = gradient.clone();
let entries = vec![
RadioEntryData::new("Linear")
.label("Linear")
.on_update(update_value(
move |_| {
let mut new_gradient = new_gradient1.clone();
new_gradient.gradient_type = GradientType::Linear;
let entries = [GradientType::Linear, GradientType::Radial]
.iter()
.map(|&grad_type| {
let gradient = gradient_for_closure.clone();
let set_input_value = update_value(
move |_: &()| {
let mut new_gradient = gradient.clone();
new_gradient.gradient_type = grad_type;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
))
.on_commit(commit_value),
RadioEntryData::new("Radial")
.label("Radial")
.on_update(update_value(
move |_| {
let mut new_gradient = new_gradient2.clone();
new_gradient.gradient_type = GradientType::Radial;
TaggedValue::Fill(Fill::Gradient(new_gradient))
},
node_id,
FillInput::<Color>::INDEX,
))
.on_commit(commit_value),
];
);
RadioEntryData::new(format!("{:?}", grad_type))
.label(format!("{:?}", grad_type))
.on_update(move |_| Message::Batched {
messages: Box::new([
set_input_value(&()),
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::Type(grad_type),
}
.into(),
]),
})
.on_commit(commit_value)
})
.collect();
row.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(entries).selected_index(Some(gradient.gradient_type as u32)).widget_instance(),
]);
@@ -2103,7 +2103,7 @@ pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) ->
};
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(x.clone())
.centered(true)
.on_update(update_value(
@@ -2331,7 +2331,7 @@ pub mod choice {
let committer = || super::commit_value;
let updater = || super::update_value(move |v: &W::Value| TaggedValue::from(v.clone()), node_id, index);
let widget = self.widget_factory.build(current, updater, committer);
widgets.extend_from_slice(&[Separator::new(SeparatorType::Unrelated).widget_instance(), widget]);
widgets.extend_from_slice(&[Separator::new(SeparatorStyle::Unrelated).widget_instance(), widget]);
}
let mut row = LayoutGroup::Row { widgets };
@@ -2,7 +2,6 @@ use glam::{DVec2, IVec2};
use graph_craft::document::NodeId;
use graph_craft::document::value::TaggedValue;
use graphene_std::Type;
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum FrontendGraphDataType {
@@ -82,6 +81,8 @@ pub struct FrontendNode {
pub reference: Option<String>,
#[serde(rename = "displayName")]
pub display_name: String,
#[serde(rename = "implementationName")]
pub implementation_name: String,
#[serde(rename = "primaryInput")]
pub primary_input: Option<FrontendGraphInput>,
#[serde(rename = "exposedInputs")]
@@ -102,29 +103,13 @@ pub struct FrontendNode {
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct FrontendNodeType {
pub name: Cow<'static, str>,
pub category: Cow<'static, str>,
pub identifier: String,
pub name: String,
pub category: String,
#[serde(rename = "inputTypes")]
pub input_types: Option<Vec<Cow<'static, str>>>,
pub input_types: Vec<String>,
}
impl FrontendNodeType {
pub fn new(name: impl Into<Cow<'static, str>>, category: impl Into<Cow<'static, str>>) -> Self {
Self {
name: name.into(),
category: category.into(),
input_types: None,
}
}
pub fn with_input_types(name: impl Into<Cow<'static, str>>, category: impl Into<Cow<'static, str>>, input_types: Vec<Cow<'static, str>>) -> Self {
Self {
name: name.into(),
category: category.into(),
input_types: Some(input_types),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct DragStart {
pub start_x: f64,
@@ -242,7 +242,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Type").table_align(true).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
RadioInput::new(vec![
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
if let GridType::Isometric { y_axis_spacing, angle_a, angle_b } = grid.grid_type {
@@ -274,7 +274,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
let mut color_widgets = vec![
TextLabel::new("Display").table_align(true).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
];
color_widgets.extend([
CheckboxInput::new(grid.dot_display)
@@ -282,7 +282,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
.tooltip_label("Display as Dotted Grid")
.on_update(update_display(grid, |grid| Some(&mut grid.dot_display)))
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
]);
color_widgets.push(
ColorInput::new(FillChoice::Solid(grid.grid_color.to_gamma_srgb()))
@@ -296,14 +296,14 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Origin").table_align(true).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(grid.origin.x))
.label("X")
.unit(" px")
.min_width(98)
.on_update(update_origin(grid, |grid| Some(&mut grid.origin.x)))
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(grid.origin.y))
.label("Y")
.unit(" px")
@@ -317,7 +317,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
GridType::Rectangular { spacing } => widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Spacing").table_align(true).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(spacing.x))
.label("X")
.unit(" px")
@@ -325,7 +325,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
.min_width(98)
.on_update(update_origin(grid, |grid| grid.grid_type.rectangular_spacing().map(|spacing| &mut spacing.x)))
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(spacing.y))
.label("Y")
.unit(" px")
@@ -339,7 +339,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Y Spacing").table_align(true).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(y_axis_spacing))
.unit(" px")
.min(0.)
@@ -351,13 +351,13 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
widgets.push(LayoutGroup::Row {
widgets: vec![
TextLabel::new("Angles").table_align(true).widget_instance(),
Separator::new(SeparatorType::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(angle_a))
.unit("°")
.min_width(98)
.on_update(update_origin(grid, |grid| grid.grid_type.angle_a()))
.widget_instance(),
Separator::new(SeparatorType::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(angle_b))
.unit("°")
.min_width(98)
@@ -3,7 +3,7 @@ use crate::consts::HIDE_HANDLE_DISTANCE;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
use crate::messages::tool::tool_messages::tool_prelude::{DocumentMessageHandler, PreferencesMessageHandler};
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::text::{Font, FontCache, TextAlign, TextContext, TypesettingConfig};
@@ -135,10 +135,7 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
overlay_context.outline_vector(&vector, transform);
}
let Some(selected_shape_state) = shape_editor.selected_shape_state.get_mut(&layer) else {
continue;
};
let selected_shape_state = shape_editor.selected_shape_state.entry(layer).or_default();
// Get the selected segments and then add a bold line overlay on them
for (segment_id, bezier, _, _) in vector.segment_iter() {
if selected_shape_state.is_segment_selected(segment_id) {
@@ -200,7 +197,7 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
}
}
pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext, preferences: &PreferencesMessageHandler) {
pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext) {
if !overlay_context.visibility_settings.anchors() {
return;
}
@@ -213,7 +210,7 @@ pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &
let selected = shape_editor.selected_shape_state.get(&layer);
let is_selected = |selected: Option<&SelectedLayerState>, point: ManipulatorPointId| selected.is_some_and(|selected| selected.is_point_selected(point));
for point in vector.extendable_points(preferences.vector_meshes) {
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);
@@ -1,7 +1,7 @@
use crate::consts::{
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW, COLOR_OVERLAY_YELLOW_DULL,
COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE,
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW,
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS,
MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_FONT_CACHE, GLOBAL_TEXT_CONTEXT};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -25,12 +25,15 @@ use std::sync::{Arc, Mutex, MutexGuard};
use vello::Scene;
use vello::peniko;
// TODO Remove duplicated definition of this in `utility_types_web.rs`
pub type OverlayProvider = fn(OverlayContext) -> Message;
// TODO Remove duplicated definition of this in `utility_types_web.rs`
pub fn empty_provider() -> OverlayProvider {
|_| Message::NoOp
}
// TODO Remove duplicated definition of this in `utility_types_web.rs`
/// Types of overlays used by DocumentMessage to enable/disable the selected set of viewport overlays.
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub enum OverlaysType {
@@ -41,6 +44,7 @@ pub enum OverlaysType {
TransformCage,
HoverOutline,
SelectionOutline,
LayerOriginCross,
Pivot,
Origin,
Path,
@@ -48,6 +52,7 @@ pub enum OverlaysType {
Handles,
}
// TODO Remove duplicated definition of this in `utility_types_web.rs`
#[derive(PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(default)]
pub struct OverlaysVisibilitySettings {
@@ -59,6 +64,7 @@ pub struct OverlaysVisibilitySettings {
pub transform_cage: bool,
pub hover_outline: bool,
pub selection_outline: bool,
pub layer_origin_cross: bool,
pub pivot: bool,
pub origin: bool,
pub path: bool,
@@ -66,6 +72,7 @@ pub struct OverlaysVisibilitySettings {
pub handles: bool,
}
// TODO Remove duplicated definition of this in `utility_types_web.rs`
impl Default for OverlaysVisibilitySettings {
fn default() -> Self {
Self {
@@ -77,6 +84,7 @@ impl Default for OverlaysVisibilitySettings {
transform_cage: true,
hover_outline: true,
selection_outline: true,
layer_origin_cross: true,
pivot: true,
origin: true,
path: true,
@@ -86,6 +94,7 @@ impl Default for OverlaysVisibilitySettings {
}
}
// TODO Remove duplicated definition of this in `utility_types_web.rs`
impl OverlaysVisibilitySettings {
pub fn all(&self) -> bool {
self.all
@@ -119,6 +128,10 @@ impl OverlaysVisibilitySettings {
self.all && self.selection_outline
}
pub fn layer_origin_cross(&self) -> bool {
self.all && self.layer_origin_cross
}
pub fn pivot(&self) -> bool {
self.all && self.pivot
}
@@ -260,6 +273,10 @@ impl OverlayContext {
self.internal().manipulator_anchor(position, selected, color);
}
pub fn gradient_color_stop(&mut self, position: DVec2, selected: bool, color: &str) {
self.internal().gradient_color_stop(position, selected, color);
}
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
self.internal().resize_handle(position, rotation);
}
@@ -391,12 +408,14 @@ impl OverlayContext {
}
}
// TODO Remove duplicated definition of this in `utility_types_web.rs`
pub enum Pivot {
Start,
Middle,
End,
}
// TODO Remove duplicated definition of this in `utility_types_web.rs`
pub enum DrawHandles {
All,
SelectedAnchors(HashMap<LayerNodeIdentifier, Vec<SegmentId>>),
@@ -476,11 +495,13 @@ impl OverlayContextInternal {
let mut path = BezPath::new();
if let Some(first) = polygon.last() {
path.move_to(kurbo::Point::new(first.x.round() - 0.5, first.y.round() - 0.5));
let p = self.snap_to_physical_pixel_center(*first);
path.move_to(kurbo::Point::new(p.x, p.y));
}
for point in polygon {
path.line_to(kurbo::Point::new(point.x.round() - 0.5, point.y.round() - 0.5));
let p = self.snap_to_physical_pixel_center(*point);
path.line_to(kurbo::Point::new(p.x, p.y));
}
path.close_path();
@@ -507,8 +528,8 @@ impl OverlayContextInternal {
fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let transform = self.get_transform();
let start = start.round() - DVec2::splat(0.5);
let end = end.round() - DVec2::splat(0.5);
let start = self.snap_to_physical_pixel_center(start);
let end = self.snap_to_physical_pixel_center(end);
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(start.x, start.y));
@@ -526,7 +547,7 @@ impl OverlayContextInternal {
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
@@ -539,8 +560,7 @@ impl OverlayContextInternal {
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
let circle = kurbo::Circle::new((position.x, position.y), (MANIPULATOR_GROUP_MARKER_SIZE + 2.) / 2.);
@@ -567,6 +587,29 @@ impl OverlayContextInternal {
self.square(position, None, Some(color_fill), Some(COLOR_OVERLAY_BLUE));
}
fn gradient_color_stop(&mut self, position: DVec2, selected: bool, color: &str) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5);
let (radius_offset, stroke_width) = if selected { (1., 3.) } else { (0., 1.) };
let radius = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset;
let mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
let circle = kurbo::Circle::new((position.x, position.y), radius);
if let Some(width) = width {
self.scene.stroke(&kurbo::Stroke::new(width), transform, Self::parse_color(color), None, &circle);
} else {
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &circle);
}
};
// Fill
draw_circle(radius, None, color);
// Stroke (inner)
draw_circle(radius + stroke_width / 2., Some(1.), COLOR_OVERLAY_BLACK);
// Stroke (outer)
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
}
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
let quad = DAffine2::from_angle_translation(rotation, position) * Quad::from_box([DVec2::splat(-RESIZE_HANDLE_SIZE / 2.), DVec2::splat(RESIZE_HANDLE_SIZE / 2.)]);
self.quad(quad, None, Some(COLOR_OVERLAY_WHITE));
@@ -590,7 +633,7 @@ impl OverlayContextInternal {
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
let corner = position - DVec2::splat(size) / 2.;
let transform = self.get_transform();
@@ -605,7 +648,7 @@ impl OverlayContextInternal {
let size = 1.;
let color_fill = color.unwrap_or(COLOR_OVERLAY_WHITE);
let position = position.round() - DVec2::splat(0.5);
let position = self.snap_to_physical_pixel_center(position);
let corner = position - DVec2::splat(size) / 2.;
let transform = self.get_transform();
@@ -617,7 +660,7 @@ impl OverlayContextInternal {
fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
let color_stroke = color_stroke.unwrap_or(COLOR_OVERLAY_BLUE);
let position = position.round();
let position = self.snap_to_physical_pixel(position);
let transform = self.get_transform();
let circle = kurbo::Circle::new((position.x, position.y), radius);
@@ -693,7 +736,7 @@ impl OverlayContextInternal {
self.draw_arc(pivot, arc_radius, offset_angle, (angle) % TAU + offset_angle);
}
fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
pub fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
let sign = scale.signum();
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_WHITE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.05).to_rgba_hex_srgb();
fill_color.insert(0, '#');
@@ -724,7 +767,7 @@ impl OverlayContextInternal {
let Some(show_hover_ring) = show_compass_with_hover_ring else { return };
let transform = self.get_transform();
let center = compass_center.round() - DVec2::splat(0.5);
let center = self.snap_to_physical_pixel_center(compass_center);
// Hover ring
if show_hover_ring {
@@ -769,7 +812,7 @@ impl OverlayContextInternal {
fn pivot(&mut self, position: DVec2, angle: f64) {
let uv = DVec2::from_angle(angle);
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let (x, y) = self.snap_to_physical_pixel_center(position).into();
let transform = self.get_transform();
@@ -799,7 +842,7 @@ impl OverlayContextInternal {
}
fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
let (x, y) = (position.round() - DVec2::splat(0.5)).into();
let (x, y) = self.snap_to_physical_pixel_center(position).into();
let color = color.unwrap_or(COLOR_OVERLAY_YELLOW_DULL);
let transform = self.get_transform();
@@ -816,7 +859,7 @@ impl OverlayContextInternal {
path.move_to(kurbo::Point::new(x, y));
path.line_to(kurbo::Point::new(start1_x, start1_y));
let arc1 = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), start1, FRAC_PI_2, 0.0);
let arc1 = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), start1, FRAC_PI_2, 0.);
arc1.to_cubic_beziers(0.1, |p1, p2, p| {
path.curve_to(p1, p2, p);
});
@@ -828,7 +871,7 @@ impl OverlayContextInternal {
path.move_to(kurbo::Point::new(x, y));
path.line_to(kurbo::Point::new(start2_x, start2_y));
let arc2 = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), start2, FRAC_PI_2, 0.0);
let arc2 = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), start2, FRAC_PI_2, 0.);
arc2.to_cubic_beziers(0.1, |p1, p2, p| {
path.curve_to(p1, p2, p);
});
@@ -875,7 +918,7 @@ impl OverlayContextInternal {
let mut path = BezPath::new();
self.bezier_to_path(bezier, transform, true, &mut path);
self.scene.stroke(&kurbo::Stroke::new(4.0), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
self.scene.stroke(&kurbo::Stroke::new(4.), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
}
fn outline_overlay_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
@@ -883,7 +926,7 @@ impl OverlayContextInternal {
let mut path = BezPath::new();
self.bezier_to_path(bezier, transform, true, &mut path);
self.scene.stroke(&kurbo::Stroke::new(4.0), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE_50), None, &path);
self.scene.stroke(&kurbo::Stroke::new(4.), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE_50), None, &path);
}
fn bezier_to_path(&self, bezier: PathSeg, transform: DAffine2, move_to: bool, path: &mut BezPath) {
@@ -906,29 +949,30 @@ impl OverlayContextInternal {
};
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
let start_point = self.snap_to_physical_pixel(start_point);
path.move_to(kurbo::Point::new(start_point.x, start_point.y));
for curve in curves {
match curve {
PathSeg::Line(line) => {
let a = transform.transform_point2(point_to_dvec2(line.p1));
let a = a.round() - DVec2::splat(0.5);
let a = self.snap_to_physical_pixel_center(a);
path.line_to(kurbo::Point::new(a.x, a.y));
}
PathSeg::Quad(quad_bez) => {
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
let a = a.round() - DVec2::splat(0.5);
let b = b.round() - DVec2::splat(0.5);
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
path.quad_to(kurbo::Point::new(a.x, a.y), kurbo::Point::new(b.x, b.y));
}
PathSeg::Cubic(cubic_bez) => {
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
let a = a.round() - DVec2::splat(0.5);
let b = b.round() - DVec2::splat(0.5);
let c = c.round() - DVec2::splat(0.5);
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
let c = self.snap_to_physical_pixel_center(c);
path.curve_to(kurbo::Point::new(a.x, a.y), kurbo::Point::new(b.x, b.y), kurbo::Point::new(c.x, c.y));
}
}
@@ -1018,16 +1062,16 @@ impl OverlayContextInternal {
fn text(&mut self, text: &str, font_color: &str, background_color: Option<&str>, transform: DAffine2, padding: f64, pivot: [Pivot; 2]) {
// Use the proper text-to-path system for accurate text rendering
const FONT_SIZE: f64 = 12.0;
const FONT_SIZE: f64 = 12.;
// Create typesetting configuration
let typesetting = TypesettingConfig {
font_size: FONT_SIZE,
line_height_ratio: 1.2,
character_spacing: 0.0,
character_spacing: 0.,
max_width: None,
max_height: None,
tilt: 0.0,
tilt: 0.,
align: TextAlign::Left, // We'll handle alignment manually via pivot
};
@@ -1042,7 +1086,7 @@ impl OverlayContextInternal {
let text_width = text_size.x;
let text_height = text_size.y;
// Create a rect from the size (assuming text starts at origin)
let text_bounds = kurbo::Rect::new(0.0, 0.0, text_width, text_height);
let text_bounds = kurbo::Rect::new(0., 0., text_width, text_height);
// Convert text to vector paths for rendering
let text_table = text_context.to_path(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
@@ -1051,7 +1095,7 @@ impl OverlayContextInternal {
let mut position = DVec2::ZERO;
match pivot[0] {
Pivot::Start => position.x = padding,
Pivot::Middle => position.x = -text_width / 2.0,
Pivot::Middle => position.x = -text_width / 2.,
Pivot::End => position.x = -padding - text_width,
}
match pivot[1] {
@@ -1130,4 +1174,20 @@ impl OverlayContextInternal {
self.line(quad.bottom_left(), quad.bottom_right(), None, None);
}
}
fn snap_to_physical_pixel(&self, p: DVec2) -> DVec2 {
let s = self.viewport.scale();
if !s.is_finite() || s <= 0.0 {
return p.round();
}
(p * s).round() / s
}
fn snap_to_physical_pixel_center(&self, p: DVec2) -> DVec2 {
let s = self.viewport.scale();
if !s.is_finite() || s <= 0.0 {
return p.round() - DVec2::splat(0.5);
}
self.snap_to_physical_pixel(p) - DVec2::splat(0.5 / s)
}
}
@@ -1,8 +1,8 @@
use super::utility_functions::overlay_canvas_context;
use crate::consts::{
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW, COLOR_OVERLAY_YELLOW_DULL,
COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE,
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SEGMENT_SELECTED_THICKNESS, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW,
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS,
MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SEGMENT_SELECTED_THICKNESS, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::Message;
@@ -37,6 +37,7 @@ pub enum OverlaysType {
TransformCage,
HoverOutline,
SelectionOutline,
LayerOriginCross,
Pivot,
Origin,
Path,
@@ -55,6 +56,7 @@ pub struct OverlaysVisibilitySettings {
pub transform_cage: bool,
pub hover_outline: bool,
pub selection_outline: bool,
pub layer_origin_cross: bool,
pub pivot: bool,
pub origin: bool,
pub path: bool,
@@ -73,6 +75,7 @@ impl Default for OverlaysVisibilitySettings {
transform_cage: true,
hover_outline: true,
selection_outline: true,
layer_origin_cross: true,
pivot: true,
origin: true,
path: true,
@@ -115,6 +118,10 @@ impl OverlaysVisibilitySettings {
self.all && self.selection_outline
}
pub fn layer_origin_cross(&self) -> bool {
self.all && self.layer_origin_cross
}
pub fn pivot(&self) -> bool {
self.all && self.pivot
}
@@ -461,6 +468,37 @@ impl OverlayContext {
self.square(position, None, Some(color_fill), Some(color_stroke));
}
pub fn gradient_color_stop(&mut self, position: DVec2, selected: bool, color: &str) {
self.start_dpi_aware_transform();
let position = position.round() - DVec2::splat(0.5);
let (radius_offset, stroke_width) = if selected { (1., 3.) } else { (0., 1.) };
let radius = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset;
let draw_circle = |radius: f64, width: Option<f64>, color: &str| {
self.render_context.begin_path();
self.render_context.arc(position.x, position.y, radius, 0., TAU).expect("Failed to draw the circle");
if let Some(width) = width {
self.render_context.set_line_width(width);
self.render_context.set_stroke_style_str(color);
self.render_context.stroke();
} else {
self.render_context.set_fill_style_str(color);
self.render_context.fill();
}
};
// Fill
draw_circle(radius, None, color);
// Stroke (inner)
draw_circle(radius + stroke_width / 2., Some(1.), COLOR_OVERLAY_BLACK);
// Stroke (outer)
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
self.end_dpi_aware_transform();
}
pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
self.start_dpi_aware_transform();
@@ -1,6 +1,7 @@
use super::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::graph_operation::transform_utils;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2};
@@ -12,6 +13,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::{PointId, Vector};
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64;
use std::sync::Arc;
// ================
// DocumentMetadata
@@ -25,7 +27,7 @@ pub struct DocumentMetadata {
pub local_transforms: HashMap<NodeId, DAffine2>,
pub first_element_source_ids: HashMap<NodeId, Option<NodeId>>,
pub structure: HashMap<LayerNodeIdentifier, NodeRelations>,
pub click_targets: HashMap<LayerNodeIdentifier, Vec<ClickTarget>>,
pub click_targets: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>,
pub clip_targets: HashSet<NodeId>,
pub vector_modify: HashMap<NodeId, Vector>,
/// Transform from document space to viewport space.
@@ -45,8 +47,8 @@ impl DocumentMetadata {
self.structure.contains_key(&layer)
}
pub fn click_targets(&self, layer: LayerNodeIdentifier) -> Option<&Vec<ClickTarget>> {
self.click_targets.get(&layer)
pub fn click_targets(&self, layer: LayerNodeIdentifier) -> Option<&[Arc<ClickTarget>]> {
self.click_targets.get(&layer).map(|x| x.as_slice())
}
/// Access the [`NodeRelations`] of a layer.
@@ -91,7 +93,8 @@ impl DocumentMetadata {
let mut use_local = true;
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer("Path")
let identifier = DefinitionIdentifier::Network("Path".into());
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier)
&& let Some(&source) = self.first_element_source_ids.get(&layer.to_node())
&& !network_interface
.upstream_flow_back_from_nodes(vec![path_node], &[], FlowType::HorizontalFlow)
@@ -114,7 +117,7 @@ impl DocumentMetadata {
let local_transform = self.local_transforms.get(&layer.to_node()).copied();
let transform = local_transform.unwrap_or_else(|| {
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain("Transform", layer, network_interface);
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::Network("Transform".into()), layer, network_interface);
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
transform_node.map(|node| transform_utils::get_current_transform(node.inputs.as_slice())).unwrap_or_default()
});
@@ -204,7 +207,7 @@ impl DocumentMetadata {
}
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &subpath::Subpath<PointId>> {
static EMPTY: Vec<ClickTarget> = Vec::new();
static EMPTY: Vec<Arc<ClickTarget>> = Vec::new();
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
click_targets.iter().filter_map(|target| match target.target_type() {
ClickTargetType::Subpath(subpath) => Some(subpath),
@@ -213,7 +216,7 @@ impl DocumentMetadata {
}
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
static EMPTY: Vec<ClickTarget> = Vec::new();
static EMPTY: Vec<Arc<ClickTarget>> = Vec::new();
let click_targets = self.click_targets.get(&layer).unwrap_or(&EMPTY);
click_targets.iter().map(|target| target.target_type())
}
@@ -7,7 +7,7 @@ use super::misc::PTZ;
use super::nodes::SelectedNodes;
use crate::consts::{EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP};
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DocumentNodeDefinition, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
@@ -31,6 +31,7 @@ use serde_json::{Value, json};
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::ops::Deref;
use std::sync::Arc;
/// All network modifications should be done through this API, so the fields cannot be public. However, all fields within this struct can be public since it it not possible to have a public mutable reference.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
@@ -79,7 +80,7 @@ impl NodeNetworkInterface {
fix_network(network);
}
if let DocumentNodeImplementation::ProtoNode(protonode) = &node.implementation
&& protonode.name.contains("PathModifyNode")
&& protonode.as_str().contains("PathModifyNode")
&& node.inputs.len() < 3
{
node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath));
@@ -470,12 +471,6 @@ impl NodeNetworkInterface {
node_template
}
/// Try and get the [`DocumentNodeDefinition`] for a node
pub fn get_node_definition(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeDefinition> {
let metadata = self.node_metadata(node_id, network_path)?;
resolve_document_node_type(metadata.persistent_metadata.reference.as_ref()?)
}
pub fn input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<&NodeInput> {
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get network in input_from_connector");
@@ -654,7 +649,7 @@ impl NodeNetworkInterface {
let export_name = if !export_name.is_empty() {
export_name
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(|nested| nested.to_string()) {
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(ToString::to_string) {
export_type_name
} else {
format!("Export #{}", export_index)
@@ -664,12 +659,19 @@ impl NodeNetworkInterface {
}
};
let valid_types = self.potential_valid_input_types(input_connector, network_path).iter().map(ToString::to_string).collect::<Vec<_>>();
let valid_types = {
// Dedupe while preserving order
let mut found = HashSet::new();
valid_types.into_iter().filter(|s| found.insert(s.clone())).collect::<Vec<_>>()
};
Some(FrontendGraphInput {
data_type,
resolved_type,
name,
description,
valid_types: self.potential_valid_input_types(input_connector, network_path).iter().map(|ty| ty.to_string()).collect(),
valid_types,
connected_to,
})
}
@@ -704,7 +706,7 @@ impl NodeNetworkInterface {
let import_name = if !import_name.is_empty() {
import_name
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(|nested| nested.to_string()) {
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(ToString::to_string) {
import_type_name
} else {
format!("Import #{}", import_index)
@@ -916,12 +918,30 @@ impl NodeNetworkInterface {
}
}
pub fn reference(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&Option<String>> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get reference for node: {node_id:?}");
pub fn reference(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DefinitionIdentifier> {
let Some(document_node) = self.document_node(node_id, network_path) else {
log::error!("Could not get document_node for node in reference: {node_id:?}");
return None;
};
Some(&node_metadata.persistent_metadata.reference)
match &document_node.implementation {
DocumentNodeImplementation::Network(_) => {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get reference for node in reference: {node_id:?}");
return None;
};
node_metadata
.persistent_metadata
.network_metadata
.as_ref()
.expect("Network metadata must exist for network node in reference")
.persistent_metadata
.reference
.clone()
.map(DefinitionIdentifier::Network)
}
DocumentNodeImplementation::ProtoNode(protonode_id) => Some(DefinitionIdentifier::ProtoNode(protonode_id.clone())),
_ => None,
}
}
pub fn implementation(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeImplementation> {
@@ -982,11 +1002,6 @@ impl NodeNetworkInterface {
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
let is_layer = self.is_layer(node_id, network_path);
let Some(reference) = self.reference(node_id, network_path) else {
log::error!("Could not get reference in untitled_layer_label");
return "".to_string();
};
let display_name = if let Some(node_metadata) = self.node_metadata(node_id, network_path) {
node_metadata.persistent_metadata.display_name.clone()
} else {
@@ -998,18 +1013,19 @@ impl NodeNetworkInterface {
if is_layer {
"Untitled Layer".to_string()
} else {
reference.clone().unwrap_or("Untitled Node".to_string())
// TODO: Have this displayed in italics in the UI
self.implementation_name(node_id, network_path)
}
} else {
display_name
}
}
/// Returns the description of the node, or an empty string if it is not set.
pub fn description(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.get_node_definition(node_id, network_path)
.map(|node_definition| node_definition.description.to_string())
.unwrap_or_default()
/// The uneditable name in the Properties panel which represents the function name of the node implementation.
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.reference(node_id, network_path)
.map(|identifier| identifier.implementation_name_from_identifier())
.unwrap_or("Custom Node".to_string())
}
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
@@ -1125,7 +1141,7 @@ impl NodeNetworkInterface {
pub fn is_artboard(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.reference(node_id, network_path)
.is_some_and(|reference| *reference == Some("Artboard".to_string()) && self.connected_to_output(node_id, &[]))
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Artboard".into()) && self.connected_to_output(node_id, &[]))
}
pub fn all_artboards(&self) -> HashSet<LayerNodeIdentifier> {
@@ -1134,12 +1150,13 @@ impl NodeNetworkInterface {
.node_metadata
.iter()
.filter_map(|(node_id, node_metadata)| {
if node_metadata
.persistent_metadata
.reference
.as_ref()
.is_some_and(|reference| reference == "Artboard" && self.connected_to_output(node_id, &[]) && self.is_layer(node_id, &[]))
{
if node_metadata.persistent_metadata.network_metadata.as_ref().is_some_and(|network_metadata| {
network_metadata
.persistent_metadata
.reference
.as_ref()
.is_some_and(|reference| reference == "Artboard" && self.connected_to_output(node_id, &[]) && self.is_layer(node_id, &[]))
}) {
Some(LayerNodeIdentifier::new(*node_id, self))
} else {
None
@@ -1345,7 +1362,6 @@ impl NodeNetworkInterface {
node.skip_deduplication = old_node.skip_deduplication;
node.original_location = old_node.original_location;
node_metadata.persistent_metadata.display_name = old_node.alias;
node_metadata.persistent_metadata.reference = if old_node.name.is_empty() { None } else { Some(old_node.name) };
node_metadata.persistent_metadata.locked = old_node.locked;
node_metadata.persistent_metadata.node_type_metadata = if old_node.is_layer {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
@@ -1844,12 +1860,12 @@ impl NodeNetworkInterface {
if *import_index == 0 {
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rect(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
} else {
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
let reorder_import = ClickTarget::new_with_subpath(Subpath::new_rect(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rect(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
let reorder_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
}
@@ -1864,12 +1880,12 @@ impl NodeNetworkInterface {
if *export_index == 0 {
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rect(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
} else {
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
let reorder_export = ClickTarget::new_with_subpath(Subpath::new_rect(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rect(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
let reorder_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
}
@@ -2482,7 +2498,7 @@ impl NodeNetworkInterface {
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let subpath = Subpath::new_rounded_rect(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let subpath = Subpath::new_rounded_rectangle(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
DocumentNodeClickTargets {
@@ -2507,12 +2523,12 @@ impl NodeNetworkInterface {
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, 24.);
let subpath = Subpath::new_rounded_rect(DVec2::new(-12., -12.) + visibility_offset, DVec2::new(12., 12.) + visibility_offset, [3.; 4]);
let subpath = Subpath::new_rounded_rectangle(DVec2::new(-12., -12.) + visibility_offset, DVec2::new(12., 12.) + visibility_offset, [3.; 4]);
let visibility_click_target = ClickTarget::new_with_subpath(subpath, 0.);
// Update grip button click target, which is positioned to the left of the left most icon
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - (GRID_SIZE as f64) / 2., 24.);
let subpath = Subpath::new_rounded_rect(DVec2::new(-8., -12.) + grip_offset_right_edge, DVec2::new(0., 12.) + grip_offset_right_edge, [0.; 4]);
let subpath = Subpath::new_rounded_rectangle(DVec2::new(-8., -12.) + grip_offset_right_edge, DVec2::new(0., 12.) + grip_offset_right_edge, [0.; 4]);
let grip_click_target = ClickTarget::new_with_subpath(subpath, 0.);
// Create layer click target, which is contains the layer and the chain background
@@ -2521,7 +2537,7 @@ impl NodeNetworkInterface {
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * crate::consts::GRID_SIZE) as f64, 0.);
let radius = 10.;
let subpath = Subpath::new_rounded_rect(chain_top_left, node_bottom_right, [radius; 4]);
let subpath = Subpath::new_rounded_rectangle(chain_top_left, node_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
DocumentNodeClickTargets {
@@ -2747,7 +2763,7 @@ impl NodeNetworkInterface {
});
let bounds = self.all_nodes_bounding_box(network_path).cloned().unwrap_or([DVec2::ZERO, DVec2::ZERO]);
let rect = Subpath::<PointId>::new_rect(bounds[0], bounds[1]);
let rect = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
let all_nodes_bounding_box = rect.to_bezpath().to_svg();
let mut modify_import_export = Vec::new();
@@ -3008,7 +3024,7 @@ impl NodeNetworkInterface {
return None;
};
let bounding_box_subpath = Subpath::<PointId>::new_rect(bounds[0], bounds[1]);
let bounding_box_subpath = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
bounding_box_subpath.bounding_box_with_transform(network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
}
@@ -3047,7 +3063,7 @@ impl NodeNetworkInterface {
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<Vector> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer("Path")
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
&& let Some(vector) = self.document_metadata.vector_modify.get(&path_node)
{
let mut modified = vector.clone();
@@ -3063,7 +3079,7 @@ impl NodeNetworkInterface {
self.document_metadata
.click_targets
.get(&layer)
.map(|click| click.iter().map(ClickTarget::target_type))
.map(|click| click.iter().map(|x| x.target_type()))
.map(|target_types| Vector::from_target_types(target_types, true))
}
@@ -3165,7 +3181,7 @@ impl NodeNetworkInterface {
}
/// Update the cached click targets of the layers
pub fn update_click_targets(&mut self, new_click_targets: HashMap<LayerNodeIdentifier, Vec<ClickTarget>>) {
pub fn update_click_targets(&mut self, new_click_targets: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>) {
self.document_metadata.click_targets = new_click_targets;
}
@@ -3200,14 +3216,6 @@ impl NodeNetworkInterface {
}
}
pub fn set_reference(&mut self, node_id: &NodeId, network_path: &[NodeId], reference: Option<String>) {
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else {
log::error!("Could not get node_metadata in set_reference");
return;
};
node_metadata.persistent_metadata.reference = reference;
}
pub fn set_transform(&mut self, transform: DAffine2, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network in set_transform");
@@ -3278,7 +3286,9 @@ impl NodeNetworkInterface {
encapsulating_node_metadata.persistent_metadata.output_names.insert(insert_index as usize, output_name.to_string());
}
// Clear the reference to the nodes definition
encapsulating_node_metadata.persistent_metadata.reference = None;
if let Some(network_metadata) = encapsulating_node_metadata.persistent_metadata.network_metadata.as_mut() {
network_metadata.persistent_metadata.reference = None
}
};
// Update the export ports and outward wires for the current network
@@ -3347,7 +3357,9 @@ impl NodeNetworkInterface {
}
// Clear the reference to the nodes definition
node_metadata.persistent_metadata.reference = None;
if let Some(network_metadata) = node_metadata.persistent_metadata.network_metadata.as_mut() {
network_metadata.persistent_metadata.reference = None
}
// Update the metadata for the encapsulating node
self.unload_node_click_targets(&node_id, &encapsulating_network_path);
@@ -3403,7 +3415,9 @@ impl NodeNetworkInterface {
return;
};
encapsulating_node_metadata.persistent_metadata.output_names.remove(export_index);
encapsulating_node_metadata.persistent_metadata.reference = None;
if let Some(network_metadata) = encapsulating_node_metadata.persistent_metadata.network_metadata.as_mut() {
network_metadata.persistent_metadata.reference = None;
}
// Update the metadata for the encapsulating node
self.unload_outward_wires(&encapsulating_network_path);
@@ -3477,7 +3491,9 @@ impl NodeNetworkInterface {
return;
};
encapsulating_node_metadata.persistent_metadata.input_metadata.remove(import_index);
encapsulating_node_metadata.persistent_metadata.reference = None;
if let Some(network_metadata) = encapsulating_node_metadata.persistent_metadata.network_metadata.as_mut() {
network_metadata.persistent_metadata.reference = None;
}
// Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path);
@@ -3523,7 +3539,9 @@ impl NodeNetworkInterface {
let name = encapsulating_node_metadata.persistent_metadata.output_names.remove(start_index);
encapsulating_node_metadata.persistent_metadata.output_names.insert(end_index, name);
encapsulating_node_metadata.persistent_metadata.reference = None;
if let Some(network_metadata) = encapsulating_node_metadata.persistent_metadata.network_metadata.as_mut() {
network_metadata.persistent_metadata.reference = None;
}
// Update the metadata for the encapsulating network
self.unload_outward_wires(&encapsulating_network_path);
@@ -3615,7 +3633,9 @@ impl NodeNetworkInterface {
let properties_row = encapsulating_node_metadata.persistent_metadata.input_metadata.remove(start_index);
encapsulating_node_metadata.persistent_metadata.input_metadata.insert(end_index, properties_row);
encapsulating_node_metadata.persistent_metadata.reference = None;
if let Some(network_metadata) = encapsulating_node_metadata.persistent_metadata.network_metadata.as_mut() {
network_metadata.persistent_metadata.reference = None;
}
// Update the metadata for the outer network
self.unload_outward_wires(&encapsulating_network_path);
@@ -3721,28 +3741,17 @@ impl NodeNetworkInterface {
let number_of_inputs = node.inputs.len();
let Some(metadata) = self.node_metadata_mut(node_id, network_path) else { return };
for added_input_index in metadata.persistent_metadata.input_metadata.len()..number_of_inputs {
let reference = metadata.persistent_metadata.reference.as_ref();
let definition = reference.and_then(|reference| resolve_document_node_type(reference));
let input_metadata = definition
let input_metadata = self
.reference(node_id, network_path)
.as_ref()
.and_then(resolve_document_node_type)
.and_then(|definition| definition.node_template.persistent_node_metadata.input_metadata.get(added_input_index))
.cloned();
let Some(metadata) = self.node_metadata_mut(node_id, network_path) else { return };
metadata.persistent_metadata.input_metadata.push(input_metadata.unwrap_or_default());
}
}
/// Used to ensure the display name is the reference name in case it is empty.
pub fn validate_display_name_metadata(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(metadata) = self.node_metadata_mut(node_id, network_path) else { return };
if metadata.persistent_metadata.display_name.is_empty()
&& let Some(reference) = metadata.persistent_metadata.reference.clone()
{
// Keep the name for merge nodes as empty
if reference != "Merge" {
metadata.persistent_metadata.display_name = reference;
}
}
}
// When opening an old document to ensure the output names match the number of exports
pub fn validate_output_names(&mut self, node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId]) {
if let DocumentNodeImplementation::Network(network) = &node.implementation {
@@ -3755,13 +3764,17 @@ impl NodeNetworkInterface {
}
}
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts
pub fn replace_reference_name(&mut self, node_id: &NodeId, network_path: &[NodeId], reference_name: String) {
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else {
log::error!("Could not get node metadata in replace_reference_name");
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts.
/// Only works with network nodes. Proto nodes use their ID as the reference.
pub fn set_reference(&mut self, node_id: &NodeId, network_path: &[NodeId], reference_name: Option<String>) {
let Some(node_network_metadata) = self
.node_metadata_mut(node_id, network_path)
.and_then(|node_metadata| node_metadata.persistent_metadata.network_metadata.as_mut())
else {
log::error!("Could not get network metadata in replace_reference_name");
return;
};
node_metadata.persistent_metadata.reference = Some(reference_name);
node_network_metadata.persistent_metadata.reference = reference_name;
}
/// Keep metadata in sync with the new implementation if this is used by anything other than the upgrade scripts
@@ -4397,7 +4410,10 @@ impl NodeNetworkInterface {
node_metadata.persistent_metadata.display_name.clone_from(&display_name);
// Keep the alias in sync with the `ToArtboard` name input
if node_metadata.persistent_metadata.reference.as_ref().is_some_and(|reference| reference == "Artboard") {
if self
.reference(node_id, network_path)
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Artboard".into()))
{
let Some(nested_network) = self.network_mut(network_path) else {
return;
};
@@ -5382,7 +5398,9 @@ impl NodeNetworkInterface {
// If a non artboard layer is attempted to be connected to the exports, and there is already an artboard connected, then connect the layer to the artboard.
if let Some(first_layer) = LayerNodeIdentifier::ROOT_PARENT.children(&self.document_metadata).next()
&& parent == LayerNodeIdentifier::ROOT_PARENT
&& self.reference(&layer.to_node(), network_path).is_none_or(|reference| *reference != Some("Artboard".to_string()))
&& self
.reference(&layer.to_node(), network_path)
.is_none_or(|reference| reference != DefinitionIdentifier::Network("Artboard".into()))
&& self.is_artboard(&first_layer.to_node(), network_path)
{
parent = first_layer;
@@ -5974,6 +5992,12 @@ impl NodeNetworkMetadata {
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeNetworkPersistentMetadata {
/// The identifier for the node definition created for custom network nodes in [`DocumentNodeDefinition`].
/// It is only used to associate network nodes with their definition. Protonodes use their ProtonodeIdentifier.
/// The reference is removed once the node is modified, since the node now stores its own implementation and inputs.
/// TODO: Used during serialization/deserialization to prevent storing implementation or inputs (and possible other fields) if they are the same as the definition.
/// TODO: Implement node versioning so that references to old nodes can be updated to the new node definition.
pub reference: Option<String>,
/// Node metadata must exist for every document node in the network
#[serde(serialize_with = "graphene_std::vector::serialize_hashmap", deserialize_with = "graphene_std::vector::deserialize_hashmap")]
pub node_metadata: HashMap<NodeId, DocumentNodeMetadata>,
@@ -6218,13 +6242,9 @@ struct InputTransientMetadata {
/// Persistent metadata for each node in the network, which must be included when creating, serializing, and deserializing saving a node.
#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DocumentNodePersistentMetadata {
/// The name of the node definition, as originally set by [`DocumentNodeDefinition`], used to display in the UI and to display the appropriate properties if no display name is set.
// TODO: Used during serialization/deserialization to prevent storing implementation or inputs (and possible other fields) if they are the same as the definition.
// TODO: The reference is removed once the node is modified, since the node now stores its own implementation and inputs.
// TODO: Implement node versioning so that references to old nodes can be updated to the new node definition.
pub reference: Option<String>,
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the reference name is displayed to the user in italics.
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed to the user in italics.
#[serde(default)]
pub display_name: String,
/// Stores metadata to override the properties in the properties panel for each input. These can either be generated automatically based on the type, or with a custom function.
@@ -6463,7 +6483,9 @@ mod network_interface_tests {
async fn copy_isolated_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let rectangle = editor.create_node_by_name("Rectangle").await;
let rectangle = editor
.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER))
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle] }).await;
let frontend_messages = editor.handle_message(NodeGraphMessage::Copy).await;
let serialized_nodes = frontend_messages
@@ -19,13 +19,14 @@ pub struct DocumentNodePersistentMetadataInputNames {
pub network_metadata: Option<NodeNetworkMetadata>,
}
impl From<DocumentNodePersistentMetadataInputNames> for DocumentNodePersistentMetadata {
impl From<DocumentNodePersistentMetadataInputNames> for DocumentNodePersistentMetadataPropertiesRow {
fn from(old: DocumentNodePersistentMetadataInputNames) -> Self {
DocumentNodePersistentMetadata {
input_metadata: Vec::new(),
DocumentNodePersistentMetadataPropertiesRow {
reference: old.reference,
input_properties: Vec::new(),
display_name: old.display_name,
output_names: old.output_names,
has_primary_output: old.has_primary_output,
locked: old.locked,
pinned: old.pinned,
node_type_metadata: old.node_type_metadata,
@@ -60,7 +61,7 @@ pub struct PropertiesRow {
pub input_description: String,
}
impl From<DocumentNodePersistentMetadataPropertiesRow> for DocumentNodePersistentMetadata {
impl From<DocumentNodePersistentMetadataPropertiesRow> for DocumentNodePersistentMetadataHasPrimaryOutput {
fn from(old: DocumentNodePersistentMetadataPropertiesRow) -> Self {
let mut input_metadata = Vec::new();
for properties_row in old.input_properties {
@@ -74,11 +75,12 @@ impl From<DocumentNodePersistentMetadataPropertiesRow> for DocumentNodePersisten
..Default::default()
})
}
DocumentNodePersistentMetadata {
DocumentNodePersistentMetadataHasPrimaryOutput {
reference: old.reference,
display_name: old.display_name,
input_metadata: Vec::new(),
output_names: old.output_names,
has_primary_output: old.has_primary_output,
locked: old.locked,
pinned: old.pinned,
node_type_metadata: old.node_type_metadata,
@@ -104,9 +106,9 @@ pub struct DocumentNodePersistentMetadataHasPrimaryOutput {
pub network_metadata: Option<NodeNetworkMetadata>,
}
impl From<DocumentNodePersistentMetadataHasPrimaryOutput> for DocumentNodePersistentMetadata {
impl From<DocumentNodePersistentMetadataHasPrimaryOutput> for DocumentNodePersistentMetadataStringReference {
fn from(old: DocumentNodePersistentMetadataHasPrimaryOutput) -> Self {
DocumentNodePersistentMetadata {
DocumentNodePersistentMetadataStringReference {
reference: old.reference,
display_name: old.display_name,
input_metadata: old.input_metadata,
@@ -119,6 +121,49 @@ impl From<DocumentNodePersistentMetadataHasPrimaryOutput> for DocumentNodePersis
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
struct DocumentNodePersistentMetadataStringReference {
pub reference: Option<String>,
#[serde(default)]
pub display_name: String,
pub input_metadata: Vec<InputMetadata>,
pub output_names: Vec<String>,
#[serde(default)]
pub locked: bool,
#[serde(default)]
pub pinned: bool,
pub node_type_metadata: NodeTypePersistentMetadata,
pub network_metadata: Option<NodeNetworkMetadata>,
}
impl From<DocumentNodePersistentMetadataStringReference> for DocumentNodePersistentMetadata {
fn from(mut old: DocumentNodePersistentMetadataStringReference) -> Self {
if let Some(metadata) = old.network_metadata.as_mut() {
metadata.persistent_metadata.reference = old.reference;
}
DocumentNodePersistentMetadata {
display_name: old.display_name,
input_metadata: old.input_metadata,
output_names: old.output_names,
locked: old.locked,
pinned: old.pinned,
node_type_metadata: old.node_type_metadata,
network_metadata: old.network_metadata,
}
}
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum DocumentNodePersistentMetadataVersioned {
// Newest first
Current(DocumentNodePersistentMetadata),
StringReference(DocumentNodePersistentMetadataStringReference),
HasPrimaryOutput(DocumentNodePersistentMetadataHasPrimaryOutput),
PropertiesRow(DocumentNodePersistentMetadataPropertiesRow),
InputNames(DocumentNodePersistentMetadataInputNames),
}
pub fn deserialize_node_persistent_metadata<'de, D>(deserializer: D) -> Result<DocumentNodePersistentMetadata, D::Error>
where
D: serde::Deserializer<'de>,
@@ -126,17 +171,31 @@ where
use serde::Deserialize;
let value = Value::deserialize(deserializer)?;
if let Ok(document) = serde_json::from_value::<DocumentNodePersistentMetadataHasPrimaryOutput>(value.clone()) {
return Ok(document.into());
let versioned_document = serde_json::from_value::<DocumentNodePersistentMetadataVersioned>(value).map_err(serde::de::Error::custom)?;
let current: DocumentNodePersistentMetadata = match versioned_document {
DocumentNodePersistentMetadataVersioned::Current(v) => v,
DocumentNodePersistentMetadataVersioned::StringReference(v) => {
let v: DocumentNodePersistentMetadataStringReference = v;
v.into()
}
DocumentNodePersistentMetadataVersioned::HasPrimaryOutput(v) => {
let v: DocumentNodePersistentMetadataStringReference = v.into();
v.into()
}
DocumentNodePersistentMetadataVersioned::PropertiesRow(v) => {
let v: DocumentNodePersistentMetadataHasPrimaryOutput = v.into();
let v: DocumentNodePersistentMetadataStringReference = v.into();
v.into()
}
DocumentNodePersistentMetadataVersioned::InputNames(v) => {
let v: DocumentNodePersistentMetadataPropertiesRow = v.into();
let v: DocumentNodePersistentMetadataHasPrimaryOutput = v.into();
let v: DocumentNodePersistentMetadataStringReference = v.into();
v.into()
}
};
if let Ok(document) = serde_json::from_value::<DocumentNodePersistentMetadata>(value.clone()) {
return Ok(document);
};
if let Ok(document) = serde_json::from_value::<DocumentNodePersistentMetadataPropertiesRow>(value.clone()) {
return Ok(document.into());
};
match serde_json::from_value::<DocumentNodePersistentMetadataInputNames>(value.clone()) {
Ok(document) => Ok(document.into()),
Err(e) => Err(serde::de::Error::custom(e)),
}
Ok(current)
}
@@ -91,8 +91,8 @@ impl TypeSource {
/// The type to display in the tooltip label.
pub fn resolved_type_tooltip_string(&self) -> String {
match self {
TypeSource::Compiled(compiled_type) => format!("Data Type: {:?}", compiled_type.nested_type().to_string()),
TypeSource::TaggedValue(value_type) => format!("Data Type: {:?}", value_type.nested_type().to_string()),
TypeSource::Compiled(compiled_type) => format!("Data Type: {}", compiled_type.nested_type()),
TypeSource::TaggedValue(value_type) => format!("Data Type: {}", value_type.nested_type()),
TypeSource::Unknown => "Unknown Data Type".to_string(),
TypeSource::Invalid => "Invalid Type Combination".to_string(),
TypeSource::Error(_) => "Error Getting Data Type".to_string(),
@@ -180,7 +180,7 @@ impl NodeNetworkInterface {
self.input_type_not_invalid(input_connector, network_path)
}
// Gets the default tagged value for an input. If its not compiled, then it tries to get a valid type. If there are no valid types, then it picks a random implementation
/// Gets the default tagged value for an input. If its not compiled, then it tries to get a valid type. If there are no valid types, then it picks a random implementation.
pub fn tagged_value_from_input(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TaggedValue {
let guaranteed_type = match self.input_type(input_connector, network_path) {
TypeSource::Compiled(compiled) => compiled,
@@ -190,12 +190,12 @@ impl NodeNetworkInterface {
// TODO: Add a NodeInput::Indeterminate which can be resolved at compile time to be any type that prevents an error. This may require bidirectional typing.
self.complete_valid_input_types(input_connector, network_path)
.into_iter()
.min_by_key(|ty| ty.nested_type().to_string())
.min_by_key(|ty| ty.nested_type().identifier_name())
// Pick a random type from the potential valid types
.or_else(|| {
self.potential_valid_input_types(input_connector, network_path)
.into_iter()
.min_by_key(|ty| ty.nested_type().to_string())
.min_by_key(|ty| ty.nested_type().identifier_name())
}).unwrap_or(concrete!(()))
}
TypeSource::Error(e) => {
@@ -3,37 +3,23 @@ use super::network_interface::NodeNetworkInterface;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::DVec2;
use graph_craft::document::{NodeId, NodeNetwork};
use serde::ser::SerializeStruct;
/// Represents an entry in the layer tree hierarchy, sent to the frontend.
/// Each entry contains its layer ID and a list of its visible children.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct RawBuffer(Vec<u8>);
impl From<&[u64]> for RawBuffer {
fn from(iter: &[u64]) -> Self {
let v_from_raw: Vec<u8> = iter.iter().flat_map(|x| x.to_ne_bytes()).collect();
Self(v_from_raw)
}
}
#[derive(Debug, Clone, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct JsRawBuffer(Vec<u8>);
impl From<RawBuffer> for JsRawBuffer {
fn from(buffer: RawBuffer) -> Self {
Self(buffer.0)
}
}
impl serde::Serialize for JsRawBuffer {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut buffer = serializer.serialize_struct("Buffer", 2)?;
buffer.serialize_field("pointer", &(self.0.as_ptr() as usize))?;
buffer.serialize_field("length", &(self.0.len()))?;
buffer.end()
}
pub struct LayerStructureEntry {
#[serde(rename = "layerId")]
pub layer_id: NodeId,
pub children: Vec<LayerStructureEntry>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, specta::Type)]
pub struct LayerPanelEntry {
pub id: NodeId,
#[serde(rename = "implementationName")]
pub implementation_name: String,
#[serde(rename = "iconName")]
pub icon_name: Option<String>,
pub alias: String,
#[serde(rename = "inSelectedNetwork")]
pub in_selected_network: bool,
Loaded 100 of 376 files, more files were not shown because too many files have changed in this diff. Show more