Compare commits

..
Author SHA1 Message Date
Dennis Kobert d4bddbd067 Rewind both registry zones on undo and stop silent undo at the published frontier 2026-09-23 15:11:14 +02:00
Dennis Kobert e061fbc9f0 Test the room framing directly and add targeted delivery to the mock network 2026-09-23 14:44:18 +02:00
Dennis Kobert bbe33f34fc Generate resource-lifecycle ops and re-examine resource references after retirement 2026-09-23 14:38:37 +02:00
Dennis Kobert 53c54333fe Assert history never drops a retired delta and generate export and input-attribute ops 2026-09-23 14:27:15 +02:00
Dennis Kobert 089efc9d27 Retire a prefix of the hot log in the simulation, not always all of it 2026-09-23 13:43:52 +02:00
Dennis Kobert 701d68d067 Retire hot ops by per-author sequence instead of Lamport counter 2026-09-23 13:39:40 +02:00
Dennis Kobert 4f9657a4a1 Resurrect a removed entity from the same delta on every peer 2026-09-23 12:59:59 +02:00
Dennis Kobert 815f9e9dba Refold the registries when a merge lands deltas out of canonical order 2026-09-23 12:59:50 +02:00
Dennis Kobert b7c77560d2 Resurrect into the retired snapshot from history only 2026-09-23 11:16:01 +02:00
Dennis Kobert af9c5dd65d Defer hot ops whose referent has not arrived instead of dropping them 2026-09-23 11:09:06 +02:00
Dennis Kobert a835005d3c Ignore a replayed hot op already held instead of keeping a second copy 2026-09-23 10:54:03 +02:00
Dennis Kobert 3a2ecdc501 Apply remote hot ops one at a time so a failure cannot lose the batch 2026-09-23 10:37:20 +02:00
Dennis Kobert 72fe9269a3 Greet new peers before handling their batch and keep the hot log free of retired ops 2026-09-23 10:30:34 +02:00
Dennis Kobert db70c1981d Generate node ops in the sync simulation 2026-09-23 09:48:19 +02:00
Dennis Kobert 04f8aa0237 Recognize retired hot ops and re-announce lost ones on membership changes 2026-09-23 09:37:17 +02:00
Dennis Kobert 8ebc85746e Cover resources and reconnects in the sync simulation and fix the bugs it found 2026-09-22 23:05:19 +02:00
Dennis Kobert 9526a4e726 Keep asking peers for missing resources and resolve them through the byte store 2026-09-22 17:19:58 +02:00
Dennis Kobert 857eb26cbd Rebuild the interface synchronously after remote changes 2026-09-22 17:19:43 +02:00
Dennis Kobert e3ea0dcf68 Add live session sharing and joining to the editor 2026-09-22 13:39:22 +02:00
Dennis Kobert 1d4d0544cc Stage local diffs against the runtime base and keep declarations in the working copy 2026-09-22 13:37:52 +02:00
Dennis Kobert 6ae878d86a Add host, join, and watch subcommands to graphene-cli 2026-09-22 13:37:21 +02:00
Dennis Kobert 6ed938f62b Add document-live crate for hosting or following a session in memory 2026-09-22 13:37:21 +02:00
Dennis Kobert 6d23f7c2f4 Add causal broadcast, mock transport, and convergence simulation to peer-transport 2026-09-22 13:37:03 +02:00
Dennis Kobert 53a0c1548d Resurrect from hot-log removals and make merge batches self-consistent 2026-09-22 13:37:03 +02:00
Dennis Kobert e2fec54ced Wire Gdd into peer-transport as host or guest 2026-09-22 13:37:02 +02:00
Dennis Kobert e92ca26fd2 Add peer-transport crate for p2p sync of hot ops and retired history 2026-09-22 13:37:01 +02:00
Dennis Kobert 5d70619c4c Add history negotiation helpers and fast-forward merge to graph-storage 2026-09-22 13:37:01 +02:00
Dennis Kobert 69398a6703 Make GDD based undo syncronous by caching protonode declarations (#4571)
* Make gdd based undo syncronous by caching protonode declarations

* Address review comments
2026-09-22 11:32:12 +00:00
Keavon Chambers d7ae6029e0 Extend the math expression parser's factorial past the whole numbers through the gamma function (#4570) 2026-09-22 00:05:35 -07:00
Keavon Chambers 343710b623 New node: 'Points to Vector' 2026-09-21 22:30:07 -07:00
Keavon Chambers f872c5cd57 New nodes: 'Math f(x)' and 'Math f(…)' (#4569)
Add the Math f(x) and Math f(…) nodes
2026-09-21 20:19:29 -07:00
Keavon Chambers 626956c950 Replace the math expression parser's % operator with a floored mod() function (#4568) 2026-09-21 17:10:08 -07:00
Keavon Chambers b22bbf6d95 Add bool-to-number auto conversion, rename 'As f64' to 'As Number', and add 'Is Nonzero' and 'As Bool' nodes (#4567)
Embed booleans as numbers across wire conversions, add the As Bool and Is Nonzero nodes, and rename As f64 to As Number
2026-09-21 15:41:59 -07:00
Keavon Chambers 75117e8d6b Polish the UX of docking to the center of a panel so it forces edges when center is invalid 2026-09-21 14:31:25 -07:00
Keavon Chambers 95672018b0 Require exactly 0/1 for bools and only-ascending-or-descending comparison chains in the math expression parser (#4566)
Require exact truth values in math expression logic and read comparison chains as one predicate
2026-09-21 14:22:42 -07:00
Keavon Chambers d0fb9a1efc Add magnitude bars to the math expression parser (#4565)
Add magnitude bars to the math expression parser, with abs() acting on each part

Magnitude bars `|x|` give the magnitude on every rung, with `|`
opening where an operand is expected and closing where an operator is,
and `||` reading as Or unless two magnitudes are open, while `abs()`
stays the absolute value of each part. The `real()`, `imag()`, and
`arg()` functions are removed in favor of the matrix literals and
`angle()` the specification defines for those readings.
2026-09-21 12:46:37 -07:00
Keavon Chambers f0622d62b6 Allow the math parser's expression results to become complex instead of NaN (#4564)
Make math expression results climb into the complex plane instead of ever producing NaN

Every value is a quaternion in principle, so narrower storage is never
observable: a result whose imaginary part is zero is the real number,
`-0` is `0`, and a real input whose answer leaves the real line climbs
into the complex plane (`sqrt(-4)` is `2i`, `ln(-1)` is `iπ`, `asin(2)`
its complex value) instead of producing NaN. No operation returns NaN
at all: an indeterminate form like `0/0` or `∞ - ∞` is an evaluation
error, as is a NaN arriving through a host binding at its point of use.
2026-09-21 11:58:25 -07:00
Keavon Chambers 2da22f2458 Add variadic statistics functions to the math expression parser (#4563)
Add variadic statistics to the math expression parser
2026-09-21 03:33:37 -07:00
Keavon Chambers 849e08829d Add math parser support for shadowing builtin identifiers and introduce \ as a prefix to reach the builtins (#4562)
Shadow the constants behind case-sensitive bindings, with the `\` prefix reaching the builtin

Constants resolve at evaluation time, after the environment, so a
binding of any spelling, word or typeset symbol, shadows the builtin of
exactly that spelling, and a host-supplied function likewise shadows a
builtin function. The `\` prefix, in LaTeX's habit, names the language's
own constant or function regardless of bindings (`\pi`, `\e`, `\sin`),
and is an error when no builtin has that name.
2026-09-21 00:46:26 -07:00
Keavon Chambers 679421ec80 Make the math parser allow a number's implicit multiplication after a non-number operand (#4561) 2026-09-20 23:31:39 -07:00
Keavon Chambers 9a925d16e5 Fix Unicode handling in the math expression for identifiers and infinity (#4560)
Lex the math expression parser's identifiers as Unicode identifiers

Names follow the `XID_Start XID_Continue*` rule of UAX #31, the same
one Rust spells, so letters from every script name a variable and
combining marks extend a name: a decomposed `é` is one name rather
than the constant `e` beside a stray mark. Digits of any script, lone
marks, invisible formatting characters like the right-to-left
override, and symbols including emoji can no longer begin a name,
which also leaves `#`, `$`, `~`, and `@` free to become namespace
prefixes once a host scope needs them. Rust's special case admitting a
leading underscore is deliberately not adopted.

Reads the character classes from unicode-ident, the table crate the
proc-macro stack already builds with, rather than hand-rolling the
ranges.
2026-09-20 23:04:57 -07:00
Keavon Chambers e49c707524 Add combinatorics functions and base-suffixed logs to the math expression parser, and rework its constants (#4559)
* Standardize on the 'nonzero' spelling in comments

* Fill small gaps in the math expression parser

Adds the unary plus operator, the `true` and `false` constants, the
`choose` and `pick` combinatorics functions, base-suffixed `logN`/
`rootN` function names with optional underscores and fractional bases
like `log3.25`, the typeset operator spellings (`−`, `×`, `⋅`, `÷`,
`∧`, `∨`, `¬`), and `Value` accessors reading results as `f32` and the
standard integer types. Constants match their lowercase spelling
exactly, since uppercase-initial names are reserved for matrices. The
`¬` spelling is the prefix logical not alone, never the postfix
factorial that `!` also spells, and punctuation never begins a name,
which leaves `#`, `$`, `~`, and `@` free to become namespace prefixes
once a host scope needs them.

Retires the `√` prefix operator, which is untypeable and duplicates
`sqrt()`, and removes the undocumented unitless `G` constant: its
9.80665 is the value of lowercase-g standard gravity under capital-G's
name, and gravity's proper home is the future unit system's `g`
acceleration unit.

Also covers the previously untested interaction between implicit
multiplication and unary minus with parenthesized operands (`2 (-3)`,
`-3(2)`) in the test suite.
2026-09-20 21:32:23 -07:00
Keavon Chambers 506690d109 Fix the 'Mix' and 'Color Overlay' nodes to use spec-compliant math for the Hue/Saturation/Color/Luminosity blend modes (#4558)
* Fix the 'Mix' and 'Color Overlay' nodes to use spec-compliant math for the Hue/Saturation/Color/Luminosity blend modes

* Fix potential NaN

* Clip light brighter than white before the luminosity construction, and assert the clipped result
2026-09-20 18:55:30 -07:00
Keavon Chambers 4813fe39b0 New node: 'Lorem Ipsum' and generator library (#4046) 2026-09-20 02:18:49 -07:00
Keavon Chambers 6e44a74254 Split apart PortfolioMessage into several sub-messages (#4555)
* Split apart PortfolioMessage into several sub-messages

* Refresh the source group's active tab after a panel split, keep recovered document file names unique, and make the failed documents state private
2026-09-19 20:29:31 -07:00
Timon 3d13dc379b Remove unnecessary web permissions request for persistent storage (#4493)
Stop requesting persistent storage
2026-09-20 01:31:56 +00:00
Timon aee07b052a Desktop: Update winit to include window dragging fix for Windows (#4550) 2026-09-20 01:27:37 +00:00
Keavon Chambers 2ed5e775e5 Add WEBP, TIFF, ICO, TGA, HDR, and EXR image import and more raster export formats (#4554)
* Add WEBP, TIFF, ICO, TGA, HDR, and EXR image import and more raster export file types

* Try a file as TGA only when no image format is recognized
2026-09-19 18:14:37 -07:00
Keavon Chambers 23e6b0f11d Make the dropdown widget's file drop a callback and keep stray file drops from navigating the browser away (#4553)
* Make the dropdown widget's file drop a callback and keep stray file drops from navigating the browser away

* Look up the dropped file's widget before reading the file
2026-09-19 16:01:58 -07:00
Keavon Chambers 97d8452a1d New node: 'Color Lookup' (#4552)
* New node: 'Color Lookup' for applying .cube, .3dl, .look, .csp, and .icc LUT files

* Add LUT ingest to the UI

* Add caching to the parsed LUT

* More code review fixes
2026-09-19 02:56:14 -07:00
Keavon Chambers ab32a60476 Add drag-and-drop support to the file picker dropdown widget (#4551)
Add drag-and-drop file ingest into file picker dropdowns
2026-09-19 00:34:37 -07:00
TimonandKeavon Chambers 7d1303f695 Unify file opening, importing, and pasting into a file ingest handler (#4548)
* Unify file and data ingest

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-09-18 22:47:02 -07:00
Keavon Chambers f90bef159c Add a dropdown for resource selection and adopt it in the 'Image' node (#4543)
* Add a dropdown for resource selection and adopt it in the Image node

* Route every image upload through a new ResourceUpload handler with desktop support and migrate wired 'Image' node inputs

* Show each resource's user count in the resource picker dropdown

* Send a picked resource file to the document that requested it, list every non-font resource in the picker, and link sibling message docs
2026-09-18 18:14:24 -07:00
Keavon Chambers cb30348215 Fix several bugs causing warning spam in the console (#4547) 2026-09-17 00:51:42 -07:00
Keavon Chambers 3f1351e3b9 Make the ColorInput's gradient rendering strategy to use that of SliderInput (#4546)
Make the ColorInput's gradient rendering strategy to use that of SliderInput, fixing a flicker in Firefox when editing gradients
2026-09-16 23:53:38 -07:00
Keavon Chambers eb4a122322 Rename the SpectrumInput widget to SliderInput (#4541)
Rename the 'SpectrumInput' widget to 'SliderInput'
2026-09-15 20:12:31 -07:00
Keavon Chambers 358eb317d2 Add a "Use Tint" toggle to the 'Black & White' node and give its tint the Luminosity blend's clipping (#4540)
* Add a 'Use Tint' toggle to the 'Black & White' node and give its tint the Luminosity blend's clipping

* Fix the Black & White migration for a wired tint and gray out the tint when unused
2026-09-15 19:51:51 -07:00
Keavon Chambers 04a401c1b8 New node: 'Photo Filter' to warm or cool an image by multiplying it with a filter color in XYZ (#4539) 2026-09-15 18:55:23 -07:00
Keavon Chambers 6f06f030d6 Retire the 'Brightness/Contrast Classic' node with the 'Brightness/Contrast' classic toggle now shader compatible (#4538) 2026-09-15 18:29:55 -07:00
Keavon Chambers fac555ab3b Add a saturation input to the 'Vibrance' node and rework both axes to work in linear light (#4537)
* Add a saturation input to the 'Vibrance' node and rework both axes to work in linear light

* Refine the sliders

* Clarify some comments
2026-09-15 17:58:25 -07:00
Keavon Chambers 8d111e37f5 Add colorize and six hue ranges to the 'Hue/Saturation' node (#4536)
* Add colorize and six hue ranges to the 'Hue/Saturation' node

* Hide the 'Hue/Saturation' range rows while colorize is on, note the +100 saturation rule, and tidy two lints and a tooltip
2026-09-15 16:38:19 -07:00
Timon fdf6cfe296 Desktop: Switch to winit clipboard API (#4519)
* Desktop: Upgrade winit and port DnD to the new data transfer API

* Desktop: Read and write the clipboard via the winit data transfer API
2026-09-15 14:17:51 +00:00
Timon c6d6f9f8be Use cargo workspace to remove duplicated version, license, and author fields (#4226)
Use cargo workspace to remove dublicated version, license and author fields
2026-09-15 10:36:17 +00:00
Keavon Chambers 68d2a06c80 Add per-channel parameters to the 'Levels' node and make its midtones a gamma value (#4535)
* Add per-channel records and a gamma midtones value to the 'Levels' node, with a channel selector in its Properties panel

* Migrate the old 'Levels' midtones through its output range and bound a lone midtone marker by the track edges
2026-09-14 22:51:43 -07:00
Keavon Chambers 0bede7969c Add dashed links between spectrum markers and typed marker scales to the shared spectrum sections (#4534) 2026-09-14 20:53:06 -07:00
Keavon Chambers e38926004f Add a selection mode to the spectrum widget so only the gradient editor supports having a highlighted stop (#4533)
* Add a selection mode to the spectrum widget so only the gradient editor keeps a highlighted stop

* Record the drag mode for every drag and require selection for reordering so a non-selecting widget cannot drag the wrong stop
2026-09-14 19:55:38 -07:00
Keavon Chambers e8f7366a43 Show a range slider beside bounded range-mode numbers in the Properties panel (#4532)
* Show a range slider beside bounded numbers in range mode

* Fall back to a plain number widget when a range's bounds are reversed or equal
2026-09-14 18:49:09 -07:00
Keavon Chambers 5e705aaa04 Add a range slider mode to the spectrum widget and slider rows to node properties (#4531)
* Add a range slider mode to the spectrum widget and slider rows to node properties

* Reset the weighted strength slider to the node's default of zero and skip markers off the track when picking up the nearest one
2026-09-14 18:03:31 -07:00
Keavon Chambers cc444da637 Improve accuracy of the 'Channel Mixer', 'Selective Color', 'Posterize', and 'Exposure' nodes (#4530) 2026-09-14 16:35:52 -07:00
Keavon Chambers 1940e430dc Replace the 'Luminance' node with a 'Desaturate' node with a better selection of desaturation methods (#4529)
* Remove the 'Threshold' node's luminance calculation dropdown so it always compares the Rec. 601 luma

* Find the HSL lightness extremes before encoding and drop a stale luminance TODO
2026-09-14 14:34:55 -07:00
James Lindsay eaadea6593 Fix cargo-about install command (#4512)
Fix cargo about install
2026-09-14 17:34:08 +00:00
Keavon Chambers ecd2007e63 Remove the 'Threshold' node's "Luminance Calculation" parameter (#4528)
Remove the 'Threshold' node's luminance calculation dropdown so it always compares the Rec. 601 luma
2026-09-13 03:02:27 -07:00
Keavon Chambers fea741cdef New node: Color Balance (#4527) 2026-09-12 22:11:51 -07:00
Keavon Chambers 98550f6f25 Fix defaulted Item parameters dropping their type alias and rejecting hex string color defaults (#4525) 2026-09-12 19:32:51 -07:00
Keavon Chambers 89b797f4c1 Make 'Gradient Map' use gamma-space luma and move it into adjustments.rs (#4524)
Move Gradient Map into adjustments.rs and position it by the classic 0.3/0.59/0.11 luma
2026-09-12 18:24:38 -07:00
Keavon Chambers 21cceeb7ba Rename the 'Hex to Color' node to 'String to Color' (#4523) 2026-09-12 16:52:32 -07:00
Keavon Chambers 96024d6c2c New node: String to Vec2 (#4522)
Add the String to Vec2 node
2026-09-12 16:40:48 -07:00
Keavon Chambers 645d346565 Ease the Smooth gradient interpolation into the ends of an open ramp (#4521) 2026-09-12 16:26:03 -07:00
Keavon Chambers 3e51b757db Add the Curves adjustment node with a Transfer Curve type and editor widget (#4520)
* Add the Curves adjustment node with a Transfer Curve type and editor widget

* Address review feedback on the Transfer Curve widget's edge cases
2026-09-12 13:03:12 -07:00
Dennis KobertandKeavon Chambers 944d00cac5 Switch the Color struct back to storing unassociated alpha (#4518)
* Switch Color struct back to storing unassociated alpha

* Address review feedback

* Update the Invert node and legacy image migration for straight alpha and add round-trip tests

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-09-12 08:22:54 +00:00
Keavon Chambers e725f55043 Relicense Graphite under the dual MIT/Apache-2.0 license (#4208)
Relicense under dual MIT/Apache-2.0
2026-09-06 23:57:37 -07:00
Keavon Chambers fb35dadf1b Remove a couple of old frontend comments 2026-09-06 23:19:06 -07:00
Keavon Chambers 5612b63633 Extend open paths from endpoints with the Freehand tool and skip hidden layers in path edits (#4508)
* Let the Freehand tool continue a selected open path from its endpoint and show endpoint overlays in the Freehand and Spline tools

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

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

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

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

* Test that undo during a Pen tool handle transform cancels it and rewinds
2026-09-06 15:47:23 -07:00
Keavon Chambers ae87be30b0 Revert #1587 and #1597 so the Pen tool no longer handles per-segment history 2026-09-06 14:03:19 -07:00
Timon f11e6f3bc6 Desktop: Port the pointer shake event detection for direct input routing (#4506)
Desktop: Port shake detection for direct input routing
2026-09-06 10:42:20 +00:00
Timon d2bf8f99d2 Desktop: Mirror direct viewport input to the UI (#4502)
Desktop: Mirror direct-routed input to the UI
2026-09-06 01:29:19 +00:00
Timon 63725ea623 Desktop: Make input routing aware of floating menus (#4498)
* Desktop: Make input routing aware of floating menus

* Desktop: Route mouse input like pen input

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

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

* Use a version floor for cargo-about and drop the Nix sync notices
2026-09-05 17:09:47 -07:00
Daniel Z. 4d9a626df2 Fix dev environment configurations with devcontainer, vscode, and cargo-about (#4372)
Some minor fixes to issues I ran into using devcontainer on this project
with vscode.
 
- Add `esbenp.prettier-vscode` to the recommended extensions list as
it's already used in `.vscode/settings.json`
- Install `wasm32-unknown-unknown` Rust target in devcontainer
- Add cargo-binstall and pin cargo-about version in devcontainer
- Remove `no-clearly-defined = true` from `about.toml`:
  - cargo-about 0.9.1 fails to run if `no-clearly-defined` is present
- cargo-about 0.8.0 already [removed
support](https://github.com/EmbarkStudios/cargo-about/blob/main/CHANGELOG.md#080---2025-09-05)
for clearlydefined.io, so the argument is a no-op
2026-09-05 22:55:20 +00:00
Timon 54c5aa32f0 Desktop: Fix node graph grid dot transparency (#4504) 2026-09-04 13:37:19 +00:00
Timon dd84cd7417 Add 'Scale with Viewport' option to the Brush tool (#4485)
* Add an Autoscale option to the Brush tool

* Put Autoscale option in a Diameter popover

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

* Remove hardcoded input indices
2026-09-02 17:44:37 +00:00
Timon 34b2312113 Desktop: Update CEF to 151 (#4490) 2026-09-02 17:44:37 +00:00
Timon de8713b686 Desktop: Improve Mac signing and notarization 2026-09-02 17:44:37 +00:00
Timon 7986cabadb Update Nix flake (#4489) 2026-08-31 11:36:39 +00:00
Timon 150cfaa550 Add the CODEOWNERS file (#4477)
Introduce `CODEOWNERS` file
2026-08-31 09:32:47 +00:00
Timon 5457b4faec Remove now obsolete disable-registration special case from node macro (#4484) 2026-08-29 15:58:14 +02:00
Keavon Chambers 1c055bfaab Add a thanks banner to the donation page's flow 2026-08-29 02:36:24 -07:00
Keavon Chambers c64a9e5cee Revamp the website's donation page 2026-08-28 23:16:22 -07:00
Keavon Chambers ff2afbccda Update the roadmap on the website 2026-08-28 23:01:48 -07:00
Keavon Chambers 3bb6aa97b9 Bump the Graphite release series to alpha 5, intended as retroactively backdated to the start of 2026 2026-08-28 22:59:49 -07:00
Timon d5bb887b79 Improve fix for corrupted font resource loading in older documents (#4482)
* Revert "Fix corrupted font resource loading in older documents"

This reverts commit 404d9f3047.

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

* Fix text node migrations

* Provide resource storage to the resource message handler

* Refetch resources whose stored bytes are missing

* Add test for refetching resources with missing bytes
2026-08-29 00:01:37 +00:00
Timon c2afc07a04 Move file filter creation from frontend to editor (#4351) 2026-08-28 09:19:44 +00:00
James Lindsay c8f38059f8 Frontend type constraints (#4334) 2026-08-27 18:13:12 +00:00
Timon c7a64fff0c Add the 'Basic Brush' node and replace the legacy Brush tool implementation with it (#4469)
* Draw raster images with pad extension instead of repeat

* Add the GPU basic brush renderer

* Rework the brush tool around the GPU basic brush

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

* Route brush strokes through the node graph

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

* Request pooled textures synchronously

* Pool cached textures by format

* Add the owned GPU buffer type

* Route the remaining GPU allocations through the executor

* Add weak texture parking to the texture cache

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

* Reuse vello image atlas slots across frames
2026-08-27 15:19:00 +00:00
Timon 681b38d3d6 Support input from drawing tablets on web (#4445)
* Rename the editor mouse state types to Pointer* and the input_ modules

* Add optional pen attributes to the editor pointer state types

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

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

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

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

* Desktop: Track double clicks on the direct editor route

* Desktop: Move the pointer lock position into InputState

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

* Fix pen input being swallowed by Windows resize helper

* Update winit to 0.31.0-beta.2 from crates.io

* Add event time to the editor pointer states

The brush trace's hot core is position plus per-sample time, and the
frame clock is too coarse for high-rate tablets: several samples share
one timestamp and speed dynamics see dt = 0. The desktop stamps
editor-routed pointer input with a monotonic arrival time since winit
does not surface hardware timestamps; the web path can thread the
PointerEvent timeStamp through later.

* Capture pen input via browser api

* Replay coalesced pointer samples for smoother pen strokes

* Handle missing or empty coalesced pen events
2026-08-27 15:18:59 +00:00
Timon 5a16e18b2a Add time since pointerdown to input event handling (#4443)
Add event time to the editor pointer states

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

* Add optional pen attributes to the editor pointer state types

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

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

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

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

* Desktop: Track double clicks on the direct editor route

* Desktop: Move the pointer lock position into InputState

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

* Fix pen input being swallowed by Windows resize helper

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

* Code review fixes

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

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

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

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

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

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

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

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

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

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

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

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

* Remove outdated todo comments

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

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

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

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

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

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

* Two code review fixes

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

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

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

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

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

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

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

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

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

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

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

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

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

* Code review fixes

* Re-save demo art

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

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

* Update demo art

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

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

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

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

* Make the 'Map Points' node accept graphic input

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* Order the gradient popover with Intrp. above Space

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

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

* Consolidate gradient settings plumbing and fix bugs

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

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

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

* Code review

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

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

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

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

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

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

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

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

* Update labels

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

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

* Clean up comments

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

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

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

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

* Add an HSV gradient interpolation space

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

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

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

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

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

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

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

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

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

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

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

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

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

* Carry the gradient hue direction attribute through boolean operations

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

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

* Add a Space interpolation dropdown to the color picker popover

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

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

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

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

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

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

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

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

* Update the demo art for the gradient form rename

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* Wire the interpolation control path input per chain node type

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

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

* Box the `ExecutionResponse` variant of `NodeGraphUpdate`

* Box the `Layer` variant of `NodeTypeClickTargets`

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

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

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

* Collapse the TransientMetadata enum into the Option inside TransientCache

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

* Validate that the pinned node order only references existing nodes

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

* Purge the deleted nodes' cached wire paths in delete_nodes

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

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

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

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

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

* Replace the remove_references_from_network selection hijack with an explicit shift set

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* Rebuild the document structure on redo to match undo

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

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

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

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

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

* Make is_artboard an identity check independent of scene connectivity

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

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

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

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

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

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

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

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

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

* Update demo artwork
2026-07-17 09:43:04 -07:00
Keavon Chambers 581bb05f5d New nodes: 'Voronoi Cells', 'Tesselate', and 'Relax Points' (#4345) 2026-07-17 01:40:39 -07:00
Keavon Chambers 048c458789 New nodes: Sort, Filter, Reverse, Shift, Shuffle, Number Sequence, List Indices, List Slice, Read Number (#4347) 2026-07-17 01:15:10 -07:00
Keavon Chambers d241cdcb2e Consolidate the rank promotion and cache chain registrations behind one value-type list (#4346) 2026-07-16 04:05:02 -07:00
Keavon Chambers a770448bc9 New nodes: Sum, Average, Minimum, Maximum, Any, All (#4344) 2026-07-15 23:41:46 -07:00
Keavon Chambers 2090e9979a Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)
* Add rank polymorphism node audit classifying all 271 nodes

* Implement StaticType for Item<T>

* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input

* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate

* Document the Item kernel implementation and staging plan

* Route Item<Vector> through TaggedValue::TypeDefault

* Add executor integration tests covering the Item and List wire variants

* Collapse element-wise Item/List wire pairs to the List form for conversion insertion

* Migrate sixteen vector modifier nodes to Item element-wise kernels

* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels

* Fix bevel_with_transform test to actually exercise the transform attribute

* Implement From<T> for Item<T>

* Register PromoteNode rank adapters wrapping bare values into Item wires

* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor

* Define a real promote node backing the PromoteNode registry identifiers

* Zip ranked Item connectors by frame slot in the mapped element-wise variant

* Register ItemToListNode singleton raise adapters

* Resolve Item wires against List connectors by inserting promotion adapters at construction

* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end

* Implement Clampable for Item and List wires with per-variant clamp bounds

* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire

* Implement ApplyTransform for Item

* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0

* Detect element-wise nodes by lazy primary connectors declaring Output = Item

* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone

* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2

* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters

* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes

* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro

* Amend the audit with the DashPattern value type resolution

* Migrate the string family to Item element-wise kernels

* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters

* Shadow owned node parameters in bodies instead of mut in signatures

* Migrate the math family and string measure nodes to Item element-wise kernels

* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows

* Flat-map expander kernels returning List under the mapped variant's frame

* Migrate the expander nodes to Item kernels flat-mapping under the frame

* Remove the unused peel_list helper

* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in

Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).

Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.

* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk

* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites

* Flip the vector shape generators to emit rank-0 Item<Vector>

The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.

Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.

* Parse ranked Item<T> parameter defaults against the bare element type

A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.

* Parse an element-wise primary's scalar default against the bare element type

An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.

* Add the DashPattern value type for stroke dash sequences

Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.

* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector

Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.

Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.

Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.

* Register rank adapters for the ranked Stroke enum parameters

The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.

* Display Item wires in the Data panel without a List's ID column

Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.

* Register MonitorNode for Item wire types so the Data panel introspects them directly

Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.

* Color and double Item/List wires and cleave layer-stack connectors in the node graph

* Route wire color and rank through hidden nodes and refresh them on type changes

* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node

* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires

* Back DashPattern with a List<f64> so the Data panel can introspect its lengths

* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>

* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions

* Rank the remaining bare and unnecessarily-List connectors across the node catalog

* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values

* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill

* Restore generator frame-from-params ranking to the roadmap as a planned stage

* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract

* Unload only the wires whose displayed style changed when types update

* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized

* Restore the whole-List Transform variant so rank-1 content wires resolve again

* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes

* Give every ranked connector a field adapter and add numeric cast variants for legacy wires

* Key a ranked param's type default off its Item wire form when no literal default exists

* Inherit the layer's content value when splicing a node into an empty chain

* Migrate stale List-form TypeDefault inputs to the definition's current default

* Generate the mapped wire variant only when the element-wise node has a frame source

* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps

* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot

* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers

* Convert the measure family to element-wise Item kernels per the audit classification

* Prefer the bare element value over the Item type default so ranked params keep their widgets

* Rename GradientStopsUI to GradientUI

* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix

* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2

* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes

* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions

* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius

* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness

* Rank the value, color, and text generator params to Item

* Rank the raster, web-request, and context-reader generator params to Item

* Fix the repeat and brush test wirings left behind by the param-ranking sweeps

* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes

* Delete the Attach Attribute node, folding its role into Write Attribute

* Add the Filter and Sort list companion nodes

* Guard the removed-definition migration swap target with a test

* Add the Box Corners value type in place of the rectangle corner radius list

* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node

* Rank the Combine Channels node's channel connectors to Item

* Make Map Points an element-wise node

* Delete the deprecated Upload Texture node

* Update the implementation roadmap to reflect the landed stages

* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path

* Prefer the rank-0 default when disconnecting a rank-capable input

* Make Path Modify an element-wise node

* Wrap node paths in a NodeIdPath newtype so they flow as a single Item

* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves

* Stop the Brush node from setting layer attributes its paint operation doesn't produce

* Present-gate Flatten Path's adopted layer path like its fill and stroke

* Gate carried layer attributes on static column presence, not runtime values

* Give the remaining graphic Item<T> types a default so unconnected primaries resolve

* Dispatch a ranked param's Properties widget from its rank-0 element type

* Make Extract Transform an element-wise node, restoring the Origins to Polyline body

* Rename Flatten Path to Combine Paths

* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath

* Drop the dead List<u8> and List<NodeId> wire rows

* Rank Flatten Graphic's Fully Flatten toggle to Item

* Update the implementation roadmap with the endgame scope

* Make Combine Paths a reducer that collapses the whole frame into one path

* Stop type-converter nodes from carrying the source's unrelated attributes

* Format the Origins to Polyline regression test

* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value

* Make Switch a framed element-wise select, bundling whole collections

* Widen and align element-type coverage across the list and graphic nodes

* Register the compiler's cache chain pair for every ranked enum and newtype wire

* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires

* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion

* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg

* Delete the vestigial Clone debug node

* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters

* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR

* Deduplicate the promotion adapter registrations into the field adapter macro

* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge

* Vertical wire styling

* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>

* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row

* Rank Path Modify's modification parameter to Item<Box<VectorModification>>

* Rename the field adapter node family to input adapter

* Drop the dead bare scalar rows from Context Modification's implementations list

* Move the dynamic executor's test module into its own file

* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode

* Materialize stored TaggedValues as ranked Item wires at the source

* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization

* Plant the input adapter for List-only inputs, composing position conversion from standard rows

* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers

* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect

* Enforce ranked node inputs in the macro, rejecting bare wire declarations

* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel

* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration

* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced

* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs

* Rewrite the element-wise accessor wire type at the primary input, not raw index 0

* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row

* Gate the remaining Raster<GPU> registry rows behind the gpu feature

* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter

* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index

* Store paint picks as plain color/gradient values, removing the FillChoice value type

* Code review restructuring

* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node

* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR

* Parse Fill and Stroke color defaults through the paint wire's Graphic element

* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing

* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration

* Migrate the legacy 4-input Fill directly to the split has-transform shape

* Upgrade the demo artwork

* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues

* Remove the rank polymorphism working documents

* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation

* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types

* Derive PartialEq for Item now that attributes participate in equality

* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types

* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
2026-07-15 19:03:01 -07:00
544 changed files with 63583 additions and 35323 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
+20 -4
View File
@@ -2,11 +2,25 @@
"image": "mcr.microsoft.com/devcontainers/base:debian",
"features": {
"ghcr.io/devcontainers/features/rust:1": {
"profile": "default"
"profile": "default",
"targets": "wasm32-unknown-unknown"
},
"ghcr.io/devcontainers/features/node:1": {}
"ghcr.io/devcontainers/features/node:1": {
// NOTICE: keep in sync with `.nvmrc`
"version": "24"
}
},
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
"containerEnv": {
"WASM_BINDGEN_CLI_VERSION": "0.2.121",
"CARGO_ABOUT_VERSION": "0.9.2",
"BINARYEN_VERSION": "130",
"CARGO_BINSTALL_VERSION": "1.23.0"
},
"onCreateCommand": {
"Install cargo-about and wasm-bindgen-cli": "curl -sSfL https://github.com/cargo-bins/cargo-binstall/releases/download/v$CARGO_BINSTALL_VERSION/cargo-binstall-$(uname -m)-unknown-linux-musl.tgz | tar xz -C $CARGO_HOME/bin && BINSTALL_DISABLE_TELEMETRY=true cargo binstall --no-confirm cargo-about@$CARGO_ABOUT_VERSION wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION",
"Install Binaryen wasm-opt": "curl -sSfL https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-$(uname -m)-linux.tar.gz | tar xz -C $CARGO_HOME/bin --strip-components=2 binaryen-version_$BINARYEN_VERSION/bin/wasm-opt"
},
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
@@ -16,14 +30,16 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
"wayou.vscode-todo-highlight",
"streetsidesoftware.code-spell-checker",
// Helpful
// Git
"mhutchie.git-graph",
"qezhu.gitlink",
// Helpful
"wmaurer.change-case"
]
}
+34
View File
@@ -0,0 +1,34 @@
# Keavon Chambers (@Keavon [email protected])
# Dennis Kobert (@TrueDoctor [email protected])
/document/format/ @TrueDoctor
/node-graph/graph-craft/ @TrueDoctor
/node-graph/preprocessor/ @TrueDoctor
/node-graph/node-macro/ @TrueDoctor
/node-graph/interpreted-executor/ @TrueDoctor
/node-graph/graphene-cli/ @TrueDoctor
# Timon Schelling (@timon-schelling [email protected])
/.nix/ @timon-schelling
/flake.nix @timon-schelling
/flake.lock @timon-schelling
/desktop/ @timon-schelling
/editor/src/messages/future/ @timon-schelling
/editor/src/messages/resource_storage/ @timon-schelling
/editor/src/messages/network/ @timon-schelling
/editor/src/messages/app_window/ @timon-schelling
/editor/src/messages/clipboard/ @timon-schelling
/editor/src/messages/viewport/ @timon-schelling
/libraries/wgpu-sync/ @timon-schelling
/node-graph/libraries/canvas-utils/ @timon-schelling
/tools/cargo-run/ @timon-schelling
/tools/third-party-licenses/ @timon-schelling
+24 -10
View File
@@ -58,6 +58,7 @@ jobs:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
@@ -302,9 +303,11 @@ jobs:
pull-requests: write
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.0"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
steps:
- name: 📥 Clone repository
@@ -341,7 +344,9 @@ jobs:
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/cargo-binstall@main
uses: cargo-bins/cargo-binstall@v1.23.0
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
- name: 🚧 Install native dependencies
shell: pwsh
@@ -497,9 +502,11 @@ jobs:
pull-requests: write
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.0"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
steps:
- name: 📥 Clone repository
@@ -535,6 +542,11 @@ jobs:
package-lock.json
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/[email protected]
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
- name: 🚧 Install native dependencies
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -544,8 +556,7 @@ jobs:
brew install \
pkg-config \
openssl@3 \
llvm \
cargo-binstall
llvm
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
@@ -650,17 +661,20 @@ jobs:
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
find "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries" -name "*.dylib" -exec codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" {} \;
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
SUBMISSION_ID=$(xcrun notarytool submit "$ZIP_PATH" --wait --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | tee /dev/stderr | jq -r '.id')
STATUS=$(xcrun notarytool info "$SUBMISSION_ID" --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | jq -r '.status')
if [ "$STATUS" != "Accepted" ]; then
echo "Notarization failed with status: $STATUS"
xcrun notarytool log "$SUBMISSION_ID" --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
exit 1
fi
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
+1
View File
@@ -13,3 +13,4 @@ flamegraph.svg
.direnv
.DS_Store
.nvim.lua
/.devcontainer/devcontainer-lock.json
+14 -12
View File
@@ -1,10 +1,10 @@
{ pkgs, ... }:
let
version = "149.0.5+g6770623+chromium-149.0.7827.197";
version = "151.3.24+g2384915+chromium-151.0.7922.174";
hashes = {
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
};
selectSystem =
@@ -12,17 +12,19 @@ let
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
src = pkgs.fetchurl {
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
inherit url;
hash = selectSystem hashes;
};
in
pkgs.cef-binary.overrideAttrs (finalAttrs: {
pkgs.cef-binary.overrideAttrs {
version = builtins.head (builtins.split "\\+" version);
inherit src;
postInstall = ''
@@ -38,9 +40,9 @@ pkgs.cef-binary.overrideAttrs (finalAttrs: {
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
name = builtins.baseNameOf url;
sha1 = "";
}
}' > $out/archive.json
'';
})
}
+1
View File
@@ -6,6 +6,7 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
Generated
+2107 -476
View File
File diff suppressed because it is too large. Load diff
+27 -11
View File
@@ -11,10 +11,13 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/peer-transport",
"document/live",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"libraries/ipsum",
"libraries/wgpu-sync",
"node-graph/libraries/graphene-hash",
"node-graph/libraries/*",
@@ -40,6 +43,7 @@ default-members = [
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"libraries/ipsum",
"node-graph/graph-craft",
"node-graph/interpreted-executor",
"node-graph/node-macro",
@@ -56,7 +60,7 @@ edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0"
license = "MIT OR Apache-2.0"
version = "0.0.0"
readme = "README.md"
publish = false
@@ -80,6 +84,7 @@ no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
brush-nodes = { path = "node-graph/nodes/brush" }
blending-nodes = { path = "node-graph/nodes/blending" }
@@ -95,6 +100,8 @@ graph-craft = { path = "node-graph/graph-craft" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
peer-transport = { path = "document/peer-transport" }
document-live = { path = "document/live" }
raster-nodes = { path = "node-graph/nodes/raster" }
graphene-std = { path = "node-graph/nodes/gstd" }
interpreted-executor = { path = "node-graph/interpreted-executor" }
@@ -104,6 +111,7 @@ wgpu-sync = { path = "libraries/wgpu-sync" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
# Workspace dependencies
rustc-hash = "2.0"
@@ -139,7 +147,7 @@ wgpu = { version = "29.0", features = [
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.98"
web-sys = { version = "=0.3.98", features = [
@@ -160,16 +168,17 @@ web-sys = { version = "=0.3.98", features = [
"HtmlImageElement",
"ImageBitmapRenderingContext",
] }
winit = { git = "https://github.com/rust-windowing/winit.git" }
winit = "0.31.0-beta.2"
keyboard-types = "0.8"
url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.9"
vello_encoding = "0.9"
vello = "0.10"
vello_encoding = "0.10"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
@@ -190,6 +199,13 @@ image = { version = "0.25", default-features = false, features = [
"jpeg",
"bmp",
"gif",
"webp",
"tiff",
"ico",
"tga",
"hdr",
"exr",
"serde",
] }
pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
@@ -209,6 +225,7 @@ syn = { version = "2.0", default-features = false, features = [
"proc-macro",
] }
lyon_geom = "1.0"
delaunator = "1.0"
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
@@ -217,8 +234,8 @@ gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "149"
cef-dll-sys = "149"
cef = "151"
cef-dll-sys = "151"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
@@ -257,8 +274,7 @@ lto = "thin"
debug = true
[patch.crates-io]
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
dpi = { git = "https://github.com/rust-windowing/winit.git" }
winit = { git = "https://github.com/timon-schelling/winit", branch = "graphite" }
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
View File
File renamed without changes.
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) Graphite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3 -1
View File
@@ -80,4 +80,6 @@ Graphite is 100% community built and funded. Please become a part of keeping the
Are you a graphics programmer or Rust developer? Graphite aims to be one of the most approachable projects for putting your engineering skills to use in the world of open source. See [instructions here](https://graphite.art/volunteer/guide/) for setting up the project and getting started.
*By submitting code for inclusion in the project, you are agreeing to license your changes under the Apache 2.0 license, and that you have the authority to do so. Some directories may have other licenses, like dual-licensed MIT/Apache 2.0, and code submissions to those directories mean you agree to the applicable license(s).*
## License
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
+1 -2
View File
@@ -18,12 +18,11 @@ accepted = [
"NCSA", # Keep this list in sync with those in `/deny.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
"Unlicense", # Keep this list in sync with those in `/deny.toml`
]
workarounds = ["ring"]
ignore-build-dependencies = true
ignore-dev-dependencies = true
# Clearly Defined's API would occasionally (every few months) return errors for at least a full day (maybe some weird rate limiting?), but we can just disable to perform local checking (see #1653)
no-clearly-defined = true
# https://raw.githubusercontent.com/briansmith/webpki/main/LICENSE
# is the ISC license but test code within the repo is BSD-3-Clause, but is not compiled into the crate when we use it
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"contextLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphiLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"StrinLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+1
View File
@@ -82,6 +82,7 @@ allow = [
"NCSA", # Keep this list in sync with those in `/about.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
"Unlicense", # Keep this list in sync with those in `/about.toml`
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
+7 -7
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop"
version = "0.1.0"
description = "Graphite Desktop"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[[bin]]
name = "graphite"
@@ -44,12 +44,12 @@ rfd = { workspace = true }
open = { workspace = true }
lzma-rust2 = { workspace = true }
serde = { workspace = true }
url = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
clap = { workspace = true, features = ["derive"] }
interprocess = "2.4.2"
fd-lock = "4.0.4"
ctrlc = "3.5.1"
window_clipboard = "0.5"
# Windows-specific dependencies
[target.'cfg(target_os = "windows")'.dependencies]
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-bundle"
version = "0.0.0"
description = "Graphite Desktop Bundle"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
cef-dll-sys = { workspace = true }
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-embedded-resources"
version = "0.1.0"
description = "Graphite Desktop Embedded Resources"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
include_dir = { workspace = true }
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-platform-linux"
version = "0.0.0"
description = "Graphite Desktop Platform Linux"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[[bin]]
name = "graphite"
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-platform-mac"
version = "0.0.0"
description = "Graphite Desktop Platform Mac"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
main = ["dep:graphite-desktop"]
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-platform-win"
version = "0.0.0"
description = "Graphite Desktop Platform Windows"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[[bin]]
name = "graphite"
+132 -89
View File
@@ -9,19 +9,22 @@ use std::sync::mpsc::{Receiver, SyncSender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::data_transfer::{DataTransferSendBuilder, TypeHint};
use winit::dpi::PhysicalSize;
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
use winit::window::WindowId;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::input::InputState;
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::ui::{UiCommand, UiInstance};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
@@ -33,8 +36,9 @@ pub(crate) struct App {
window_maximized: bool,
window_fullscreen: bool,
window_pending_drag: bool,
pointer_position: PhysicalPosition<f64>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
pending_dnd_fetch: Option<AsyncRequestSerial>,
pending_clipboard_fetch: Option<AsyncRequestSerial>,
input_state: InputState,
ui_scale: f64,
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
@@ -106,8 +110,9 @@ impl App {
window_maximized: false,
window_fullscreen: false,
window_pending_drag: false,
pointer_position: Default::default(),
pointer_lock_position: Default::default(),
pending_dnd_fetch: None,
pending_clipboard_fetch: None,
input_state: InputState::new(),
ui_scale: 1.,
app_event_receiver,
app_event_scheduler,
@@ -125,8 +130,8 @@ impl App {
}
}
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
event_loop.run_app(&mut self).unwrap();
pub(crate) fn run(mut self, mut event_loop: EventLoop) -> ExitReason {
event_loop.run_app_on_demand(&mut self).unwrap();
self.exit_reason
}
@@ -200,15 +205,15 @@ impl App {
};
self.send_or_queue_web_message(bytes);
}
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
let app_event_scheduler = self.app_event_scheduler.clone();
let _ = thread::spawn(move || {
let mut dialog = AsyncFileDialog::new().set_title(title);
for filter in filters {
for filter in options.filters {
dialog = dialog.add_filter(filter.name, &filter.extensions);
}
let handles = if multiple {
let handles = if options.multiple {
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
} else {
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
@@ -218,7 +223,8 @@ impl App {
let path = handle.path().to_path_buf();
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
let action = action.clone();
let message = DesktopWrapperMessage::IngestFile { path, content, action };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
@@ -264,6 +270,8 @@ impl App {
});
}
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
if let Some(render_state) = &mut self.render_state
&& let Some(window) = &self.window
{
@@ -278,6 +286,9 @@ impl App {
render_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
}
}
DesktopFrontendMessage::WindowUpdateDirectInput { enabled } => {
self.input_state.set_direct_input(enabled);
}
DesktopFrontendMessage::UpdateUIScale { scale } => {
self.ui_scale = scale;
self.resize();
@@ -330,19 +341,13 @@ impl App {
}
}
DesktopFrontendMessage::ClipboardRead => {
if let Some(window) = &self.window {
let content = window.clipboard_read();
let message = DesktopWrapperMessage::ClipboardReadResult { content };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
self.app_event_scheduler.schedule(AppEvent::ClipboardRead);
}
DesktopFrontendMessage::ClipboardWrite { content } => {
if let Some(window) = &mut self.window {
window.clipboard_write(content);
}
self.app_event_scheduler.schedule(AppEvent::ClipboardWrite { content });
}
DesktopFrontendMessage::PointerLock => {
self.pointer_lock_position = Some(self.pointer_position);
self.input_state.lock_pointer();
if let Some(window) = &self.window {
window.start_pointer_lock();
}
@@ -462,6 +467,32 @@ impl App {
self.ui_frame_received = true;
}
}
AppEvent::ClipboardRead => {
let result = event_loop.clipboard().and_then(|id| {
let Some(id) = id else { return Ok(None) };
let data_transfer = event_loop.data_transfer(id)?;
if !data_transfer.has_type(&TypeHint::Plaintext) {
return Ok(None);
}
event_loop.fetch_data_transfer(id, &TypeHint::Plaintext).map(Some)
});
match result {
Ok(Some(serial)) => self.pending_clipboard_fetch = Some(serial),
Ok(None) => self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None }),
Err(e) => {
tracing::error!("Failed to read from clipboard: {e}");
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None });
}
}
}
AppEvent::ClipboardWrite { content } => {
let send_data = DataTransferSendBuilder::new(content)
.with_type(TypeHint::Plaintext, |content: &String, _| Some(content.clone()))
.build();
if let Err(e) = event_loop.set_clipboard(send_data) {
tracing::error!("Failed to write to clipboard: {e}");
}
}
AppEvent::CursorChange(cursor) => {
if let Some(window) = &mut self.window {
window.set_cursor(event_loop, cursor);
@@ -490,7 +521,11 @@ impl App {
for path in paths {
tracing::info!("Opening file: {}", path.display());
if let Ok(content) = fs::read(&path) {
let message = DesktopWrapperMessage::OpenFile { path, content };
let message = DesktopWrapperMessage::IngestFile {
path,
content,
action: IngestAction::Open,
};
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
} else {
tracing::error!("Failed to read file: {}", path.display());
@@ -533,28 +568,28 @@ 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
if let WindowEvent::PointerButton {
state: ElementState::Released,
button,
..
} = &event && button.clone().mouse_button() == Some(MouseButton::Left)
&& let Some(pointer_lock_position) = self.input_state.unlock_pointer()
{
self.pointer_lock_position = None;
if let Some(window) = &self.window {
window.end_pointer_lock();
}
self.ui.send(UiCommand::Input(WindowEvent::PointerMoved {
device_id: None,
position: pointer_lock_position,
primary: true,
source: winit::event::PointerSource::Mouse,
}));
self.ui.send(UiCommand::Input(
InputEvent::pointer().position(pointer_lock_position).moved().modifiers(self.input_state.modifiers()).build(),
));
}
self.ui.send(UiCommand::Input(event.clone()));
self.input_state.process(
&event,
|message| self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Input(message))),
|input| self.ui.send(UiCommand::Input(input)),
);
match event {
WindowEvent::CloseRequested => {
@@ -596,65 +631,73 @@ impl ApplicationHandler for App {
self.exit(Some(ExitReason::UiAccelerationFailure));
}
}
WindowEvent::DragDropped { paths, .. } => {
for path in paths {
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::ImportFile { path, content };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => {
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
return;
}
};
WindowEvent::DragEntered { id, .. } => {
let accepts = event_loop.data_transfer(id).is_ok_and(|data_transfer| data_transfer.has_type(&TypeHint::UriList));
let actions: &[DndAction] = if accepts { &[DndAction::Copy] } else { &[] };
if let Err(e) = event_loop.set_valid_dnd_actions(id, actions) {
tracing::error!("Failed to set valid drag and drop actions: {e}");
}
}
// Forward and Back buttons are not supported by CEF and thus need to be directly forwarded the editor
WindowEvent::PointerButton {
button: ButtonSource::Mouse(button),
state: ElementState::Pressed,
..
} => {
let mouse_keys = match button {
MouseButton::Back => Some(MouseKeys::BACK),
MouseButton::Forward => Some(MouseKeys::FORWARD),
_ => None,
};
if let Some(mouse_keys) = mouse_keys {
let message = DesktopWrapperMessage::Input(InputMessage::PointerDown {
editor_mouse_state: MouseState { mouse_keys, ..Default::default() },
modifier_keys: Default::default(),
});
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
let message = DesktopWrapperMessage::Input(InputMessage::PointerUp {
editor_mouse_state: Default::default(),
modifier_keys: Default::default(),
});
WindowEvent::DragDropped { id, .. } => match event_loop.fetch_data_transfer(id, &TypeHint::UriList) {
Ok(serial) => self.pending_dnd_fetch = Some(serial),
Err(e) => tracing::error!("Failed to fetch dropped data: {e}"),
},
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_clipboard_fetch == Some(serial) => match value.try_as_string() {
Ok(content) => {
self.pending_clipboard_fetch = None;
let message = DesktopWrapperMessage::ClipboardReadResult { content: Some(content) };
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;
if self.window_pending_drag {
self.window_pending_drag = false;
if let Some(window) = &self.window {
window.start_drag();
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => {
self.pending_clipboard_fetch = None;
tracing::error!("Failed to read from clipboard: {e}");
let message = DesktopWrapperMessage::ClipboardReadResult { content: None };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
},
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_dnd_fetch == Some(serial) => match value.try_as_uris() {
Ok(uris) => {
self.pending_dnd_fetch = None;
let paths = uris.iter().filter_map(|uri| url::Url::parse(uri).ok()?.to_file_path().ok());
for path in paths {
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::IngestFile {
path,
content,
action: IngestAction::Import,
};
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => {
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
return;
}
};
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => {
self.pending_dnd_fetch = None;
tracing::error!("Failed to read dropped data: {e}");
}
},
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
if !self.input_state.pointer_locked() && self.window_pending_drag =>
{
self.window_pending_drag = false;
if let Some(window) = &self.window {
window.start_drag();
}
}
WindowEvent::PointerButton {
button: ButtonSource::Mouse(MouseButton::Left),
button,
state: ElementState::Released,
..
} => {
} if button.clone().mouse_button() == Some(MouseButton::Left) => {
self.window_pending_drag = false;
}
@@ -663,7 +706,7 @@ impl ApplicationHandler for App {
}
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()
if self.input_state.pointer_locked()
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
{
let message = DesktopWrapperMessage::PointerLockMove { x, y };
+4
View File
@@ -8,6 +8,10 @@ pub(crate) enum AppEvent {
WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult),
ClipboardRead,
ClipboardWrite {
content: String,
},
Exit,
UiCrashed,
OpenFiles(Vec<std::path::PathBuf>),
+455
View File
@@ -0,0 +1,455 @@
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use winit::dpi::PhysicalPosition;
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
use winit::keyboard::ModifiersState;
use crate::ui::{InputEvent, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use crate::wrapper::messages::{EditorPointerState, InputMessage, ModifierKeys, MouseKeys, ScrollDelta};
// Marks input event as observe-only, meaning it should not result in any input messages being send by the frontend.
// And should instead be ignored by frontend input processing and only be used to update the UI state (hover, cursor).
// TODO(Timon): Remove and find a less hacky solution
trait ObserveOnlyExt {
fn observe_only(self) -> Self;
}
impl ObserveOnlyExt for crate::ui::InputEventBuilder {
fn observe_only(self) -> Self {
self.num_lock(true)
}
}
pub(crate) struct InputState {
start: Instant,
viewport_info: Option<ViewportInfo>,
direct_input: bool,
modifiers: ModifiersState,
pointer_position: PhysicalPosition<f64>,
pointer_state: PointerState,
click_tracker: ClickTracker,
shake_tracker: ShakeTracker,
}
impl InputState {
pub(crate) fn new() -> Self {
Self {
start: Instant::now(),
viewport_info: None,
direct_input: false,
modifiers: ModifiersState::default(),
pointer_position: PhysicalPosition::default(),
pointer_state: PointerState::Hover { route: Route::Ui },
click_tracker: ClickTracker::default(),
shake_tracker: ShakeTracker::default(),
}
}
pub(crate) fn set_viewport_info(&mut self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
}
pub(crate) fn set_direct_input(&mut self, enabled: bool) {
self.direct_input = enabled;
}
pub(crate) fn lock_pointer(&mut self) {
self.pointer_state = match self.pointer_state {
PointerState::Hover { route } => PointerState::Locked {
route,
keys: MouseKeys::empty(),
position: self.pointer_position,
},
PointerState::Stroke { route, keys } | PointerState::Locked { route, keys, .. } => PointerState::Locked {
route,
keys,
position: self.pointer_position,
},
};
}
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
let PointerState::Locked {
route: resume,
keys,
position: restore,
} = self.pointer_state
else {
return None;
};
self.pointer_position = restore;
self.pointer_state = match keys.is_empty() {
true => PointerState::Hover { route: Route::Ui },
false => PointerState::Stroke { route: resume, keys },
};
Some(restore)
}
pub(crate) fn pointer_locked(&self) -> bool {
matches!(self.pointer_state, PointerState::Locked { .. })
}
pub(crate) fn modifiers(&self) -> ModifiersState {
self.modifiers
}
pub(crate) fn process(&mut self, event: &WindowEvent, mut editor_callback: impl FnMut(InputMessage), mut ui_callback: impl FnMut(InputEvent)) {
match event {
WindowEvent::PointerMoved { position, source, .. } => {
self.pointer_position = *position;
let route = match self.pointer_state {
PointerState::Hover { .. } => {
let next = self.route(*position);
self.pointer_state = PointerState::Hover { route: next };
next
}
PointerState::Stroke { route, .. } => route,
PointerState::Locked { keys, route: resume, .. } => match keys.is_empty() {
true => Route::Ui,
false => resume,
},
};
match route {
Route::Ui => ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).build()),
Route::Editor => {
if !self.pointer_locked() {
ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).observe_only().build());
}
let editor_mouse_state = match source {
PointerSource::TabletTool { kind, data } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys();
if self.shake_tracker.detect(*position, self.start.elapsed()) {
editor_callback(InputMessage::PointerShake { editor_mouse_state, modifier_keys });
}
editor_callback(InputMessage::PointerMove { editor_mouse_state, modifier_keys });
}
}
}
WindowEvent::PointerEntered { position, .. } => {
self.pointer_position = *position;
ui_callback(InputEvent::pointer().position(*position).entered().modifiers(self.modifiers).build())
}
WindowEvent::PointerLeft { position: Some(position), .. } => {
self.pointer_position = *position;
ui_callback(InputEvent::pointer().position(*position).exited().modifiers(self.modifiers).build())
}
WindowEvent::PointerLeft { position: None, .. } => ui_callback(InputEvent::pointer().exited().modifiers(self.modifiers).build()),
WindowEvent::PointerButton { state, button, position, .. } => {
self.pointer_position = *position;
let mouse_button = button.clone().mouse_button();
let keys = match mouse_button {
Some(MouseButton::Left) => MouseKeys::LEFT,
Some(MouseButton::Right) => MouseKeys::RIGHT,
Some(MouseButton::Middle) => MouseKeys::MIDDLE,
Some(MouseButton::Back) => MouseKeys::BACK,
Some(MouseButton::Forward) => MouseKeys::FORWARD,
_ => MouseKeys::NONE,
};
let (pointer, route) = match self.pointer_state {
PointerState::Hover { route } => match (state.is_pressed(), keys.is_empty()) {
(true, false) => {
let route = self.route(*position);
(PointerState::Stroke { route, keys }, route)
}
(true, true) => (PointerState::Hover { route }, self.route(*position)),
(false, _) => (PointerState::Hover { route }, route),
},
PointerState::Stroke { route, keys: mut held } => {
match state.is_pressed() {
true => held.insert(keys),
false => held.remove(keys),
}
match held.is_empty() {
true => (PointerState::Hover { route }, route),
false => (PointerState::Stroke { route, keys: held }, route),
}
}
PointerState::Locked { route, keys: mut held, position } => {
let resume = if state.is_pressed() && held.is_empty() { Route::Ui } else { route };
match state.is_pressed() {
true => held.insert(keys),
false => held.remove(keys),
}
(PointerState::Locked { route: resume, keys: held, position }, Route::Ui)
}
};
self.pointer_state = pointer;
let count = mouse_button.map_or(1, |button| self.click_tracker.input(*position, button, *state));
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
let pointer = InputEvent::pointer().position(*position);
let input = match state {
ElementState::Pressed => pointer.pressed(button.clone(), count),
ElementState::Released => pointer.released(button.clone(), count),
}
.modifiers(self.modifiers);
if self.pointer_locked() || keys.is_empty() || !(back_or_forward || route == Route::Editor) {
ui_callback(input.build());
return;
}
if route == Route::Editor {
ui_callback(input.observe_only().build());
}
let editor_mouse_state = match button {
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys();
match state {
ElementState::Pressed => editor_callback(InputMessage::PointerDown { editor_mouse_state, modifier_keys }),
ElementState::Released if count % 2 == 0 => {
editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys });
editor_callback(InputMessage::DoubleClick {
editor_mouse_state: EditorPointerState {
mouse_keys: keys,
..editor_mouse_state
},
modifier_keys,
});
}
ElementState::Released => editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys }),
}
}
WindowEvent::MouseWheel { delta, .. } => {
if self.pointer_locked() || self.ui_captures(self.pointer_position) {
let input = match delta {
MouseScrollDelta::LineDelta(x, y) => InputEvent::pointer().scrolled_lines(f64::from(*x), f64::from(*y)),
MouseScrollDelta::PixelDelta(position) => InputEvent::pointer().scrolled_pixels(position.x, position.y),
_ => return,
};
ui_callback(input.modifiers(self.modifiers).build());
return;
}
let (x, y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
_ => return,
};
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys(),
});
}
WindowEvent::PinchGesture { delta, .. } => {
if self.pointer_locked() || self.ui_captures(self.pointer_position) || !delta.is_normal() {
ui_callback(InputEvent::pointer().zoomed(*delta).modifiers(self.modifiers).build());
return;
}
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys() | ModifierKeys::CONTROL,
});
}
WindowEvent::ModifiersChanged(modifiers) => {
self.modifiers = modifiers.state();
}
WindowEvent::KeyboardInput { event, .. } => ui_callback(InputEvent::key(event).modifiers(self.modifiers).build()),
_ => {}
}
}
fn scale(&self) -> f64 {
self.viewport_info.as_ref().map_or(1., |info| info.scale)
}
fn ui_captures(&self, position: PhysicalPosition<f64>) -> bool {
!self.direct_input || !self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
}
fn route(&self, position: PhysicalPosition<f64>) -> Route {
if self.ui_captures(position) { Route::Ui } else { Route::Editor }
}
fn pointer_keys(&self) -> MouseKeys {
match self.pointer_state {
PointerState::Hover { .. } => MouseKeys::empty(),
PointerState::Stroke { keys, .. } | PointerState::Locked { keys, .. } => keys,
}
}
fn pointer_state(&self) -> EditorPointerState {
EditorPointerState {
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
mouse_keys: self.pointer_keys(),
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
..Default::default()
}
}
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> EditorPointerState {
EditorPointerState {
pressure: data.force.map(|force| force.normalized(None)),
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
twist: data.twist.map(f64::from),
wheel: data.tangential_force.map(f64::from),
eraser: matches!(kind, TabletToolKind::Eraser),
..self.pointer_state()
}
}
fn modifier_keys(&self) -> ModifierKeys {
let mut keys = ModifierKeys::empty();
keys.set(ModifierKeys::SHIFT, self.modifiers.shift_key());
keys.set(ModifierKeys::CONTROL, self.modifiers.control_key());
keys.set(ModifierKeys::ALT, self.modifiers.alt_key());
keys.set(ModifierKeys::META_OR_COMMAND, self.modifiers.meta_key());
keys
}
}
#[derive(Clone, Copy)]
enum PointerState {
Hover { route: Route },
Stroke { route: Route, keys: MouseKeys },
Locked { route: Route, keys: MouseKeys, position: PhysicalPosition<f64> },
}
#[derive(Clone, Copy, PartialEq)]
enum Route {
Ui,
Editor,
}
struct ViewportInfo {
x: f64,
y: f64,
width: f64,
height: f64,
scale: f64,
}
impl ViewportInfo {
fn contains(&self, position: PhysicalPosition<f64>) -> bool {
position.x >= self.x && position.y >= self.y && position.x <= self.x + self.width && position.y <= self.y + self.height
}
}
#[derive(Default)]
struct ClickTracker {
left: ClickChains,
right: ClickChains,
middle: ClickChains,
back: ClickChains,
forward: ClickChains,
}
impl ClickTracker {
fn input(&mut self, position: PhysicalPosition<f64>, button: MouseButton, state: ElementState) -> u32 {
let position = (position.x as i32, position.y as i32);
let clicks = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
MouseButton::Back => &mut self.back,
MouseButton::Forward => &mut self.forward,
_ => return 1,
};
let chain = match state {
ElementState::Pressed => &mut clicks.down,
ElementState::Released => &mut clicks.up,
};
let now = Instant::now();
let count = match chain {
Some(previous) => {
let within_time = now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT;
let dx = position.0.abs_diff(previous.position.0) as usize;
let dy = position.1.abs_diff(previous.position.1) as usize;
let within_distance = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
if within_time && within_distance { previous.count.saturating_add(1) } else { 1 }
}
None => 1,
};
*chain = Some(Click { time: now, position, count });
count
}
}
#[derive(Default)]
struct ClickChains {
down: Option<Click>,
up: Option<Click>,
}
struct Click {
time: Instant,
position: (i32, i32),
count: u32,
}
#[derive(Default)]
struct ShakeTracker {
samples: VecDeque<(PhysicalPosition<f64>, Duration)>,
last: Option<Duration>,
}
// Keep heuristic and constants in sync with `detectShake` in `frontend/src/utility-functions/input.ts`.
impl ShakeTracker {
const SENSITIVITY_DIRECTION_CHANGES: usize = 3;
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO: f64 = 0.1;
const DETECTION_WINDOW: Duration = Duration::from_millis(500);
const DEBOUNCE: Duration = Duration::from_millis(1000);
fn detect(&mut self, position: PhysicalPosition<f64>, now: Duration) -> bool {
self.samples.push_back((position, now));
while self.samples.front().is_some_and(|&(_, time)| now.saturating_sub(time) > Self::DETECTION_WINDOW) {
self.samples.pop_front();
}
if self.samples.len() <= 3 || self.last.is_some_and(|time| now.saturating_sub(time) <= Self::DEBOUNCE) {
return false;
}
let mut total_distance_squared = 0.;
for i in 1..self.samples.len() {
let (p1, _) = self.samples[i - 1];
let (p2, _) = self.samples[i];
total_distance_squared += (p2.x - p1.x).powi(2) + (p2.y - p1.y).powi(2);
}
let mut direction_changes = 0;
let mut average = PhysicalPosition::new(0., 0.);
let interior_count = self.samples.len() - 2;
for i in 0..interior_count {
let (p1, _) = self.samples[i];
let (p2, _) = self.samples[i + 1];
let (p3, _) = self.samples[i + 2];
let vector1 = (p2.x - p1.x, p2.y - p1.y);
let vector2 = (p3.x - p2.x, p3.y - p2.y);
if vector1.0 * vector2.0 + vector1.1 * vector2.1 < 0. {
direction_changes += 1;
}
average.x += p2.x;
average.y += p2.y;
}
average.x /= interior_count as f64;
average.y /= interior_count as f64;
let (last, _) = self.samples[self.samples.len() - 1];
let displacement_squared = (last.x - average.x).powi(2) + (last.y - average.y).powi(2);
if Self::SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * total_distance_squared >= displacement_squared && direction_changes >= Self::SENSITIVITY_DIRECTION_CHANGES {
self.last = Some(now);
self.samples.clear();
return true;
}
false
}
}
+1
View File
@@ -17,6 +17,7 @@ mod cli;
mod dirs;
mod event;
mod gpu_context;
mod input;
mod persist;
mod preferences;
mod render;
+4 -5
View File
@@ -52,13 +52,12 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return srgb_to_linear(immediates.background_color);
}
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
if (ui_linear.a >= 0.999) {
return ui_linear;
let ui_sample = textureSample(t_ui, s_diffuse, ui_coordinate);
if (ui_sample.a >= 0.999) {
return srgb_to_linear(ui_sample);
}
// UI texture is premultiplied, we need to unpremultiply before blending
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
let ui_srgb = unpremultiply(ui_sample);
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
+9 -9
View File
@@ -1,7 +1,7 @@
use wgpu::PresentMode;
use crate::window::Window;
use crate::wrapper::{WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
use crate::wrapper::{Texture, WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
#[derive(derivative::Derivative)]
#[derivative(Debug)]
@@ -10,14 +10,14 @@ pub(crate) struct RenderState {
executor: WgpuExecutor,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
transparent_texture: std::sync::Arc<wgpu::Texture>,
transparent_texture: Texture,
sampler: wgpu::Sampler,
desired_width: u32,
desired_height: u32,
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
viewport_texture: Option<Texture>,
overlays_texture: Option<Texture>,
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
@@ -46,8 +46,8 @@ impl RenderState {
surface.configure(&context.device, &config);
let transparent_texture = std::sync::Arc::new(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("Transparent Texture"),
let transparent_texture = Texture::from(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("transparent_fallback"),
size: wgpu::Extent3d {
width: 1,
height: 1,
@@ -193,7 +193,7 @@ impl RenderState {
self.surface_outdated = true;
}
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: std::sync::Arc<wgpu::Texture>) {
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: Texture) {
self.viewport_texture = Some(viewport_texture);
self.update_bindgroup();
}
@@ -228,10 +228,10 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
match result {
Ok(texture) => {
self.overlays_texture = Some(texture.into());
self.overlays_texture = Some(texture);
}
Err(e) => {
self.overlays_texture = None;
-33
View File
@@ -43,13 +43,6 @@ pub(crate) struct Window {
#[allow(dead_code)]
native_handle: native::NativeWindowImpl,
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
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 {
@@ -70,12 +63,10 @@ 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) }.ok();
Self {
winit_window: winit_window.into(),
native_handle,
custom_cursors: HashMap::new(),
clipboard,
}
}
@@ -208,28 +199,4 @@ impl Window {
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
self.native_handle.update_menu(entries);
}
pub(crate) fn clipboard_read(&self) -> Option<String> {
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}");
None
}
}
}
pub(crate) fn clipboard_write(&mut self, data: String) {
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}")
}
}
}
+8
View File
@@ -344,6 +344,14 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
let outer = unsafe { CreateRectRgn(0, 0, w, h) };
let inner = unsafe { CreateRectRgn(RESIZE_BAND_THICKNESS, RESIZE_BAND_THICKNESS, w - RESIZE_BAND_THICKNESS, h - RESIZE_BAND_THICKNESS) };
let _ = unsafe { CombineRgn(Some(outer), Some(outer), Some(inner), RGN_DIFF) };
let _ = unsafe { DeleteObject(inner.into()) };
if unsafe { SetWindowRgn(helper, Some(outer), false) } == 0 {
let _ = unsafe { DeleteObject(outer.into()) };
}
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
+3 -1
View File
@@ -2,9 +2,11 @@
name = "graphite-desktop-ui"
description = "Renders the Graphite editor frontend UI into wgpu textures"
version.workspace = true
authors.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
default = []
+18 -18
View File
@@ -1,5 +1,23 @@
use std::time::Duration;
pub const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
pub const SCROLL_LINE_HEIGHT: f64 = 40.;
pub const SCROLL_LINE_WIDTH: f64 = 40.;
#[cfg(target_os = "linux")]
pub const SCROLL_SPEED_X: f64 = 3.;
#[cfg(target_os = "linux")]
pub const SCROLL_SPEED_Y: f64 = 3.;
#[cfg(not(target_os = "linux"))]
pub const SCROLL_SPEED_X: f64 = 1.;
#[cfg(not(target_os = "linux"))]
pub const SCROLL_SPEED_Y: f64 = 1.;
pub const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
@@ -17,21 +35,3 @@ pub(crate) const HOST_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(target_os = "macos")]
pub(crate) const IPC_BOOTSTRAP_PREFIX: &str = "art.graphite.Graphite.ipc.";
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
+4 -6
View File
@@ -223,6 +223,7 @@ fn create_browser(delegate: BrowserDelegate, frames: FrameStreamer, view_info_se
.map(|browser| BrowserContext {
delegate,
browser,
input: input::InputState::default(),
view_info_sender,
_instance_dir: instance_dir,
})
@@ -252,12 +253,8 @@ pub(crate) enum InitError {
pub(crate) struct CefContextHandle;
impl CefContextHandle {
pub(crate) fn apply_input(&self, events: Vec<InputEvent>) {
with_context(move |context| {
for event in &events {
input::apply(&context.browser, event);
}
});
pub(crate) fn process_input(&self, event: InputEvent) {
with_context(move |context| input::process(&mut context.input, &context.browser, &event));
}
pub(crate) fn update_view_info(&self, update: ViewInfoUpdate) {
@@ -276,6 +273,7 @@ impl CefContextHandle {
struct BrowserContext {
delegate: BrowserDelegate,
browser: Browser,
input: input::InputState,
view_info_sender: Sender<ViewInfoUpdate>,
_instance_dir: TempDir,
}
+195 -211
View File
@@ -1,251 +1,235 @@
use cef::sys::{cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
pub(crate) mod event;
pub(crate) use event::InputEvent;
mod keymap;
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
mod state;
pub(crate) use state::{CefModifiers, InputState};
use cef::sys::{cef_event_flags_t, cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::dpi::PhysicalPosition;
use winit::keyboard::{Key, KeyLocation, NamedKey};
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use event::{InputEventKind, KeyAction, Modifiers, MouseButton, PointerAction};
/// A window input translated into the plain data CEF consumes — no winit types, so it can
/// be applied to a browser living in another process.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum InputEvent {
MouseMove { data: MouseData, leave: bool },
MouseClick { data: MouseData, button: MouseButtonKind, up: bool, click_count: i32 },
MouseWheel { data: MouseData, delta_x: i32, delta_y: i32 },
Key(KeyData),
#[derive(Default)]
pub(crate) struct InputState {
position: PhysicalPosition<f64>,
buttons: ButtonStates,
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct MouseData {
pub(crate) x: i32,
pub(crate) y: i32,
pub(crate) modifiers: u32,
impl InputState {
fn pointer_move(&mut self, position: PhysicalPosition<f64>) -> bool {
let moved = (position.x as i32, position.y as i32) != (self.position.x as i32, self.position.y as i32);
self.position = position;
moved
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum MouseButtonKind {
Left,
Right,
Middle,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum KeyEventKind {
RawKeyDown,
KeyUp,
Char,
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct KeyData {
pub(crate) kind: KeyEventKind,
pub(crate) modifiers: u32,
pub(crate) windows_key_code: i32,
pub(crate) native_key_code: i32,
pub(crate) character: u16,
pub(crate) unmodified_character: u16,
}
/// Turns a winit event into zero or more [`InputEvent`]s, updating the tracked input state
/// (cursor position, click counting, modifiers) along the way.
pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Vec<InputEvent> {
match event {
WindowEvent::PointerMoved { position, .. } => {
if !input_state.cursor_move(position) {
return Vec::new();
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
WindowEvent::PointerEntered { position, .. } => {
let _ = input_state.cursor_move(position);
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
WindowEvent::PointerLeft { position, .. } => {
if let Some(position) = position {
let _ = input_state.cursor_move(position);
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: true,
}]
}
WindowEvent::PointerButton { state, button, position, .. } => {
let mouse_button = match button {
ButtonSource::Mouse(mouse_button) => mouse_button,
_ => {
return Vec::new(); // TODO: Handle touch input
pub(crate) fn process(state: &mut InputState, browser: &Browser, event: &InputEvent) {
let Some(host) = browser.host() else { return };
match &event.kind {
InputEventKind::Pointer { position, action } => {
let position = position.unwrap_or(state.position);
match *action {
PointerAction::Move => {
if !state.pointer_move(position) {
return;
}
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
}
};
PointerAction::Enter => {
state.pointer_move(position);
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
}
PointerAction::Exit => {
state.pointer_move(position);
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 1);
}
PointerAction::Press { button, count } | PointerAction::Release { button, count } => {
state.pointer_move(position);
let cef_button = match button {
MouseButton::Left => cef_mouse_button_type_t::MBT_LEFT,
MouseButton::Right => cef_mouse_button_type_t::MBT_RIGHT,
MouseButton::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
MouseButton::Unknown => return,
};
let up = matches!(action, PointerAction::Release { .. });
state.buttons.update(button, !up);
let _ = input_state.cursor_move(position);
let click_count = input_state.mouse_input(mouse_button, state).into();
let up = matches!(state, ElementState::Released);
let button = match mouse_button {
MouseButton::Left => MouseButtonKind::Left,
MouseButton::Right => MouseButtonKind::Right,
MouseButton::Middle => MouseButtonKind::Middle,
_ => return Vec::new(),
};
// CEF only understands single, double and triple clicks; further clicks alternate between double and triple.
let count = match count {
0 | 1 => 1,
count if count % 2 == 0 => 2,
_ => 3,
};
vec![InputEvent::MouseClick {
data: input_state.mouse_data(),
button,
up,
click_count,
}]
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_click_event(Some(&mouse_event(position, flags)), cef::MouseButtonType::from(cef_button), up as i32, count);
}
PointerAction::ScrollLines { x, y } => {
let flags = event_flags(&event.modifiers, &state.buttons);
let delta_x = (x * SCROLL_LINE_WIDTH * SCROLL_SPEED_X) as i32;
let delta_y = (y * SCROLL_LINE_HEIGHT * SCROLL_SPEED_Y) as i32;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), delta_x, delta_y);
}
PointerAction::ScrollPixels { x, y } => {
let flags = event_flags(&event.modifiers, &state.buttons) | PRECISION_SCROLLING_DELTA;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), (x * SCROLL_SPEED_X) as i32, (y * SCROLL_SPEED_Y) as i32);
}
PointerAction::Zoom(delta) => {
if !delta.is_normal() {
return;
}
let flags = CONTROL_DOWN | PRECISION_SCROLLING_DELTA;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), 0, (delta * PINCH_ZOOM_SPEED).round() as i32);
}
}
}
WindowEvent::MouseWheel { delta, phase: _, device_id: _, .. } => {
let (mut delta_x, mut delta_y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
};
delta_x *= SCROLL_SPEED_X;
delta_y *= SCROLL_SPEED_Y;
InputEventKind::Key {
key,
key_without_modifiers,
physical_key,
location,
text,
action,
} => {
let mut flags = event_flags(&event.modifiers, &state.buttons);
vec![InputEvent::MouseWheel {
data: input_state.mouse_data(),
delta_x: delta_x as i32,
delta_y: delta_y as i32,
}]
}
WindowEvent::ModifiersChanged(modifiers) => {
input_state.modifiers_changed(&modifiers.state());
Vec::new()
}
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
let mut kind = match (event.state, &event.logical_key) {
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => KeyEventKind::Char,
(ElementState::Pressed, _) => KeyEventKind::RawKeyDown,
(ElementState::Released, _) => KeyEventKind::KeyUp,
};
let modifiers = input_state.cef_modifiers(&event.location, event.repeat).into();
let windows_key_code = match &event.logical_key {
winit::keyboard::Key::Named(named) => named.to_vk_bits(),
winit::keyboard::Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
let own_flag = match key {
Key::Named(NamedKey::Shift) => SHIFT_DOWN,
Key::Named(NamedKey::Control) => CONTROL_DOWN,
Key::Named(NamedKey::Alt) => ALT_DOWN,
Key::Named(NamedKey::AltGraph) => ALTGR_DOWN,
Key::Named(NamedKey::Meta) => COMMAND_DOWN,
_ => 0,
};
match action {
KeyAction::Press | KeyAction::Repeat => flags |= own_flag,
KeyAction::Release => flags &= !own_flag,
}
let native_key_code = event.physical_key.to_native_keycode();
flags |= match location {
KeyLocation::Left => IS_LEFT,
KeyLocation::Right => IS_RIGHT,
KeyLocation::Numpad => IS_KEY_PAD,
KeyLocation::Standard => 0,
};
if *action == KeyAction::Repeat {
flags |= IS_REPEAT;
}
let char_representation = event.logical_key.to_char_representation();
let windows_key_code = match key {
Key::Named(named) => named.to_vk_bits(),
Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
_ => 0,
};
let native_key_code = physical_key.to_native_keycode();
let char_representation = key.to_char_representation();
#[allow(unused_mut)]
let mut character = char_representation as u16;
if event.state == ElementState::Pressed && character != 0 {
kind = KeyEventKind::Char;
}
let unmodified_character = event.key_without_modifiers.to_char_representation() as u16;
let unmodified_character = key_without_modifiers.to_char_representation() as u16;
#[cfg(target_os = "macos")] // See https://www.magpcss.org/ceforum/viewtopic.php?start=10&t=11650
if character == 0 && unmodified_character == 0 && event.text_with_all_modifiers.is_some() {
if character == 0 && unmodified_character == 0 && text.is_some() {
character = 1;
}
#[cfg(not(target_os = "macos"))]
let _ = text;
let key = KeyData {
kind,
modifiers,
let key_event = |kind: cef_key_event_type_t, windows_key_code: i32| KeyEvent {
type_: kind.into(),
modifiers: flags,
windows_key_code,
native_key_code,
character,
unmodified_character,
};
if kind == KeyEventKind::Char {
// CEF expects a raw key-down before the character event it produces.
vec![
InputEvent::Key(KeyData {
kind: KeyEventKind::RawKeyDown,
..key
}),
InputEvent::Key(KeyData {
windows_key_code: char_representation as i32,
..key
}),
]
} else {
vec![InputEvent::Key(key)]
}
}
WindowEvent::PinchGesture { delta, .. } => {
if !delta.is_normal() {
return Vec::new();
}
let data = MouseData {
modifiers: CefModifiers::PINCH_MODIFIERS.into(),
..input_state.mouse_data()
};
vec![InputEvent::MouseWheel {
data,
delta_x: 0,
delta_y: (delta * PINCH_ZOOM_SPEED).round() as i32,
}]
}
_ => Vec::new(),
}
}
/// Sends a translated [`InputEvent`] to the browser. Must run on the thread owning the browser.
pub(crate) fn apply(browser: &Browser, event: &InputEvent) {
let Some(host) = browser.host() else { return };
match event {
InputEvent::MouseMove { data, leave } => {
host.send_mouse_move_event(Some(&data.into()), *leave as i32);
}
InputEvent::MouseClick { data, button, up, click_count } => {
let cef_button = cef::MouseButtonType::from(match button {
MouseButtonKind::Left => cef_mouse_button_type_t::MBT_LEFT,
MouseButtonKind::Right => cef_mouse_button_type_t::MBT_RIGHT,
MouseButtonKind::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
});
host.send_mouse_click_event(Some(&data.into()), cef_button, *up as i32, *click_count);
}
InputEvent::MouseWheel { data, delta_x, delta_y } => {
host.send_mouse_wheel_event(Some(&data.into()), *delta_x, *delta_y);
}
InputEvent::Key(key) => {
let key_event = KeyEvent {
type_: match key.kind {
KeyEventKind::RawKeyDown => cef_key_event_type_t::KEYEVENT_RAWKEYDOWN,
KeyEventKind::KeyUp => cef_key_event_type_t::KEYEVENT_KEYUP,
KeyEventKind::Char => cef_key_event_type_t::KEYEVENT_CHAR,
}
.into(),
modifiers: key.modifiers,
windows_key_code: key.windows_key_code,
native_key_code: key.native_key_code,
character: key.character,
unmodified_character: key.unmodified_character,
..Default::default()
};
host.send_key_event(Some(&key_event));
match action {
KeyAction::Press | KeyAction::Repeat if char_representation != '\0' => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_CHAR, char_representation as i32)));
}
KeyAction::Press | KeyAction::Repeat => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
}
KeyAction::Release => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_KEYUP, windows_key_code)));
}
}
}
}
}
impl From<&MouseData> for MouseEvent {
fn from(data: &MouseData) -> Self {
MouseEvent {
x: data.x,
y: data.y,
modifiers: data.modifiers,
#[derive(Default)]
struct ButtonStates {
left: bool,
right: bool,
middle: bool,
}
impl ButtonStates {
fn update(&mut self, button: MouseButton, held: bool) {
match button {
MouseButton::Left => self.left = held,
MouseButton::Right => self.right = held,
MouseButton::Middle => self.middle = held,
MouseButton::Unknown => {}
}
}
}
fn mouse_event(position: PhysicalPosition<f64>, flags: u32) -> MouseEvent {
MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: flags,
}
}
fn event_flags(modifiers: &Modifiers, buttons: &ButtonStates) -> u32 {
let bit = |condition: bool, flag: u32| if condition { flag } else { 0 };
bit(modifiers.shift, SHIFT_DOWN)
| bit(modifiers.control, CONTROL_DOWN)
| bit(modifiers.alt, ALT_DOWN)
| bit(modifiers.alt_graph, ALTGR_DOWN)
| bit(modifiers.meta, COMMAND_DOWN)
| bit(modifiers.caps_lock, CAPS_LOCK_ON)
| bit(modifiers.num_lock, NUM_LOCK_ON)
| bit(buttons.left, LEFT_MOUSE_BUTTON)
| bit(buttons.right, RIGHT_MOUSE_BUTTON)
| bit(buttons.middle, MIDDLE_MOUSE_BUTTON)
}
const fn flag(flag: cef_event_flags_t) -> u32 {
#[cfg(not(target_os = "windows"))]
{
flag.0
}
#[cfg(target_os = "windows")]
{
flag.0 as u32
}
}
const SHIFT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_SHIFT_DOWN);
const CONTROL_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_CONTROL_DOWN);
const ALT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALT_DOWN);
const ALTGR_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALTGR_DOWN);
const COMMAND_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_COMMAND_DOWN);
const CAPS_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_CAPS_LOCK_ON);
const NUM_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_NUM_LOCK_ON);
const LEFT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON);
const MIDDLE_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON);
const RIGHT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON);
const IS_LEFT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_LEFT);
const IS_RIGHT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_RIGHT);
const IS_KEY_PAD: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_KEY_PAD);
const IS_REPEAT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_REPEAT);
const PRECISION_SCROLLING_DELTA: u32 = flag(cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA);
+245
View File
@@ -0,0 +1,245 @@
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, KeyEvent};
use winit::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey, SmolStr};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct InputEvent {
pub(crate) kind: InputEventKind,
pub(crate) modifiers: Modifiers,
}
impl InputEvent {
pub fn pointer() -> PointerInputEventBuilder {
PointerInputEventBuilder { position: UnknownPosition }
}
pub fn key(event: &KeyEvent) -> InputEventBuilder {
let action = match (event.state, event.repeat) {
(ElementState::Pressed, false) => KeyAction::Press,
(ElementState::Pressed, true) => KeyAction::Repeat,
(ElementState::Released, _) => KeyAction::Release,
};
InputEventBuilder::new(InputEventKind::Key {
key: event.logical_key.clone(),
key_without_modifiers: event.key_without_modifiers.clone(),
physical_key: event.physical_key,
location: event.location,
text: event.text_with_all_modifiers.clone(),
action,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MouseButton {
Left,
Right,
Middle,
Unknown,
}
impl From<winit::event::MouseButton> for MouseButton {
fn from(button: winit::event::MouseButton) -> Self {
match button {
winit::event::MouseButton::Left => Self::Left,
winit::event::MouseButton::Right => Self::Right,
winit::event::MouseButton::Middle => Self::Middle,
_ => Self::Unknown,
}
}
}
impl From<winit::event::ButtonSource> for MouseButton {
fn from(button: winit::event::ButtonSource) -> Self {
button.mouse_button().map_or(Self::Unknown, Self::from)
}
}
#[must_use]
#[derive(Clone, Debug)]
pub struct PointerInputEventBuilder<P = UnknownPosition> {
position: P,
}
impl PointerInputEventBuilder<UnknownPosition> {
pub fn position(self, position: PhysicalPosition<f64>) -> PointerInputEventBuilder<PhysicalPosition<f64>> {
PointerInputEventBuilder { position }
}
}
impl PointerInputEventBuilder<PhysicalPosition<f64>> {
pub fn moved(self) -> InputEventBuilder {
self.finish(PointerAction::Move)
}
pub fn entered(self) -> InputEventBuilder {
self.finish(PointerAction::Enter)
}
}
impl<P: PointerPosition> PointerInputEventBuilder<P> {
pub fn exited(self) -> InputEventBuilder {
self.finish(PointerAction::Exit)
}
pub fn pressed(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
self.finish(PointerAction::Press { button: button.into(), count })
}
pub fn released(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
self.finish(PointerAction::Release { button: button.into(), count })
}
pub fn scrolled_lines(self, x: f64, y: f64) -> InputEventBuilder {
self.finish(PointerAction::ScrollLines { x, y })
}
pub fn scrolled_pixels(self, x: f64, y: f64) -> InputEventBuilder {
self.finish(PointerAction::ScrollPixels { x, y })
}
pub fn zoomed(self, delta: f64) -> InputEventBuilder {
self.finish(PointerAction::Zoom(delta))
}
fn finish(self, action: PointerAction) -> InputEventBuilder {
InputEventBuilder::new(InputEventKind::Pointer {
position: self.position.position(),
action,
})
}
}
#[must_use]
#[derive(Clone, Debug)]
pub struct InputEventBuilder {
kind: InputEventKind,
modifiers: Modifiers,
}
impl InputEventBuilder {
fn new(kind: InputEventKind) -> Self {
Self {
kind,
modifiers: Modifiers::default(),
}
}
pub fn shift(mut self, on: bool) -> Self {
self.modifiers.shift = on;
self
}
pub fn control(mut self, on: bool) -> Self {
self.modifiers.control = on;
self
}
pub fn alt(mut self, on: bool) -> Self {
self.modifiers.alt = on;
self
}
pub fn alt_graph(mut self, on: bool) -> Self {
self.modifiers.alt_graph = on;
self
}
pub fn meta(mut self, on: bool) -> Self {
self.modifiers.meta = on;
self
}
pub fn caps_lock(mut self, on: bool) -> Self {
self.modifiers.caps_lock = on;
self
}
pub fn num_lock(mut self, on: bool) -> Self {
self.modifiers.num_lock = on;
self
}
pub fn modifiers(mut self, modifiers: ModifiersState) -> Self {
self.modifiers.shift = modifiers.shift_key();
self.modifiers.control = modifiers.control_key();
self.modifiers.alt = modifiers.alt_key();
self.modifiers.meta = modifiers.meta_key();
self
}
pub fn build(self) -> InputEvent {
InputEvent {
kind: self.kind,
modifiers: self.modifiers,
}
}
}
#[expect(private_bounds)]
pub trait PointerPosition: OptionalPosition {}
impl PointerPosition for UnknownPosition {}
impl PointerPosition for PhysicalPosition<f64> {}
#[derive(Clone, Copy, Debug)]
pub struct UnknownPosition;
trait OptionalPosition {
fn position(self) -> Option<PhysicalPosition<f64>>;
}
impl OptionalPosition for UnknownPosition {
fn position(self) -> Option<PhysicalPosition<f64>> {
None
}
}
impl OptionalPosition for PhysicalPosition<f64> {
fn position(self) -> Option<PhysicalPosition<f64>> {
Some(self)
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum InputEventKind {
Pointer {
position: Option<PhysicalPosition<f64>>,
action: PointerAction,
},
Key {
key: Key,
key_without_modifiers: Key,
physical_key: PhysicalKey,
location: KeyLocation,
text: Option<SmolStr>,
action: KeyAction,
},
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum PointerAction {
Move,
Enter,
Exit,
Press { button: MouseButton, count: u32 },
Release { button: MouseButton, count: u32 },
ScrollLines { x: f64, y: f64 },
ScrollPixels { x: f64, y: f64 },
Zoom(f64),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum KeyAction {
Press,
Repeat,
Release,
}
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub(crate) struct Modifiers {
pub(crate) shift: bool,
pub(crate) control: bool,
pub(crate) alt: bool,
pub(crate) alt_graph: bool,
pub(crate) meta: bool,
pub(crate) caps_lock: bool,
pub(crate) num_lock: bool,
}
-256
View File
@@ -1,256 +0,0 @@
use cef::sys::cef_event_flags_t;
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, MouseButton};
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
use super::MouseData;
use crate::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
#[derive(Default)]
pub(crate) struct InputState {
modifiers: ModifiersState,
mouse_position: MousePosition,
mouse_state: MouseState,
mouse_click_tracker: ClickTracker,
}
impl InputState {
pub(crate) fn modifiers_changed(&mut self, modifiers: &ModifiersState) {
self.modifiers = *modifiers;
}
pub(crate) fn modifiers_apply_key_event(&mut self, key: &Key, state: &ElementState) {
let bits = match key {
Key::Named(NamedKey::Shift) => ModifiersState::SHIFT,
Key::Named(NamedKey::Control) => ModifiersState::CONTROL,
Key::Named(NamedKey::Alt) => ModifiersState::ALT,
Key::Named(NamedKey::Meta) => ModifiersState::META,
_ => return,
};
let is_pressed = matches!(state, ElementState::Pressed);
self.modifiers.set(bits, is_pressed);
}
pub(crate) fn cursor_move(&mut self, position: &PhysicalPosition<f64>) -> bool {
let new = position.into();
if self.mouse_position == new {
return false;
}
self.mouse_position = new;
true
}
pub(crate) fn mouse_input(&mut self, button: &MouseButton, state: &ElementState) -> ClickCount {
self.mouse_state.update(button, state);
self.mouse_click_tracker.input(button, state, self.mouse_position)
}
pub(crate) fn cef_modifiers(&self, location: &KeyLocation, is_repeat: bool) -> CefModifiers {
CefModifiers::new(self, location, is_repeat)
}
pub(crate) fn cef_mouse_modifiers(&self) -> CefModifiers {
self.cef_modifiers(&KeyLocation::Standard, false)
}
pub(crate) fn mouse_data(&self) -> MouseData {
MouseData {
x: self.mouse_position.x,
y: self.mouse_position.y,
modifiers: self.cef_mouse_modifiers().into(),
}
}
}
#[derive(Default, Clone, Copy, Eq, PartialEq)]
pub(crate) struct MousePosition {
x: i32,
y: i32,
}
impl From<&PhysicalPosition<f64>> for MousePosition {
fn from(position: &PhysicalPosition<f64>) -> Self {
Self {
x: position.x as i32,
y: position.y as i32,
}
}
}
#[derive(Default, Clone)]
pub(crate) struct MouseState {
left: bool,
right: bool,
middle: bool,
}
impl MouseState {
pub(crate) fn update(&mut self, button: &MouseButton, state: &ElementState) {
match state {
ElementState::Pressed => match button {
MouseButton::Left => self.left = true,
MouseButton::Right => self.right = true,
MouseButton::Middle => self.middle = true,
_ => {}
},
ElementState::Released => match button {
MouseButton::Left => self.left = false,
MouseButton::Right => self.right = false,
MouseButton::Middle => self.middle = false,
_ => {}
},
}
}
}
#[derive(Default)]
struct ClickTracker {
left: Option<ClickRecord>,
middle: Option<ClickRecord>,
right: Option<ClickRecord>,
}
impl ClickTracker {
fn input(&mut self, button: &MouseButton, state: &ElementState, position: MousePosition) -> ClickCount {
let record = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
_ => return ClickCount::Single,
};
let Some(record) = record else {
*record = Some(ClickRecord {
down_position: position,
up_position: position,
..Default::default()
});
return ClickCount::Single;
};
let now = Instant::now();
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
let (prev_count, prev_position) = match state {
ElementState::Pressed => (record.down_count, record.down_position),
ElementState::Released => (record.up_count, record.up_position),
};
let dx = position.x.abs_diff(prev_position.x) as usize;
let dy = position.y.abs_diff(prev_position.y) as usize;
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let count = match (prev_count, within_time, within_dist) {
(ClickCount::Single, true, true) => ClickCount::Double,
(ClickCount::Double, true, true) => ClickCount::Triple,
(ClickCount::Triple, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
record.time = now;
match state {
ElementState::Pressed => {
record.down_position = position;
record.down_count = count;
}
ElementState::Released => {
record.up_position = position;
record.up_count = count;
}
}
count
}
}
#[derive(Clone, Copy, PartialEq, Default)]
pub(crate) enum ClickCount {
#[default]
Single,
Double,
Triple,
}
impl From<ClickCount> for i32 {
fn from(count: ClickCount) -> i32 {
match count {
ClickCount::Single => 1,
ClickCount::Double => 2,
ClickCount::Triple => 3,
}
}
}
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
down_position: MousePosition,
up_position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
down_position: Default::default(),
up_position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
}
}
pub(crate) struct CefModifiers(cef_event_flags_t);
impl CefModifiers {
fn new(input_state: &InputState, location: &KeyLocation, is_repeat: bool) -> Self {
let mut inner = cef_event_flags_t::EVENTFLAG_NONE;
if input_state.modifiers.shift_key() {
inner |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;
}
if input_state.modifiers.control_key() {
inner |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;
}
if input_state.modifiers.alt_key() {
inner |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;
}
if input_state.modifiers.meta_key() {
inner |= cef_event_flags_t::EVENTFLAG_COMMAND_DOWN;
}
if input_state.mouse_state.left {
inner |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON;
}
if input_state.mouse_state.right {
inner |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON;
}
if input_state.mouse_state.middle {
inner |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON;
}
if is_repeat {
inner |= cef_event_flags_t::EVENTFLAG_IS_REPEAT;
}
inner |= match location {
KeyLocation::Left => cef_event_flags_t::EVENTFLAG_IS_LEFT,
KeyLocation::Right => cef_event_flags_t::EVENTFLAG_IS_RIGHT,
KeyLocation::Numpad => cef_event_flags_t::EVENTFLAG_IS_KEY_PAD,
KeyLocation::Standard => cef_event_flags_t::EVENTFLAG_NONE,
};
Self(inner)
}
pub(super) const PINCH_MODIFIERS: Self = Self(cef_event_flags_t(
cef_event_flags_t::EVENTFLAG_CONTROL_DOWN.0 | cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA.0,
));
}
impl From<CefModifiers> for u32 {
fn from(val: CefModifiers) -> Self {
#[cfg(not(target_os = "windows"))]
return val.0.0;
#[cfg(target_os = "windows")]
return val.0.0 as u32;
}
}
+5 -15
View File
@@ -22,6 +22,9 @@ mod resources;
mod utility;
mod view;
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
pub use input::event::{InputEvent, InputEventBuilder, MouseButton, PointerInputEventBuilder, PointerPosition, UnknownPosition};
pub struct UiContext<S: Stage = Started> {
inner: S::ContextData,
}
@@ -67,7 +70,6 @@ impl UiContext<Started> {
Ok(UiInstance {
inner: Arc::new(UiInstanceInner {
host: self.inner.clone(),
input: Mutex::new(input::InputState::default()),
events: Mutex::new(events),
queue,
shutdown_complete: Mutex::new(shutdown_complete),
@@ -141,7 +143,6 @@ pub struct UiInstance {
pub(crate) struct UiInstanceInner {
host: Arc<HostHandle>,
input: Mutex<input::InputState>,
events: Mutex<Receiver<UiEvent>>,
queue: events::EventQueue,
shutdown_complete: Mutex<Receiver<()>>,
@@ -152,18 +153,7 @@ impl UiInstance {
pub fn send(&self, command: UiCommand) {
let shared = &self.inner;
match command {
UiCommand::Input(event) => {
let events = {
let Ok(mut input) = shared.input.lock() else {
tracing::error!("Failed to lock the input state");
return;
};
input::translate(&mut input, &event)
};
if !events.is_empty() {
shared.host.send(HostControlMessage::Input(events));
}
}
UiCommand::Input(event) => shared.host.send(HostControlMessage::Input(event)),
UiCommand::Resized { width, height } => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
UiCommand::ScaleChanged(scale) => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
UiCommand::Refresh => shared.host.send(HostControlMessage::RefreshViewInfo),
@@ -220,7 +210,7 @@ impl Drop for UiInstanceInner {
#[derive(Debug)]
pub enum UiCommand {
Input(winit::event::WindowEvent),
Input(InputEvent),
Resized { width: u32, height: u32 },
ScaleChanged(f64),
Refresh,
+1 -1
View File
@@ -99,7 +99,7 @@ enum ControlOutcome {
fn control_loop(receiver: &IpcReceiver<HostControlMessage>, context: &CefContextHandle, sequence: &SequenceState) -> ControlOutcome {
loop {
match receiver.recv() {
Ok(HostControlMessage::Input(events)) => context.apply_input(events),
Ok(HostControlMessage::Input(event)) => context.process_input(event),
Ok(HostControlMessage::UpdateViewInfo(update)) => context.update_view_info(update),
Ok(HostControlMessage::RefreshViewInfo) => context.refresh_view_info(),
Ok(HostControlMessage::SendWebMessage(message)) => context.send_web_message(message),
+1 -1
View File
@@ -8,7 +8,7 @@ use crate::view::ViewInfoUpdate;
#[derive(Serialize, Deserialize)]
pub(crate) enum HostControlMessage {
Input(Vec<InputEvent>),
Input(InputEvent),
UpdateViewInfo(ViewInfoUpdate),
RefreshViewInfo,
SendWebMessage(Vec<u8>),
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-wrapper"
version = "0.1.0"
description = "Graphite Desktop Wrapper"
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -2,7 +2,7 @@ use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
use graphite_editor::messages::prelude::*;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, SaveFileDialogContext};
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
match message {
@@ -15,14 +15,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
DesktopWrapperMessage::Input(message) => {
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
}
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 });
}
},
DesktopWrapperMessage::IngestFile { path, content, action } => {
dispatcher.queue_editor_message(IngestMessage::Ingest {
data: content,
action,
mime_type: String::new(),
path: Some(path),
});
}
DesktopWrapperMessage::SaveFileDialogResult { path, context } => match context {
SaveFileDialogContext::Document { document_id, content } => {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: path.clone(), content });
@@ -35,14 +35,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
}
},
DesktopWrapperMessage::OpenFile { path, content } => {
let message = PortfolioMessage::OpenFile { path, content };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::ImportFile { path, content } => {
let message = PortfolioMessage::ImportFile { path, content };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
DesktopWrapperMessage::UpdateMaximized { maximized } => {
let message = FrontendMessage::UpdateMaximized { maximized };
@@ -3,27 +3,23 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
use graphite_editor::messages::prelude::FrontendMessage;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, IngestAction, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
FrontendMessage::RenderOverlays { context } => {
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
}
FrontendMessage::TriggerOpen => {
FrontendMessage::TriggerBrowse { options, action } => {
let title = match action {
IngestAction::Open => "Open Document",
IngestAction::Import => "Import File",
_ => "Select File",
};
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Open Document".to_string(),
filters: vec![],
multiple: true,
context: OpenFileDialogContext::Open,
});
}
FrontendMessage::TriggerImport => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters: vec![],
multiple: false,
context: OpenFileDialogContext::Import,
title: title.to_string(),
options,
action,
});
}
FrontendMessage::TriggerSaveDocument {
@@ -31,32 +27,29 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
name,
path,
folder,
filters,
content,
} => {
let content = content.into_vec();
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
} else {
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: folder,
filters: vec![FileFilter {
name: "Graphite Document".to_string(),
extensions: vec![extension],
}],
filters,
context: SaveFileDialogContext::Document { document_id, content },
});
}
}
FrontendMessage::TriggerSaveFile { name, folder, content } => {
FrontendMessage::TriggerSaveFile { name, folder, filters, content } => {
let content = content.into_vec();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save File".to_string(),
default_filename: name,
default_folder: folder,
filters: Vec::new(),
filters,
context: SaveFileDialogContext::File { content },
});
}
@@ -125,6 +118,9 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
FrontendMessage::WindowUpdateDirectInput { enabled } => {
dispatcher.respond(DesktopFrontendMessage::WindowUpdateDirectInput { enabled });
}
FrontendMessage::WindowClose => {
dispatcher.respond(DesktopFrontendMessage::WindowClose);
}
+3 -2
View File
@@ -10,6 +10,7 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
@@ -55,14 +56,14 @@ impl DesktopWrapper {
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
}
pub enum NodeGraphExecutionResult {
HasRun(Option<std::sync::Arc<wgpu::Texture>>),
HasRun(Option<Texture>),
NotRun,
}
+10 -20
View File
@@ -3,9 +3,10 @@ use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileDialogOptions, FileFilter, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ScrollDelta};
pub use graphite_editor::messages::portfolio::ingest::utility_types::IngestAction;
pub use graphite_editor::messages::prelude::DocumentId;
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
@@ -15,9 +16,8 @@ pub enum DesktopFrontendMessage {
OpenLaunchDocuments,
OpenFileDialog {
title: String,
filters: Vec<FileFilter>,
multiple: bool,
context: OpenFileDialogContext,
options: FileDialogOptions,
action: IngestAction,
},
SaveFileDialog {
title: String,
@@ -40,6 +40,9 @@ pub enum DesktopFrontendMessage {
UpdateUIScale {
scale: f64,
},
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
@@ -84,10 +87,8 @@ pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Wake,
Input(InputMessage),
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
OpenFile { path: PathBuf, content: Vec<u8> },
ImportFile { path: PathBuf, content: Vec<u8> },
PollNodeGraphEvaluation,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
@@ -100,17 +101,6 @@ pub enum DesktopWrapperMessage {
LoadThirdPartyLicenses { text: String },
}
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
#[derive(Clone, Copy)]
pub enum OpenFileDialogContext {
Open,
Import,
}
pub enum SaveFileDialogContext {
Document { document_id: DocumentId, content: Vec<u8> },
File { content: Vec<u8> },
+1 -1
View File
@@ -3,7 +3,7 @@ pub(crate) mod menu {
use base64::engine::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
use graphite_editor::messages::layout::LayoutMessage;
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId, WidgetRow};
+3 -1
View File
@@ -1,10 +1,12 @@
[package]
name = "document-container"
description = "Container abstraction for the on-disk side of the .gdd document format"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
default = []
+7 -2
View File
@@ -1,10 +1,12 @@
[package]
name = "document-format"
description = "Typed handle for the .gdd document format, sitting over document-graph-storage and document-container"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
@@ -15,11 +17,14 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
zip = ["document-container/zip"]
xz = ["document-container/xz"]
default = ["conversion", "zip", "xz"]
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
network = ["dep:peer-transport"]
default = ["conversion", "zip", "xz", "network"]
[dependencies]
document-container = { workspace = true }
document-graph-storage = { workspace = true, default-features = false }
peer-transport = { workspace = true, optional = true }
graph-craft = { workspace = true, optional = true }
graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
+4
View File
@@ -47,4 +47,8 @@ pub enum Error {
/// An export marked a resource for embedding but its bytes were absent from the byte store.
#[error("embedded resource {0} missing from the byte store")]
MissingResource(ResourceHash),
/// A packet for the collaboration session failed to encode.
#[cfg(feature = "network")]
#[error("network error: {0}")]
Network(#[from] peer_transport::PacketError),
}
+1
View File
@@ -150,6 +150,7 @@ impl<L: Layout> Gdd<L> {
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
+67 -19
View File
@@ -20,7 +20,7 @@ use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
use graphene_resource::{ResourceHash, ResourceStorage};
pub mod codec;
pub mod error;
@@ -28,6 +28,8 @@ pub mod export;
pub mod io;
pub mod layout;
pub mod manifest;
#[cfg(feature = "network")]
pub mod network;
pub mod persist;
pub mod resource;
pub mod session_state;
@@ -68,8 +70,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
/// not carried over, so a clone is a read-only copy for asynchronous writes.
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
@@ -84,6 +86,42 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
/// Where this document's resource bytes live. `None` means the working copy's own content-addressed
/// store, which is what a standalone handle uses. The editor points this at its application-wide
/// cache, the single store resources are kept in there.
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
#[cfg(feature = "network")]
pub(crate) network: Option<peer_transport::Replica>,
#[cfg(feature = "network")]
pub(crate) pending_persist: PendingPersist,
}
/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs
/// one rewrite of each file rather than one per packet.
#[cfg(feature = "network")]
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct PendingPersist {
pub(crate) history: bool,
pub(crate) hot_log: bool,
pub(crate) snapshot: bool,
}
impl<L: Layout + Clone> Clone for Gdd<L> {
fn clone(&self) -> Self {
Self {
session: self.session.clone(),
working: self.working.clone(),
layout: self.layout.clone(),
manifest: self.manifest.clone(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
byte_store: self.byte_store.clone(),
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
}
}
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -144,7 +182,15 @@ impl<L: Layout> Gdd<L> {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(
peer,
registry,
history,
session_state.head_rev,
session_state.redo_stack,
session_state.next_node_counter,
session_state.next_hot_sequence,
)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
@@ -168,6 +214,11 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: session_state.view_settings,
network_view_settings: session_state.network_view_settings,
byte_store: None,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
})
}
@@ -190,6 +241,11 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
byte_store: None,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
})
}
}
@@ -292,24 +348,16 @@ impl<L: Layout> Gdd<L> {
(working, self.layout)
}
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
/// because resource loads are.
/// Resolve every proto-node declaration referenced by the registry or its history into a
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
#[cfg(feature = "conversion")]
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
use document_graph_storage::Implementation;
let registry = self.session.registry();
let mut declarations = document_graph_storage::Declarations::new();
for node in registry.node_instances.values() {
let Implementation::ProtoNode(id) = node.implementation() else { continue };
if declarations.contains_key(id) {
continue;
}
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else {
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
continue;
};
@@ -319,7 +367,7 @@ impl<L: Layout> Gdd<L> {
};
match document_graph_storage::decode_declaration(resource.as_ref()) {
Ok(proto) => {
declarations.insert(*id, proto);
declarations.insert(id, proto);
}
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
}
+162
View File
@@ -0,0 +1,162 @@
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
//! then broadcasts staged hot ops and (as host) retired deltas, and `poll_peers` applies what peers
//! send through the [`SyncTarget`] impl below, which persists inbound state the same way local
//! edits are.
use std::collections::HashSet;
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session, UserId};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
use crate::error::Error;
use crate::layout::Layout;
use crate::{Gdd, PendingPersist};
impl<L: Layout> Gdd<L> {
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::host(transport, self.session.peer(), user));
}
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::guest(transport, self.session.peer(), user));
}
pub fn leave(&mut self) {
if let Some(mut replica) = self.network.take() {
replica.leave();
}
}
pub fn role(&self) -> Option<Role> {
self.network.as_ref().map(Replica::role)
}
pub fn is_synced(&self) -> bool {
self.network.as_ref().is_none_or(Replica::is_synced)
}
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
pub fn mark_runtime_current(&mut self) {
self.session.mark_runtime_current();
}
pub fn poll_peers(&mut self) -> Vec<Event> {
let Some(mut replica) = self.network.take() else { return Vec::new() };
let events = replica.poll(self);
self.network = Some(replica);
events
}
/// Answer an [`Event::ResourceRequested`].
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.send_resource(to, hash, bytes)?;
}
Ok(())
}
}
impl<L: Layout> SyncTarget for Gdd<L> {
fn peer(&self) -> PeerId {
self.session.peer()
}
fn head(&self) -> Option<Rev> {
self.session.head_rev()
}
fn retired_registry(&self) -> Registry {
self.session.retired_registry().clone()
}
fn hot_log(&self) -> Vec<HotOp> {
self.session.hot_log().to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
self.session.known_revs()
}
fn contains_rev(&self, rev: Rev) -> bool {
self.session.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
<Session as SyncTarget>::deltas_unknown_to(&self.session, known)
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
self.session.load(registry, history, head)?;
self.pending_persist = PendingPersist {
history: true,
hot_log: true,
snapshot: true,
};
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// An op naming an entity that has not arrived here yet is handed back for a later retry, so only
// what actually applied reaches the hot frame log.
let mut deferred = Vec::new();
for hot_op in ops {
if self.session.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
continue;
}
self.append_hot_frame(&hot_op)?;
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
self.session.merge_remote(deltas, retires)?;
// Whatever a peer sent is shared by definition, so it sits behind the published frontier too: a
// guest must no more silently rewind the host's history than the host may rewind its own.
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.pending_persist.history = true;
self.pending_persist.hot_log |= !retires.is_empty();
self.pending_persist.snapshot = true;
Ok(())
}
fn retired_marks(&self) -> RetiredMarks {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)?;
self.pending_persist.hot_log = true;
Ok(())
}
fn flush(&mut self) -> Result<(), TargetError> {
let pending = std::mem::take(&mut self.pending_persist);
if pending.history {
self.rewrite_history()?;
}
if pending.hot_log {
self.rewrite_hot_log()?;
}
if pending.snapshot {
self.persist_registry_snapshot()?;
self.persist_session_state()?;
}
Ok(())
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.unstored_resources().into_iter().collect()
}
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
self.hold_resource(bytes)?;
Ok(())
}
}
+73 -21
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp};
use document_graph_storage::{HotOp, RegistryDelta, Rev, TimeStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
/// interaction.
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
///
/// # Errors
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
@@ -60,19 +60,34 @@ impl<L: Layout> Gdd<L> {
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<(), Error> {
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
self.persist_staged(&hot_ops)?;
// Persist proto-node declaration content to the byte store (the global cache in the editor,
// the working-copy container for standalone export). Content-addressed, so re-storing
// identical bytes on every commit is an idempotent no-op.
for bytes in declaration_bytes.values() {
for bytes in conversion.declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(conversion.declarations)
}
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.session.stage_ops(ops)?;
self.persist_staged(&hot_ops)?;
Ok(hot_ops)
}
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_hot_ops(hot_ops)?;
}
Ok(())
}
@@ -159,7 +174,7 @@ impl<L: Layout> Gdd<L> {
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
fn rewrite_history(&mut self) -> Result<(), Error> {
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for delta in self.session.history() {
self.manifest.codecs.history.append(&mut buffer, delta)?;
@@ -168,13 +183,14 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
fn persist_session_state(&mut self) -> Result<(), Error> {
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -186,7 +202,7 @@ impl<L: Layout> Gdd<L> {
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
pub(crate) fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
Ok(())
}
@@ -215,7 +231,7 @@ impl<L: Layout> Gdd<L> {
self.persist_session_state()
}
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
let mut buffer = Vec::new();
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
@@ -232,6 +248,12 @@ impl<L: Layout> Gdd<L> {
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() {
return Ok(Vec::new());
}
#[cfg(feature = "network")]
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
let new_revs = self.session.retire(up_to)?;
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
@@ -239,21 +261,51 @@ impl<L: Layout> Gdd<L> {
self.session.mark_interaction_end(last);
}
// In a session these deltas are about to reach peers, so the published frontier moves with them.
// Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire
// to tell them, so undo past this point has to go through forward inverse ops instead. Set before
// the persists below so the frontier survives a reopen.
#[cfg(feature = "network")]
if self.network.is_some()
&& let Some(&last) = new_revs.last()
{
self.session.publish_up_to(last);
}
if !new_revs.is_empty() {
self.append_history_deltas(&new_revs)?;
}
// Rewrite hot log with whatever survived retirement.
let mut hot_buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
}
self.working
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
replica.broadcast_retired(&deltas, &retired_hot_ops)?;
}
Ok(new_revs)
}
/// Guests leave retirement to the session host and keep their hot ops until the host's retired
/// deltas arrive.
fn retires_locally(&self) -> bool {
#[cfg(feature = "network")]
{
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
}
#[cfg(not(feature = "network"))]
true
}
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
}
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
Ok(())
}
}
+36
View File
@@ -91,6 +91,36 @@ impl<L: Layout> Gdd<L> {
{
ResourceProxy(self.working.clone(), self.layout.clone())
}
/// Point resource lookups at an external store instead of the working copy, for an embedder that
/// already keeps one cache for every open document.
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
self.byte_store = Some(byte_store);
}
/// Whether this document's resource bytes are on hand, in whichever store backs it.
pub fn holds_resource(&self, hash: &ResourceHash) -> bool {
match &self.byte_store {
Some(byte_store) => byte_store.contains(hash),
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
}
}
/// Put resource bytes into whichever store backs this document.
pub fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
match &self.byte_store {
Some(byte_store) => {
byte_store.store(bytes);
Ok(())
}
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
}
}
/// Resources the registry or its history names whose bytes are not on hand.
pub fn unstored_resources(&self) -> Vec<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
}
}
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
@@ -104,6 +134,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
+4
View File
@@ -31,6 +31,10 @@ pub struct SessionState {
/// collide on minted IDs.
#[serde(default)]
pub next_node_counter: u64,
/// How many hot ops this peer has authored, feeding `HotOp::sequence`. Persisted so a reopen
/// continues the run: a reused sequence would look like one already retired and be dropped.
#[serde(default)]
pub next_hot_sequence: u64,
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+5
View File
@@ -128,6 +128,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -154,6 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -161,6 +163,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: 2,
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -200,6 +203,7 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
@@ -655,6 +659,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: 1,
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
+3 -1
View File
@@ -1,10 +1,12 @@
[package]
name = "document-graph-storage"
description = "Provides a delta based graph representation used in the Graphite file format"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
+101 -26
View File
@@ -1,6 +1,6 @@
use crate::{
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
apply_attribute_delta, reverse_attribute_delta,
CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, RetiredMarks, Rev,
SourceValue, TimeStamp, apply_attribute_delta, reverse_attribute_delta,
};
#[derive(Clone, Debug)]
@@ -11,6 +11,10 @@ pub struct Document {
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
pub(crate) hot_log: Vec<HotOp>,
/// Which hot ops history already covers, so one that arrives after its own retirement is recognized
/// and dropped rather than re-entering the hot log for good. Retirement discards the link from a
/// delta back to the hot op it came from, so this is the only record of it. See [`RetiredMarks`].
pub(crate) retired: RetiredMarks,
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
@@ -36,6 +40,8 @@ pub struct Document {
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
/// reading the same counter still produce distinct IDs.
pub(crate) next_node_counter: u64,
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
pub(crate) next_hot_sequence: u64,
}
impl Document {
@@ -66,24 +72,16 @@ impl Document {
self.revert_delta(target, delta)
}
/// Search every delta reachable from `head` (following all parents, including a merge's
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
/// ancestry reachability, so a node added only on a merged-in branch is still found.
/// The last delta in canonical history order matching `predicate`, among those reachable from `head`
/// or any history tip (following all parents, including a merge's `extra_parents`). Tips cover deltas
/// absorbed mid-merge that `head` doesn't reach yet.
///
/// Resurrection reads the removed entity out of the match, so every peer has to pick the same one.
/// Canonical order is agreed; a walk from `head` is not, since peers sit on different merge revs.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
while let Some(rev) = queue.pop_front() {
let Some(delta) = self.history.get(rev) else { continue };
if predicate(delta) {
return Some(delta.clone());
}
for parent in delta.all_parents() {
if seen.insert(parent) {
queue.push_back(parent);
}
}
}
None
let reachable = self.history.ancestors(self.head.into_iter().chain(self.history.tips()));
self.history.iter().filter(|delta| reachable.contains(&delta.id) && predicate(delta)).last().cloned()
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
@@ -111,11 +109,55 @@ impl Document {
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
/// than an error.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
// Its effect is already in retired history, and re-adding it would leave an entry no retirement
// list will ever name.
if self.is_retired(hot_op.id()) {
return Ok(());
}
// A hot op is identified by its timestamp, so a re-announcement of one already held is a no-op
// rather than a second copy that replays and re-broadcasts as though it were new work.
if self.hot_log.iter().any(|held| held.timestamp == hot_op.timestamp) {
return Ok(());
}
// Replaying our own persisted ops after a reload is what restores the sequence counter.
if hot_op.timestamp.peer == self.peer {
self.next_hot_sequence = self.next_hot_sequence.max(hot_op.sequence);
}
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_log.push(hot_op);
Ok(())
}
/// Whether this hot op has already been promoted into history.
pub(crate) fn is_retired(&self, id: HotOpId) -> bool {
self.retired.covers(id)
}
/// Record newly retired hot ops, dropping any the hot log still holds.
pub(crate) fn mark_retired(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
self.retired.extend(retired);
self.drop_retired_hot_ops();
}
/// Take on another peer's retirement marks as well as this peer's.
pub(crate) fn absorb_retired(&mut self, remote: &RetiredMarks) {
self.retired.absorb(remote);
self.drop_retired_hot_ops();
}
/// Drop hot ops history already covers, so a retired op never sits in the hot log whatever path
/// put it there.
fn drop_retired_hot_ops(&mut self) {
let retired = std::mem::take(&mut self.retired);
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
self.retired = retired;
}
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
/// targets, Remove on missing ones) since hot ops already produced the structural state.
/// The point is to bump field timestamps to T_retire via the LWW arms.
@@ -296,7 +338,7 @@ impl Document {
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
/// before the node. No-op for ops that reference nothing absent.
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
pub(crate) fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
match op {
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
@@ -321,17 +363,50 @@ impl Document {
}
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
self.restore_node_from_history(target, node_id)?;
if self.registry_ref(target).node_instances.contains_key(&node_id) {
return Ok(());
}
Ok(())
let removal = self.hot_log_node_removal(target, node_id);
match removal {
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
None => self.restore_node_from_history(target, node_id),
}
}
/// The most recent hot removal of a network, for reviving it in the working zone. Returns `None`
/// for the snapshot, which must stay a function of history alone.
fn hot_log_removal(&self, target: RegistryTarget, network_id: NetworkId) -> Option<(RegistryDelta, TimeStamp)> {
if target != RegistryTarget::Working {
return None;
}
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
RegistryDelta::RemoveNetwork { id, snapshot } if *id == network_id => Some((RegistryDelta::AddNetwork { id: *id, network: snapshot.clone() }, hot_op.timestamp)),
_ => None,
})
}
/// The node equivalent of [`hot_log_removal`](Self::hot_log_removal).
fn hot_log_node_removal(&self, target: RegistryTarget, node_id: NodeId) -> Option<(RegistryDelta, TimeStamp)> {
if target != RegistryTarget::Working {
return None;
}
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
RegistryDelta::RemoveNode { id, snapshot } if *id == node_id => Some((RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, hot_op.timestamp)),
_ => None,
})
}
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
if !self.registry_ref(target).networks.contains_key(&network_id) {
self.restore_network_from_history(target, network_id)?;
if self.registry_ref(target).networks.contains_key(&network_id) {
return Ok(());
}
// The hot log is this peer's own, so reviving the snapshot zone from it would make the retired
// state depend on which hot ops happened to be here. Only history is shared.
let removal = self.hot_log_removal(target, network_id);
match removal {
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
None => self.restore_network_from_history(target, network_id),
}
Ok(())
}
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
+8 -19
View File
@@ -89,33 +89,17 @@ impl TryFrom<&NodeNetwork> for Registry {
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
/// the `ResourceId`/`ResourceHash` references.
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
pub struct RuntimeConversion {
pub registry: Registry,
pub declaration_bytes: DeclarationBytes,
pub declarations: crate::Declarations,
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
impl RuntimeConversion {
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
/// their byte store instead.
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
self.declaration_bytes
.iter()
.map(|(hash, bytes)| {
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
Ok((ResourceId::from_hash(hash), proto))
})
.collect()
}
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
@@ -149,6 +133,7 @@ impl Registry {
let mut ctx = ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -167,6 +152,7 @@ impl Registry {
Ok(RuntimeConversion {
registry,
declaration_bytes: ctx.declaration_bytes,
declarations: ctx.declarations,
network_ids: ctx.network_ids,
})
}
@@ -254,6 +240,8 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
declaration_ids: HashMap<String, ResourceId>,
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
declaration_bytes: DeclarationBytes,
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
declarations: crate::Declarations,
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
@@ -555,6 +543,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
ctx.declarations.insert(id, proto);
ctx.declaration_ids.insert(identifier_str, id);
Implementation::ProtoNode(id)
+51 -15
View File
@@ -8,7 +8,7 @@
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
@@ -64,22 +64,13 @@ impl History {
self.deltas.iter()
}
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
fn canonical_sort(&mut self) {
///
/// The sort is deterministic, so two peers that absorb the same delta set produce byte-identical
/// history, not merely two different valid orderings. This is the history-convergence mechanism:
/// arrival order is erased.
pub fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
@@ -119,6 +110,51 @@ impl History {
}
}
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if !seen.insert(rev) {
continue;
}
if let Some(delta) = self.get(rev) {
stack.extend(delta.all_parents());
}
}
seen
}
pub fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
self.ancestors([descendant]).contains(&ancestor)
}
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
/// so it can locate the divergence point within a factor of two of the true distance.
pub fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
let mut samples = vec![tip];
let mut current = tip;
let mut distance = 0;
let mut next_sample_distance = 1;
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
current = parent;
distance += 1;
if distance == next_sample_distance {
samples.push(current);
next_sample_distance *= 2;
}
}
samples
}
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
let known = self.ancestors(known);
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
+21
View File
@@ -43,6 +43,27 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
let slot = InputSlot {
input: NodeInput::Value {
value: serde_json::Value::Null,
exposed: false,
},
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
};
Self {
implementation,
inputs: vec![slot; inputs],
attributes: Attributes::new(),
network,
}
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
+287 -36
View File
@@ -2,7 +2,7 @@
use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@@ -16,6 +16,9 @@ pub struct Session {
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
remote_tips: HashMap<PeerId, Rev>,
/// The registry the runtime was last built from or staged to. Local diffs are taken against it,
/// so edits peers applied to the working registry in the meantime are not diffed away.
runtime_base: Option<Registry>,
}
impl Session {
@@ -36,14 +39,17 @@ impl Session {
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
retired: RetiredMarks::default(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
next_hot_sequence: 0,
},
remote_tips: HashMap::new(),
runtime_base: None,
}
}
@@ -64,8 +70,7 @@ impl Session {
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
/// proto-node declaration bytes the conversion extracted, keyed by content hash, for the caller
/// to persist into its byte store (`document-graph-storage` itself is byte-unaware).
/// conversion, whose extracted declarations the caller persists and caches.
///
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
@@ -76,11 +81,18 @@ impl Session {
network: &graph_craft::document::NodeNetwork,
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
let base = self.runtime_base.as_ref().unwrap_or(&self.document.working_registry);
let ops = crate::delta::compute_deltas(base, &conversion.registry);
self.runtime_base = Some(conversion.registry.clone());
let hot_ops = self.stage_ops(ops)?;
Ok((hot_ops, conversion.declaration_bytes))
Ok((hot_ops, conversion))
}
/// Record that the runtime now reflects the working registry, after the caller rebuilt it from there.
pub fn mark_runtime_current(&mut self) {
self.runtime_base = Some(self.document.working_registry.clone());
}
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
@@ -136,7 +148,7 @@ impl Session {
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
if pending.is_empty() {
return Ok(Vec::new());
@@ -149,9 +161,11 @@ impl Session {
let mut staged = Vec::with_capacity(pending.len());
for op in pending {
self.document.next_hot_sequence += 1;
let hot_op = HotOp {
op,
timestamp: self.document.clock.tick(),
sequence: self.document.next_hot_sequence,
};
self.document.apply_hot_op(hot_op.clone())?;
staged.push(hot_op);
@@ -181,6 +195,8 @@ impl Session {
self.document.redo_stack.clear();
}
// The reverse must read the pre-op value of a target that may have been concurrently removed.
self.document.ensure_referenced_exist(target, &op)?;
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = self.document.clock.tick();
let parent = self.document.head;
@@ -208,7 +224,7 @@ impl Session {
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
/// (topological) order.
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64, next_hot_sequence: u64) -> Self {
let mut clock = LamportClock::new(peer);
for delta in &history {
clock.observe(delta.timestamp);
@@ -222,14 +238,17 @@ impl Session {
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
retired: RetiredMarks::default(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
next_hot_sequence,
},
remote_tips: HashMap::new(),
runtime_base: None,
}
}
@@ -251,47 +270,124 @@ impl Session {
Ok(session)
}
/// Apply a hot op without going through the broadcast stream.
/// Apply a hot op received from another peer.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.apply_hot_op(hot_op)
}
/// The hot ops a `retire(up_to)` call would drain. Broadcast alongside the retired deltas so guests
/// drop exactly these; a cutoff alone doesn't transfer, since a lagging peer's op can carry a
/// timestamp below the cutoff yet reach the host only after that retirement.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
}
/// Drop hot ops another peer has retired without retiring them locally.
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) {
self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id()));
// How a peer that did not retire these learns they are in history now.
self.document.mark_retired(retired.iter().copied());
}
/// Which hot ops history already covers, for a peer catching up. See [`RetiredMarks`].
pub fn retired_marks(&self) -> &RetiredMarks {
&self.document.retired
}
/// Take on another peer's retirement marks as well as this peer's.
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
self.document.absorb_retired(remote);
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
/// where the registry may already reflect the op's effect from a prior retired snapshot.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.replay_hot_op(hot_op)
}
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
/// deltas must arrive in causal order.
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
let mut absorbed: Vec<Delta> = Vec::new();
/// Rebuild both registries by refolding canonically sorted history, then re-layering the hot tail.
/// Every peer sorts history the same way, so the result no longer depends on the order deltas
/// happened to arrive in. Costs a full replay, so callers check that it is needed first.
fn refold_registries(&mut self) -> Result<(), CrdtError> {
let replay: Vec<(RegistryDelta, TimeStamp)> = self.document.history.iter().map(|delta| (delta.kind.clone(), delta.timestamp)).collect();
self.document.retired_snapshot = Registry::default();
for (kind, timestamp) in replay {
self.document.apply_op_with(RegistryTarget::Snapshot, kind, timestamp, ApplyMode::Idempotent)?;
}
// A hot op the refold left unapplicable is kept rather than dropped, since a later delta or hot
// op can still supply the referent it names.
self.document.working_registry = self.document.retired_snapshot.clone();
let mut failure = None;
for hot_op in std::mem::take(&mut self.document.hot_log) {
if let Err(error) = self.document.replay_hot_op(hot_op.clone()) {
self.document.hot_log.push(hot_op);
failure = failure.or(Some(error));
}
}
match failure {
Some(error) => Err(error),
None => Ok(()),
}
}
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
/// without a new delta when the incoming history extends it, otherwise joins `head` and the
/// incoming tips with a [`RegistryDelta::Merge`].
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
let length_before = self.document.history.len();
// Each delta enters history before the next is applied, so a later delta in the batch that
// targets something an earlier one removed can resurrect it.
let mut absorbed_ids = HashSet::new();
let mut arrival_order = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
arrival_order.push(delta.id);
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
absorbed.push(delta);
// The working registry is the snapshot plus the hot tail, so a retired delta lands on both
// rather than cloning one over the other, which would promote unretired hot ops.
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
absorbed_ids.insert(delta.id);
self.document.history.push(delta);
}
if absorbed.is_empty() {
return Ok(None);
if absorbed_ids.is_empty() {
return Ok(MergeOutcome::NoOp);
}
self.document.history.canonical_sort();
// The registries were folded in arrival order, and concurrent ops do not all commute: a remove
// and a change to the same target resolve by whichever lands second. Refold unless the sort
// happened to leave the batch appended in the order it was applied.
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
if !folded_in_canonical_order {
self.refold_registries()?;
}
self.document.history.merge(absorbed);
let tips = self.document.history.tips();
let timestamp = self.document.clock.tick();
let merge = Delta::merge(tips, self.document.peer, timestamp);
let merge_rev = merge.id;
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
// order without re-sorting the whole history.
self.document.history.push(merge);
self.document.head = Some(merge_rev);
let history = &self.document.history;
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
let parents: Vec<Rev> = candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect();
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(Some(merge_rev))
let outcome = match parents.as_slice() {
[tip] => MergeOutcome::FastForward(*tip),
_ => {
let timestamp = self.document.clock.tick();
let merge = Delta::merge(parents, self.document.peer, timestamp);
let merge_rev = merge.id;
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
self.document.history.push(merge);
MergeOutcome::Merged(merge_rev)
}
};
self.document.head = outcome.head();
Ok(outcome)
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
@@ -299,6 +395,8 @@ impl Session {
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
// Drained in hot-log order, which is causal, so the deltas commit in an order their references
// survive.
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
for hot_op in self.document.hot_log.drain(..) {
@@ -309,6 +407,7 @@ impl Session {
}
}
self.document.hot_log = remaining;
self.document.mark_retired(drained.iter().map(HotOp::id));
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
}
@@ -374,6 +473,8 @@ impl Session {
return Err(CrdtError::NothingToUndo);
}
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
// The caller rebuilds the runtime from the rewound registry; until then diff against it directly.
self.runtime_base = None;
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
// interaction's boundary (its `interaction_end` delta) or the root.
@@ -382,7 +483,11 @@ impl Session {
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
let parent = delta.parent;
self.document.revert_delta(RegistryTarget::Working, delta)?;
self.document.revert_delta(RegistryTarget::Working, delta.clone())?;
// The working registry is the snapshot plus the hot tail, so rewind both rather than copying
// one over the other, which would promote unretired hot ops into retired state.
self.document.revert_delta(RegistryTarget::Snapshot, delta)?;
self.document.head = parent;
match parent {
@@ -392,9 +497,6 @@ impl Session {
}
}
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
// working registry (the next interaction's reverses are computed against it).
self.document.retired_snapshot = self.document.working_registry.clone();
self.document.redo_stack.push(checkpoint);
Ok(checkpoint)
}
@@ -404,6 +506,7 @@ impl Session {
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
self.runtime_base = None;
let mut forward = Vec::new();
let mut cursor = Some(checkpoint);
@@ -418,11 +521,11 @@ impl Session {
// at the same timestamp. Symmetric with `revert_delta`.
for delta in forward.into_iter().rev() {
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
// Both zones move together, for the same reason `undo` rewinds both.
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Force)?;
}
self.document.head = Some(checkpoint);
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(checkpoint)
}
@@ -442,6 +545,17 @@ impl Session {
self.document.history.iter()
}
/// Revs sampled at exponentially growing distances behind `head`, for a remote peer to locate what
/// this session is missing (see [`History::sample_chain`]).
pub fn known_revs(&self) -> Vec<Rev> {
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
}
/// Retired deltas not reachable from `known`, in replay order.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
self.document.history.deltas_unknown_to(known)
}
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
@@ -473,6 +587,40 @@ impl Session {
hashes
}
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
/// with its content hash, or `None` where the hash never resolved.
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
let registry = &self.document.working_registry;
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
hashes.insert(*id, *hash);
}
_ => {}
}
}
let current_nodes = registry.node_instances.values();
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
RegistryDelta::AddNode { node, .. } => Some(node),
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
_ => None,
});
current_nodes
.chain(historic_nodes)
.filter_map(|node| match node.implementation() {
Implementation::ProtoNode(id) => Some(*id),
Implementation::Network(_) => None,
})
.map(|id| (id, hashes.get(&id).copied()))
.collect()
}
pub fn hot_log(&self) -> &[HotOp] {
&self.document.hot_log
}
@@ -514,6 +662,12 @@ impl Session {
pub fn next_node_counter(&self) -> u64 {
self.document.next_node_counter
}
/// How many hot ops this peer has authored. Persisted and carried across a reload so a fresh op
/// never reuses a sequence an earlier one already spent. See [`HotOp::sequence`].
pub fn next_hot_sequence(&self) -> u64 {
self.document.next_hot_sequence
}
}
/// Errors from `Session::commit_from_runtime`.
@@ -533,12 +687,109 @@ impl Default for Session {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MergeOutcome {
NoOp,
FastForward(Rev),
Merged(Rev),
}
impl MergeOutcome {
/// The head after the merge, or `None` when nothing changed.
pub fn head(self) -> Option<Rev> {
match self {
Self::NoOp => None,
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
}
}
}
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
/// Position in its author's own run of hot ops, counting from 1 with no gaps. The Lamport counter
/// skips whenever a higher remote timestamp is observed, so it cannot tell a missing op from a
/// skipped tick; this can, which is what lets a watermark stand for a contiguous prefix.
pub sequence: u64,
}
impl HotOp {
/// Identifies the op for retirement, which tracks a contiguous prefix per author.
pub fn id(&self) -> HotOpId {
HotOpId {
peer: self.timestamp.peer,
sequence: self.sequence,
}
}
}
/// One hot op's author and position in that author's run. Retirement names the ops it promoted with
/// these rather than with timestamps, so a receiver can tell which prefix history now covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HotOpId {
pub peer: PeerId,
pub sequence: u64,
}
/// Which hot ops history already covers. `through` is how far each author's run has retired without a
/// gap, and `above` names the retired ops past that point, which is where an op lands when it retires
/// before an earlier one from the same author has arrived. Replicated so a peer catching up can tell
/// an op already in the history it was handed from one still owed to it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetiredMarks {
pub through: HashMap<PeerId, u64>,
pub above: HashSet<HotOpId>,
}
impl RetiredMarks {
/// Whether history already holds this hot op.
pub fn covers(&self, id: HotOpId) -> bool {
self.through.get(&id.peer).is_some_and(|&through| id.sequence <= through) || self.above.contains(&id)
}
/// Take on `remote`'s coverage as well as this one's.
pub fn absorb(&mut self, remote: &Self) {
for (&peer, &remote_through) in &remote.through {
let through = self.through.entry(peer).or_default();
*through = (*through).max(remote_through);
}
self.above.extend(remote.above.iter().copied());
self.compact();
}
/// Record newly retired ops.
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
self.above.extend(retired);
self.compact();
}
/// Fold every exception that continues its author's prefix into `through`, so the set only ever
/// holds ops still separated from the prefix by a gap.
fn compact(&mut self) {
let mut by_author: HashMap<PeerId, Vec<u64>> = HashMap::new();
for id in &self.above {
by_author.entry(id.peer).or_default().push(id.sequence);
}
for (peer, mut sequences) in by_author {
sequences.sort_unstable();
let through = self.through.entry(peer).or_default();
for sequence in sequences {
if sequence == *through + 1 {
*through = sequence;
}
}
}
let through = std::mem::take(&mut self.through);
self.above.retain(|id| through.get(&id.peer).is_none_or(|&covered| id.sequence > covered));
self.through = through;
}
}
#[derive(Debug, thiserror::Error)]
+216 -2
View File
@@ -40,6 +40,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
let hot_op = HotOp {
op: remove_node_op(NodeId(99)),
timestamp: observed,
sequence: 1,
};
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
@@ -182,9 +183,10 @@ fn merge_converges_to_identical_history() {
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
let deltas_a = session_a.cloned_deltas();
let deltas_b = session_b.cloned_deltas();
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
assert!(matches!(merge_a, crate::MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
@@ -193,6 +195,29 @@ fn merge_converges_to_identical_history() {
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
}
/// A peer whose history is a prefix of the incoming one moves its head forward without minting a
/// merge delta, and the negotiated transfer sends only the deltas past the sampled known revs.
#[test]
fn merge_fast_forwards_a_prefix_history() {
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
for value in 1..=5 {
session_b.commit_op_for_test(set_document_attribute("compute::b", value)).expect("B edit");
}
let known = session_a.known_revs();
let missing: Vec<_> = session_b.deltas_unknown_to(known).into_iter().cloned().collect();
assert_eq!(missing.len(), 5, "only B's new commits are unknown to A");
let outcome = session_a.merge(missing).expect("merge failed");
assert_eq!(outcome, crate::MergeOutcome::FastForward(session_b.head_rev().unwrap()));
assert_eq!(session_a.history().count(), session_b.history().count(), "no merge delta was added");
assert_eq!(session_b.merge(session_a.cloned_deltas()).expect("merge failed"), crate::MergeOutcome::NoOp);
}
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
@@ -879,3 +904,192 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
}
/// Commit a retired delta and mirror it onto the working registry, which sits at
/// `retired_snapshot + hot tail`. `commit_op_for_test` alone only advances the snapshot zone.
fn commit_retired(session: &mut Session, op: RegistryDelta) {
let before = session.history().count();
session.commit_op_for_test(op).expect("commit failed");
for delta in session.cloned_deltas().into_iter().skip(before) {
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
}
}
/// Merge `deltas` into a copy of `base` in the given order and report whether node 7 survived,
/// with the stamp on its `tint` attribute.
fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> Option<(serde_json::Value, TimeStamp)> {
let mut session = base.clone();
let ordered: Vec<Delta> = order.iter().map(|&index| deltas[index].clone()).collect();
session.merge(ordered).expect("merge failed");
session
.retired_registry()
.node_instances
.get(&NodeId(7))
.and_then(|node| node.attributes.get("tint"))
.map(|value| (value.value.clone(), value.timestamp))
}
/// Retired deltas reach the registries in arrival order while only `history` is canonically sorted,
/// so concurrent deltas must commute. A remove concurrent with an attribute change does not: applied
/// change-then-remove the node is gone, while remove-then-change resurrects it from the removal's
/// embedded snapshot and reapplies the change on top.
#[test]
fn a_concurrent_remove_and_attribute_change_commute() {
let network_id = NetworkId(5);
let node = Node::new(network_id, crate::Implementation::Network(network_id), 0);
// Shared base holding node 7, then the two peers diverge.
let mut base = Session::with_peer(PeerId(1));
commit_retired(
&mut base,
RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
);
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
let mut remover = base.clone();
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
let mut changer = Session::with_peer(PeerId(2));
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
commit_retired(
&mut changer,
RegistryDelta::ChangeNodeAttribute {
id: NodeId(7),
delta: crate::AttributeDelta {
key: "tint".to_string(),
value: Some(serde_json::json!(75)),
},
},
);
// One delta from each branch, neither an ancestor of the other.
let removal = remover.cloned_deltas().into_iter().last().expect("removal delta");
let change = changer.cloned_deltas().into_iter().last().expect("change delta");
let deltas = [removal, change];
let removal_first = merge_order_outcome(&base, &deltas, [0, 1]);
let change_first = merge_order_outcome(&base, &deltas, [1, 0]);
assert_eq!(removal_first, change_first, "the retired registry must not depend on delta arrival order");
}
/// A hot op can retire before an earlier one from the same author has arrived, so the marks have to
/// cover it out of order. The prefix absorbs it once the gap fills, which is what keeps the exception
/// set from growing.
#[test]
fn retired_marks_cover_a_gap_and_compact_once_it_fills() {
let author = PeerId(1);
let id = |sequence| crate::HotOpId { peer: author, sequence };
let mut marks = crate::RetiredMarks::default();
marks.extend([id(1), id(2)]);
assert_eq!(marks.through.get(&author), Some(&2), "a contiguous run folds straight into the prefix");
assert!(marks.above.is_empty());
// Sequence 3 never arrived, so 4 retires above the prefix rather than extending it.
marks.extend([id(4)]);
assert_eq!(marks.through.get(&author), Some(&2));
assert!(marks.covers(id(4)), "an op past the gap is still recognized as retired");
assert!(!marks.covers(id(3)), "the missing op is not claimed");
// The gap fills, so the prefix swallows both it and the exception behind it.
marks.extend([id(3)]);
assert_eq!(marks.through.get(&author), Some(&4));
assert!(marks.above.is_empty(), "the exception set empties once the prefix reaches it");
}
/// Marks merge by union, and a peer adopting another's wholesale must not lose its own coverage.
#[test]
fn absorbing_marks_keeps_both_sides_coverage() {
let author = PeerId(1);
let id = |sequence| crate::HotOpId { peer: author, sequence };
let mut local = crate::RetiredMarks::default();
local.extend([id(1), id(4)]);
let mut remote = crate::RetiredMarks::default();
remote.extend([id(1), id(2), id(3), id(5)]);
local.absorb(&remote);
// The union is 1..=5 contiguous, so it all collapses into the prefix.
assert_eq!(local.through.get(&author), Some(&5));
assert!(local.above.is_empty());
for sequence in 1..=5 {
assert!(local.covers(id(sequence)), "sequence {sequence} must stay covered");
}
}
/// Undo rewinds retired history, so it must leave the hot tail alone. The retired snapshot is the
/// state history alone produces; copying the working registry onto it promotes live work nobody has
/// retired, which is the same mistake `Session::merge` used to make.
#[test]
fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
let mut session = Session::with_peer(PeerId(1));
// Two retired interactions, so the second is undoable.
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
// Unretired live work sitting on top, on a key no retired delta touches.
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
assert!(session.registry().attributes.contains_key("hot"), "the hot op must be in the working registry");
assert!(!session.retired_registry().attributes.contains_key("hot"), "and must not be in the snapshot");
session.undo().expect("undo");
assert!(!session.retired_registry().attributes.contains_key("second"), "undo must rewind the retired snapshot");
assert!(
!session.retired_registry().attributes.contains_key("hot"),
"undo promoted an unretired hot op into the retired snapshot"
);
}
/// Redo puts the interaction back on both zones, so the pair stays `snapshot + hot tail` rather than
/// drifting apart in the other direction.
#[test]
fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
session.undo().expect("undo");
session.redo().expect("redo");
assert!(session.retired_registry().attributes.contains_key("second"), "redo must restore the retired delta");
assert!(
!session.retired_registry().attributes.contains_key("hot"),
"redo promoted an unretired hot op into the retired snapshot"
);
assert!(session.registry().attributes.contains_key("hot"), "the hot op must survive an undo/redo round trip");
}
/// Silent undo rewrites the local registries without emitting anything, so it is only legal while a
/// commit is still unpublished. Once peers hold it, a rewind would diverge from them for good.
#[test]
fn publishing_a_commit_disables_silent_undo() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
let head = session.head_rev().expect("a head");
assert!(session.can_undo(), "an unpublished interaction is undoable");
session.publish_up_to(head);
assert!(!session.can_undo(), "a published interaction must not be silently rewound");
}
@@ -20,12 +20,10 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
/// `Declarations` map for the back-conversion.
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
let declarations = conversion.declarations().expect("rebuild declarations");
(conversion.registry, declarations)
(conversion.registry, conversion.declarations)
}
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
@@ -246,10 +244,10 @@ fn test_nested_network_flattening() {
#[test]
fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata
let context_features = ContextDependencies::new(
core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
core_types::context::ContextFeatures::empty(),
);
let context_features = ContextDependencies {
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default()
};
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -477,7 +475,7 @@ fn test_ui_metadata_round_trip() {
);
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "document-live"
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
document-container = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true }
peer-transport = { workspace = true }
graph-craft = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
[lints]
workspace = true
+116
View File
@@ -0,0 +1,116 @@
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
//! async runtime: the caller spawns the transport driver and decides how to render.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout, ResourceProxy};
use document_graph_storage::{PeerId, UserId};
use graph_craft::document::NodeNetwork;
use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
pub use document_graph_storage::to_runtime::ConversionError;
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
#[error(transparent)]
Format(#[from] FormatError),
#[error(transparent)]
Conversion(#[from] ConversionError),
}
pub struct LiveDocument {
gdd: GddV1,
token: SessionToken,
}
impl LiveDocument {
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
/// future for as long as the session lives.
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let gdd = Self::empty_document(peer).await?;
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
}
/// Host a session on an already opened document.
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.share(room, user);
Self { gdd, token }
}
/// Join the session under `token`; the document fills in once the host's sync arrives.
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let mut gdd = Self::empty_document(peer).await?;
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.join(room, user);
Ok(Self { gdd, token })
}
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
let version = env!("CARGO_PKG_VERSION").to_string();
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, peer.0, version.clone(), version).await
}
pub fn token(&self) -> SessionToken {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
/// Synced and holding every resource the document references, so `network` can be built and run.
pub fn is_ready(&self) -> bool {
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
}
/// Apply whatever peers sent since the last call and answer their resource requests. Call it regularly.
pub async fn poll(&mut self) -> Vec<Event> {
let events = self.gdd.poll_peers();
for event in &events {
let Event::ResourceRequested { from, hash } = event else { continue };
match self.gdd.read_resource(hash).await {
Ok(bytes) => {
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
log::warn!("Failed to send resource {hash}: {error}");
}
}
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
}
}
events
}
pub fn document(&self) -> &GddV1 {
&self.gdd
}
pub fn document_mut(&mut self) -> &mut GddV1 {
&mut self.gdd
}
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
Ok(network)
}
/// Byte store for resources received from peers, for an executor to load from.
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
self.gdd.resource_proxy()
}
pub fn leave(&mut self) {
self.gdd.leave();
}
}
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "peer-transport"
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
rust-version.workspace = true
edition.workspace = true
authors.workspace = true
homepage.workspace = true
repository.workspace = true
license.workspace = true
version.workspace = true
publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
rmp-serde = { workspace = true }
base64 = { workspace = true }
thiserror = { workspace = true }
uuid = "1"
[target.'cfg(not(target_family = "wasm"))'.dependencies]
rustls = { version = "0.23", default-features = false, features = ["ring"] }
[dev-dependencies]
serde_json = { workspace = true }
env_logger = { workspace = true }
[lints]
workspace = true
+19
View File
@@ -0,0 +1,19 @@
pub mod mock;
mod packet;
mod replica;
mod room;
mod target;
mod token;
mod transport;
pub use packet::{PacketError, Role, SyncPacket, SyncPayload};
pub use replica::{Event, Replica, ReplicaError};
pub use room::Room;
pub use target::{SyncTarget, TargetError};
pub use token::{InvalidSessionToken, SessionToken};
pub use transport::{Transport, TransportEvent, TransportPeerId};
pub use matchbox_socket::MessageLoopFuture;
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
+175
View File
@@ -0,0 +1,175 @@
//! In-process transport for deterministic simulation. Every packet sits in a per-(sender, receiver)
//! queue until `step` delivers it, so interleavings across peers are driven by the seed while each
//! pair stays ordered like a reliable channel.
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
#[derive(Default)]
struct Shared {
connected: Vec<TransportPeerId>,
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
next_peer: u128,
}
impl Shared {
fn disconnect(&mut self, id: TransportPeerId) {
self.connected.retain(|&other| other != id);
self.in_flight.retain(|&(from, to), _| from != id && to != id);
for &other in &self.connected.clone() {
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
}
}
}
pub struct MockNetwork {
shared: Arc<Mutex<Shared>>,
rng: SplitMix64,
}
impl MockNetwork {
pub fn new(seed: u64) -> Self {
Self {
shared: Arc::new(Mutex::new(Shared::default())),
rng: SplitMix64(seed),
}
}
/// A new, not yet connected peer.
pub fn endpoint(&mut self) -> MockEndpoint {
let mut shared = self.shared.lock().unwrap();
shared.next_peer += 1;
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
shared.inboxes.insert(id, VecDeque::new());
MockEndpoint {
id,
shared: self.shared.clone(),
known_peers: Vec::new(),
}
}
pub fn connect(&mut self, id: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
if shared.connected.contains(&id) {
return;
}
for &other in &shared.connected.clone() {
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
}
shared.connected.push(id);
}
pub fn disconnect(&mut self, id: TransportPeerId) {
self.shared.lock().unwrap().disconnect(id);
}
pub fn pending(&self) -> usize {
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
}
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
pub fn step(&mut self) -> bool {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
if queues.is_empty() {
return false;
}
let (from, to) = queues[self.rng.below(queues.len())];
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
true
}
pub fn deliver_all(&mut self) {
while self.step() {}
}
/// Deliver everything in flight to one peer, leaving every other peer's queues untouched. Random
/// stepping cannot target a receiver, so this is how a test puts a packet in one peer's hands and
/// not another's.
pub fn deliver_to(&mut self, to: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
for key in queues {
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
for packet in packets {
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
}
}
}
pub fn random_below(&mut self, bound: usize) -> usize {
self.rng.below(bound)
}
}
/// Like a real socket, an endpoint only knows the peers whose connect events it has polled, so it
/// can't send to a peer before it had the chance to greet it.
pub struct MockEndpoint {
id: TransportPeerId,
shared: Arc<Mutex<Shared>>,
known_peers: Vec<TransportPeerId>,
}
impl MockEndpoint {
pub fn id(&self) -> TransportPeerId {
self.id
}
}
impl Transport for MockEndpoint {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
if self.known_peers.contains(&to) {
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
}
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
for to in self.known_peers.clone() {
if Some(to) != excluded {
self.send(to, packet)?;
}
}
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
for event in &events {
match event {
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
_ => {}
}
}
events
}
fn close(&mut self) {
self.shared.lock().unwrap().disconnect(self.id);
}
}
struct SplitMix64(u64);
impl SplitMix64 {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, bound: usize) -> usize {
(self.next() % bound as u64) as usize
}
}
+100
View File
@@ -0,0 +1,100 @@
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
use serde::{Deserialize, Serialize};
/// The host is the single peer that retires hot ops.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Role {
Host,
Guest,
}
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts
/// `seq`, so `epoch` names the incarnation that produced it and counters from different epochs are
/// never compared.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerSeq {
pub peer: PeerId,
pub epoch: u64,
pub seq: u64,
}
/// MessagePack-encoded on the wire.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SyncPacket {
/// Sent first on every new connection. `epoch` and `seq` anchor the receiver's counter for this
/// sender, since broadcasts made before the connection were never sent to it.
Hello {
peer: PeerId,
user: UserId,
role: Role,
epoch: u64,
seq: u64,
},
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
SyncRequest {
known_revs: Vec<Rev>,
},
Sync(Box<SyncPayload>),
Broadcast(Broadcast),
ResourceRequest(Vec<ResourceHash>),
Resource {
hash: ResourceHash,
#[serde(with = "serde_bytes")]
bytes: Vec<u8>,
},
}
/// The host's answer to a `SyncRequest`. `registry` is only sent when the host recognized none of
/// the requester's revs; otherwise `deltas` extend the requester's history. `seen` is the host's
/// delivery vector at snapshot time, which the guest adopts so later broadcasts line up.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncPayload {
pub registry: Option<Registry>,
pub deltas: Vec<Delta>,
pub head: Option<Rev>,
pub hot_log: Vec<HotOp>,
pub known_revs: Vec<Rev>,
pub seen: Vec<PeerSeq>,
/// Which hot ops the history being handed over already covers, so the requester can recognize one
/// it is holding rather than re-entering it as live work.
pub retired: RetiredMarks,
}
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen`
/// is the sender's delivery vector; a receiver holds the packet until it has delivered everything in
/// `seen`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Broadcast {
pub epoch: u64,
pub seq: u64,
pub seen: Vec<PeerSeq>,
pub body: BroadcastBody,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BroadcastBody {
HotOps(Vec<HotOp>),
/// `deltas` are in causal order. `retires` names the hot ops they replace (empty for a plain history transfer).
Deltas {
deltas: Vec<Delta>,
retires: Vec<HotOpId>,
},
}
#[derive(Debug, thiserror::Error)]
pub enum PacketError {
#[error("failed to encode packet: {0}")]
Encode(#[from] rmp_serde::encode::Error),
#[error("failed to decode packet: {0}")]
Decode(#[from] rmp_serde::decode::Error),
}
impl SyncPacket {
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
}
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
Ok(rmp_serde::from_slice(bytes)?)
}
}
+588
View File
@@ -0,0 +1,588 @@
use crate::packet::{Broadcast, BroadcastBody, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
use crate::target::{SyncTarget, TargetError};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, ResourceHash, UserId};
use std::collections::{HashMap, HashSet};
pub enum Event {
PeerJoined {
peer: PeerId,
user: UserId,
},
PeerLeft {
peer: PeerId,
},
/// The guest has applied the host's state.
Synced,
/// Remote ops changed the target.
Changed,
ResourceReceived {
hash: ResourceHash,
bytes: Vec<u8>,
},
/// The target couldn't serve this synchronously; answer with `send_resource`.
ResourceRequested {
from: TransportPeerId,
hash: ResourceHash,
},
}
#[derive(Debug, thiserror::Error)]
pub enum ReplicaError {
#[error(transparent)]
Packet(#[from] PacketError),
#[error(transparent)]
Target(#[from] TargetError),
}
struct RemotePeer {
peer: PeerId,
#[expect(dead_code, reason = "Read once peers are surfaced in the UI")]
user: UserId,
#[expect(dead_code, reason = "Read once host handover is implemented")]
role: Role,
}
/// How far one peer's broadcasts have been delivered here.
#[derive(Clone, Copy)]
struct PeerProgress {
epoch: u64,
seq: u64,
}
/// Broadcasts that arrive before the host's `Sync` are held back, since they target state the guest
/// doesn't have yet.
enum SyncState {
Synced,
AwaitingSync { pending: Vec<(PeerId, Broadcast)> },
}
/// Protocol state for one peer in a room. Owns no document; `poll` applies into a `SyncTarget`.
///
/// Broadcasts are delivered in causal order: each carries the sender's sequence number and delivery
/// vector, and is held until everything the sender had delivered has been delivered here too.
pub struct Replica {
transport: Box<dyn Transport>,
role: Role,
peer: PeerId,
user: UserId,
peers: HashMap<TransportPeerId, RemotePeer>,
sync: SyncState,
/// This incarnation, drawn fresh so a reconnect or a reload never reuses one. See [`PeerSeq`].
epoch: u64,
seq: u64,
delivered: HashMap<PeerId, PeerProgress>,
held: Vec<(PeerId, Broadcast)>,
/// Hot ops whose referents had not arrived when they did, retried as later ops fill the gaps.
/// A missing entity is not distinguishable from one that was concurrently removed, so the op is
/// kept rather than applied against state it does not fit.
deferred: Vec<HotOp>,
/// Broadcasts that arrived before their sender's hello, parked rather than dropped so a reordering
/// on a fresh link cannot lose ops.
ungreeted: HashMap<TransportPeerId, Vec<Broadcast>>,
/// Resources asked for and not yet received, so a standing request is not resent every poll.
requested_resources: HashSet<ResourceHash>,
/// Requests that arrived before the bytes did, answered once they turn up here.
owed_resources: HashMap<ResourceHash, HashSet<TransportPeerId>>,
/// Whether the target's resource references may have moved since they were last examined.
resources_stale: bool,
}
impl Replica {
pub fn host(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
Self::new(Box::new(transport), Role::Host, peer, user, SyncState::Synced)
}
pub fn guest(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
Self::new(Box::new(transport), Role::Guest, peer, user, SyncState::AwaitingSync { pending: Vec::new() })
}
fn new(transport: Box<dyn Transport>, role: Role, peer: PeerId, user: UserId, sync: SyncState) -> Self {
Self {
transport,
role,
peer,
user,
peers: HashMap::new(),
sync,
epoch: core_types::uuid::generate_uuid(),
seq: 0,
delivered: HashMap::new(),
held: Vec::new(),
deferred: Vec::new(),
ungreeted: HashMap::new(),
requested_resources: HashSet::new(),
owed_resources: HashMap::new(),
resources_stale: false,
}
}
pub fn role(&self) -> Role {
self.role
}
pub fn is_synced(&self) -> bool {
matches!(self.sync, SyncState::Synced)
}
/// Broadcasts waiting on causal dependencies. Non-zero in an idle room means a stuck delivery.
pub fn held_broadcasts(&self) -> usize {
self.held.len()
}
/// Ops held back for a referent that had not arrived. Non-zero in an idle room means one never did.
pub fn deferred_ops(&self) -> usize {
self.deferred.len()
}
/// Resources asked for whose bytes have not come back yet.
pub fn pending_resource_requests(&self) -> impl Iterator<Item = ResourceHash> + '_ {
self.requested_resources.iter().copied()
}
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
if ops.is_empty() {
return Ok(());
}
// A local edit can name a resource whose bytes are not here, a pasted node referencing a font for
// instance, so the references are worth re-examining even though nothing arrived from the wire.
self.resources_stale = true;
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
}
/// Host only.
pub fn broadcast_retired(&mut self, deltas: &[Delta], retires: &[HotOpId]) -> Result<(), PacketError> {
debug_assert_eq!(self.role, Role::Host);
if deltas.is_empty() {
return Ok(());
}
// Retirement moves ops into history, which referenced resources are read from as well as from the
// registry, so a hash the registry has since overwritten becomes referenced again from here.
self.resources_stale = true;
self.broadcast(BroadcastBody::Deltas {
deltas: deltas.to_vec(),
retires: retires.to_vec(),
})
}
fn broadcast(&mut self, body: BroadcastBody) -> Result<(), PacketError> {
self.seq += 1;
let broadcast = Broadcast {
epoch: self.epoch,
seq: self.seq,
seen: self.seen_vector(),
body,
};
self.transport.broadcast(&SyncPacket::Broadcast(broadcast))
}
/// Everything delivered here, including this peer's own broadcasts.
fn seen_vector(&self) -> Vec<PeerSeq> {
let delivered = self.delivered.iter().map(|(&peer, progress)| PeerSeq {
peer,
epoch: progress.epoch,
seq: progress.seq,
});
delivered
.chain([PeerSeq {
peer: self.peer,
epoch: self.epoch,
seq: self.seq,
}])
.collect()
}
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
}
pub fn leave(&mut self) {
self.transport.close();
}
pub fn poll(&mut self, target: &mut dyn SyncTarget) -> Vec<Event> {
let mut events = Vec::new();
let transport_events = self.transport.poll();
// Greet every new peer before handling anything else in the batch. A transport adds them to its
// send set for the whole batch up front, so a broadcast made while handling an earlier event
// would reach a peer that has not been greeted; the hello that followed would then carry a
// sequence number covering it, and the receiver would rightly treat those ops as unneeded.
for transport_event in &transport_events {
if let TransportEvent::PeerConnected(transport_peer) = transport_event
&& let Err(error) = self.send_hello(*transport_peer)
{
log::error!("Sync error: {error}");
}
}
for transport_event in transport_events {
let result = match transport_event {
TransportEvent::PeerConnected(_) => Ok(()),
TransportEvent::PeerDisconnected(transport_peer) => {
let departed = self.peers.remove(&transport_peer);
if let Some(remote) = &departed {
events.push(Event::PeerLeft { peer: remote.peer });
}
// A peer that left may have been the one still owing bytes, so let the rest be asked again.
self.requested_resources.clear();
self.resources_stale = true;
// The hello those were waiting on is never coming now.
self.ungreeted.remove(&transport_peer);
match departed {
Some(remote) => self.close_epoch(remote.peer, target, &mut events),
None => Ok(()),
}
}
TransportEvent::Packet(transport_peer, packet) => self.handle_packet(transport_peer, packet, target, &mut events),
TransportEvent::Malformed(transport_peer, error) => {
log::warn!("Dropping malformed packet from {transport_peer}: {error}");
Ok(())
}
};
if let Err(error) = result {
log::error!("Sync error: {error}");
}
}
self.retry_deferred(target, &mut events);
if let Err(error) = target.flush() {
log::error!("Sync error: {error}");
}
if let Err(error) = self.request_missing_resources(target) {
log::error!("Sync error: {error}");
}
if let Err(error) = self.serve_owed_resources(target) {
log::error!("Sync error: {error}");
}
events
}
/// Re-announce every hot op held here that history does not yet cover, whoever wrote it. A peer can
/// hold the only copy of another's op, so replaying only our own would leave that one to die with the
/// connection it arrived on. Ops the watermark covers replay as no-ops on every receiver.
fn reannounce_hot_ops(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
let retired = target.retired_marks();
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
self.broadcast_hot_ops(&unretired)
}
/// Retry ops held back for a missing referent. A later op can supply the entity an earlier one
/// named, so this runs once per poll rather than only where the op arrived.
fn retry_deferred(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) {
if self.deferred.is_empty() {
return;
}
let pending = std::mem::take(&mut self.deferred);
let waiting = pending.len();
match target.apply_remote_hot_ops(pending) {
Ok(deferred) => {
// One that finally applied can name a resource nobody here has seen, and leaves the target
// changed, neither of which anything else in the poll would notice.
if deferred.len() < waiting {
self.resources_stale = true;
events.push(Event::Changed);
}
self.deferred = deferred;
}
Err(error) => log::error!("Retrying deferred hot ops: {error}"),
}
}
/// Ask the room for referenced bytes nobody here has yet. Runs after every batch of packets rather
/// than once at sync, since an op delivered later can reference a resource this peer has never seen.
/// Only the hashes without a standing request go out, so a slow transfer is not re-requested.
fn request_missing_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
if !self.resources_stale {
return Ok(());
}
self.resources_stale = false;
let missing = target.missing_resources();
// A resource that turned up some other way, staged here for instance, leaves its request behind.
// Clearing those keeps a later ask for the same hash from being suppressed.
self.requested_resources.retain(|hash| missing.contains(hash));
let unasked: Vec<ResourceHash> = missing.into_iter().filter(|hash| !self.requested_resources.contains(hash)).collect();
if unasked.is_empty() {
return Ok(());
}
self.requested_resources.extend(unasked.iter().copied());
self.transport.broadcast(&SyncPacket::ResourceRequest(unasked))
}
/// Answer requests that arrived before their bytes did. A resource can turn up locally rather than
/// over the wire, so this runs every poll; a requester never asks twice, so nothing else would.
fn serve_owed_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
if self.owed_resources.is_empty() {
return Ok(());
}
let ready: Vec<(ResourceHash, Vec<u8>)> = self.owed_resources.keys().filter_map(|&hash| target.resource_bytes(hash).map(|bytes| (hash, bytes))).collect();
for (hash, bytes) in ready {
for to in self.owed_resources.remove(&hash).unwrap_or_default() {
self.transport.send(to, &SyncPacket::Resource { hash, bytes: bytes.clone() })?;
}
}
Ok(())
}
fn send_hello(&mut self, transport_peer: TransportPeerId) -> Result<(), ReplicaError> {
let hello = SyncPacket::Hello {
peer: self.peer,
user: self.user,
role: self.role,
epoch: self.epoch,
seq: self.seq,
};
self.transport.send(transport_peer, &hello)?;
Ok(())
}
fn handle_packet(&mut self, from: TransportPeerId, packet: SyncPacket, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
match packet {
SyncPacket::Hello { peer, user, role, epoch, seq } => {
self.peers.insert(from, RemotePeer { peer, user, role });
self.anchor_delivered(peer, epoch, seq);
// Now that the sender is known, whatever arrived ahead of its hello can be handled.
for broadcast in self.ungreeted.remove(&from).unwrap_or_default() {
self.handle_packet(from, SyncPacket::Broadcast(broadcast), target, events)?;
}
// The anchor can unblock broadcasts held against the counter an earlier link reached.
self.deliver_held(target, events)?;
self.reannounce_hot_ops(&*target)?;
events.push(Event::PeerJoined { peer, user });
// A fresh peer may hold bytes nobody else here could serve.
self.requested_resources.clear();
self.resources_stale = true;
if role == Role::Host && !self.is_synced() {
self.transport.send(from, &SyncPacket::SyncRequest { known_revs: target.known_revs() })?;
}
}
SyncPacket::SyncRequest { known_revs } => {
if self.role != Role::Host {
return Ok(());
}
let shares_history = known_revs.iter().any(|&rev| target.contains_rev(rev));
let sync = SyncPayload {
registry: (!shares_history).then(|| target.retired_registry()),
deltas: target.deltas_unknown_to(&known_revs),
head: target.head(),
hot_log: target.hot_log(),
known_revs: target.known_revs(),
seen: self.seen_vector(),
retired: target.retired_marks(),
};
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
}
SyncPacket::Sync(sync) => {
let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) else {
return Ok(());
};
match sync.registry {
Some(registry) => target.load(registry, sync.deltas, sync.head)?,
None => target.merge_remote(sync.deltas, &[])?,
}
target.absorb_retired_marks(&sync.retired)?;
self.deferred.extend(target.apply_remote_hot_ops(sync.hot_log)?);
self.resources_stale = true;
// The host's hot log is not a superset of the room's: this peer may hold the only copy of an
// op that never reached the host, and history is the only way it survives.
self.reannounce_hot_ops(&*target)?;
// Broadcasts the host had delivered before answering are already reflected in the snapshot.
for mark in sync.seen {
self.observe_delivered(mark);
}
// An earlier seq is baked into the snapshot already.
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
self.held.extend(worth_holding);
self.deliver_held(target, events)?;
let host_is_missing = target.deltas_unknown_to(&sync.known_revs);
if !host_is_missing.is_empty() {
self.broadcast(BroadcastBody::Deltas {
deltas: host_is_missing,
retires: Vec::new(),
})?;
}
// Hot ops only ever existed in flight, so a drop loses them where retired work survives in
// history. Re-announce the ones authored here.
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
self.broadcast_hot_ops(&own_hot_ops)?;
events.push(Event::Synced);
}
SyncPacket::Broadcast(broadcast) => {
// Its sender is only known from a hello, so park it rather than drop it.
let Some(remote) = self.peers.get(&from) else {
self.ungreeted.entry(from).or_default().push(broadcast);
return Ok(());
};
let sender = remote.peer;
match &mut self.sync {
SyncState::AwaitingSync { pending } => pending.push((sender, broadcast)),
SyncState::Synced => {
if self.worth_holding(sender, &broadcast) {
self.held.push((sender, broadcast));
self.deliver_held(target, events)?;
}
}
}
}
SyncPacket::ResourceRequest(hashes) => {
for hash in hashes {
match target.resource_bytes(hash) {
Some(bytes) => self.transport.send(from, &SyncPacket::Resource { hash, bytes })?,
None => {
self.owed_resources.entry(hash).or_default().insert(from);
events.push(Event::ResourceRequested { from, hash });
}
}
}
}
SyncPacket::Resource { hash, bytes } => {
if ResourceHash::from(bytes.as_slice()) != hash {
log::warn!("Resource from {from} does not match its hash; dropping");
return Ok(());
}
target.store_resource(hash, &bytes)?;
self.requested_resources.remove(&hash);
events.push(Event::ResourceReceived { hash, bytes });
}
}
Ok(())
}
/// Record that a peer's broadcasts up to `mark` need not be waited for. Monotonic, since a hello
/// and a host's `seen` vector can carry the same fact in either order.
fn observe_delivered(&mut self, mark: PeerSeq) {
if mark.peer == self.peer {
return;
}
match self.delivered.get_mut(&mark.peer) {
Some(progress) if progress.epoch == mark.epoch => progress.seq = progress.seq.max(mark.seq),
Some(_) => {}
None => {
self.delivered.insert(mark.peer, PeerProgress { epoch: mark.epoch, seq: mark.seq });
}
}
}
/// Set where a peer's broadcasts resume on a newly opened link. Nothing before its hello was ever
/// sent here, so this replaces rather than raises.
fn anchor_delivered(&mut self, peer: PeerId, epoch: u64, seq: u64) {
if peer == self.peer {
return;
}
self.delivered.insert(peer, PeerProgress { epoch, seq });
// Held broadcasts from an earlier incarnation can never be delivered in order, and the sender
// re-announces what is still hot once it resyncs.
self.held.retain(|(sender, broadcast)| *sender != peer || broadcast.epoch == epoch);
}
/// Settle up after a peer leaves: its own held broadcasts can never fill their gaps, and anything
/// waiting on it is now free to go.
fn close_epoch(&mut self, peer: PeerId, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
// Buffered broadcasts go too, in both queues. Applying them after their author left would mint a
// fresh orphan with no departure left to clean it up, and nothing has been applied yet, so
// dropping them breaks no dependency. Anything else waiting on this peer is released instead.
if let SyncState::AwaitingSync { pending } = &mut self.sync {
pending.retain(|(sender, _)| *sender != peer);
}
self.held.retain(|(sender, _)| *sender != peer);
// Its ops waiting on a referent have nobody left to supply one, so they stop being held open.
// Retirement drains the rest: an op the watermark covers replays as a no-op and leaves the queue.
self.deferred.retain(|hot_op| hot_op.timestamp.peer != peer);
self.deliver_held(target, events)?;
// The departed peer's unretired work reached some peers and not others, and it can no longer
// re-announce the difference itself. Passing on the whole hot tail covers it along with anything
// that depends on it, so the host can retire the lot into history.
self.reannounce_hot_ops(&*target)?;
Ok(())
}
/// Whether a link to this peer is open, meaning more of its broadcasts may still turn up.
fn is_connected(&self, peer: PeerId) -> bool {
self.peers.values().any(|remote| remote.peer == peer)
}
/// Deliver every held broadcast whose causal dependencies are met, repeating since each delivery
/// can unblock others.
fn deliver_held(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
while let Some(index) = self.held.iter().position(|(sender, broadcast)| self.is_deliverable(*sender, broadcast)) {
let (sender, broadcast) = self.held.remove(index);
self.delivered.insert(
sender,
PeerProgress {
epoch: broadcast.epoch,
seq: broadcast.seq,
},
);
// Applying is best effort: the ops that did land still have to be accounted for, so a failure
// is reported rather than abandoning the bookkeeping and the rest of the queue.
let applied = match broadcast.body {
BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
BroadcastBody::Deltas { deltas, retires } => target.merge_remote(deltas, &retires),
};
if let Err(error) = applied {
log::error!("Applying a delivered broadcast: {error}");
}
self.resources_stale = true;
events.push(Event::Changed);
}
Ok(())
}
fn is_deliverable(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
let Some(progress) = self.delivered.get(&sender) else { return false };
if progress.epoch != broadcast.epoch || broadcast.seq != progress.seq + 1 {
return false;
}
broadcast.seen.iter().all(|&mark| mark.peer == sender || self.has_delivered(mark))
}
/// Whether a broadcast can still come up for delivery. A stale epoch or an already-delivered seq
/// never will, so holding one would park it for good.
fn worth_holding(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
self.delivered.get(&sender).is_none_or(|progress| progress.epoch == broadcast.epoch && broadcast.seq > progress.seq)
}
/// Whether one of a broadcast's dependencies is met. Dependencies that can never be met count as
/// met, rather than stalling their sender for good.
fn has_delivered(&self, mark: PeerSeq) -> bool {
if mark.peer == self.peer {
return mark.epoch != self.epoch || mark.seq <= self.seq;
}
match self.delivered.get(&mark.peer) {
Some(progress) if progress.epoch != mark.epoch => true,
Some(progress) if progress.seq >= mark.seq => true,
// A peer with no open link sends nothing more, including one whose hello never arrived.
_ => !self.is_connected(mark.peer),
}
}
}
+229
View File
@@ -0,0 +1,229 @@
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use matchbox_socket::{MessageLoopFuture, PeerState, WebRtcSocket};
use std::collections::HashMap;
const CHANNEL: usize = 0;
/// Largest SCTP message every browser accepts.
const CHUNK_BYTES: usize = 16 * 1024;
const FRAME_FINAL: u8 = 1;
const FRAME_MORE: u8 = 0;
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so a receiver finds
/// the packet boundary without a length prefix.
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// An empty packet still gets one frame. Chunking it would yield none at all, and the packet would
// leave no trace on the wire rather than arriving empty.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
chunks
.iter()
.enumerate()
.map(|(index, chunk)| {
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
std::iter::once(flag).chain(chunk.iter().copied()).collect()
})
.collect()
}
/// Per-peer reassembly of framed packets. The channel is reliable and ordered per peer, so chunks
/// arrive in the order they were sent and a packet ends at the first [`FRAME_FINAL`].
#[derive(Default)]
struct Reassembler {
partial: HashMap<TransportPeerId, Vec<u8>>,
}
impl Reassembler {
/// The packet's bytes once its final chunk lands, or `None` while more are still to come.
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
let (&flag, chunk) = frame.split_first()?;
let buffer = self.partial.entry(peer).or_default();
buffer.extend_from_slice(chunk);
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
}
/// Drop a peer's half-received packet, which nothing will ever complete.
fn forget(&mut self, peer: TransportPeerId) {
self.partial.remove(&peer);
}
}
/// One matchbox room over WebRTC. Packets are split into `[flag][bytes]` chunks; the reliable
/// channel is ordered per peer, so the receiver reassembles by appending until the final flag.
/// The returned future must be polled continuously by the caller.
pub struct Room {
socket: WebRtcSocket,
incoming: Reassembler,
}
impl Room {
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
#[cfg(not(target_family = "wasm"))]
let _ = rustls::crypto::ring::default_provider().install_default();
let (socket, driver) = WebRtcSocket::new_reliable(signaling_url);
(
Self {
socket,
incoming: Reassembler::default(),
},
driver,
)
}
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
let channel = self.socket.channel_mut(CHANNEL);
for frame in frames(bytes) {
for &peer in peers {
channel.send(frame.clone(), peer);
}
}
}
}
impl Transport for Room {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
self.send_chunks(&bytes, &[to]);
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
self.send_chunks(&bytes, &peers);
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let mut events = Vec::new();
for (peer, state) in self.socket.update_peers() {
events.push(match state {
PeerState::Connected => TransportEvent::PeerConnected(peer),
PeerState::Disconnected => {
self.incoming.forget(peer);
TransportEvent::PeerDisconnected(peer)
}
});
}
let received: Vec<_> = self.socket.channel_mut(CHANNEL).receive();
for (peer, frame) in received {
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
events.push(match SyncPacket::decode(&bytes) {
Ok(packet) => TransportEvent::Packet(peer, packet),
Err(error) => TransportEvent::Malformed(peer, error),
});
}
events
}
fn close(&mut self) {
self.socket.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn peer(byte: u128) -> TransportPeerId {
TransportPeerId(uuid::Uuid::from_u128(byte))
}
/// Push every frame at a reassembler and collect whatever packets come back out.
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
let mut incoming = Reassembler::default();
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
}
/// A packet within one chunk travels as a single final frame.
#[test]
fn a_small_packet_is_one_frame() {
let bytes = b"hello".to_vec();
let framed = frames(&bytes);
assert_eq!(framed.len(), 1);
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes]);
}
/// Chunking an empty packet yields no chunks at all, so it needs a frame of its own or it would
/// leave no trace on the wire.
#[test]
fn an_empty_packet_still_produces_one_frame() {
let framed = frames(&[]);
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
}
/// The boundary either side of the SCTP limit: exactly one chunk stays one frame, one byte more
/// splits, and both rebuild byte for byte.
#[test]
fn packets_around_the_chunk_boundary_round_trip() {
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
let framed = frames(&bytes);
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
}
}
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet would be
/// spliced into the other.
#[test]
fn interleaved_peers_reassemble_separately() {
let (first, second) = (peer(1), peer(2));
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
let short = b"short".to_vec();
let long_frames = frames(&long);
let short_frames = frames(&short);
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
// The short packet arrives whole between the long packet's two chunks.
assert_eq!(incoming.accept(first, &long_frames[0]), None);
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
}
/// A peer that drops mid-packet leaves a partial buffer, which must not be prepended to whatever
/// the next peer to reuse that id sends.
#[test]
fn forgetting_a_peer_discards_its_partial_packet() {
let sender = peer(1);
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
incoming.forget(sender);
let fresh = b"fresh".to_vec();
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
}
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
#[test]
fn an_empty_frame_is_ignored() {
let mut incoming = Reassembler::default();
assert_eq!(incoming.accept(peer(1), &[]), None);
}
}
+114
View File
@@ -0,0 +1,114 @@
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
use std::collections::HashSet;
pub type TargetError = Box<dyn std::error::Error>;
/// The document state a `Replica` reads from and applies remote changes to.
pub trait SyncTarget {
fn peer(&self) -> PeerId;
fn head(&self) -> Option<Rev>;
fn retired_registry(&self) -> Registry;
fn hot_log(&self) -> Vec<HotOp>;
fn known_revs(&self) -> Vec<Rev>;
fn contains_rev(&self, rev: Rev) -> bool;
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta>;
/// Highest hot-op counter retired per author.
fn retired_marks(&self) -> RetiredMarks;
/// Take on a peer's retirement watermark, dropping any hot op it shows as already retired.
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError>;
/// Replace all state with the given retired state.
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
/// Must be idempotent on structural ops: a buffered op may already be reflected by the sync.
/// Returns the ops it could not apply, whose referents have not arrived yet; the caller retries
/// them as later ops fill the gaps.
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError>;
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll),
/// so a target that rewrites whole files can do it once for a batch rather than once per packet.
fn flush(&mut self) -> Result<(), TargetError> {
Ok(())
}
/// Referenced resources whose bytes are not available locally.
fn missing_resources(&self) -> HashSet<ResourceHash> {
HashSet::new()
}
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
let _ = hash;
None
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
let _ = (hash, bytes);
Ok(())
}
}
impl SyncTarget for Session {
fn peer(&self) -> PeerId {
Session::peer(self)
}
fn head(&self) -> Option<Rev> {
self.head_rev()
}
fn retired_registry(&self) -> Registry {
Session::retired_registry(self).clone()
}
fn hot_log(&self) -> Vec<HotOp> {
Session::hot_log(self).to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
Session::known_revs(self)
}
fn contains_rev(&self, rev: Rev) -> bool {
self.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
Session::deltas_unknown_to(self, known.iter().copied()).into_iter().cloned().collect()
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
// Kept across the replace: a sequence this peer already spent must not come round again, or an
// op of its own would be taken for one already retired.
*self = Session::load(self.peer(), registry, history, head, Vec::new(), self.next_node_counter(), self.next_hot_sequence());
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// Every op gets its turn even if one fails, since the broadcast that carried them is consumed by
// the time this runs. A failure usually means the entity the op names has not arrived here yet,
// so it is handed back to be retried rather than dropped.
let mut deferred = Vec::new();
for hot_op in ops {
if self.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
}
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
// Hot ops stay until after the merge: a delta may target something a still-hot removal took away.
self.merge(deltas)?;
self.discard_hot_ops(retires);
Ok(())
}
fn retired_marks(&self) -> RetiredMarks {
Session::retired_marks(self).clone()
}
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
Session::absorb_retired_marks(self, remote);
Ok(())
}
}
+55
View File
@@ -0,0 +1,55 @@
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fmt;
use std::str::FromStr;
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
const PREFIX: &str = "graphite-";
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SessionToken(pub [u8; 16]);
impl SessionToken {
pub fn signaling_url(&self, signaling_server: &str) -> String {
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
}
}
impl fmt::Display for SessionToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
}
}
#[derive(Debug, thiserror::Error)]
#[error("invalid session token")]
pub struct InvalidSessionToken;
impl FromStr for SessionToken {
type Err = InvalidSessionToken;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
Ok(Self(bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_string() {
let token = SessionToken([7; 16]);
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
}
#[test]
fn rejects_wrong_length_or_missing_prefix() {
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
}
}
+23
View File
@@ -0,0 +1,23 @@
use crate::packet::{PacketError, SyncPacket};
pub use matchbox_socket::PeerId as TransportPeerId;
pub enum TransportEvent {
PeerConnected(TransportPeerId),
PeerDisconnected(TransportPeerId),
Packet(TransportPeerId, SyncPacket),
Malformed(TransportPeerId, PacketError),
}
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
/// sender, which is what lets the `Replica` skip acknowledgements and buffering.
pub trait Transport: Send + Sync {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
fn poll(&mut self) -> Vec<TransportEvent>;
fn close(&mut self);
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
self.broadcast_except(None, packet)
}
}
+735
View File
@@ -0,0 +1,735 @@
//! Deterministic simulation over the mock transport: random edits on every peer, random delivery
//! order, random host retirement. After quiescence every peer must hold the same retired state.
//!
//! Inspect one run with `SEED=<n> GUESTS=<n> cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
use document_graph_storage::{
AttributeDelta, Delta, HotOp, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId, RetiredMarks, Rev,
Session, SourceKey, TimeStamp, UserId,
};
use peer_transport::mock::{MockEndpoint, MockNetwork};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
static TOTAL_NODES: AtomicUsize = AtomicUsize::new(0);
static TOTAL_WIRED: AtomicUsize = AtomicUsize::new(0);
static TOTAL_EXPORTS: AtomicUsize = AtomicUsize::new(0);
static TOTAL_INPUT_ATTRIBUTES: AtomicUsize = AtomicUsize::new(0);
static TOTAL_SOURCES: AtomicUsize = AtomicUsize::new(0);
/// A peer's document plus the byte store the editor keeps application-wide. Bare `Session` takes the
/// trait's no-op resource defaults, which would leave the whole request path unexercised.
struct SimTarget {
session: Session,
resources: HashMap<ResourceHash, Vec<u8>>,
/// History as of the last `flush`, to check the sync path never leaves applied state undurable.
durable_history: Vec<Rev>,
flushes: usize,
/// Every rev this peer has ever held, to check none is later dropped. See [`SimTarget::flush`].
seen_revs: HashSet<Rev>,
seed: u64,
}
impl SimTarget {
fn new(peer: PeerId, seed: u64) -> Self {
Self {
session: Session::with_peer(peer),
resources: HashMap::new(),
durable_history: Vec::new(),
flushes: 0,
seen_revs: HashSet::new(),
seed,
}
}
fn history_revs(&self) -> Vec<Rev> {
self.session.history().map(|delta| delta.id).collect()
}
}
impl SyncTarget for SimTarget {
fn peer(&self) -> PeerId {
SyncTarget::peer(&self.session)
}
fn head(&self) -> Option<Rev> {
SyncTarget::head(&self.session)
}
fn retired_registry(&self) -> Registry {
SyncTarget::retired_registry(&self.session)
}
fn hot_log(&self) -> Vec<HotOp> {
SyncTarget::hot_log(&self.session)
}
fn known_revs(&self) -> Vec<Rev> {
SyncTarget::known_revs(&self.session)
}
fn contains_rev(&self, rev: Rev) -> bool {
SyncTarget::contains_rev(&self.session, rev)
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
SyncTarget::deltas_unknown_to(&self.session, known)
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
SyncTarget::load(&mut self.session, registry, history, head)
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
SyncTarget::apply_remote_hot_ops(&mut self.session, ops)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
SyncTarget::merge_remote(&mut self.session, deltas, retires)
}
fn retired_marks(&self) -> RetiredMarks {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)
}
fn flush(&mut self) -> Result<(), TargetError> {
// History is append-only. Hot ops are explicitly transient and a rejoin may drop the lot, but a
// retired delta is the durable record, so losing one is data loss no convergence check would see.
let current: HashSet<Rev> = self.history_revs().into_iter().collect();
if let Some(dropped) = self.seen_revs.iter().find(|rev| !current.contains(rev)) {
panic!("seed {}: peer {:?} dropped retired delta {dropped:?} from history", self.seed, self.session.peer());
}
self.seen_revs.extend(current);
self.durable_history = self.history_revs();
self.flushes += 1;
Ok(())
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash)).collect()
}
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
self.resources.get(&hash).cloned()
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
self.resources.insert(hash, bytes.to_vec());
Ok(())
}
}
struct Peer {
target: SimTarget,
replica: Replica,
peer: PeerId,
user: UserId,
transport: TransportPeerId,
/// Gone for good, unlike a rejoin. Its document stops taking part and stops being asserted on.
departed: bool,
}
impl Peer {
fn new(endpoint: MockEndpoint, role: Role, index: u64, seed: u64) -> Self {
let (peer, user) = (PeerId(index), UserId(index));
let transport = endpoint.id();
let replica = match role {
Role::Host => Replica::host(endpoint, peer, user),
Role::Guest => Replica::guest(endpoint, peer, user),
};
Self {
target: SimTarget::new(peer, seed),
replica,
peer,
user,
transport,
departed: false,
}
}
/// Drop off the room, keeping the document. The editor rebuilds the `Replica` on a reconnect but
/// reuses the `Gdd`'s persisted `PeerId`, so protocol state resets while document state does not.
fn rejoin(&mut self, network: &mut MockNetwork) {
network.disconnect(self.transport);
let endpoint = network.endpoint();
self.transport = endpoint.id();
self.replica = Replica::guest(endpoint, self.peer, self.user);
network.connect(self.transport);
}
/// Close the tab. The peer is never heard from again, so the room has to settle without whatever
/// it alone knew.
fn depart(&mut self, network: &mut MockNetwork) {
network.disconnect(self.transport);
self.departed = true;
}
fn session(&self) -> &Session {
&self.target.session
}
fn stage(&mut self, op: RegistryDelta) {
let hot_ops = self.target.session.stage_ops([op]).expect("stage");
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
}
/// Introduce a resource only this peer holds the bytes for, so every other peer has to fetch them.
fn stage_resource(&mut self, bytes: Vec<u8>) {
let hash = ResourceHash::from(bytes.as_slice());
self.target.resources.insert(hash, bytes);
// Each peer names its resources itself, the way live resources get a fresh `ResourceId`. Deriving
// the id from the content instead would collide across peers, which `AddResource` resolves by
// replay order rather than by merging.
let id = ResourceId::from(u64::from(ResourceId::from_hash(&hash)) ^ self.peer.0);
let hot_ops = self.target.session.stage_embedded_resource(id, hash).expect("stage resource");
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
}
fn retire(&mut self) {
let Some(up_to) = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
return;
};
self.retire_up_to(up_to);
}
/// Retire only part of the hot log, leaving newer ops live. A later op of one author can then retire
/// while an earlier one is still in flight, which is what puts entries above the retired prefix.
fn retire_prefix(&mut self, nth: usize) {
let mut timestamps: Vec<TimeStamp> = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).collect();
if timestamps.is_empty() {
return;
}
timestamps.sort();
self.retire_up_to(timestamps[nth.min(timestamps.len() - 1)]);
}
fn retire_up_to(&mut self, up_to: TimeStamp) {
let retired_hot_ops = self.target.session.hot_ops_up_to(up_to);
let revs = self.target.session.retire(up_to).expect("retire");
let deltas: Vec<_> = revs.iter().filter_map(|&rev| self.target.session.delta(rev).cloned()).collect();
self.replica.broadcast_retired(&deltas, &retired_hot_ops).expect("broadcast retired");
}
fn poll(&mut self) -> Vec<Event> {
let flushes_before = self.target.flushes;
let events = self.replica.poll(&mut self.target);
assert_eq!(self.target.flushes, flushes_before + 1, "poll must flush the target exactly once");
events
}
}
/// Node-level ops, which reach the input-slot LWW arms and the resurrection path a concurrent remove
/// triggers. `None` when the registry holds nothing the drawn op could target.
fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<RegistryDelta> {
let registry = session.registry();
let node_id = NodeId(1 + network.random_below(4) as u64);
let live_nodes: Vec<NodeId> = registry.node_instances.keys().copied().collect();
let live_networks: Vec<NetworkId> = registry.networks.keys().copied().collect();
match network.random_below(8) {
// Per-slot attributes, the one place `InputSlot.attributes` is written.
6 => {
let node = registry.node_instances.get(&node_id)?;
let index = network.random_below(node.inputs().len().max(1)) as u32;
Some(RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index,
delta: AttributeDelta {
key: "label".into(),
value: Some(serde_json::json!(network.random_below(100))),
},
})
}
// A node needs a live network to sit in, and `AddNode` errors on one that already exists.
0 | 1 if !registry.node_instances.contains_key(&node_id) => {
let network_id = *pick(network, &live_networks)?;
Some(RegistryDelta::AddNode {
id: node_id,
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 2),
})
}
2 => registry.node_instances.get(&node_id).map(|node| RegistryDelta::RemoveNode { id: node_id, snapshot: node.clone() }),
3 | 4 => {
let node = registry.node_instances.get(&node_id)?;
let index = network.random_below(node.inputs().len().max(1)) as u32;
// Wiring to a node that is live here can still land on a peer that concurrently removed it,
// which is what drives the resurrection path.
let wire_to = pick(network, &live_nodes).copied();
let new_input = match wire_to {
Some(target) if network.random_below(3) > 0 => NodeInput::Node { id: target, index: 0 },
_ => NodeInput::Value {
value: serde_json::json!(network.random_below(100)),
exposed: false,
},
};
Some(RegistryDelta::ChangeNodeInput { id: node_id, index, new_input })
}
_ => pick(network, &live_nodes).copied().map(|node_id| RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: AttributeDelta {
key: "name".into(),
value: Some(serde_json::json!(network.random_below(100))),
},
}),
}
}
/// Resource-lifecycle ops past creation. `AddResource` already rides the staged-resource path, so
/// these cover the rest of the chain: the resolved hash, the source fallback list, and removal.
/// `None` when the registry holds no resource to target.
fn random_resource_op(network: &mut MockNetwork, target: &SimTarget) -> Option<RegistryDelta> {
let session = &target.session;
let registry = session.registry();
let live: Vec<ResourceId> = registry.resources.keys().copied().collect();
let id = *pick(network, &live)?;
// A small pool of priorities, so concurrent adds sometimes collide on a key and sometimes stack up
// as distinct entries in the same chain.
let key = SourceKey {
priority: Priority::new(network.random_below(3) as f64).expect("a whole number is finite"),
peer: session.peer(),
};
Some(match network.random_below(5) {
// Only a hash this peer holds the bytes for: a resolved hash is content derived, so in the editor
// the peer that resolves a resource is the one that fetched it.
0 => {
let held: Vec<ResourceHash> = target.resources.keys().copied().collect();
RegistryDelta::SetResourceHash {
id,
hash: Some(*pick(network, &held)?),
}
}
1 => RegistryDelta::SetResourceHash { id, hash: None },
2 => RegistryDelta::AddSource {
id,
key,
source: serde_json::json!("Embedded"),
},
3 => RegistryDelta::RemoveSource { id, key },
_ => RegistryDelta::RemoveResource {
id,
snapshot: registry.resources.get(&id)?.clone(),
},
})
}
/// One element at random, or `None` when there is nothing to choose from.
fn pick<'a, T>(network: &mut MockNetwork, options: &'a [T]) -> Option<&'a T> {
(!options.is_empty()).then(|| &options[network.random_below(options.len())])
}
fn random_op(network: &mut MockNetwork, target: &SimTarget) -> RegistryDelta {
let session = &target.session;
let network_id = NetworkId(1 + network.random_below(3) as u64);
// Half the ops are node-level, falling through to the network-level ones when nothing fits.
if network.random_below(2) == 0
&& let Some(op) = random_node_op(network, session)
{
return op;
}
// Resources exist only once a peer has staged one, so this yields nothing early in a run.
if network.random_below(5) == 0
&& let Some(op) = random_resource_op(network, target)
{
return op;
}
match network.random_below(6) {
// Export slots resize on demand and LWW per slot, and clearing one leaves a tombstone that must
// still compare equal to the slot being absent.
4 | 5 if session.registry().networks.contains_key(&network_id) => {
let live_nodes: Vec<NodeId> = session.registry().node_instances.keys().copied().collect();
let export = match pick(network, &live_nodes).copied() {
Some(id) if network.random_below(4) > 0 => Some(NodeInput::Node { id, index: 0 }),
_ => None,
};
RegistryDelta::SetNetworkExport {
id: network_id,
index: network.random_below(3) as u32,
export,
}
}
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: format!("key{}", network.random_below(3)),
value: Some(serde_json::json!(network.random_below(100))),
},
},
2 if let Some(network) = session.registry().networks.get(&network_id) => RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: network.clone(),
},
_ if session.registry().networks.contains_key(&network_id) => RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: "name".into(),
value: Some(serde_json::json!(network.random_below(100))),
},
},
_ => RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
}
}
fn present_guests(peers: &[Peer]) -> usize {
peers.iter().skip(1).filter(|peer| !peer.departed).count()
}
/// Run until nothing is in flight and no peer reports progress. Resource transfers need several
/// rounds (request out, bytes back), so this is not a fixed number of passes.
fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) {
for _ in 0..1000 {
network.deliver_all();
let events: usize = peers.iter_mut().filter(|peer| !peer.departed).map(|peer| peer.poll().len()).sum();
if events == 0 && network.pending() == 0 {
return;
}
}
panic!("the room never went idle");
}
fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Peer>) {
let mut network = MockNetwork::new(seed);
let mut peers: Vec<Peer> = (0..=guest_count)
.map(|index| {
let endpoint = network.endpoint();
let id = endpoint.id();
let role = if index == 0 { Role::Host } else { Role::Guest };
let peer = Peer::new(endpoint, role, index as u64 + 1, seed);
network.connect(id);
peer
})
.collect();
for _ in 0..steps {
let index = network.random_below(peers.len());
if peers[index].departed {
continue;
}
match network.random_below(16) {
// A guest edits only once synced; anything staged earlier would be invisible to its peers.
0..=2 if peers[index].replica.is_synced() => {
let op = random_op(&mut network, &peers[index].target);
peers[index].stage(op);
}
// A small pool of distinct payloads, so peers sometimes introduce the same resource
// concurrently and sometimes one nobody else can serve.
8 if peers[index].replica.is_synced() => {
let bytes = format!("resource-{}", network.random_below(5)).into_bytes();
peers[index].stage_resource(bytes);
}
0..=2 | 8 => {}
// Mostly a partial retire, so the host's history lags its hot log the way a real one does.
3 => {
let nth = network.random_below(4);
peers[0].retire_prefix(nth);
}
4..=7 => {
network.step();
}
// The host cannot hand over, so only guests drop and come back.
9 if index > 0 => peers[index].rejoin(&mut network),
9 => {
let endpoint = network.endpoint();
let id = endpoint.id();
peers.push(Peer::new(endpoint, Role::Guest, peers.len() as u64 + 1, seed));
network.connect(id);
}
// Keep one guest around, so the room stays a room.
10 if index > 0 && present_guests(&peers) > 1 => peers[index].depart(&mut network),
_ => {
peers[index].poll();
}
}
}
quiesce(&mut network, &mut peers);
peers[0].retire();
quiesce(&mut network, &mut peers);
(network, peers)
}
/// Dump every peer's state for one seed: `SIM_DUMP=<seed> cargo test ... -- --nocapture`.
fn dump_if_requested(seed: u64, peers: &[Peer]) {
if std::env::var("SIM_DUMP").ok().and_then(|value| value.parse::<u64>().ok()) != Some(seed) {
return;
}
for (index, peer) in peers.iter().enumerate() {
eprintln!(
"DUMP {index} {:?} departed {} synced {} held {} pending_resources {} history {} hot {:?} watermark {:?}",
peer.peer,
peer.departed,
peer.replica.is_synced(),
peer.replica.held_broadcasts(),
peer.replica.pending_resource_requests().count(),
peer.session().history().count(),
peer.session()
.hot_log()
.iter()
.map(|h| format!("{}:{}#{}", h.timestamp.peer.0, h.timestamp.counter, h.sequence))
.collect::<Vec<_>>(),
{
let retired = peer.session().retired_marks();
let mut through: Vec<_> = retired.through.iter().map(|(p, c)| (p.0, *c)).collect();
through.sort();
let mut above: Vec<_> = retired.above.iter().map(|id| (id.peer.0, id.sequence)).collect();
above.sort();
format!("{through:?} above {above:?}")
}
);
}
}
/// Whether every `AddNode` in history names a network that history itself creates. Retirement promotes
/// whatever the host managed to apply, so a referent that only ever existed as an unretired hot op
/// could in principle leave a durable hole here.
fn assert_history_self_contained(seed: u64, peers: &[Peer]) {
for (index, peer) in peers.iter().enumerate().filter(|(_, peer)| !peer.departed) {
let created: HashSet<NetworkId> = peer
.session()
.history()
.filter_map(|delta| match delta.kind {
RegistryDelta::AddNetwork { id, .. } => Some(id),
_ => None,
})
.chain(peer.session().history().filter_map(|delta| match delta.reverse {
RegistryDelta::AddNetwork { id, .. } => Some(id),
_ => None,
}))
.collect();
for delta in peer.session().history() {
if let RegistryDelta::AddNode { node, .. } = &delta.kind {
assert!(
created.contains(&node.network()),
"seed {seed}: peer {index} history has AddNode into {:?} that nothing in history creates",
node.network()
);
}
}
}
}
/// A hot op is identified by its timestamp, so holding one twice means some path appended a copy of
/// something already there, which then replays and re-broadcasts as if it were new work.
fn assert_no_duplicate_hot_ops(seed: u64, peers: &[Peer]) {
for (index, peer) in peers.iter().enumerate() {
let mut seen = HashSet::new();
for hot_op in peer.session().hot_log() {
assert!(seen.insert(hot_op.timestamp), "seed {seed}: peer {index} holds {:?} twice", hot_op.timestamp);
}
}
}
fn assert_converged(seed: u64, peers: &[Peer]) {
dump_if_requested(seed, peers);
assert_no_duplicate_hot_ops(seed, peers);
assert_history_self_contained(seed, peers);
let present = || peers.iter().enumerate().filter(|(_, peer)| !peer.departed);
// A sparse `known_revs` sample only describes a peer's state if history is parent-complete, so a
// hole makes the host under-send on the next resync.
for (index, peer) in present() {
let present_revs: HashSet<Rev> = peer.session().history().map(|delta| delta.id).collect();
for delta in peer.session().history() {
for parent in delta.all_parents() {
assert!(present_revs.contains(&parent), "seed {seed}: peer {index} has {:?} without its parent {parent:?}", delta.id);
}
}
}
let host = &peers[0];
let host_history: Vec<_> = host.session().history().map(|delta| delta.id).collect();
for (index, guest) in present().skip(1) {
let guest_history: Vec<_> = guest.session().history().map(|delta| delta.id).collect();
assert_eq!(guest_history, host_history, "seed {seed}: guest {index} history diverged");
assert_eq!(guest.session().head_rev(), host.session().head_rev(), "seed {seed}: guest {index} head diverged");
assert_eq!(guest.session().retired_registry(), host.session().retired_registry(), "seed {seed}: guest {index} registry diverged");
assert!(guest.session().hot_log().is_empty(), "seed {seed}: guest {index} still holds hot ops");
}
// Bytes that left with a departed peer are gone for good, so the room is only answerable for the
// resources someone still in it could have served.
let servable: HashSet<ResourceHash> = present().flat_map(|(_, peer)| peer.target.resources.keys().copied()).collect();
// An idle room with anything outstanding is stuck, which convergence of content alone can miss:
// a broadcast held forever behind a dependency that will never arrive changes nothing observable.
for (index, peer) in present() {
assert_eq!(peer.replica.held_broadcasts(), 0, "seed {seed}: peer {index} still holds undelivered broadcasts");
assert_eq!(peer.replica.deferred_ops(), 0, "seed {seed}: peer {index} still holds ops waiting on a referent");
assert_eq!(peer.target.durable_history, peer.target.history_revs(), "seed {seed}: peer {index} has unflushed history");
let unserved: Vec<_> = SyncTarget::missing_resources(&peer.target).into_iter().filter(|hash| servable.contains(hash)).collect();
assert!(unserved.is_empty(), "seed {seed}: peer {index} is missing resource bytes another peer holds: {unserved:?}");
}
}
#[test]
fn peers_converge_under_random_interleavings() {
// The committed corpus is the first 1000 seeds; `SIM_SEEDS` pushes the frontier further by hand.
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(1000);
for seed in 0..seeds {
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200);
{
let registry = peers[0].session().retired_registry();
TOTAL_NODES.fetch_add(registry.node_instances.len(), Ordering::Relaxed);
let wired = registry
.node_instances
.values()
.flat_map(|node| node.inputs())
.filter(|slot| matches!(slot.input, NodeInput::Node { .. }))
.count();
TOTAL_WIRED.fetch_add(wired, Ordering::Relaxed);
let exports = registry.networks.values().flat_map(|net| &net.exports).filter(|slot| slot.target.is_some()).count();
TOTAL_EXPORTS.fetch_add(exports, Ordering::Relaxed);
let input_attributes = registry.node_instances.values().flat_map(|node| node.inputs()).filter(|slot| !slot.attributes.is_empty()).count();
TOTAL_INPUT_ATTRIBUTES.fetch_add(input_attributes, Ordering::Relaxed);
// More than one source on a resource can only come from `AddSource`, which the staging path
// never emits, so this is what proves the resource-chain ops reach the registry.
let stacked_sources = registry.resources.values().filter(|entry| entry.sources.len() > 1).count();
TOTAL_SOURCES.fetch_add(stacked_sources, Ordering::Relaxed);
}
assert_converged(seed, &peers);
}
// The node ops are guarded on what the registry holds, so a generator change can quietly stop
// producing them. Without nodes wired to other nodes nothing reaches the resurrection path.
assert!(TOTAL_NODES.load(Ordering::Relaxed) > 0, "the corpus produced no nodes");
assert!(TOTAL_WIRED.load(Ordering::Relaxed) > 0, "the corpus produced no node-to-node inputs");
assert!(TOTAL_EXPORTS.load(Ordering::Relaxed) > 0, "the corpus set no network exports");
assert!(TOTAL_INPUT_ATTRIBUTES.load(Ordering::Relaxed) > 0, "the corpus wrote no input-slot attributes");
assert!(TOTAL_SOURCES.load(Ordering::Relaxed) > 0, "the corpus never stacked a second source on a resource");
}
/// A guest that drops and comes back keeps its `PeerId` but gets a fresh `Replica`, so its broadcast
/// sequence restarts. The room must follow the restart rather than keep waiting on the sequence the
/// old connection had reached.
#[test]
fn a_rejoining_guest_is_still_heard() {
let mut network = MockNetwork::new(0);
let mut peers: Vec<Peer> = (0..2)
.map(|index| {
let endpoint = network.endpoint();
let id = endpoint.id();
let role = if index == 0 { Role::Host } else { Role::Guest };
let peer = Peer::new(endpoint, role, index as u64 + 1, 0);
network.connect(id);
peer
})
.collect();
quiesce(&mut network, &mut peers);
peers[1].stage(RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
});
quiesce(&mut network, &mut peers);
assert!(peers[0].session().registry().networks.contains_key(&NetworkId(1)), "the host missed the first edit");
peers[1].rejoin(&mut network);
quiesce(&mut network, &mut peers);
peers[1].stage(RegistryDelta::AddNetwork {
id: NetworkId(2),
network: Network::default(),
});
quiesce(&mut network, &mut peers);
assert_eq!(peers[0].replica.held_broadcasts(), 0, "the host is holding the rejoined guest's broadcast");
assert!(peers[0].session().registry().networks.contains_key(&NetworkId(2)), "the host missed the edit made after the rejoin");
}
#[test]
#[ignore = "manual inspection of one seed"]
fn inspect_seed() {
let _ = env_logger::builder().is_test(true).try_init();
let seed = std::env::var("SEED").ok().and_then(|value| value.parse().ok()).unwrap_or(0);
let guests = std::env::var("GUESTS").ok().and_then(|value| value.parse().ok()).unwrap_or(1);
let (_, peers) = simulate(seed, guests, 200);
for (index, peer) in peers.iter().enumerate() {
eprintln!("=== peer {index} head {:?}", peer.session().head_rev());
eprintln!("registry {}", serde_json::to_string(peer.session().retired_registry()).unwrap());
eprintln!("hot log {:?}", peer.session().hot_log());
eprintln!("resources {:?}", peer.target.resources.keys().collect::<Vec<_>>());
for delta in peer.session().history() {
eprintln!("{:?} parent {:?} author {:?} ts {} {:?}", delta.id, delta.parent, delta.author, delta.timestamp.counter, delta.kind);
}
}
assert_converged(seed, &peers);
}
/// A hot op can reach one guest and not the host, and its author can then leave for good. The guest
/// holds the only copy, so unless it passes the op on the work is lost with the peer that made it.
/// Random delivery reaches this only by luck, so it is built by hand.
#[test]
fn a_guest_holding_the_only_copy_gets_it_retired() {
let mut network = MockNetwork::new(0);
let mut peers: Vec<Peer> = (0..3)
.map(|index| {
let endpoint = network.endpoint();
let id = endpoint.id();
let role = if index == 0 { Role::Host } else { Role::Guest };
let peer = Peer::new(endpoint, role, index as u64 + 1, 0);
network.connect(id);
peer
})
.collect();
quiesce(&mut network, &mut peers);
// The author stages one op, and only the other guest is allowed to receive it.
let author_transport = peers[1].transport;
peers[1].stage(RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
});
let witness_transport = peers[2].transport;
network.deliver_to(witness_transport);
peers[2].poll();
assert!(peers[2].session().registry().networks.contains_key(&NetworkId(9)), "the witness must have received the op");
assert!(peers[0].session().hot_log().is_empty(), "the host must not have received it yet");
// The author leaves for good, taking its own copy and its undelivered packets with it.
network.disconnect(author_transport);
peers[1].departed = true;
quiesce(&mut network, &mut peers);
peers[0].retire();
quiesce(&mut network, &mut peers);
assert!(
peers[0].session().retired_registry().networks.contains_key(&NetworkId(9)),
"the op the witness alone held never reached history"
);
assert_converged(0, &peers);
}
+10 -9
View File
@@ -1,14 +1,11 @@
[package]
name = "graphite-editor"
publish = false
version = "0.0.0"
rust-version = "1.88"
authors = ["Graphite Authors <[email protected]>"]
edition = "2024"
readme = "../README.md"
homepage = "https://graphite.art"
repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
default = ["gpu"]
@@ -22,6 +19,7 @@ graph-craft = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
graphene-hash = { workspace = true }
interpreted-executor = { workspace = true }
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
@@ -44,6 +42,7 @@ tsify = { workspace = true }
dyn-any = { workspace = true }
num_enum = { workspace = true }
usvg = { workspace = true }
simplecss = { workspace = true }
once_cell = { workspace = true }
web-sys = { workspace = true }
vello = { workspace = true }
@@ -71,3 +70,5 @@ wasm-bindgen-futures = { workspace = true }
# Workspace dependencies
env_logger = { workspace = true }
futures = { workspace = true }
node-macro = { workspace = true }
core-types = { workspace = true }
+1 -1
View File
@@ -1,7 +1,7 @@
use std::env;
use std::process::Command;
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 4";
const GRAPHITE_RELEASE_SERIES: &str = "Alpha 5";
fn main() {
// Instruct Cargo to rerun this build script if any of these environment variables change.
+3 -1
View File
@@ -135,7 +135,9 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;
// BRUSH TOOL
pub const BRUSH_SIZE_CHANGE_KEYBOARD: f64 = 5.;
pub const DEFAULT_BRUSH_SIZE: f64 = 20.;
pub const BRUSH_SIZE_DEFAULT: f64 = 40.;
pub const BRUSH_HARDNESS_DEFAULT: f64 = 0.;
pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
// EYEDROPPER TOOL
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
+11 -7
View File
@@ -36,7 +36,7 @@ pub struct DispatcherMessageHandlers {
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
preferences_message_handler: PreferencesMessageHandler,
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
tool_message_handler: ToolMessageHandler,
pub(crate) tool_message_handler: ToolMessageHandler,
viewport_message_handler: ViewportMessageHandler,
}
@@ -96,8 +96,9 @@ impl Dispatcher {
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::default();
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
@@ -265,8 +266,8 @@ 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.workspace_panel_layout.focus_document;
let layout = &self.message_handlers.portfolio_message_handler.workspace_panel_layout;
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
@@ -426,6 +427,7 @@ impl Dispatcher {
#[cfg(test)]
mod test {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
pub use crate::test_utils::test_prelude::*;
#[tokio::test]
@@ -477,9 +479,11 @@ 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::OpenFile {
path: file_name.into(),
content: document_serialized_content.bytes().collect(),
let responses = editor.editor.handle_message(IngestMessage::Ingest {
data: document_serialized_content.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some(file_name.into()),
});
// Check if the graph renders
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
pub enum AppWindowMessage {
PointerLock,
PointerLockMove { x: f64, y: f64 },
DirectInput { enabled: bool },
Restart,
Close,
Minimize,
@@ -17,6 +17,12 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
AppWindowMessage::PointerLockMove { x, y } => {
responses.add(FrontendMessage::WindowPointerLockMove { position: (x, y) });
}
AppWindowMessage::DirectInput { enabled } => {
#[cfg(not(target_family = "wasm"))]
responses.add(FrontendMessage::WindowUpdateDirectInput { enabled });
#[cfg(target_family = "wasm")]
let _ = enabled;
}
AppWindowMessage::Close => {
#[cfg(not(target_family = "wasm"))]
responses.add(FrontendMessage::WindowClose);
@@ -8,5 +8,7 @@ pub enum EventMessage {
CanvasTransformed,
ToolAbort,
SelectionChanged,
/// The document graph's nodes or wires changed, so state derived from the selection's chains may be stale
GraphChanged,
WorkingColorChanged,
}
@@ -11,11 +11,10 @@ use crate::messages::tool::utility_types::ToolType;
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::subpath::BezierHandles;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
use graphite_proc_macros::{ExtractField, message_handler_data};
use kurbo::ParamCurve;
use std::sync::Arc;
const CLIPBOARD_PREFIX: &str = "graphite: ";
@@ -51,22 +50,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
responses.add(FrontendMessage::TriggerSelectionWrite { content: text });
}
}
ClipboardContentRaw::Svg(svg) => {
responses.add(PortfolioMessage::InsertSvg {
svg,
name: None,
mouse: None,
parent_and_insert_index: None,
});
}
ClipboardContentRaw::Image { data, width, height } => {
responses.add(PortfolioMessage::InsertImage {
image: Image::from_image_data(&data, width, height),
name: None,
mouse: None,
parent_and_insert_index: None,
});
}
},
ClipboardMessage::ReadSelection { content, cut } => {
if let Some(text) = content {
@@ -182,13 +165,8 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut resource_ids = HashSet::new();
for item in &items {
match item {
ClipboardItem::Layer(entry) => entry
.nodes
.iter()
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
ClipboardItem::Nodes(nodes) => nodes
.iter()
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
ClipboardItem::Nodes(nodes) => nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
}
}
@@ -252,9 +230,20 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut vectors = Vec::new();
let mut resources = Vec::new();
for item in items {
// Pasted templates skip document migration, so stored types normalize here
match item {
ClipboardItem::Layer(entry) => layers.push(entry),
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
ClipboardItem::Layer(mut entry) => {
for (_, template) in &mut entry.nodes {
template.normalize_stored_types();
}
layers.push(entry);
}
ClipboardItem::Nodes(mut nodes) => {
for (_, template) in &mut nodes {
template.normalize_stored_types();
}
node_groups.push(nodes);
}
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
@@ -419,7 +408,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
// Create new segment ids and add the segments into the existing Vector path
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
for (segment_id, segment, start, end) in new_vector.segment_iter() {
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
warn!("Skipping pasted vector segment with an unknown endpoint");
continue;
@@ -428,10 +417,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let handles = match bezier.handles {
let segment_start = point_to_dvec2(segment.start());
let segment_end = point_to_dvec2(segment.end());
let handles = match segment_to_handles(&segment) {
BezierHandles::Linear => [None, None],
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
BezierHandles::Quadratic { handle } => [Some(handle - segment_start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - segment_start), Some(handle_end - segment_end)],
};
let points = [start_point, end_point];
@@ -10,8 +10,6 @@ use graphene_std::vector::Vector;
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ClipboardContentRaw {
Text(String),
Svg(String),
Image { data: Vec<u8>, width: u32, height: u32 },
}
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -1,6 +1,6 @@
use crate::messages::layout::utility_types::widgets::input_widgets::{SpectrumInputUpdate, VisualColorPickersInputUpdate};
use crate::messages::layout::utility_types::widgets::input_widgets::{SliderInputUpdate, VisualColorPickersInputUpdate};
use crate::messages::prelude::*;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::{FillChoice, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
/// Identifies which RGB channel a numeric input change targets.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -45,8 +45,18 @@ pub enum ColorPickerMessage {
/// Swap the current "new" color with the captured "old" color.
SwapNewWithOld,
/// `SpectrumInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
GradientUpdate { update: SpectrumInputUpdate },
/// `SliderInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
GradientUpdate { update: SliderInputUpdate },
/// Gradient spread choice from the gradient "Ends" selection.
SetGradientSpread { gradient_spread: GradientSpread },
/// Gradient cyclic choice: whether the stops wrap as a cycle, from the "Cyclic" checkbox.
SetGradientCyclic { gradient_cyclic: bool },
/// Gradient space choice: the color space the stops interpolate in, from the "Space" dropdown.
SetGradientSpace { gradient_space: GradientSpace },
/// Gradient hue direction choice: which way around the hue wheel the stops interpolate in a polar space, from the "Arc" dropdown.
SetGradientHueDirection { gradient_hue_direction: GradientHueDirection },
/// Gradient interpolation choice: the path the stops interpolate along, from the "Intrp." dropdown.
SetGradientInterpolation { gradient_interpolation: GradientInterpolation },
/// Tell the frontend to start an undo transaction (forwarded as a `FrontendMessage` it bridges out to the picker's parent).
StartTransaction,
@@ -1,11 +1,11 @@
use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SliderInputUpdate, SliderMarker, VisualColorPickersInputUpdate};
use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::parse_css_color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
use graphene_std::vector::style::{FillChoice, Gradient, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops};
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
const MIN_MIDPOINT: f64 = 0.01;
@@ -28,7 +28,12 @@ pub struct ColorPickerMessageHandler {
old_is_none: bool,
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
gradient: Option<GradientStops>,
gradient: Option<Gradient>,
gradient_spread: GradientSpread,
gradient_space: GradientSpace,
gradient_cyclic: bool,
gradient_hue_direction: GradientHueDirection,
gradient_interpolation: GradientInterpolation,
active_marker_index: Option<u32>,
active_marker_is_midpoint: bool,
@@ -50,6 +55,11 @@ impl Default for ColorPickerMessageHandler {
old_alpha: 1.,
old_is_none: true,
gradient: None,
gradient_spread: GradientSpread::default(),
gradient_space: GradientSpace::default(),
gradient_cyclic: false,
gradient_hue_direction: GradientHueDirection::default(),
gradient_interpolation: GradientInterpolation::default(),
active_marker_index: None,
active_marker_is_midpoint: false,
allow_none: true,
@@ -70,20 +80,36 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
FillChoice::None => {
self.set_new_hsva(0., 0., 0., 1., true);
self.gradient = None;
self.gradient_spread = GradientSpread::default();
self.gradient_space = GradientSpace::default();
self.gradient_cyclic = false;
self.gradient_hue_direction = GradientHueDirection::default();
self.gradient_interpolation = GradientInterpolation::default();
self.active_marker_index = None;
self.active_marker_is_midpoint = false;
}
FillChoice::Solid(color) => {
self.gradient = None;
self.gradient_spread = GradientSpread::default();
self.gradient_space = GradientSpace::default();
self.gradient_cyclic = false;
self.gradient_hue_direction = GradientHueDirection::default();
self.gradient_interpolation = GradientInterpolation::default();
self.active_marker_index = None;
self.active_marker_is_midpoint = false;
self.adopt_color(color);
}
FillChoice::Gradient(stops) => {
FillChoice::Gradient(ramp) => {
self.active_marker_index = Some(0);
self.active_marker_is_midpoint = false;
let first_color = stops.color.first().copied().unwrap_or(Color::BLACK);
self.gradient = Some(stops);
self.gradient_spread = ramp.gradient_spread;
self.gradient_space = ramp.gradient_space;
self.gradient_cyclic = ramp.gradient_cyclic;
self.gradient_hue_direction = ramp.gradient_hue_direction;
self.gradient_interpolation = ramp.gradient_interpolation;
let gradient = Gradient::from(ramp);
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
self.gradient = Some(gradient);
self.adopt_color(first_color);
}
}
@@ -154,7 +180,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
match preset {
FillChoice::None => {
self.set_new_hsva(0., 0., 0., 1., true);
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::<SRGBA8>::None });
}
FillChoice::Solid(color) => {
self.adopt_color(color);
@@ -179,13 +205,62 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
self.set_old_hsva(temp.0, temp.1, temp.2, temp.3, temp.4);
if self.is_none {
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::<SRGBA8>::None });
} else {
self.emit_color(responses);
}
self.send_layouts(responses);
}
ColorPickerMessage::GradientUpdate { update } => self.apply_gradient_update(update, responses),
ColorPickerMessage::SetGradientSpread { gradient_spread } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_spread = gradient_spread;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientCyclic { gradient_cyclic } => {
let Some(gradient) = &mut self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
let previous_cyclic = std::mem::replace(&mut self.gradient_cyclic, gradient_cyclic);
gradient.hold_positions_across_cyclic_change(previous_cyclic, gradient_cyclic);
let ramp = GradientRamp::from(&*gradient);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(ramp.with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientSpace { gradient_space } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_space = gradient_space;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientHueDirection { gradient_hue_direction } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_hue_direction = gradient_hue_direction;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientInterpolation { gradient_interpolation } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_interpolation = gradient_interpolation;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::StartTransaction => {
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
}
@@ -234,6 +309,17 @@ impl ColorPickerMessageHandler {
self.old_is_none = is_none;
}
/// The whole-ramp settings the picker is currently editing with, bundled for sampling and for emitting ramps.
fn gradient_settings(&self) -> GradientSettings {
GradientSettings {
spread: self.gradient_spread,
cyclic: self.gradient_cyclic,
space: self.gradient_space,
hue_direction: self.gradient_hue_direction,
interpolation: self.gradient_interpolation,
}
}
fn snapshot_old(&mut self) {
self.old_hue = self.hue;
self.old_saturation = self.saturation;
@@ -266,18 +352,16 @@ impl ColorPickerMessageHandler {
if let Some(gradient) = &mut self.gradient
&& let Some(active_index) = self.active_marker_index
&& let Some(stop_color) = gradient.color.get_mut(active_index as usize)
&& (active_index as usize) < gradient.len()
{
*stop_color = color;
let stops = gradient.clone();
let fill_choice = FillChoice::Gradient(stops);
gradient.set_color(active_index as usize, color);
let ramp = GradientRamp::from(&*gradient);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoiceUI::from(&fill_choice),
value: FillChoice::Gradient(ramp.with_settings(self.gradient_settings())),
});
} else {
let fill_choice = FillChoice::Solid(color);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoiceUI::from(&fill_choice),
value: FillChoice::Solid(SRGBA8::from(color)),
});
}
}
@@ -293,10 +377,10 @@ impl ColorPickerMessageHandler {
});
}
/// Apply an incoming `SpectrumInput` intent to the gradient state and broadcast the result.
fn apply_gradient_update(&mut self, update: SpectrumInputUpdate, responses: &mut VecDeque<Message>) {
/// Apply an incoming `SliderInput` intent to the gradient state and broadcast the result.
fn apply_gradient_update(&mut self, update: SliderInputUpdate, responses: &mut VecDeque<Message>) {
// Active marker selection is the one update that doesn't mutate the gradient
if let SpectrumInputUpdate::ActiveMarker {
if let SliderInputUpdate::ActiveMarker {
active_marker_index,
active_marker_is_midpoint,
} = update
@@ -305,7 +389,7 @@ impl ColorPickerMessageHandler {
self.active_marker_is_midpoint = active_marker_is_midpoint;
if let Some(index) = active_marker_index
&& let Some(gradient) = &self.gradient
&& let Some(color) = gradient.color.get(index as usize).copied()
&& let Some(color) = gradient.color(index as usize)
{
self.adopt_color(color);
self.snapshot_old();
@@ -317,39 +401,40 @@ impl ColorPickerMessageHandler {
let Some(mut gradient) = self.gradient.clone() else { return };
match update {
SpectrumInputUpdate::MoveMarker { index, position } => {
let new_index = gradient.move_stop(index as usize, position);
SliderInputUpdate::MoveMarker { index, position } => {
let new_index = gradient.move_stop(index as usize, position, self.gradient_cyclic);
if Some(index) == self.active_marker_index {
self.active_marker_index = Some(new_index as u32);
}
}
SpectrumInputUpdate::MoveMidpoint { index, position } => {
if let Some(midpoint) = gradient.midpoint.get_mut(index as usize) {
*midpoint = position.clamp(MIN_MIDPOINT, MAX_MIDPOINT);
} else {
SliderInputUpdate::MoveMidpoint { index, position } => {
if (index as usize) >= gradient.len() {
return;
}
gradient.set_midpoint(index as usize, position.clamp(MIN_MIDPOINT, MAX_MIDPOINT));
}
SpectrumInputUpdate::InsertMarker { position } => {
let new_index = gradient.insert_stop(position);
SliderInputUpdate::InsertMarker { position } => {
let new_index = gradient.insert_stop(position, self.gradient_settings());
self.active_marker_index = Some(new_index as u32);
self.active_marker_is_midpoint = false;
if let Some(color) = gradient.color.get(new_index).copied() {
if let Some(color) = gradient.color(new_index) {
self.adopt_color(color);
self.snapshot_old();
}
}
SpectrumInputUpdate::InsertDuplicate { index, position } => {
SliderInputUpdate::InsertDuplicate { index, position } => {
let source = index as usize;
let Some(insert_index) = gradient.duplicate_stop(source, position) else { return };
let Some(insert_index) = gradient.duplicate_stop(source, position, self.gradient_cyclic) else {
return;
};
// The dragged stop (the duplication source) stays active. Its index shifts up if the frozen copy landed at or before it.
let dragged_index = if insert_index <= source { source + 1 } else { source };
self.active_marker_index = Some(dragged_index as u32);
self.active_marker_is_midpoint = false;
}
SpectrumInputUpdate::RemoveDuplicate { index } => {
SliderInputUpdate::RemoveDuplicate { index } => {
let anchor = index as usize;
if anchor >= gradient.position.len() || gradient.position.len() <= 2 {
if anchor >= gradient.len() || gradient.len() <= 2 {
return;
}
// Never remove the active (dragged) stop itself, this should only ever target the frozen copy.
@@ -364,47 +449,47 @@ impl ColorPickerMessageHandler {
self.active_marker_index = Some(active - 1);
}
}
SpectrumInputUpdate::DeleteMarker { index } => {
SliderInputUpdate::DeleteMarker { index } => {
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
if gradient.position.len() <= 2 || (index as usize) >= gradient.position.len() {
if gradient.len() <= 2 || (index as usize) >= gradient.len() {
return;
}
gradient.remove(index as usize);
let new_active = (index as usize).min(gradient.position.len() - 1);
let new_active = (index as usize).min(gradient.len() - 1);
self.active_marker_index = Some(new_active as u32);
self.active_marker_is_midpoint = false;
if let Some(color) = gradient.color.get(new_active).copied() {
if let Some(color) = gradient.color(new_active) {
self.adopt_color(color);
self.snapshot_old();
}
}
SpectrumInputUpdate::ResetMidpoint { index } => {
SliderInputUpdate::ResetMidpoint { index } => {
gradient.reset_midpoint(index as usize);
}
SpectrumInputUpdate::ResetMarker { index } => {
SliderInputUpdate::ResetMarker { index } => {
let i = index as usize;
let count = gradient.position.len();
let count = gradient.len();
if i >= count {
return;
}
// Each stop's "natural" position is its evenly-spaced fraction along 0..1, e.g., for 5 stops: 0, 0.25, 0.5, 0.75, 1. Falls back to the midpoint between neighbors when the natural position would push the stop past another.
let left = if i == 0 { 0. } else { gradient.position[i - 1] };
let right = gradient.position.get(i + 1).copied().unwrap_or(1.);
let natural = if count <= 1 { 0. } else { i as f64 / (count - 1) as f64 };
// Each stop's "natural" position is its evenly-spaced fraction along 0..1, e.g., for 5 stops: 0, 0.25, 0.5, 0.75, 1 (or fifths when cyclic, leaving the wrapped interval its share). Falls back to the midpoint between neighbors when the natural position would push the stop past another.
let left = if i == 0 { 0. } else { gradient.position(i - 1, self.gradient_cyclic) };
let right = if i + 1 < count { gradient.position(i + 1, self.gradient_cyclic) } else { 1. };
let denominator = if self.gradient_cyclic { count } else { count - 1 };
let natural = if count <= 1 { 0. } else { i as f64 / denominator as f64 };
let new_position = if (left..=right).contains(&natural) { natural } else { (left + right) / 2. };
let new_index = gradient.move_stop(i, new_position);
let new_index = gradient.move_stop(i, new_position, self.gradient_cyclic);
if Some(index) == self.active_marker_index {
self.active_marker_index = Some(new_index as u32);
}
}
SpectrumInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
SliderInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
}
self.gradient = Some(gradient.clone());
let fill_choice = FillChoice::Gradient(gradient);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoiceUI::from(&fill_choice),
value: FillChoice::Gradient(GradientRamp::from(&gradient).with_settings(self.gradient_settings())),
});
self.gradient = Some(gradient);
self.send_layouts(responses);
}
@@ -428,9 +513,15 @@ impl ColorPickerMessageHandler {
// Gradient editor (only present when the picker is in gradient mode)
if let Some(gradient) = &self.gradient {
// For gradient editing, the markers' handle colors mirror their gradient stop colors
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
let markers = (0..gradient.len())
.filter_map(|i| Some(SliderMarker::new(gradient.position(i, self.gradient_cyclic), gradient.midpoint(i), gradient.color(i)?)))
.collect();
let mut row_widgets = vec![
SpectrumInput::new(GradientStopsUI::from(gradient))
SliderInput::new(GradientStops::from(gradient))
.track_space(self.gradient_space)
.track_cyclic(self.gradient_cyclic)
.track_hue_direction(self.gradient_hue_direction)
.track_interpolation(self.gradient_interpolation)
.markers(markers)
.active_marker_index(self.active_marker_index)
.active_marker_is_midpoint(self.active_marker_is_midpoint)
@@ -438,17 +529,18 @@ impl ColorPickerMessageHandler {
.allow_insert(!self.disabled)
.allow_delete(!self.disabled)
.allow_reorder(true)
.allow_select(true)
.disabled(self.disabled)
.on_update(|update: &SpectrumInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
.on_update(|update: &SliderInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
.widget_instance(),
];
if let Some(active) = self.active_marker_index {
let active_index = active as usize;
let position_value = if self.active_marker_is_midpoint {
gradient.midpoint.get(active_index).copied().unwrap_or(0.)
} else {
gradient.position.get(active_index).copied().unwrap_or(0.)
let position_value = match (self.active_marker_is_midpoint, active_index < gradient.len()) {
(_, false) => 0.,
(true, true) => gradient.midpoint(active_index),
(false, true) => gradient.position(active_index, self.gradient_cyclic),
};
let is_midpoint = self.active_marker_is_midpoint;
let captured_index = active;
@@ -464,12 +556,12 @@ impl ColorPickerMessageHandler {
return Message::NoOp;
};
let update = if is_midpoint {
SpectrumInputUpdate::MoveMidpoint {
SliderInputUpdate::MoveMidpoint {
index: captured_index,
position: new_value / 100.,
}
} else {
SpectrumInputUpdate::MoveMarker {
SliderInputUpdate::MoveMarker {
index: captured_index,
position: new_value / 100.,
}
@@ -524,7 +616,11 @@ impl ColorPickerMessageHandler {
// Hex
groups.push(LayoutGroup::row(vec![
TextLabel::new("Hex").tooltip_label("Hex Color Code").tooltip_description(HEX_DESCRIPTION).widget_instance(),
TextLabel::new("Hex")
.disabled(self.disabled)
.tooltip_label("Hex Color Code")
.tooltip_description(HEX_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(hex_value)
.centered(true)
@@ -537,7 +633,11 @@ impl ColorPickerMessageHandler {
// RGB
groups.push(LayoutGroup::row(vec![
TextLabel::new("RGB").tooltip_label("Red/Green/Blue").tooltip_description("Integers 0–255.").widget_instance(),
TextLabel::new("RGB")
.disabled(self.disabled)
.tooltip_label("Red/Green/Blue")
.tooltip_description("Integers 0–255.")
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
rgb_input(RgbChannel::Red, rgb_255.map(|(r, _, _)| r), "Red Channel", self.disabled),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -549,8 +649,9 @@ impl ColorPickerMessageHandler {
// HSV
groups.push(LayoutGroup::row(vec![
TextLabel::new("HSV")
.disabled(self.disabled)
.tooltip_label("Hue/Saturation/Value")
.tooltip_description("Also known as Hue/Saturation/Brightness (HSB). Not to be confused with Hue/Saturation/Lightness (HSL), a different color model.")
.tooltip_description("Also known as Hue/Saturation/Brightness (HSB), but distinct from Hue/Saturation/Lightness (HSL), a different color model.")
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
hsv_input(
@@ -586,7 +687,11 @@ impl ColorPickerMessageHandler {
// Alpha
groups.push(LayoutGroup::row(vec![
TextLabel::new("Alpha").tooltip_label("Alpha").tooltip_description(ALPHA_DESCRIPTION).widget_instance(),
TextLabel::new("Alpha")
.disabled(self.disabled)
.tooltip_label("Alpha")
.tooltip_description(ALPHA_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(if self.is_none { None } else { Some(self.alpha * 100.) })
.disabled(self.disabled)
@@ -602,6 +707,98 @@ impl ColorPickerMessageHandler {
.widget_instance(),
]));
// Gradient spread, trailed by the cyclic wrap toggle (only present when the picker is in gradient mode)
if self.gradient.is_some() {
let entries = RadioEntryData::list_from_choice_type(|gradient_spread| ColorPickerMessage::SetGradientSpread { gradient_spread }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Ends")
.disabled(self.disabled)
.tooltip_label("Gradient Spread / Cyclic")
.tooltip_description(ENDS_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
RadioInput::new(entries)
.narrow(true)
.selected_index(Some(self.gradient_spread as u32))
.disabled(self.disabled)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.gradient_cyclic)
.icon("Link")
.disabled(self.disabled)
.tooltip_label("Cyclic")
.tooltip_description(CYCLIC_DESCRIPTION)
.on_update(|checkbox_input: &CheckboxInput| {
ColorPickerMessage::SetGradientCyclic {
gradient_cyclic: checkbox_input.checked,
}
.into()
})
.widget_instance(),
]));
}
// Gradient interpolation (only present when the picker is in gradient mode)
if self.gradient.is_some() {
let entries = MenuListEntry::sections_from_choice_type(|gradient_interpolation| ColorPickerMessage::SetGradientInterpolation { gradient_interpolation }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Intrp.")
.disabled(self.disabled)
.tooltip_label("Gradient Interpolation")
.tooltip_description(INTERPOLATION_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
DropdownInput::new(entries)
.selected_index(Some(self.gradient_interpolation as u32))
.disabled(self.disabled)
.tooltip_label("Gradient Interpolation")
.tooltip_description(INTERPOLATION_DESCRIPTION)
.widget_instance(),
]));
}
// Gradient color space (only present when the picker is in gradient mode)
if self.gradient.is_some() {
let entries = MenuListEntry::sections_from_choice_type(|gradient_space| ColorPickerMessage::SetGradientSpace { gradient_space }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Space")
.disabled(self.disabled)
.tooltip_label("Gradient Space")
.tooltip_description(SPACE_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
DropdownInput::new(entries)
.selected_index(Some(self.gradient_space as u32))
.disabled(self.disabled)
.tooltip_label("Gradient Space")
.tooltip_description(SPACE_DESCRIPTION)
.widget_instance(),
]));
}
// Gradient hue direction (only present when the chosen space is polar)
if self.gradient.is_some() && self.gradient_space.is_polar() {
let entries = MenuListEntry::sections_from_choice_type(|gradient_hue_direction| ColorPickerMessage::SetGradientHueDirection { gradient_hue_direction }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Arc")
.disabled(self.disabled)
.tooltip_label("Gradient Hue Direction")
.tooltip_description(HUE_DIRECTION_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
DropdownInput::new(entries)
.selected_index(Some(self.gradient_hue_direction as u32))
.disabled(self.disabled)
.tooltip_label("Gradient Hue Direction")
.tooltip_description(HUE_DIRECTION_DESCRIPTION)
.widget_instance(),
]));
}
// Color presets (None / Black / White / pure colors / eyedropper)
groups.push(LayoutGroup::row(vec![
ColorPresetsInput::default()
@@ -655,6 +852,11 @@ const HUE_DESCRIPTION: &str = "The shade along the spectrum of the rainbow.";
const SATURATION_DESCRIPTION: &str = "The vividness from grayscale to full color.";
const VALUE_DESCRIPTION: &str = "The brightness from black to full color.";
const ALPHA_DESCRIPTION: &str = "The level of translucency, from transparent (0%) to opaque (100%).";
const ENDS_DESCRIPTION: &str = "The method for how the gradient continues beyond its ends, and whether its stops cycle back around from last to first.";
const CYCLIC_DESCRIPTION: &str = "Treats the stops as a cycle, interpolating from the last stop back around to the first.";
const SPACE_DESCRIPTION: &str = "The color space where stops interpolate toward their neighbors.";
const HUE_DIRECTION_DESCRIPTION: &str = "Which way around the hue wheel the stops interpolate.";
const INTERPOLATION_DESCRIPTION: &str = "The path the stops interpolate along, deciding whether the gradient jumps, turns corners, or flows smoothly through them.";
/// The popover's background color as sRGB gamma-encoded channels (the `--color-2-mildblack` design token, `#222`).
/// Used by the comparison swatch's outline computation to brighten the inset border for colors close to this background.
@@ -94,19 +94,38 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
impl LayoutHolder for ExportDialogMessageHandler {
fn layout(&self) -> Layout {
let entries = [(FileType::Png, "PNG"), (FileType::Jpg, "JPG"), (FileType::Svg, "SVG")]
// The vector type, then the raster ones
let file_types = [
vec![(FileType::Svg, "SVG")],
vec![
(FileType::Png, "PNG"),
(FileType::Jpg, "JPG"),
(FileType::Webp, "WEBP"),
(FileType::Tiff, "TIFF"),
(FileType::Bmp, "BMP"),
(FileType::Tga, "TGA"),
(FileType::Ico, "ICO"),
],
];
let selected_index = file_types.iter().flatten().position(|(file_type, _)| *file_type == self.file_type);
let entries = file_types
.into_iter()
.map(|(file_type, name)| {
RadioEntryData::new(format!("{file_type:?}"))
.label(name)
.on_update(move |_| ExportDialogMessage::FileType { file_type }.into())
.map(|section| {
section
.into_iter()
.map(|(file_type, name)| {
MenuListEntry::new(format!("{file_type:?}"))
.label(name)
.on_commit(move |_| ExportDialogMessage::FileType { file_type }.into())
})
.collect()
})
.collect();
let export_type = vec![
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(),
DropdownInput::new(entries).selected_index(selected_index.map(|index| index as u32)).min_width(200).widget_instance(),
];
let resolution = vec![
@@ -275,11 +275,7 @@ impl PreferencesDialogMessageHandler {
let checkbox_id = CheckboxId::new();
let brush_tool_description = "
Enable the Brush tool to support basic raster-based layer painting.\n\
\n\
This legacy experimental tool has performance and quality limitations and is slated for replacement in future versions of Graphite that will have a renewed focus on raster graphics editing.\n\
\n\
Content created with the Brush tool may not be compatible with future versions of Graphite.\n\
Enable the Brush tool to support basic layer painting.\n\
\n\
*Default: Off.*
"
@@ -18,7 +18,7 @@ impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
.tooltip_description("Save the raw document data to disk so it can be recovered later.")
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::DownloadFailedToLoadDocuments.into()],
followups: vec![FailedDocumentsMessage::DownloadFailedToLoadDocuments.into()],
}
.into()
})
@@ -27,7 +27,7 @@ impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
.tooltip_description("Permanently delete the autosaved data for these documents.")
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::DiscardFailedToLoadDocuments.into()],
followups: vec![FailedDocumentsMessage::DiscardFailedToLoadDocuments.into()],
}
.into()
})
@@ -46,11 +46,15 @@ impl LayoutHolder for LicensesDialog {
let year = &self.localized_commit_year;
let description = format!(
"
Graphite source code is copyright © {year} Graphite contrib-\nutors and is available under the Apache License 2.0. See\n\"Source Code License\" for details.\n\
Graphite source code is copyright © {year} Graphite contrib-\n\
utors and is available under both the MIT and Apache 2.0\n\
licenses. See \"Source Code License\" for details.\n\
\n\
The Graphite logo, icons, and visual identity are copyright ©\n{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
The Graphite logo, icons, and visual identity are copyright ©\n\
{year} Graphite Labs, LLC. See \"Branding License\" for details.\n\
\n\
Graphite is distributed with third-party open source code\ndependencies. See \"Dependency Licenses\" for details.
Graphite is distributed with third-party open source code\n\
dependencies. See \"Dependency Licenses\" for details.
"
);
let description = description.trim();
@@ -1,7 +1,7 @@
use super::IconName;
use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
@@ -9,12 +9,13 @@ use crate::messages::portfolio::document::node_graph::utility_types::{
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoiceUI;
use graphene_std::vector::style::FillChoice;
use std::path::PathBuf;
#[cfg(not(target_family = "wasm"))]
@@ -87,22 +88,29 @@ pub enum FrontendMessage {
commit_date: String,
},
TriggerDisplayThirdPartyLicensesDialog,
TriggerBrowse {
options: FileDialogOptions,
action: IngestAction,
},
TriggerSaveDocument {
document_id: DocumentId,
name: String,
path: Option<PathBuf>,
folder: Option<PathBuf>,
filters: Vec<FileFilter>,
content: serde_bytes::ByteBuf,
},
TriggerSaveFile {
name: String,
folder: Option<PathBuf>,
filters: Vec<FileFilter>,
content: serde_bytes::ByteBuf,
},
TriggerExportImage {
svg: String,
name: String,
mime: String,
#[serde(rename = "fileType")]
file_type: FileType,
size: (f64, f64),
},
TriggerFetchAndOpenDocument {
@@ -128,8 +136,6 @@ pub enum FrontendMessage {
},
TriggerOpenLaunchDocuments,
TriggerLoadPreferences,
TriggerOpen,
TriggerImport,
TriggerSavePreferences {
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
preferences: PreferencesMessageHandler,
@@ -144,6 +150,10 @@ pub enum FrontendMessage {
url: String,
},
TriggerClipboardRead,
/// Copy a link to join the live session behind `token`, built from the page's own origin.
TriggerSessionLinkCopy {
token: String,
},
TriggerClipboardWrite {
content: String,
},
@@ -165,7 +175,7 @@ pub enum FrontendMessage {
},
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker />` forwards this as its `colorOrGradient` event.
ColorPickerColorChanged {
value: FillChoiceUI,
value: FillChoice<SRGBA8>,
},
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker />` forwards this as its `startHistoryTransaction` event.
ColorPickerStartHistoryTransaction,
@@ -344,6 +354,10 @@ pub enum FrontendMessage {
position: (f64, f64),
},
#[cfg(not(target_family = "wasm"))]
WindowUpdateDirectInput {
enabled: bool,
},
#[cfg(not(target_family = "wasm"))]
WindowClose,
#[cfg(not(target_family = "wasm"))]
WindowMinimize,
+130 -5
View File
@@ -47,23 +47,96 @@ pub enum MouseCursorIcon {
Rotate,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum FileType {
#[default]
Png,
Jpg,
Webp,
Tiff,
Bmp,
Tga,
Ico,
Svg,
}
impl FileType {
pub fn to_mime(self) -> &'static str {
pub fn extension(self) -> &'static str {
match self {
FileType::Png => "image/png",
FileType::Jpg => "image/jpeg",
FileType::Svg => "image/svg+xml",
FileType::Png => "png",
FileType::Jpg => "jpg",
FileType::Webp => "webp",
FileType::Tiff => "tiff",
FileType::Bmp => "bmp",
FileType::Tga => "tga",
FileType::Ico => "ico",
FileType::Svg => "svg",
}
}
pub fn file_filter(self) -> FileFilter {
let name = match self {
FileType::Png => "PNG Image",
FileType::Jpg => "JPEG Image",
FileType::Webp => "WEBP Image",
FileType::Tiff => "TIFF Image",
FileType::Bmp => "BMP Image",
FileType::Tga => "TGA Image",
FileType::Ico => "ICO Image",
FileType::Svg => "SVG Image",
};
FileFilter {
name: name.into(),
extensions: vec![self.extension().into()],
mime_types: Vec::new(),
}
}
/// Encodes 8-bit RGBA pixels with straight alpha as a file of this raster type.
pub fn encode(self, width: u32, height: u32, rgba: Vec<u8>) -> Result<Vec<u8>, String> {
use image::buffer::ConvertBuffer;
use image::{ImageFormat, RgbImage, RgbaImage};
let Some(mut image) = RgbaImage::from_raw(width, height, rgba) else {
return Err("Failed to create image buffer for export".to_string());
};
let format = match self {
FileType::Png => ImageFormat::Png,
FileType::Jpg => ImageFormat::Jpeg,
FileType::Webp => ImageFormat::WebP,
FileType::Tiff => ImageFormat::Tiff,
FileType::Bmp => ImageFormat::Bmp,
FileType::Tga => ImageFormat::Tga,
FileType::Ico => ImageFormat::Ico,
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
};
if self == FileType::Ico && (width > 256 || height > 256) {
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
}
let mut encoded = Vec::new();
let mut cursor = std::io::Cursor::new(&mut encoded);
let result = if self == FileType::Jpg {
// Composite onto a white background since JPG doesn't support transparency
for pixel in image.pixels_mut() {
let [r, g, b, a] = pixel.0;
let alpha = a as f32 / 255.;
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
}
let image: RgbImage = image.convert();
image.write_to(&mut cursor, format)
} else {
image.write_to(&mut cursor, format)
};
result.map_err(|error| format!("Failed to encode {self:?}: {error}"))?;
Ok(encoded)
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -91,3 +164,55 @@ pub struct RasterizedImage {
pub height: u32,
pub pixels: serde_bytes::ByteBuf,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
#[serde(rename = "mimeTypes")]
pub mime_types: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FileDialogOptions {
pub filters: Vec<FileFilter>,
pub multiple: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use graphene_std::raster::Image;
#[test]
fn every_raster_file_type_encodes_an_image_that_reads_back() {
// Opaque red, then fully transparent
let pixels = vec![255, 0, 0, 255, 0, 0, 0, 0];
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
// Only JPG lacks transparency, so it lands on white
let transparent = decoded.to_flat_u8().0[4..8].to_vec();
if file_type == FileType::Jpg {
assert!(transparent.iter().all(|&channel| channel > 250), "{transparent:?}");
} else {
assert_eq!(transparent[3], 0, "{file_type:?}");
}
}
}
#[test]
fn file_types_that_cannot_hold_the_image_say_so() {
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
assert!(too_large.contains("256 pixels"), "{too_large}");
assert!(FileType::Ico.encode(256, 1, vec![0; 256 * 4]).is_ok());
}
}
@@ -1,5 +1,5 @@
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
use crate::messages::prelude::*;
#[impl_message(Message, KeyMappingMessage, Lookup)]
@@ -1,7 +1,7 @@
use super::utility_types::input_keyboard::KeysGroup;
use super::utility_types::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::keyboard::{self, Key};
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
use crate::messages::prelude::*;
@@ -58,7 +58,7 @@ impl InputMapperMessageHandler {
.map(|i| {
// TODO: Use a safe solution eventually
assert!(
i < input_keyboard::NUMBER_OF_KEYS,
i < keyboard::NUMBER_OF_KEYS,
"Attempting to convert a Key with enum index {i}, which is larger than the number of Key enums",
);
(i as u8).try_into().unwrap()
Loaded 100 of 544 files, more files were not shown because too many files have changed in this diff. Show more