Compare commits

..
Author SHA1 Message Date
Keavon Chambers 95c1ab81f3 Prep for the RC6 release of the desktop app 2026-07-01 04:55:57 -07:00
Keavon Chambers 7ae7bda3d3 Add persistence to the collapsed state of Properties panel node sections (#4300)
* Add persistence to the collapsed state of Properties panel node sections

* Improve comments

* Fix generator node handling with #4299
2026-07-01 04:54:39 -07:00
Keavon Chambers 1648e33c1f Implement dragging to reorder Properties panel node sections (#4299)
* Implement dragging to reorder Properties panel node sections

* Code review
2026-07-01 03:39:52 -07:00
TimonandKeavon Chambers 8a38af5be7 Rework clipboard handling to carry embedded resources across documents (#4296)
* Move clipboard code to its dedicated handler

* Adapt clipboard format to work with resources

* Restore visibility, lock, and collapse state when pasting layers

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-07-01 09:31:55 +00:00
Keavon Chambers 7c870d9426 Fix skewed linear gradient layers ignoring the horizontal shear axis in Vello 2026-06-30 21:48:51 -07:00
TimonandKeavon Chambers 0882637801 Auto-recover from corrupt Wasm builds that emit undefined env imports (#4287)
Co-authored-by: Keavon Chambers <[email protected]>
2026-06-30 22:07:17 +00:00
Timon 9626c047a4 Fix CI builds by pinning cargo-about for Windows and Mac 2026-06-30 21:40:18 +00:00
Keavon Chambers 3e674c939b Revamp the stand-in for embedded YouTube videos on the website 2026-06-30 01:42:40 -07:00
Keavon Chambers 2a3f1a12a8 Fix nondeterministic Vector point IDs from the 'As Vector' node 2026-06-29 23:52:51 -07:00
Timon 6ee0239b96 Desktop: Update CEF to 149 (#4286) 2026-06-29 15:25:30 +00:00
Keavon Chambers 244b25708d Add color picker gradient color stop duplication by holding Alt (#4291)
* Add color picker gradient color stop duplication by holding Alt

* Fix bugs

* Bug fix
2026-06-28 17:34:27 -07:00
Dennis Kobert a979ccd5bd Add document-format RFC draft (#4264)
* Add document-format RFC draft

* Align document-format RFC with graph-storage implementation

* Update writing style

* Recharacterize resource source chain as LWW-element-set, not add-wins OR-set

* Add Rev identity rationale framed against Git, plus patch-id future item

* Correct RFC inaccuracies found in implementation audit

* Mark unimplemented retirement coarsening and leader election as future; fix resurrection mechanism

* Add hot-log to the on-disk payload list in the architecture diagram
2026-06-28 19:05:30 +00:00
Keavon Chambers fa27d53b98 Add a Vite plugin to auto-prefix -webkit-user-select so it's not so often forgotten (#4288)
* Add a Vite plugin to auto-prefix -webkit-user-select so it's not so often forgotten

* Enforce a property boundary on the left
2026-06-28 00:20:26 -07:00
Keavon Chambers cc465d6f2a Fix the 'Separate Subpaths' node dropping a layer's transform when it has no subpaths (#4289)
Fix the Separate Subpaths node dropping a layer's transform when it has no subpaths
2026-06-27 23:42:25 -07:00
Timon 21bf290013 Hide node parameters connected to a NodeInput::Scope in the Properties panel (#4284)
Hide inputs connected to a scope in properties panel
2026-06-26 09:48:14 +00:00
TimonandJames Lindsay 684496109a Fix a previewed node's dashed output wire appearing at the wrong position (#4282)
* Fix node graph connection to export in wrong place

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

* Review

---------

Co-authored-by: James Lindsay <[email protected]>
2026-06-26 09:43:00 +00:00
Timon f3faefd460 Snap overlays to device instead of UI pixels on web (#4281)
Snap overlays to physical instead of logical pixels on web
2026-06-25 09:04:36 +00:00
Timon 6fb6e83d68 Desktop: Prefer Vulkan as the WGPU backend on Linux (#4270)
* Manual wgpu adapter selection

* Fall back to remaining adapters when the preferred one fails to initialize
2026-06-25 00:09:39 +00:00
Keavon Chambers ebbbb6bd1b Fix the Shift-drag alignment guide anchoring to the prior selection instead of the dragged layer (#4278) 2026-06-23 02:28:06 -07:00
Dennis Kobert 03c33dc784 Fix error from running cargo check with a system global Cargo config.toml rustflags override (#4277)
Fix error caused by running cargo check in the workspace
2026-06-23 09:09:19 +00:00
jneemandKeavon Chambers 57ee2b00ca Bump linesweeper to 0.4 (#4273)
* Bump linesweeper to 0.4

* Avoid crash if there's an indexing bug

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-23 00:15:55 +00:00
Keavon Chambers 1158d93bb4 Migrate legacy gradients via an isolated measurement pre-pass (#4268)
* Migrate legacy gradients via an isolated measurement pre-pass

Convert legacy bounding-box-relative Fill::Gradient values to absolute
space on document load by measuring each fill's evaluated geometry,
rather than walking each layer's primary flow. The pre-pass scans the
whole root network so fills on secondary branches (e.g. a Copy to Points
instance) and fills in hidden, disabled, or orphaned branches are all
found, redirecting the document export to each fill in turn to force its
branch to evaluate and reading its geometry back from the inspect result.

With every legacy gradient converted before any render, the legacy
bounding-box render path is removed: the ATTR_GRADIENT_LEGACY marker, the
renderer's legacy brush branch, and fill_to_graphic_list's bbox bake all
go away. Gradients nested inside subgraph node networks are out of scope
and warned about.

* Address review: harden gradient migration against stalls and document switches

- Advance the queue on dispatch early returns (missing export or channel
  send error) so a failure can't leave the migration permanently stuck
  with the document unable to render.
- Tag the migration with its DocumentId: cancel-and-restart when a
  different document's migration is requested, and only apply a
  measurement to the active document's in-progress migration, so
  switching documents mid-migration can't stall or cross-apply.

* Remove nested network non-migration warning

* Cleanup

* Also add migrations for Fill node backup colors

* Apply migrations to the demo art
2026-06-22 16:59:22 -07:00
Keavon Chambers c1fa8ba8da Move NumberInput.svelte input processing from JS to Rust (#4274)
* Move NumberInput.svelte input processing from JS to Rust

* Fix edge cases
2026-06-22 14:57:11 -07:00
TimonandKeavon Chambers f798b48b83 Move branding and package install into cargo-run (#4266)
* Move branding asset fetch into cargo-run

* Move frontend npm install into cargo-run

* Rename branding::ensure to branding::setup

* Wording nits

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-22 20:21:46 +00:00
Keavon Chambers b286e89746 Make the Pen tool's preview segment follow the cursor during a G/R/S handle transform (#4269) 2026-06-22 01:37:23 -07:00
Timon d753ce26f7 Make the cargo-run tool auto-install its wasm-opt build dependency (#4256)
* Allow auto downloading wasm-opt

* Fix for mac

* Review
2026-06-21 20:17:54 +00:00
TimonandKeavon Chambers a72ac39059 Replace the dev server's wasm-pack, cargo-watch, and concurrently tools with custom cargo-run tooling (#4254)
Replace wasm-pack, cargo-watch and concurrently with custom build tooling

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-21 12:48:31 -07:00
Keavon Chambers 1f05000238 Exclude viewport zoom from influencing scale in the Transform node set by the drawing tools (#4260)
* Keep viewport zoom out of drawing tools' Transform node

* Simplify window-aligned transform helpers and fix spline DragStop fallback
2026-06-21 12:09:21 -07:00
Dennis Kobert b45cc312dd Add support for opening GDD documents from the CLI (#4262)
* Wire document-format into graphene-cli

* Support loading both legacy and new graphite files in the cli

* Address PR review: propagate CLI errors and use dyn resolver

* Fix CLI network wrap + preprocessor ordering

* Cleanup preprocessor

* Remove unused import
2026-06-21 18:17:01 +02:00
Dennis Kobert de11d29d8e Add document-format crate (#4234)
* Add document-format crate

* Adapt document-format to merged graph-storage and consolidate errors

* Fix resource write ordering, codec error masking, and export docs

* Remove document-format RFC; tracked in a dedicated PR

* Restructure document-format into gdd/persist/export/resource modules

Split the 963-line lib.rs by responsibility: persist path into persist.rs, resource I/O into resource.rs, export engine into export.rs. Rename the GddV1 layout struct to GddV1Layout and add a GddV1 = Gdd<GddV1Layout> alias.

* Feature-split document-format and graph-storage for minimal builds

* Address PR review: O(1) history-delta lookup and no-default-features test build

* Address PR review: propagate apply_hot_op persist error and assert resource hash

* Make decompression from archive streaming

* Share archive export body between export and export_to_bytes

* Review cleanup

* Export documents with un-retired hot ops losslessly

* Persist last_broadcast_rev in session.json, drop unused last_retired_at

* Move peer_id from manifest to session.json

* Rename gesture to interaction in document-format storage layer
2026-06-21 12:35:47 +00:00
Keavon Chambers 194c5b2222 Fix the Select tool's transform dial not working on rotated layers (#4259) 2026-06-20 15:05:30 -07:00
Keavon Chambers e8f9413e03 Fix double-clicking a gradient stop under snapping influence not opening color picker (#4258)
* Fix double-clicking a gradient stop under snapping influence not opening color picker

* Simplify
2026-06-20 14:48:26 -07:00
YohYamasakiandKeavon Chambers 7bc0f042ce Transition gradients from bbox-relative to document-absolute space (#4241)
* Use userSpaceOnUse to render gradient on SVG

* Allow non-uniform transform to radial gradient on vello

* Position gradients absolutely instead of by bbox

* Fix SVG import by removing multiplication of bound's inverse transform

* Represent sheared linear gradients via their equivalent gradient line

* Migration

* Fix migration for radial (elliptical) gradients

* Fix boolean operation gradients

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-20 21:21:28 +00:00
Timon 674b3a213f Extract pipelines from WgpuExecutor into scope-provided pipeline nodes (#4210)
* Implement generic pipeline caching

* Fix WIP

* Fix

* Fix

* Fix

* Fix bench

* Migrations

* Review
2026-06-19 21:20:25 +00:00
YohYamasakiandKeavon Chambers 3bf32443ed Improve graphic List<T> fill/stroke paint handling (#4240)
* Fix empty color list ignoring paint target

* Avoid cloning renderable lists for paint presence checks

* Refactor after code review by gemini

* Make singular matrix check more robust

* Extract transform_is_invertible helper; clarify has_paint_at docs

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-19 20:42:49 +00:00
Jatin BhartiandKeavon Chambers 5f100946f2 Add String[] as a graphic type for typography (#4141)
* feat: Render List<String> as raw paths in SVG and Vell mode

* chore: code review

* chore: change the hardcoded layout bounds to parley's

* chore: code review

* feat: Split text node to text_layer and text_to_vector node

* fix: CI fail because of difference in nature of Mac and github action

* chore: fix

* chore: replace FontStack as it got removed in parley 0.9

* chore: fmt

* chore: migrate the rendering as of new resource architechture

* chore: add text_layer node to text tool for testing

* code review

* Make boolean ops support the Text type

* chore: Move fallback_font_resource authority from editor to text node

* Fix 'Text Layer' node missing font dropdown

* Change node doc comments from Vec<T> to T[]

* Add migrations from the old Text node to Text -> Text to Vector

* Consolidate

* Rename the text attributes and reorder tilt to come before max_width/height

* Detect legacy Text nodes in the split migration by their trailing separate_glyphs input

* Code review

* Frame Text layer thumbnails by laying out their text for bounds

* Give Text layers click targets and selection outlines via collect_metadata

* Route Text tool through Text to Vector with fill, fixing editing-preview placement

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-19 19:39:52 +00:00
Keavon Chambers 13abf9fa8c Make vector mesh branch detection and free-point click targets O(n) instead of O(n^2) (#4255)
* Make is_branching and free-point click targets O(n) instead of O(n^2)

* usize -> u8

* Fix profiling CI treating performance improvements as regressions
2026-06-18 21:52:02 -07:00
Timon 236ab7a11c Move TaggedValue::ResourceHash to macro definition site (#4232) 2026-06-19 01:36:45 +00:00
Keavon Chambers 5b008936d2 Make the node graph's "Merge Selected Nodes" target the right-clicked node, and fix it crashing (#4252) 2026-06-17 22:31:06 -07:00
Keavon Chambers 9a9436c5b9 Fix "Untitled Document {N}" numbering progression when another doc includes that substring (#4253)
* Fix "Untitled Document {N}" numbering progression when another doc includes that substring

* Fix names with non-numeric suffixes blocking the base name
2026-06-17 22:00:31 -07:00
Dennis Kobert b1d8ac0e64 Add History type and merge-commit model to graph-storage (#4238)
* Add History type and merge-commit model to graph-storage

* Add History::merge with canonical-sort convergence to graph-storage

* Append merge delta without re-sorting the whole history

* Resurrect across merges by searching all ancestors, not the primary chain
2026-06-16 15:02:48 +02:00
Keavon Chambers a5e7a4f905 Simplify comments on the Color struct 2026-06-15 22:20:31 -07:00
Keavon Chambers 9f01e54a9b Add layer and artboard nudge resizing (#4242)
* Add layer and artboard nudge resizing

* Improve bounding box validation for layer resizing to ensure only finite bounds are considered
2026-06-15 21:37:40 -07:00
Keavon Chambers 8b8cac23d1 Remove layer and artboard nudge resizing 2026-06-15 18:51:15 -07:00
Keavon Chambers 82879c7a08 Simplify helper function signatures in document_message_handler.rs 2026-06-15 17:11:01 -07:00
Keavon Chambers 3414b32d5e Remove dead code from the unused curves adjustment widget 2026-06-15 14:46:43 -07:00
Keavon Chambers 971d1fb16b Fix loading documents saved before #4129 with raster images appearing missing 2026-06-15 11:19:21 -07:00
Timon 077d11bdba Resolve scopes before flattening network (#4235)
* Compiler changes

* Run preprocessor on wrapping network

* Remove test nodes

* FIx

* move generate_node_paths call to compiler

* Make it more obvious what input is set to
2026-06-15 11:19:21 -07:00
Keavon Chambers 34e0fd7757 Replace the 'Vec2 to Point' node with automatic conversion machinery (#4236)
* Replace the 'Vec2 to Point' node with an 'As Vector' node and automatic conversion

* Accept a Vec2 as content for the Wrap Graphic node

* Rename the type-assertion nodes from 'To' to 'As'

* Fix the Transform node reversing a Vec2 input's direction

* Fix text migration bug
2026-06-14 21:44:08 -07:00
Dennis KobertandTimon b56af15e5e Add graph-storage crate (#4198)
* Add graph-storage crate

* Split graph-storage lib.rs into smaller modules

* Make graph_craft/core_types dependency optional

* Fix CRDT correctness issues flagged in graph-storage PR review

* Treat trailing empty export slots as value-equal in Network::value_equal

* Address graph-storage review: parameterize CrdtError, reject hot-log corruption, drop LamportClock Default

* Address graph-storage review: fix root-delta history walk, validate cross-network refs, make compute_deltas deterministic, harden Priority, index nodes by network

* Address graph-storage review: sort sources on deserialize, treat inputs_attributes length as structural, dedupe demo-artwork loader

* Add opt-in Delta rev validation, dedup resource sources on deserialize, fix doc grammar

* Persist scope injections through storage; harden gesture-end and embedded-source checks

* Review

* Review

* Review

* Use new types for NodeId and NetworkId

* Adress minor review comments

---------

Co-authored-by: Timon <[email protected]>
2026-06-13 16:47:04 +00:00
Keavon Chambers cde8dd78e6 Remove stray float literal .0 suffixes in lieu of just ending with a point (#4233)
Remove the .0 suffix on floats in lieu of just ending with a point
2026-06-12 19:47:36 -07:00
YohYamasakiandKeavon Chambers 2b8ef42086 Add renderer support for painting vector with "fill" and "stroke" attributes with graphic List<T> types (#4111)
* Add conversion from Fill to Table<Graphic>

* Refactor Vector vello renderer for Gradient / Color

* Refactor Vector SVG renderer for Gradient / Color

* Fix conflicts

* Add basic clipping-based fill for SVG rendering

* Use Cow to avoid cloning graphic list for fill

* Cleanup for Cow usage

* format code

* Use `<pattern>` instead of `<clipPath>` for clip

This simplifies the future implementation of clipping-based rendering
for strokes, as the stroke does not support the use of a clip path but
rather paint sources from a paint server.

* Move svg pattern rendering function to RenderExt

* Fix comment

* Fix empty fill list rendering as default black

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Move opaque check function to Graphic impl

* Add color converter and debug node to use graphic

* WIP: Use List<Graphic> to render Color & Gradient

* Use `Arc<List<Vector>>` for vector_data metadata

This exposes List's attributes to message handlers, enabling them to
access the necessary attribute data such as ATTR_STROKE_PAINT_GRAPHIC
as `Fill` and `Stroke` will not have paint information in the future.

* Recurse opacity checks on nested `Graphic`

Also extracts `fill_graphic_list_at` /
`stroke_paint_graphic_list_at` to share the row-attribute
lookup across the existing call sites.

* Fix fill and stroke visibility check degradation

* Fix clipping based stroke paint positioning

* Refactor vello renderer for stroke to use graphic

* Reduce `Fill` / `Stroke.color` to `List<Graphic>` allocations

* Revert "Use `Arc<List<Vector>>` for vector_data metadata"

This reverts commit 4285243a5d

* Expose paint row attributes as dedicated metadata for vectors

Add `fill_attributes` / `stroke_paint_attributes` to `DocumentMetadata`
so the `ExpandFillStrokeOnSelectedLayers` handler can read row paint
visibility without exposing entire `List<Vector>`.

* Fix transparency check to consider fill opacity

* Fix consistency of gradient placement for SVG stroke

* Rename `stroke_paint_..` to `stroke_..`

* Remove debug nodes

* Allow to use any graphic type without casting

* Rename `fill_graphic` / `stroke_graphic` to `fill` / `stroke`

* Fix SVG pattern placement when stroke transform differs from item transform

* Fix click target fill check for empty list in graphic

* Fix blank fill/stroke attribute masking legacy style

* Fix SVG's paint order trick for vector/raster fills

* Add zero-division guard for pattern wraparound prevention

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-12 23:29:34 +00:00
TimonandDennis Kobert e524dff1a7 Add node macro support for injecting nodes into global scope (#4221)
* Macro support

* Preprocessor support

* Allow Cow str as scope name

* Use Passthrough node to work around compiler auto wrapping the producer node and invalidating the node id

* Stable NodeIds

* Less hacky but with bad performace

* Remove Cow from RegistryValueSource::Scope

* Connect scope injections to the inner network export

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-06-11 18:14:58 +00:00
Timon 05d3d66587 Desktop: Block network requests in CEF that are not explicitly allowlisted (#4225) 2026-06-11 15:32:53 +00:00
YohYamasaki 26a0b901d4 Unify the gradient chain lookup used by the stops and attribute reads (#4223) 2026-06-11 05:36:43 +00:00
Keavon Chambers 97324cd852 Fix the Gradient tool breaking the layer deletion hotkey (#4224)
* Fix the Gradient tool breaking the layer deletion hotkey

* Fix
2026-06-10 22:32:39 -07:00
Keavon Chambers f658665d4a Fix CI deploying all PR preview builds to dev.graphite.art
Fixes a regression introduced in 9dccc526b
2026-06-10 16:18:41 -07:00
Keavon Chambers a7171f5939 Stop flatten_graphic_list() from adding unused attributes (#4220) 2026-06-10 14:37:14 -07:00
Vishnu Tejas f2c83d2278 Desktop: Fix double-clicking top bar not toggling maximize on Linux (#3940)
Fix double-clicking top bar not toggling maximize in linux
2026-06-10 10:19:19 +00:00
Keavon Chambers 863b1f9993 Fix opacity attributes from defaulting to 0 rather than 1 (#4219)
* Fix opacity attribute padding to default to 1 instead of 0

* Perf fixes
2026-06-09 23:00:57 -07:00
Keavon Chambers 02a40a860f Add a wave propagation ripple effect to the website navbar (#4150)
* WIP: Website navbar ripple

* Fix performance and other bugs

* Make the navbar ripple's active button explicitly inert
2026-06-08 23:15:12 -07:00
Keavon Chambers b4e04e616a Fix the SVG renderer not representing skewed raster images (#4218)
Fix the SVG renderer not skewing raster images to fit their bounds
2026-06-08 21:28:38 -07:00
Keavon Chambers bc1f63ccc6 Add Alt+drag layer duplication to the Layers panel (#4216)
* Add Alt+drag layer duplication to the Layers panel

* Code review
2026-06-08 21:08:16 -07:00
Keavon Chambers 04bca4a877 Fix the Pen tool's preview being misplaced and angle-locked after undo or redo (#4215)
* Fix the Pen tool's preview being misplaced and angle-locked after undo or redo

* Clear the Pen tool's stale angle-lock flag after undo or redo
2026-06-08 13:28:57 -07:00
Vatsal KumarandKeavon Chambers cc7d700bfd Fix the Pen tool preview segment disappearing during repeated undo (#3791)
* fix preview line to be visible on multiple undo

* fixed regression issue for last anchor

* Remove unneeded preview-state resync from the Pen tool undo handler

* Prevent a transient vector gap from ending the Pen tool drawing session

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-08 11:46:10 -07:00
Jatin Bharti 2835c3b536 Fix the Fill node not restoring its solid color after switching to gradient and back (#4159)
* fix: Fill node solid colour backup update

* chore: refactor
2026-06-08 04:18:10 +00:00
Keavon Chambers 7a6e4f6f25 Fix new nodes being added in the wrong place near graph edges (#4211) 2026-06-07 19:22:30 -07:00
Hemu b645871dbc Fix duplicated dropdown selection styling when multiple entries have identical labels (#4180)
* Fix dropdown select if options have identical labels

* update other uses of label in favor of value

* simplify null checks
2026-06-07 17:53:58 -07:00
Keavon Chambers 85ee5e41b9 Fix strokes with inside/outside alignment not being selectable when above other layers (#4207) 2026-06-07 17:08:04 -07:00
Dennis Kobert d5c67eeb55 Drop MemoHash's std Hash impl and route cache-identity hashing through CacheHash (#4209) 2026-06-07 17:49:56 +00:00
Keavon Chambers 2c29d2c406 Fix Gradient tool inserting new nodes in the wrong position when updating a Fill node's gradient chain (#4203)
* Fix Gradient tool inserting new nodes in the wrong position when updating a Fill node's gradient chain

* Improve robustness
2026-06-05 21:02:42 -07:00
YohYamasakiandKeavon Chambers a3b62dac00 Make the Gradient tool work with gradient node chains feeding a Fill node (#4177)
* Add Gradient node

* Add support of new Gradient node for Gradient tool

* Adapt gemini reviews

* Add tests

* Bring back visibility check

* Remove the 'Gradient' node since it's unwanted after all

* Formatting

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-06-06 03:23:14 +00:00
Timon 9d2071ce6a Desktop: Disable UI acceleration by default on Linux (#4201) 2026-06-05 22:16:37 +00:00
Dennis KobertandTimon 6fe1af3afe Add document-container crate (#4191)
* Add document-container crate: container backends and archive codecs

* Address PR review: path/prefix split, safe size casts, OPFS stream aborts

* Address PR review round 2: mmap read check, UTF8 entry names, prefix normalization

* Make MmappedBytes::new fallible so mmap reads can't silently degrade

* Address PR review round 3: backend contract uniformity (symlinks, remove, list)

* Apply symlink-component check to FolderBackend listing paths

* Address PR review: idempotent OPFS delete logging, tar default-features, shared entry-size cap

* Fix validate_path doc: dotfiles pass, CurDir/ParentDir rejected

* Omit symlink entries from FolderBackend listings for consistency with resolve

* Preserve zip I/O errors and reject non-canonical paths in validate_path

* Extend archive apis to return the archive writer

* Rename document/document-container directory to document/container

* Add archive format sniffing and deserialize_auto

* Drop temporal hedge from checked_entry_size comment

* Tighten verbose doc comments in document-container

* Coalesce consecutive same-path OPFS appends to avoid O(n^2) file copies

* Review

* Update document-container for the deserialize/store_non_blocking renames

---------

Co-authored-by: Timon <[email protected]>
2026-06-05 13:28:02 -04:00
Timon 08c6d02e5b Introduce network request handler (#4194)
* Impl NetworkMessageHandler

* Repalce Frontend fetch like messages with NetworkMessage

* Reimpl resource loading with NetworkMessage

* Fix wasm

* dedublicate resource requests

* Embedd font resources created by migration

* Fixup

* Fix tests

* Fix font catalog not loading

* Cleanup

* Fix layouts not updating when font catalog is loaded

* Review

* Review

* Cleanup
2026-06-05 13:27:45 -04:00
Timon cd8ea1f554 Migrate fonts to be stored as resources (#4165)
* Good start

* Impl

* allow responses.add(async { Message::NoOp });

* Fix

* Cache font blob in text node

* Refactor font handling to use Font struct direcly

* Fix fmt

* Embedd Font Resources by default

* Review

* Review

* Cache font info based on ResourceHash
2026-06-05 13:27:25 -04:00
Dennis Kobert 7b9c480a8d Make ResourceStorage trait &self-based and remove 'static requirement (#4188)
* Make ResourceStorage trait &self-based with elided-lifetime ResourceFuture

* Adress review comments
2026-06-01 10:37:05 +00:00
Timon e32ff4b7f0 Make Resource aware of its own hash (#4187)
* Fix future message handler field name

* Add Resource::hash()

* Move all remaining resource types from core-types to graphene-resources

* Review
2026-05-31 23:08:01 +00:00
Dennis KobertandTimon 78679a5ba2 Implement editor level future message handler (#4182)
* Implement proper editor level async message handler

* Take application_io and wake callback as Editor::new arguments

* Rename AsyncMessage -> FutureMessage

* add DesktopWrapperMessage::Wake

---------

Co-authored-by: Timon <[email protected]>
2026-05-31 21:26:29 +00:00
Timon 51427bef5f Fix CI profiling compile failure (#4184) 2026-05-31 20:32:34 +00:00
Timon a40e0d2887 Use ResourceId for referring to Resources (#4176)
* Use ResourceId for referring to Resources

* Use Doc

* use error for preprocessor ResourceId replacement failure

* Keep hashes in DocumentInfo

* Migrate with less mem copy

* Global ResourceMessage -> ResourceStorageMessage

* Add document ResourceMessage

* Move embedding logic

* Fix

* Cleanup

* Review

* Fix
2026-05-29 10:56:32 +00:00
TimonandDennis Kobert bbbe04903f Define data types for ID-based resource handling (#4168)
* Add resource lib

* rename ResourceSource to ResourceInput

* Rename ResourceInput -> DataSource and improve API

* Review

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-05-25 10:50:57 +00:00
Keavon Chambers d0d9a350c7 Add new May 2026 release update video to website home page 2026-05-23 02:04:59 -04:00
Keavon Chambers 9dccc526bb Add the May 2026 release message to the welcome screen 2026-05-23 01:41:42 -04:00
Keavon Chambers 96be4ec351 Add an "Initializing Renderer…" overlay when Vello shader compilation is slow on web 2026-05-23 01:07:26 -04:00
Keavon Chambers 62287d7893 Add a recovery path for autosaved documents that don't open successfully (#4157)
* Add a recovery path for autosaved documents that don't open successfully

* Fix file naming edge case

* Add edge cases for Windows zip names

* Simplify comments and remove desktop portion
2026-05-22 21:14:28 -07:00
Timon c3b0c87cfe Antialias checkered artboard background edges (#4163)
* Antialias checkered artboard background edges

* Review
2026-05-22 16:48:05 +00:00
Timon 2770df7567 Implement content-addressed resource storage for raster images (#4148)
* Implement content-addressed resource storage

* Implement OPFS resource storage

* Remove ResourceStorage::read

* Review
2026-05-21 19:31:07 +00:00
Keavon Chambers 21d2994059 Fix 'Solidify Strokes' node to produce dashed segments in an ordered sequence per open subpath (#3820)
Fix the ordering of dashed segments of open paths with the 'Solidify Stroke' node
2026-05-17 10:56:40 -07:00
Timon d5f0140f26 Upgrade WGPU and Linebender dependencies (#4154) 2026-05-17 15:36:59 +00:00
Keavon Chambers c4a978009a Fix SVG import treating gamma-encoded colors as linear-light 2026-05-16 05:37:01 -07:00
Keavon Chambers 256dd26b99 Recognize ExtractPosition/InjectPosition in the node macro context analyzer
Also, fix migration missing alias
2026-05-16 01:40:49 -07:00
Keavon Chambers 06e2a049de Implement dragging layers into the group/new/delete buttons in the Layers panel (#4153) 2026-05-15 15:39:01 -07:00
Keavon Chambers 79df7cfa87 Implement dragging the visibility/lock icons in the Layers panel to toggle each (#4152)
* Implement dragging the visibility/lock icons in the Layers panel to toggle each

* Code review fixes
2026-05-15 15:16:40 -07:00
Keavon Chambers 16c7544d96 Add the Layer > Expand Fill/Stroke menu action (#4151)
* Add the Layer > Expand Fill/Stroke menu action

* Code review feedback
2026-05-15 13:10:50 -07:00
Keavon Chambers a56746c6bf Deprecate all usages of the Color struct representing gamma space values, fixing round-trip precision bugs (#4149)
* Deprecate all usages of the Color struct representing gamma space values, fixing round-trip precision bugs

* Code review fixes
2026-05-14 22:48:33 -07:00
gamma0987andDennis Kobert 456a7c868d Migrate iai-callgrind to the renamed successor gungraun (#4056)
* Add .nvim.lua to gitignore

* Migrate from iai-callgrind to the renamed successor gungraun

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-05-14 08:18:59 +00:00
Keavon Chambers 1c9c19a697 Simplify and standardize how data types are presented in user-facing strings (#4147)
* User-facing type formatting

* Parse unicode not ASCII chars
2026-05-14 00:56:43 -07:00
Keavon Chambers 696b625a3e Fix hover transfer bugs occurring with the color picker popover (#4146)
* Fix hover transfer bugs occurring with the color picker popover

* Code review fix
2026-05-13 20:19:56 -07:00
Keavon Chambers 4d5dce976e Replace the control bar's stroke weight with a full stroke properties popover (#4145)
* Replace the control bar's stroke weight with a full stroke properties popover

* Code review
2026-05-13 03:58:12 -07:00
Keavon Chambers 629a1f4b4c Redesign how the control bar handles fill and stroke colors (#4137)
* Revamp how the control bar handles fill and stroke colors

* Fix bugs

* Code review
2026-05-11 18:13:02 -07:00
Keavon Chambers f6def3b911 Add icons for stroke align, cap, join, and order (#4136) 2026-05-11 03:53:38 -07:00
Timon 98daa75c26 Desktop: Add support for opening files through the already-running instance via a local socket (#4123)
* Desktop: Forward file-open args from a second launch to the running instance

Also adds socket infrastructure that can be used in the future to allow dispatching actions from another process

* Use socket instead of ipc terminologie

* Fix

* Fix

* Better pipe name on windows
2026-05-09 18:11:44 +00:00
Keavon Chambers a28b9437aa Rename the "Table" type to "List" everywhere (#4133)
* Rename the "Table" type to "List" everywhere

* Fix a few missed ones

* Re-save demo artwork
2026-05-09 01:33:39 -07:00
Keavon Chambers 6b3e4757de Rename the Table type's "rows" -> "items" and "columns" -> "attributes" everywhere (#4130)
* Rename TableRow -> Item

* Rename row -> item and column -> attribute throughout

* Fix a few missed ones

* Format
2026-05-08 23:11:33 -07:00
Keavon Chambers cb21e5960b Remove serialization from Table<T> and make TaggedValue only store tooling/widget node inputs (#4129)
* Add TaggedValue::TypeDefault to avoid baking placeholder Tables into saved documents

* Add TaggedValue::TypeDefault to avoid baking placeholder Tables into saved documents

* Migrate empty Vector/Raster/Graphic/Artboard placeholder values to TypeDefault on load

Documents written before the TypeDefault mechanism existed have empty Table<Vector>/<Raster>/<Graphic>/<Artboard> values baked into every unwired exposed input. Walk each migrated node's inputs and rewrite any such placeholder NodeInput::Value into the equivalent NodeInput::type_default, so re-saved documents shed the placeholder payloads. Marked with a TODO for eventual removal once enough documents have been re-saved.

* Re-save demo artwork

* Remove Graphic and Artboard placeholder containers from TaggedValue

* Remove Raster placeholder TaggedValue variant

* Simplify document migration

* Remove Vector placeholder TaggedValue variant

* Remove NodeIdTable from the TaggedValue

* Remove StringTable from the TaggedValue

* Remove F64Table in place of F64Array in TaggedValue

* Replace TaggedValue::Color(Table<Color>) with ::Color(Option<Color>)

* Replace TaggedValue::GradientTable(Table<GradientStops>) with ::Gradient(GradientStops)

* Replace TaggedValue::BrushStrokeTable(Table<BrushStroke>) with ::BrushStrokes(Vec<BrushStroke>)

* Make TaggedValue::DocumentNode runtime-only with TypeDefault placeholder

* Make TaggedValue::ContextFeatures runtime-only

* Remove Serialize/Deserialize from Table<T>

* Add a widget for TaggedValue::BrushStrokes to visualize strokes and samples

* Define a reusable list of TaggedValue::TypeDefault types for its generated methods

* Re-save demo artwork
2026-05-08 16:11:25 -07:00
Timon d97fe835b5 Desktop: Focus app window when loading a document (#4124) 2026-05-08 15:00:20 +00:00
Keavon Chambers 9d876ab27d Add support for opening multiple selected files from disk (#4128) 2026-05-07 21:21:45 -07:00
Keavon Chambers dff8ac5511 Remove code for the deprecated and unused Curve type (#4127)
* Remove the unused Curve type

* Fix frontend
2026-05-07 16:16:19 -07:00
Keavon Chambers 0834bff2da Make the Brush node store its cache as internal #[data] state instead of a serialized node input (#4126)
* Make the Brush node store its cache as internal #[data] state instead of a serialized node input

* Remove BrushCacheImpl::unique_id
2026-05-07 15:34:21 -07:00
Keavon Chambers 525e49f7e9 Make the Shape tool's modes' parameter controls sync with the selected shape layer (#4121)
* Make the Shape tool's modes' parameter controls sync with the selected shape layer

* Fix populating the Shape tool mode selection list
2026-05-07 02:42:39 -07:00
Keavon Chambers 1596469e92 Make the drawing tools' Weight control sync with the selected layer (#4120) 2026-05-07 02:12:38 -07:00
Keavon Chambers 9512f7df41 Make the Gradient tool default to the primary/secondary working colors as its initial gradient (#4119)
* Make the Gradient tool default to the primary/secondary working colors as its initial gradient

* Fix drawing direction
2026-05-07 01:41:01 -07:00
Keavon Chambers 24c857ddc7 Make the Text tool control bar font family, style, and size sync with the selected layer (#4118)
* Fix contenteditable preview alignment

* Make the Text tool control bar font family, style, and size sync with the selected layer

* Tidying up
2026-05-06 20:50:41 -07:00
Keavon Chambers 2ae35a67e7 Add icons for text alignment/justification 2026-05-06 19:26:26 -07:00
Jatin BhartiandKeavon Chambers c0a8241f50 Add text last-line alignment modes for "Justify Center", "Justify Right", and "Justify All" (#4024)
* feat: Add justify proper alignments(right/left/centre/all)

* chore: fmt

* chore: refactor

* Cleanup

* Fix crash when changing selected layer's alignment from the Text tool control bar

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-05-06 19:16:19 -07:00
Timon 1c2ac19b16 Desktop: Register the Graphite app as a file handler on Mac (#4106)
* Desktop: Implement native file open handler

* Desktop: Register file types on Mac

* Review
2026-05-06 13:05:30 +00:00
Timon 8ae8c47fe1 Fix the Fix > Close All action not resulting in the welcome screen being shown (#4107)
Fix missing welcome panel after closing all documents

Closing all documents left the Welcome panel as the only tab, but the old active document index could still point to a tab that no longer existed. The fix is to reset it to 0 when the document list becomes empty.
2026-05-06 12:03:14 +00:00
Keavon Chambers 023cf1bedd Fix the 'Flatten Vector' node losing child layer transforms for the editor tools (#4116) 2026-05-06 04:35:23 -07:00
Keavon Chambers d106bedecd Fix Pen tool regression that broke dragging a sharp tangent out of the last-placed anchor (#4115) 2026-05-06 03:16:24 -07:00
Keavon Chambers ecf94258fa Fix tool overlays and snap targets to use upstream Path node geometry, not downstream final geometry (#4114)
* Fix tool overlays and snap targets to use upstream Path node geometry not downstream final geometry

* Snap to upstream Path free points, dedupe the lookup via a helper
2026-05-06 03:00:38 -07:00
Keavon Chambers 22a6e0d767 Preserve editor:layer_path through Table<Vector>::into_graphic_table() (#4113) 2026-05-06 02:21:45 -07:00
Keavon Chambers 9565d43481 Include stroke thickness in the bounds of document exports sized to fit "All Artwork" or "Selection" (#4112)
* Include stroke thickness in the bounds of document exports sized to fit "All Artwork" or "Selection"

* Code review fixes
2026-05-06 02:05:19 -07:00
Keavon Chambers 05f6138b65 Fix 'Offset Path' node crash on empty or zero-scaled geometry 2026-05-06 01:33:11 -07:00
Keavon Chambers 39a7c45ccd Fix rendering semi-opaque paths with "Outside" stroke alignment (#4110) 2026-05-06 01:26:43 -07:00
Keavon Chambers 269a217cf9 Fix Vello renderer cropping open paths with Inside-aligned strokes and an opacity or blend mode set (#4109)
* Fix blend layers wrongly cropping Inside-aligned strokes on open paths

* Skip the closed-subpath check when stroke alignment can't apply

* Compute `can_draw_aligned_stroke` once and share it with the blend layer

* Use the actual axis scale, not the column-vector diagonal, when sizing stroke clip rects

* Fix under skew
2026-05-06 00:28:51 -07:00
Keavon Chambers 5becf132e7 Fix Vello renderer cropping wide miter joins and square caps (#4108)
* Fix renderer compositing layers cropping wide miter joins and square caps

* Fix double-scaled inflation on the Vello blend layer's clip rect
2026-05-05 22:02:02 -07:00
Keavon Chambers 644e9cf91e New nodes: 'Attach Attribute' and 'Read Attribute *' (#4100)
* New nodes: 'Zip Attribute' and 'Read Attribute {Vector, Number, Bool, String, Transform, Color, Blend Mode, Gradient Type, Spread Method}

* Cleanup

* Reduce type explosion
2026-05-05 04:03:41 -07:00
Keavon Chambers 9db91a1ac4 Use the SpectrumInput widget for the adjustment node Properties panel layouts (#4105) 2026-05-05 03:42:44 -07:00
Keavon Chambers e59612c4ce Port the color picker popover to a Rust-defined layout (#4102)
* Break out VisualColorPickersInput.svelte

* Break out ColorComparisonInput.svelte and ColorPresetsInput.svelte

* Add backend definitions and plumbing for the 4 new widgets

* Port the ColorPicker.svelte layout and business logic to Rust

* Port more ColorComparisonInput.svelte logic to Rust

* Port more SpectrumInput.svelte logic to Rust

* Port more frontend logic to Rust

* Code review

* Code review

* Fix some CSS
2026-05-05 02:47:53 -07:00
Keavon Chambers 62203cb171 Fix the 'Solidify Stroke' node to snapshot its merged children 2026-05-03 21:30:49 -07:00
Keavon Chambers 21e5e06b0b Clean up document message wrappers around proto nodes so they're now used directly (#4101)
* Rename the 'Identity' node to 'Passthrough' internally

* Rename the 'Memoize'  node to 'Cache' internally

* Let skip_impl proto nodes auto-generate as document node definitions

* Remove the wrapper 'Passthrough' node from document_node_definitions.rs

* Remove the wrapper 'Cache' node from document_node_definitions.rs

* Remove the wrapper 'Monitor' node from document_node_definitions.rs

* Remove the wrapper 'Noise Pattern' node from document_node_definitions.rs

* Remove the wrapper 'Brush' node from document_node_definitions.rs

* Remove the wrapper 'Transform' node from document_node_definitions.rs

* Code review improvements

* Rename Cache node back to Memoize

* More code review
2026-05-03 19:26:36 -07:00
Keavon Chambers b27b4c6be7 Remove gaps between text glyph bounding box click targets so selection is more reliable (#4098)
* Remove gaps between text glyph bounding box click targets so selection is more reliable

* Code review
2026-05-02 21:53:33 -07:00
Keavon Chambers ebdb835890 Properly track the Text node's text frame via the attribute system to fix misalignment (#4097)
* Compensate for upstream row-0 transform absorption in viewport-space 'TransformSet'

* Add 'editor:text_frame' row attribute so the Text tool's drag cage tracks multi-row text

* "Separate Glyph Elements" -> "Separate Glyphs"

* Improve artboard migration robustness from older documents

* Code review

* Make the tools visualize the text frame based on attribute not upstream node
2026-05-02 21:04:30 -07:00
Keavon Chambers de2ae29edd Improve click targets to use compound paths so interior negative space is excluded (#4096)
* Add ClickTargetType::CompoundPath variant for fill-rule-aware compound shape hit testing

* Generate one compound click target per Vector so glyph holes aren't treated as filled

* Fix insidenss logic
2026-05-02 18:47:43 -07:00
Keavon Chambers 325e9aff06 Add custom click targets to make Text node output easier to select (#4095)
* Stop pushing duplicate layer entries when re-clicking an already-selected layer

* Make Text node generate per-glyph bounding box click targets

* Show source-geometry outlines and aggregate all rows for layer click targets

* Strip 'editor:click_target' override on Path node so direct edits restore precise hit testing

* Fix inverting a zero-determinate transform
2026-05-02 18:12:42 -07:00
Keavon Chambers ab7f59ca61 Prep for the RC5 release of the desktop app 2026-05-01 21:58:16 -07:00
Keavon Chambers a0d5f418d9 Replace Table<Table<Graphic>> with Table<Artboard> where Artboard is a type boundary newtype (#4093)
Replace Table<Table<Graphic>> with Table<Artboard> with Artboard as a type boundary newtype
2026-05-01 21:57:50 -07:00
Keavon Chambers 9943af5248 Fix SVG renderer not playing animation due to a regression from the tile cache discarding the context (#4092) 2026-05-01 20:32:53 -07:00
Keavon Chambers 485bac89e5 Fix regression with the color picker in the Properties panel being broken 2026-05-01 19:55:50 -07:00
Keavon Chambers eeb1f85e25 Fix 'Boolean Operation' node outputs having the reversed winding direction (#4091) 2026-05-01 19:23:44 -07:00
Keavon Chambers 42f4c1396b Implement ruler bounds visualization for the AABB of selected layers (#4090)
* Implement ruler bounds visualization for the AABB of selected layers

* Code review fixes
2026-05-01 18:23:51 -07:00
Keavon Chambers eddd742f9b Fix additional panel docking and restoration bugs (#4089)
* Fix another panel docking bug where restoring would leave a blank no-panel space

* Improve panel hide/show to restore position, size, and adjacency

* Check full subtree for document panel and avoid double traversal in insert
2026-05-01 17:14:52 -07:00
Keavon Chambers 0acfd3e178 Add a pointer hover marker line to the rulers (#4088)
* Add a pointer hover marker line to the rulers

* Fix rulers and pointer marker when document is flipped

* Reduce duplicate code

* Fix ruler label placement

* Performance
2026-05-01 15:18:01 -07:00
Timon 29f6e686ee Reimplement checkered background rendering (#4034)
* Reimplement background checkerboard rendering
2026-05-01 17:02:10 +00:00
Keavon Chambers 7cd5531730 Optimize the node graph panel while panning 2026-05-01 17:02:10 +00:00
Keavon Chambers 83d03ad67d Fix panel docking bugs and polish its behavior (#4087)
* Fix panel docking bugs and polish its behavior

* Fix bug
2026-05-01 17:02:10 +00:00
KulcodeandKeavon Chambers 4c1974c200 Improve viewport rulers by tilting tick marks to align with tilted documents (#3844)
* Add support for tilted rulers

* Fix Ruler Text

* Address PR review

* Fix per review

* Code review

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-05-01 17:01:43 +00:00
Keavon Chambers 4474de4662 Replace the AlphaBlending struct with separate attributes (#4086)
* Replace the AlphaBlending struct with separate attributes

* Fix bug

* Fix bug
2026-05-01 03:27:42 -07:00
Keavon Chambers 86134c26b4 Remove the 'Blending' node, moving clip into a new 'Clipping Mask' node and fill into the 'Opacity' node (#4085)
* Separate 'Clip' into its own node out from the removed 'Blending' node

* Code review

* Rename to Clipping Mask

* Update Opacity node in demo art that use it

* Use DIsplay not Debug for printing blend modes
2026-04-30 20:04:04 -07:00
Keavon Chambers 4b2430290c New nodes: 'Gradient Type' and 'Spread Method', and add Gradient tool support for controlling these nodes (#4084)
* Use 'Transform', 'Gradient Type', and 'Spread Method' nodes for table gradients

* Add gradient widget to the tool's control bar and update where the two swap buttons go

* Fix gradient rendering

* Format

* Code review
2026-04-29 19:27:44 -07:00
YohYamasakiandKeavon Chambers e686ee9f42 Add Table<GradientStops> gradient rendering (#3989)
* Add Table<GradientStops> gradient rendering

* Add SVG and Vello renderers for Table<GradientStops>

* Add thumbnail rendering for Table<GradientStops>

* Use row transform to map (0,0), (1,0) unit line to document space

* Set 100px width for the initially created gradient

* Add support of table gradients for the gradient tool

* Fix after review

* Thumbnail rendering of artboard with infinite gradient layer

* Hide radial gradient's reverse direction button for gradient table

* Remove unused imports

* Format

* Fix conflict with spread method

* Code review

* Fix thumbnails

* Connect up gradient_type and spread_method to attributes

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-04-29 05:45:50 -07:00
Keavon Chambers 8cadafa063 Update demo artwork 2026-04-29 04:44:09 -07:00
Keavon Chambers f52009b402 Fix hashing not being based on all attributes of Table (#4079)
* Fix hashing not being based on all attributes of Table

* Cover all attributes in Table PartialEq and CacheHash

---------
2026-04-29 04:37:51 -07:00
Keavon Chambers ba63c26c62 Replace the Artboard struct with a Table<Table<Graphic>> shape (#4077)
* Replace the Artboard struct with a Table<Table<Graphic>> shape

* Remove the never-functional, seemingly unneeded migrate_type_descriptor_names due to typo

* Allow negative artboard sizes
2026-04-28 22:58:33 -07:00
Keavon Chambers 0847d7b0ab Centralize attribute strings in consts and rename "editor:layer" to "editor:layer_path" (#4076)
* Rename "editor:layer" to "editor:layer_path" and centralize it in a const

* Centralize "editor:merged_layers" in a const

* Centralize all other attributes in consts

* Rename consts with ATTR_ prefix

* Format
2026-04-28 21:53:30 -07:00
Keavon Chambers 5774ec215d Replace deprecated row/cell/instance terminology with "item" and "value" terms (#4075) 2026-04-28 19:12:59 -07:00
Keavon Chambers f6c73d1c20 Update roadmap with progress 2026-04-28 18:52:54 -07:00
Keavon Chambers b6ac217b70 Fix menu bar sub-menus being incorrectly positioned (#4073) 2026-04-28 18:51:45 -07:00
Keavon Chambers d44b0cd308 Make documents fall back to "Untitled Document" (+ number suffix) if given a blank name (#4074)
* Make documents fall back to "Untitled Document" (+ number suffix) if given a blank name

* Bug fix
2026-04-28 18:37:13 -07:00
Keavon Chambers b152f46380 Add support for double-clicking to rename document tabs (#4072) 2026-04-28 17:54:58 -07:00
Keavon Chambers fc7348d08a Add support for double-clicking to rename layers in the graph view (#4071)
* Add support for double-clicking to rename layers in the graph view

* Fix text double-click area ending 10px too early from the right

* Fix clicking out and intermittent cursor clicking in text field
2026-04-28 17:30:25 -07:00
Keavon Chambers 6b11b47753 Improve the Data panel with type-specific detail pages and nested-layer support (#4070)
* Improve the Data panel with more type-specific detail pages

* Add network_path to SetDisplayName so renames target any network depth

* Track nested layers via full editor:layer paths and rename parent_layer to path_of_subgraph

* Polish the data panel NodeId leaf page with an editable name field

* Make lock and visibility toggles work for layers in nested subgraphs

* Fix formatting

* Fix connected_to_output running in the wrong network for nested-layer toggles
2026-04-28 15:37:07 -07:00
Keavon Chambers 84fb901b5a Add useful attributes to the JSON and Regex nodes (#4069)
* Add useful attributes to the JSON and Regex nodes

* Code review fix
2026-04-28 14:11:34 -07:00
Keavon Chambers b396d17211 Migrate remaining node graph data types from Vec to Table (#4067)
* Move Vec<String> to Table<String>

* Remove old VecDVec2

* Move Vec<u8> to Table<u8>

* Move Vec<f64> to Table<f64>

* Move [f64; 4] to Table<f64>

* Move Vec<NodeId> to Table<NodeId>

* Tidy up the TaggedValue variants

* Move Vec<BrushStroke> to Table<BrushStroke>

* Add missing type implementations

* Fix tests

---------
2026-04-28 13:44:25 -07:00
Keavon Chambers cf150b5cff Make the Data panel able to display data from selected nodes living in subgraphs (#4064)
Enable the Data panel to display data from selected nodes living in subgraphs
2026-04-28 12:55:13 -07:00
Keavon Chambers df8c2125d9 Migrate 'Scatter Points' and 'Boolean Operation' from subgraphs to memoized proto nodes (#4066) 2026-04-28 12:40:03 -07:00
Dennis Kobert e0368435b9 Add the "memoize" attribute to the node macro (#4065)
* Add memoization attribute to node macro

* Fix memoization insertion for networks without conversion nodes
2026-04-28 11:55:38 +00:00
Keavon Chambers 3eba762135 Migrate 'Sample Polylines' from a subgraph to a proto node (#4063) 2026-04-28 04:20:47 -07:00
Keavon Chambers 881784ba66 Make the Data panel show type-driven widgets for attributes (#4062) 2026-04-28 03:52:04 -07:00
Keavon Chambers afc2c9178e Move source_node_id to "editor:layer" and Vector<Upstream> to "editor:merged_layers", backed by a new 'Write Attribute' node (#4061)
* Fix click target propagation with the Rasterize node

* Add the 'Write Attribute' node

* Remove tag_layer in favor of the new Write Attribute node, prune redundant attribute writes

* Replace the Vector<Upstream> type argument with the "editor:merged_layers" attribute
2026-04-28 03:28:31 -07:00
Keavon Chambers 76938eb69a Implement dynamic table attributes to generalize the graphic-specific Table type (#4050)
* Feature-gate serde derives behind cfg_attr in all runtime node graph type crates

* Refactor Table to move its hard-coded fields into an attributes field

* Encapsulate TableRow/TableRowRef/TableRowMut attribute fields behind accessor methods

* Remove TaggedValue::GraphicUnused

* Refactor Table<T> to use dynamic attributes instead fixed names

* Fix code review soundness concerns

* Add todo work

* Replace row-oriented Table<T> API with column-oriented access

* Fix attribute propagation bugs

---------
2026-04-28 03:25:16 -07:00
Timon 324b9e664c Desktop: Update CEF (#4048)
* Update CEF to version 147

* Fix fmt

* Move CEF package

* Fix nix package

* Improve

* Cleanup

* Fix
2026-04-28 02:25:39 +02:00
Firestar99andTimon 824d1162eb Update rust-gpu to 0.10.0-alpha.1 (#4033)
* rust-gpu alpha.1: update nix flake

* rust-gpu alpha.1: disable non-working mold shell hook

* rust-gpu alpha.1: update rust-gpu to `0.10.0-alpha.1` on crates

* Review

* Fix gpu nodes

* Reduce wasm size

---------

Co-authored-by: Timon <[email protected]>
2026-04-27 23:53:49 +00:00
Dennis KobertandKeavon Chambers 3d84e63ef9 Migrate usage of the Hash trait for cache invalidation to the dedicated CacheHash trait (#4051)
* WIP start migrating usages of hash for cache invalidadion to dedicated trait

* Finish migrating usages

* Code review

* Add comments clearifying the reasoning for using random ids in the VectorModification cach hash impl

* Fix some remaining hash violations

* Finish migration and fix compilation

* Fix import ordering

* Cleanup

* Fix code review stuff

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-04-27 05:18:47 +00:00
Keavon Chambers 7bb01c9651 Fix dropdown menus spawning offset in scrolled panels, a regression from upgrading to Svelte 5.54 (#4047)
* Fix dropdown menus spawning offset in scrolled panels, a regression from upgrading to Svelte 5.54

Regression introduced in #3933 by upgrading from Svelte 5.47.1 to 5.54.1

* Code review

* Fix unrelated typo

* Add assets build size to build link comment
2026-04-24 12:17:27 -07:00
Keavon Chambers c9c76df40c New nodes: 'Regex Contains', 'Regex Replace', 'Regex Find', 'Regex Find All', and 'Regex Split' (#4045)
* Add a family of 5 regex nodes for string processing

* Fix unstaged change
2026-04-24 00:55:24 -07:00
Keavon Chambers c32c808d5b New nodes: 'Format JSON', 'Query JSON', and 'Query JSON All', replacing the 'JSON Get' node (#4044)
* New nodes: 'Format JSON', 'Query JSON', and 'Query JSON All', replacing the 'JSON Get' node

* Fix bugs
2026-04-24 00:26:29 -07:00
Keavon Chambers 6c0af72053 Add a family of 14 new string processing nodes (#4010)
* Add new string processing nodes

* Remove the IntegerCount = u32 type alias

* Add the 'Format Number' node

* Add "Up To" parameter to the 'String Pad' node

* Fix 'String Capitalization' behavior

* Add 'Map String' and 'Read String' nodes

* Add separator_escaping to 'String Repeat'

* Add 'Regex Replace'

* Add 'Regex Match' node

* Regex Find and Regex Find All

* Code review

* Add the 'Escape String' node

* Improve implementations

* Move nodes from logic.rs to text/src/lib.rs

* Clean up migrations

* Fix #[{hard, soft}_{min, max}(...)] node macro attribute

* Improve Data panel number and text display

* Add the 'Query JSON' and 'Query JSON All' nodes

* Add the 'Lorem Ipsum' node and Ipsum library

* Add the 14 nodes back in their final state

* Add handling for fixed decimal places in number formatting

* Code review fixes
2026-04-23 22:46:20 -07:00
Keavon Chambers 328c4f272b New node: 'String Capitalization' (#4043)
* New node: 'String Capitalization'

* Clarify comment
2026-04-23 19:12:00 -07:00
Keavon Chambers a59fed9d1c Move the "Text" category nodes from gcore/src/logic.rs to text/src/lib.rs (#4042)
Move the String category nodes from gcore/src/logic.rs to text/src/lib.rs
2026-04-23 18:12:28 -07:00
Keavon Chambers 1444c333ab Fix CI not preserving the "View deployment" button for old build links in PRs 2026-04-23 16:16:23 -07:00
Keavon Chambers f42d12da9e Improve type handling for ints/floats with the #[hard/soft_min/max(...)] node macro parameter attributes (#4041) 2026-04-23 15:49:30 -07:00
Keavon Chambers fcf9396a71 Improve the Data panel's data display with monospaced text and copyable number values (#4040)
* Improve the Data panel's data display with monospaced text and copyable number values

* Revert attempted fix for dropdown menus appearing lower in scrolled Properties panel, since it makes other floating menus freeze the app

* Code review
2026-04-23 15:32:18 -07:00
Keavon Chambers e2117d9a02 Fix CI not attaching a "View deployment" button in PRs for build links 2026-04-23 02:29:20 -07:00
Keavon Chambers d3f36a95cf Rename 'Image Value' node to 'Image' and have its input value be an image not a raster table (#4037)
* Rename 'Image Value' node to 'Image' and have its input value be Image<Color> not Table<Raster<CPU>>

* Add a Properties panel widget labeling "width x height" for images in the Image node

* Add Image<Color> node registry entry for MonitorNode

* Code review
2026-04-22 16:00:03 -07:00
Keavon Chambers c2e1208d82 Add Path node differential edit summary widget, and store imported SVG content in that VectorModification struct (#4036)
* Make paste/import SVG store as the Path node's VectorModification not Table<Vector>

* Add a migration from Table<Vector> to VectorModification for existing documents

* Add a VectorModification widget to visualize change counts

* Refactor VectorModification to compute per-category counts for additions, removals, and modifications
2026-04-22 12:08:53 -07:00
Timon 6c5e3c97f8 Refactor persistence to combine document handling and workspace layout (#4031)
* Unify editor state persistence

* Review

* Fix

* Remove redundant DocumentDetails

* LoadDocumentContent indirection
2026-04-19 09:31:21 +00:00
Timon 2a2a60883d Desktop: Use the OS temp directory for CEF caches (#4030)
* Desktop: Use the OS temp dir

* Review
2026-04-15 10:47:45 +00:00
Keavon ChambersandTimon 60f16d72a5 Refactor IndexedDB document persistence to reuse data structures of desktop persistence (#4020)
* Switch indexedDb document serialized struct from camelCase to snake_case

* Refactor and migrate old indexedDb format to the same shape as desktop persistence

* Avoid duplicate struct definitions in the desktop crate

* Refactor frontend message handling to consolidate auto-save document loading

* Code review

* Review

---------

Co-authored-by: Timon <[email protected]>
2026-04-15 02:29:23 -07:00
YohYamasaki 79d778a535 Add support for setting the spread method for gradient fills (#3953)
* Add spread method support for gradients

* Add GradientSpreadMethod enum (Pad, Repeat, Reflect) to vector-types

* Add radio buttons to gradient tool and fill properties panel

* Convert spread method when importing SVGs via usvg

* Sync backup gradient input when changing spread method

* Table<GradientStops> rendering is not yet updated for spread method

* Sync gradient tool options with layer's gradient

* Sync gradient_type and spread_method from the selected
  layer's existing gradient to the tool options bar when
  switching to the gradient tool

* Refactor has_gradient_on_selected_layers
  to reuse a new get_gradient_on_selected_layer helper

* Swap Reflect and Repeat order in UI radio buttons

* Fix alignment of the radio buttons in right panel

* Fix the position of the radio buttons in the tool

* Rename SpreadMethod to SetSpreadMethod

* Move default spread method omission logic
2026-04-14 08:09:57 +00:00
Keavon Chambers da45ab2f87 Add a checkered background to transparent artboards and the infinite canvas (#4022)
* Add checkered transparency rendering to infinite canvas and artboards

* Enable artboard clipping by default

* Make new infinite canvas documents begin with a white background layer

* Remove the export dialog's transparency option now that it's redundant

* Make exporting transparent JPGs use white not black

* Code review
2026-04-10 03:21:21 -07:00
Timon 661e8bc569 Remove surface and window from ApplicationIo (#3941)
* Remove surface and window from ApplicationIo

* Seperate Wasm and Native ApplicationIo

* Fix warnings

* Fix tests

* Remove redundant PlatformApplicationIo::new_offscreen

* Fixup

* Remove unused From implementaitions for ApplicationIo
2026-04-09 20:12:53 +00:00
Keavon Chambers b100892bfa Add support for persistent storage of panel layouts, sizes, and active tabs (#4017)
* Add persistence to panel layouts

* Fix and persist the Window > Focus Document mode

* Add a Window > Reset Workspace action

* workspace_layout.json -> workspace_layout.ron

* Fix native app hole punch

* Cleanup review pass
2026-04-08 21:05:58 -07:00
Keavon Chambers b099e2faca Add support for interactive panel docking (#4015)
* Add interactive panel docking

* Preserve active tab when a panel group is docked

* Add inter-panel gutter hover color

* Code review fixes

* More code review
2026-04-08 06:09:20 -07:00
Keavon Chambers 39656d4c73 Refactor panel layouts to generalize recursive panel group subdivision splits (#4014)
* Generalize recursive panel group splits

* Code review
2026-04-08 00:44:58 -07:00
Timon 0eb440db14 Desktop: Improve Nix build times with more caching (#4007) 2026-04-08 01:46:38 +02:00
Timon 211111a01f Desktop: Fix document tab reorder not being persisted (#4002)
* Desktop: Fix reorder not beeing persisted

* Desktop: Use rfd fork to support starting_directory with zenity dialog backend
2026-04-08 01:13:30 +02:00
Keavon Chambers 1d0337285a Fix CSS regressions breaking the native app hole punch
Regressions introduced in e0212ca4b9
2026-04-04 14:33:41 -07:00
Keavon Chambers 848ff5fd52 Add support for dragging panel tabs docked into other panel tab bars (#4006)
* Add support for dragging panel tabs docked into other panel tab bars

* Fix terminology

* Add Group suffix to PanelGroupId enums variants

* Code review
2026-04-04 06:28:53 -07:00
Dennis Kobert 19aaeb374b Remove sample based image hashing to avoid false equalities (#3980)
* Remove sample based image hashing to avoid false equalities

This was originally introduced to improve the performance of working with
image data, but since the memo hash wrapper got introduced this should no
longer be really necessary.

* Fix todo comment
2026-04-04 11:46:08 +00:00
Timon bf269d7693 Introduce development Nix binary cache (#3911)
* Desktop: Introduce development Nix binary cache

* Configure caches in CI

* Cache nix shell

* Fix
2026-04-04 11:12:57 +00:00
Keavon Chambers a99b2806ff Update npm dependencies (#4004) 2026-04-04 00:19:08 -07:00
Keavon Chambers e0212ca4b9 Remove the svelte-preprocess dev dependency, keeping global styles with a custom Vite plugin (#4003)
* Remove the svelte-preprocess dev dependency, keeping global styles with a custom Vite plugin

* More robust style tag detection

* Fix CSS regressions
2026-04-03 23:53:46 -07:00
Keavon Chambers 55463fe0aa Refactor platform detection to use import.meta.env.MODE instead of isPlatformNative() 2026-04-03 21:26:27 -07:00
Keavon ChambersandTimon 4360359d60 Finalize and unify the design of the 'Morph' and 'Blend' nodes (#3974)
* Fix Morph node transform interpolation and preservation in the table

* Fix click target positions for Morph's nested layers by pre-compensating upstream_data transforms

* Redesign Morph node (v3) with control path input and uniformly spaced progression, and fix Stroke::lerp interpolation weights

* Add migration from Morph node v2 to v3

* Redesign the 'Blend Shapes' node behavior and subgraph definition

* Add the Layer > Blend menu entry to easily set up a blend

* Optimize the Morph node

* Refactor the Morph node to remove the roundtrip through BezPath

* Fine-tune Morph node Bezier order promotion and handle interpolation

* Add the Layer > Morph menu bar entry

* Fix NaN and guard against other potential NaN bugs breaking the editor

* Add InterpolationDistribution parameter to Morph with weighted progression, swap parameter orders, and rename shear to skew

* Add the Reverse parameter to the Morph node

* Update the order of the inputs to Blend Shapes for consistency with Morph

* Make Layer > Morph create the Morph Path control layer

* Fix migrations

* Move 10 to a constant

* Avoid division by 0 in the Blend Shapes node internals

* Rename nodes 'Blend' -> 'Mix' and 'Blend Shapes' to 'Blend'

* Fix a crash encountered while testing

* Final code review

* Make domain push dupe checks debug-only and use push_unchecked in the Morph node

* Pre-allocate for pushes to the vector domains

* Add fast path at t=0

* Inline reserve()

* Set up the control path layer above not below, and starting collapsed

* Review fixes

---------

Co-authored-by: Timon <[email protected]>
2026-04-03 20:45:58 -07:00
Keavon Chambers 7077e877f9 Allow double-clicking a gutter between panels to reset its sizing to default (#4000)
Support double-clicking to reset inter-panel gutter sizing
2026-04-03 14:43:25 -07:00
Keavon Chambers b52bf7b7d4 Add support for reordering document tabs (#3999)
* Add support for reordering document tabs

* Fix tab bar scrolling

* Close tab without activating it on pointerdown
2026-04-03 06:35:52 -07:00
Keavon Chambers 55115d89d5 Fix several cases of errors appearing in the console
One appeared on load (a deprecated meta tag). One appeared when adding an Identity (Passthrough) node. One appeared when exposing the the Weight parameter of the Stroke node. This also fixes the intended behavior of the bisect script, which was involved when finding the prevenance of these errors.
2026-04-03 03:20:04 -07:00
Keavon Chambers 5edb00bd9a Fix virtual scrolling MenuList font family dropdowns shrinking when wider content is unmounted (#3987)
* Fix virtual scrolling MenuList dropdowns shrinking when wider content goes away

* Code review fixes

* Fix small CI workflow bug

* Stop scrolling in dropdowns from horizontally scrolling the control bar

* Use more robust way of getting commit hash in CI workflow
2026-04-02 19:24:41 -07:00
Keavon Chambers ab822afae4 Implement window-controls-overlay PWA window frameless mode (#3986)
* Implement window-controls-overlay PWA window frameless mode

* Avoid warning
2026-04-02 18:17:36 -07:00
Keavon Chambers 1a06d3ea80 Improve PWA support with service worker-based offline caching (#3985)
* Implement the service worker for cached offline mode

* Improve pre-loaded font menu preview visualization

* Code review fixes

* Simplify Response construction

* Attempt to fix ERR_FAILED when reloading page on CF Pages

* Reject service worker install if any precache fetch fails
2026-04-02 18:14:40 -07:00
Keavon Chambers 87bd3d41df Make Alt+click on a handle in the Path tool split it from its colinear pair 2026-04-01 23:04:56 -07:00
Keavon Chambers 662691f32a New node: 'Offset Points' 2026-04-01 23:02:59 -07:00
Keavon Chambers 1543d974ac Fix 'Jitter Points' and 'Sample Polylines' working incorrectly with X or Y scale of 0 content (#3984)
* Fix NaN points produced by Sample Polylines on 0-scaled input

* Fix Jitter Points inverse transform for zero-scale axes and stop resetting stroke transform

* Remove a couple confusing Debug nodes

* Fix edge case

* Update demo art

* Fix order change in Jitter Points causing different results from earlier

* Fix bug in bisect tool

* Break out functionality into helper functions
2026-04-01 22:51:48 -07:00
Keavon Chambers 79bf1ab688 Fix preprocessor crash when document nodes have outdated input counts 2026-04-01 19:39:12 -07:00
Keavon Chambers 211b9113a1 Add the "Along Normals" parameter to the 'Jitter Points' node (#3983)
* Add the "Along Normals" parameter to the 'Jitter Points' node

* Fix the edge case of a self-loops
2026-04-01 05:18:56 -07:00
Keavon Chambers d41883a942 Add Layers panel support for displaying multiple groups with instances of the same children layers (#3982)
* Add Layers panel support for displaying multiple groups with instances of the same children layers

* Fix insert folder box drawing
2026-04-01 00:13:42 -07:00
Keavon Chambers 86e41a110a Make the node macro include doc comments when hovering a node's function (#3979) 2026-03-31 02:55:27 -07:00
Keavon Chambers 203910a92f Replace the vite-multiple-assets dev dependency with a small custom Vite plugin (#3976)
* Replace the vite-multiple-assets dev dependency with a small custom Vite plugin

* Restore exception
2026-03-29 03:36:31 -07:00
Keavon Chambers a3ea6ab0af Refactor transform decomposition API with skew support, add 'Decompose Skew' node, and fix stroke transform interpolation (#3973)
* Refactor transform decomposition API with skew support, add Decompose Skew node, and fix stroke transform interpolation

* Fix bug in master with skew changing Area node calculated value

* Code review simplification

* More code review fixes

* Rename cases where "shear" terminology was used in place of "skew"
2026-03-28 20:47:32 -07:00
Keavon Chambers e2a142333f Fix the Auto-Tangents node for linear polylines, and track colinear handles in manipulator data (#3972)
* Fix the Auto-Tangents node for linear polylines, and track colinear handles in manipulator data

* Simplify
2026-03-28 18:26:08 -07:00
Keavon Chambers 71ff4c937f Update 'Solidify Stroke' to preserve the original fill (#3971)
* Update 'Solidify Stroke' to preserve the original fill

* Efficiency improvements
2026-03-28 18:11:26 -07:00
Keavon Chambers 50a618ad12 New node: Path is Closed (#3970)
Add the 'Path is Closed' node
2026-03-28 17:37:50 -07:00
Keavon Chambers 6388a32ac5 Fix an assortment of small bugs (#3968)
* Fix an assertion failure bug when scaling a line in the transform cage

* Fix missing defaults on node gradient inputs

* Fix Blend Shapes path input wire not updating to show in the UI after Layer > Blend

* Fix assertion failure due to browser non-monotonic timestamp

* Fix SVG renderer drawing 1px strokes as half-width when using stroke alignment

* Fix incorrect appearance of the ColorInput widget when set to "none" and "disabled"

* Fix lerp function in Fill enum to handle None cases correctly

* Fix stroke alignment bug
2026-03-28 17:12:13 -07:00
Keavon Chambers 865e9713ad Refactor eval_pathseg_euclidean() to use kurbo's faster/more accurate inv_arclen() (#3969) 2026-03-28 16:30:26 -07:00
Keavon Chambers e529f74495 Fix click target metadata not propagating through intermediate wrapper table rows (#3967) 2026-03-28 15:39:27 -07:00
Vishnu TejasandTimon 36366b34f2 Desktop: Fix drag followed by a click causing a double click (#3721)
* Fix drag followed by a click causing a double click

* Review

* Fix quadruple click bug and cleanup

bug: quadruple bypassing time and distance check logic

* Improve readability

---------

Co-authored-by: Timon <[email protected]>
2026-03-24 00:21:02 +00:00
Keavon Chambers 11b7af61ef Fix image and SVG import transform bugs (#3942)
* Fix half-pixel offset on imported images

* Break out reused function

* Fix SVG/image open flow placing content with unnecessary Transform nodes

* Fix redundant Transform nodes when opening SVG/image files as documents

* Offset the parent to its destination position not the child objects

* Fix SVG/image File > Open artboard dimensions, origin, and clipping

* Fix the SVG to drag in at the mouse position relative to its visible center

* Fix importing images into offset artboards so they don't get offset as well

* Code review
2026-03-23 16:26:10 -07:00
Keavon Chambers a10092c10c Fix abysmal O(n^2) SVG import performance (#3938)
* Remove O(n^2) import by disabling bumping

* Add an import mode to avoid acyclic checks

* Rebuild the layer tree at the end, not after each step

* Incrementally update outward wires instead of repeatedly rebuilding them

* Add import->export direct connection guard

* Code review fixes

* Replace magic number offsets with consts

* Add consts for magic numbers

* Improve code structuring
2026-03-22 23:33:58 -07:00
548 changed files with 50593 additions and 19791 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/8ae15dc9c51a3855475d8cab1d0f29d9d9bc622c.tar.gz
c19abe4ac848f3c835e43dc065c59e20e60233ae023ea0a064c5fed442be2d3d
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
+8 -1
View File
@@ -1,4 +1,8 @@
[target.wasm32-unknown-unknown]
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native and the wasm target.
[target.'cfg(not(target_family = "wasm"))']
rustflags = ["--cfg=web_sys_unstable_apis"]
[target.'cfg(target_family = "wasm")']
rustflags = [
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
# The current simd implementation leads to undefined behavior
@@ -9,6 +13,9 @@ rustflags = [
"-C",
"link-arg=--max-memory=4294967296",
"--cfg=web_sys_unstable_apis",
# TODO: Remove this and find a better way to stay within the 25MB limit of cloudflare pages
"-C",
"opt-level=s",
]
[env]
+1 -1
View File
@@ -6,7 +6,7 @@
},
"ghcr.io/devcontainers/features/node:1": {}
},
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]00",
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]21",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
+98 -37
View File
@@ -20,9 +20,6 @@ on:
linux:
description: "Linux"
type: boolean
push_to_nix_cache:
description: "Linux: push to Nix cache"
type: boolean
debug:
description: "Debug build"
type: boolean
@@ -36,8 +33,6 @@ on:
type: boolean
linux:
type: boolean
push_to_nix_cache:
type: boolean
debug:
type: boolean
checkout_repo:
@@ -63,6 +58,8 @@ jobs:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
@@ -70,19 +67,11 @@ jobs:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: 🗑 Clear wasm-bindgen cache
run: rm -r ~/.cache/.wasm-pack || true
- name: 🟢 Install Node.js
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
- name: 🚧 Install build dependencies
run: |
cd frontend
npm run setup
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
@@ -92,6 +81,19 @@ jobs:
rustflags: ""
target: wasm32-unknown-unknown
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
run: |
if ! wasm-bindgen --version 2>/dev/null | grep -qF "$WASM_BINDGEN_CLI_VERSION"; then
cargo install -f "wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION"
fi
BINARYEN_DIR="$HOME/.cache/binaryen-version_$BINARYEN_VERSION"
if [ ! -x "$BINARYEN_DIR/bin/wasm-opt" ]; then
mkdir -p "$BINARYEN_DIR"
curl -sSfL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-x86_64-linux.tar.gz" | tar xz -C "$BINARYEN_DIR" --strip-components=1
fi
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
- name: 🔀 Choose production deployment environment and insert template
id: production-env
if: github.event_name == 'push'
@@ -124,11 +126,21 @@ jobs:
echo "No Cloudflare API token available (fork PR), skipping deploy."
exit 0
fi
if [ "${{ github.event_name }}" = "push" ]; then
DEPLOY_BRANCH="master"
else
DEPLOY_BRANCH="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
if [ "$DEPLOY_BRANCH" = "master" ] || [ -z "$DEPLOY_BRANCH" ]; then
DEPLOY_BRANCH="preview-${{ github.run_id }}"
fi
fi
MAX_ATTEMPTS=8
DELAY=15
for ATTEMPT in $(seq 1 $MAX_ATTEMPTS); do
echo "Attempt $ATTEMPT of $MAX_ATTEMPTS..."
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --branch="$DEPLOY_BRANCH" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
if [ ${PIPESTATUS[0]} -eq 0 ]; then
URL=$(grep -oP 'https://[^\s]+\.pages\.dev' /tmp/wrangler_output | head -1)
echo "url=$URL" >> "$GITHUB_OUTPUT"
@@ -158,22 +170,38 @@ jobs:
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
REF="latest-stable"
ENVIRONMENT="graphite-editor (Production)"
AUTO_INACTIVE="true"
TRANSIENT_ENVIRONMENT="false"
elif [ "${{ github.event_name }}" = "push" ]; then
REF="master"
ENVIRONMENT="graphite-dev (Production)"
AUTO_INACTIVE="true"
TRANSIENT_ENVIRONMENT="false"
else
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
ENVIRONMENT="graphite-dev (Preview)"
AUTO_INACTIVE="false"
TRANSIENT_ENVIRONMENT="true"
fi
DEPLOY_ID=$(gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
repos/${{ github.repository }}/deployments \
--input - \
--jq '.id' <<EOF
{"ref":"$REF","environment":"$ENVIRONMENT","auto_merge":false,"required_contexts":[]}
create_deployment() {
gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
repos/${{ github.repository }}/deployments \
--input - \
--jq '.id' <<EOF
{
"ref": "$1",
"environment": "$ENVIRONMENT",
"auto_merge": false,
"required_contexts": [],
"auto_inactive": $AUTO_INACTIVE,
"transient_environment": $TRANSIENT_ENVIRONMENT
}
EOF
)
}
# Try branch name first (needed for GitHub's PR "View deployment" button), fall back to commit SHA if the branch was deleted
DEPLOY_ID=$(create_deployment "$REF" 2>/dev/null) || DEPLOY_ID=$(create_deployment "$(git rev-parse HEAD)")
gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
@@ -193,9 +221,19 @@ jobs:
exit 0
fi
size_of() { find frontend/dist/assets "$@" -printf '%s\n' | awk '{s+=$1} END {printf "%.2f MB", s/1048576}'; }
WASM_SIZE=$(size_of -name '*.wasm')
JS_SIZE=$(size_of -name '*.js')
CSS_SIZE=$(size_of -name '*.css')
FONT_SIZE=$(size_of \( -name '*.woff2' -o -name '*.woff' -o -name '*.ttf' -o -name '*.otf' \))
IMAGE_SIZE=$(size_of \( -name '*.png' -o -name '*.jpg' -o -name '*.svg' \))
ALL_SIZE=$(size_of -type f)
COMMENT_BODY="| 📦 **Web Build Complete for** $(git rev-parse HEAD) |
|-|
| $CF_URL |"
| $CF_URL |
Wasm: **$WASM_SIZE** — JS: **$JS_SIZE** — CSS: **$CSS_SIZE** — Fonts: **$FONT_SIZE** — Images: **$IMAGE_SIZE** — All Assets: **$ALL_SIZE**"
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
# Push tag: skip commenting (commit was already commented on master merge)
@@ -262,7 +300,9 @@ jobs:
pull-requests: write
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -310,14 +350,16 @@ jobs:
winget install --id LLVM.LLVM -e --accept-package-agreements --accept-source-agreements
winget install --id Kitware.CMake -e --accept-package-agreements --accept-source-agreements
winget install --id OpenSSL.OpenSSL -e --accept-package-agreements --accept-source-agreements
winget install --id WebAssembly.Binaryen -e --accept-package-agreements --accept-source-agreements
winget install --id GnuWin32.PkgConfig -e --accept-package-agreements --accept-source-agreements
"OPENSSL_DIR=C:\Program Files\OpenSSL-Win64" | Out-File -FilePath $env:GITHUB_ENV -Append
"PKG_CONFIG_PATH=C:\Program Files\OpenSSL-Win64\lib\pkgconfig" | Out-File -FilePath $env:GITHUB_ENV -Append
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
curl.exe -sSfL -o "$env:RUNNER_TEMP\binaryen.tar.gz" "https://github.com/WebAssembly/binaryen/releases/download/version_$env:BINARYEN_VERSION/binaryen-version_$env:BINARYEN_VERSION-x86_64-windows.tar.gz"
tar -xzf "$env:RUNNER_TEMP\binaryen.tar.gz" -C $env:RUNNER_TEMP
"$env:RUNNER_TEMP\binaryen-version_$env:BINARYEN_VERSION\bin" | Out-File -FilePath $env:GITHUB_PATH -Append
cargo binstall --no-confirm --force "cargo-about@$env:CARGO_ABOUT_VERSION"
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
- name: 🏗 Build Windows bundle
@@ -453,7 +495,9 @@ jobs:
pull-requests: write
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -498,7 +542,6 @@ jobs:
brew install \
pkg-config \
openssl@3 \
binaryen \
llvm \
cargo-binstall
@@ -506,8 +549,14 @@ jobs:
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
echo "$(brew --prefix llvm)/bin" >> $GITHUB_PATH
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
BINARYEN_DIR="$HOME/.cache/binaryen-version_$BINARYEN_VERSION"
if [ ! -x "$BINARYEN_DIR/bin/wasm-opt" ]; then
mkdir -p "$BINARYEN_DIR"
curl -sSfL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-arm64-macos.tar.gz" | tar xz -C "$BINARYEN_DIR" --strip-components=1
fi
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
cargo binstall --no-confirm --force "cargo-about@${CARGO_ABOUT_VERSION}"
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
- name: 🏗 Build Mac bundle
@@ -639,23 +688,35 @@ jobs:
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🗑 Free disk space
run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache
- name: 📦 Build Nix package
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths --print-build-logs
- name: 📤 Push to Nix cache
if: (github.event_name == 'push' || inputs.push_to_nix_cache) && !inputs.debug
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
NIX_CACHE_AUTH_TOKEN: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && secrets.NIX_CACHE_AUTH_TOKEN || secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && 'graphite' || 'graphite-dev' }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
- name: 📤 Push Dependencies to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite${{ inputs.debug && '-dev' || '' }}.deps --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
- name: 🏗 Build Linux bundle
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }}-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
run: nix build .#graphite-bundle${{ inputs.debug && '-dev' || '' }}.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
- name: 📦 Upload Linux bundle
uses: actions/upload-artifact@v6
@@ -693,7 +754,7 @@ jobs:
- name: 🏗 Build Flatpak
run: |
nix build .#graphite${{ inputs.debug && '-dev' || '' }}-flatpak-manifest
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
rm -rf .flatpak
mkdir -p .flatpak
+2 -1
View File
@@ -57,7 +57,8 @@ jobs:
- name: 🧪 Run Rust tests
env:
RUSTFLAGS: -Dwarnings
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: mold -run cargo test --all-features
# Rust format check on GitHub runner
@@ -22,27 +22,14 @@ jobs:
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install Valgrind
run: |
sudo apt update
sudo apt install -y valgrind
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
# Cache on Cargo.lock file
cache-on-failure: true
- name: Cache iai-callgrind binary
id: cache-iai
uses: actions/cache@v5
with:
path: ~/.cargo/bin/iai-callgrind-runner
key: ${{ runner.os }}-iai-callgrind-runner-0.16.1
- name: Install iai-callgrind
if: steps.cache-iai.outputs.cache-hit != 'true'
run: cargo install [email protected]
- name: Install gungraun-runner and valgrind
uses: gungraun/setup-gungraun@v1
- name: Checkout master branch
run: |
@@ -66,21 +53,21 @@ jobs:
id: cache-benchmark-baselines
uses: actions/cache@v5
with:
path: target/iai
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
path: target/gungraun
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
restore-keys: |
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-
- name: Run baseline benchmarks
if: steps.cache-benchmark-baselines.outputs.cache-hit != 'true'
run: |
# Compile benchmarks
cargo bench --bench compile_demo_art_iai -- --save-baseline=master
cargo bench --bench compile_demo_art_gungraun -- --save-baseline=master
# Runtime benchmarks
cargo bench --bench update_executor_iai -- --save-baseline=master
cargo bench --bench run_once_iai -- --save-baseline=master
cargo bench --bench run_cached_iai -- --save-baseline=master
cargo bench --bench update_executor_gungraun -- --save-baseline=master
cargo bench --bench run_once_gungraun -- --save-baseline=master
cargo bench --bench run_cached_gungraun -- --save-baseline=master
- name: Checkout PR branch
run: git checkout ${{ github.event.pull_request.head.sha }}
@@ -88,12 +75,12 @@ jobs:
- name: Run PR benchmarks
run: |
# Compile benchmarks
cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
cargo bench --bench compile_demo_art_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
# Runtime benchmarks
cargo bench --bench update_executor_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
cargo bench --bench run_once_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
cargo bench --bench run_cached_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
cargo bench --bench update_executor_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
cargo bench --bench run_once_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
cargo bench --bench run_cached_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
- name: Make old comments collapsed by default
# Only run if we have write permissions (not a fork)
@@ -150,6 +137,7 @@ jobs:
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution'];
let hasSignificantChanges = false;
let hasRegressions = false;
let regressionDetails = [];
for (let i = 0; i < allOutputs.length; i++) {
@@ -166,19 +154,25 @@ jobs:
if (isSignificantChange(diffPct, absoluteChange, outputName)) {
hasSignificantChanges = true;
regressionDetails.push({
module_path: benchmark.module_path,
id: benchmark.id,
diffPct,
absoluteChange,
sectionTitle
});
// Only an increase in instruction count is a regression; improvements must not fail CI.
if (diffPct > 0) {
hasRegressions = true;
regressionDetails.push({
module_path: benchmark.module_path,
id: benchmark.id,
diffPct,
absoluteChange,
sectionTitle
});
}
}
}
}
}
core.setOutput('has-significant-changes', hasSignificantChanges);
core.setOutput('has-regressions', hasRegressions);
core.setOutput('regression-details', JSON.stringify(regressionDetails));
- name: Comment PR
@@ -332,7 +326,7 @@ jobs:
}
- name: Fail on significant regressions
if: steps.analyze.outputs.has-significant-changes == 'true'
if: steps.analyze.outputs.has-regressions == 'true'
uses: actions/github-script@v8
with:
script: |
+51
View File
@@ -0,0 +1,51 @@
name: "Nix Housekeeping"
on:
push:
branches:
- master
workflow_dispatch: {}
jobs:
cache-dev-shell:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
with:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🔎 Check whether development shell is already in binary cache
id: cache-check
run: |
out_path="$(nix eval --raw .#devShells.x86_64-linux.default.outPath)"
if nix path-info --store https://graphite-dev.cachix.org "$out_path" &>/dev/null; then
echo "cached=true" >> "$GITHUB_OUTPUT"
echo "Development shell is already cached at $out_path"
else
echo "cached=false" >> "$GITHUB_OUTPUT"
echo "Development shell is not cached"
fi
- name: 📦 Build Nix development shell
if: steps.cache-check.outputs.cached == 'false'
run: nix build .#devShells.x86_64-linux.default --no-link --print-out-paths
- name: 📤 Push Nix development shell to binary cache
if: steps.cache-check.outputs.cached == 'false'
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#devShells.x86_64-linux.default --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite-dev
+12 -3
View File
@@ -17,9 +17,10 @@ jobs:
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
- name: 💾 Set up Nix cache
uses: DeterminateSystems/magic-nix-cache-action@main
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
@@ -34,3 +35,11 @@ jobs:
raster_nodes_shaders_entrypoint.wgsl \
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
${{ secrets.ARTIFACTS_REPO_TOKEN }}
- name: 📤 Push shaders to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite-raster-nodes-shaders --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
+1
View File
@@ -12,3 +12,4 @@ flamegraph.svg
.idea/
.direnv
.DS_Store
.nvim.lua
+3 -7
View File
@@ -31,7 +31,6 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
cef = lib.call ./deps/cef.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
};
@@ -60,15 +59,12 @@ in
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-dev-bundle = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
graphite-dev-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-dev-bundle; };
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
tools = {
third-party-licenses = lib.call ./pkgs/tools/third-party-licenses.nix;
};
}
);
-27
View File
@@ -1,27 +0,0 @@
{ pkgs, ... }:
let
cefPath = pkgs.cef-binary.overrideAttrs (finalAttrs: {
postInstall = ''
rm -r $out/* $out/.* || true
strip ./Release/*.so*
mv ./Release/* $out/
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
});
in
{
env.CEF_PATH = cefPath;
}
+25 -2
View File
@@ -1,5 +1,28 @@
{ pkgs, inputs, ... }:
{
pkgs,
inputs,
...
}:
{
lib = inputs.crane.mkLib pkgs;
lib = (inputs.crane.mkLib pkgs) // {
vendorCargoDepsFlatten =
src:
pkgs.stdenvNoCC.mkDerivation (finalAttrs: {
name = "graphite-cargo-vendored";
inherit src;
installPhase = ''
cp -rL --no-preserve=mode "$src" "$out"
chmod -R u+w "$out"
find "$out" -type f -print0 | xargs -r -0 sed -i "s|$src|$out|g"
'';
disallowedReferences = [ finalAttrs.src ];
dontUnpack = true;
dontConfigure = true;
dontBuild = true;
});
};
}
+14 -17
View File
@@ -1,16 +1,15 @@
{ pkgs, ... }:
let
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
toolchain = pkgs.rust-bin.nightly."2025-06-23".default.override {
inherit extensions;
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
};
cargo = pkgs.writeShellScriptBin "cargo" ''
#!${pkgs.lib.getExe pkgs.bash}
@@ -32,14 +31,12 @@ let
}).buildRustPackage
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0-unstable-2025-08-04";
src = pkgs.fetchFromGitHub {
owner = "Firestar99";
repo = "rust-gpu-new";
rev = "c12f216121820580731440ee79ebc7403d6ea04f";
hash = "sha256-rG1cZvOV0vYb1dETOzzbJ0asYdE039UZImobXZfKIno=";
version = "0.10.0-alpha.1";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
};
cargoHash = "sha256-AEigcEc5wiBd3zLqWN/2HSbkfOVFneAqNvg9HsouZf4=";
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
+10 -10
View File
@@ -1,4 +1,10 @@
{ pkgs, deps, ... }:
{
pkgs,
deps,
self,
system,
...
}:
let
libs = [
@@ -22,10 +28,8 @@ pkgs.mkShell (
pkgs.lld
pkgs.nodejs
pkgs.nodePackages.npm
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-pack
pkgs.wasm-bindgen-cli_0_2_121
pkgs.cargo-about
pkgs.rustc
@@ -36,7 +40,6 @@ pkgs.mkShell (
pkgs.git
pkgs.cargo-watch
pkgs.cargo-nextest
pkgs.cargo-expand
@@ -52,13 +55,10 @@ pkgs.mkShell (
pkgs.graphviz
];
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}";
CEF_PATH = self.packages.${system}.graphite-cef;
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
shellHook = ''
alias cargo='mold --run cargo'
'';
}
// deps.cef.env
// deps.rustGPU.env
)
+2 -1
View File
@@ -1,5 +1,6 @@
{
pkgs,
deps,
self,
system,
...
@@ -33,7 +34,7 @@ let
cp -r ${graphite}/share out/share
mkdir -p out/lib/cef
mkdir -p ./cef
tar -xvf ${pkgs.cef-binary.src} -C ./cef --strip-components=1
tar -xvf ${self.packages.${system}.graphite-cef.src} -C ./cef --strip-components=1
cp -r ./cef/Release/* out/lib/cef/
cp -r ./cef/Resources/* out/lib/cef/
find "out/lib/cef/locales" -type f ! -name 'en-US*' -delete
+46
View File
@@ -0,0 +1,46 @@
{ pkgs, ... }:
let
version = "149.0.5+g6770623+chromium-149.0.7827.197";
hashes = {
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
};
selectSystem =
attrs:
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
src = pkgs.fetchurl {
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
hash = selectSystem hashes;
};
in
pkgs.cef-binary.overrideAttrs (finalAttrs: {
version = builtins.head (builtins.split "\\+" version);
inherit src;
postInstall = ''
rm -r $out/* $out/.* || true
strip ./Release/*.so*
mv ./Release/* $out/
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
})
+9 -9
View File
@@ -1,16 +1,16 @@
{ info, deps, ... }:
{
info,
deps,
self,
system,
...
}:
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
pname = "raster-nodes-shaders";
pname = "graphite-raster-nodes-shaders";
inherit (info) version src;
cargoVendorDir = deps.crane.lib.vendorMultipleCargoDeps {
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
};
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
strictDeps = true;
+78 -91
View File
@@ -14,125 +14,105 @@
let
branding = self.packages.${system}.graphite-branding;
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
resourcesCommon = {
pname = "${info.pname}-resources";
inherit (info) version src;
inherit cargoVendorDir;
strictDeps = true;
nativeBuildInputs = [
pkgs.pkg-config
pkgs.lld
pkgs.nodejs
pkgs.nodePackages.npm
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_100
pkgs.wasm-pack
pkgs.cargo-about
];
buildInputs = [ pkgs.openssl ];
env.CARGO_PROFILE = if dev then "dev" else "release";
cargoExtraArgs = "--target wasm32-unknown-unknown -p graphite-wasm-wrapper --no-default-features --features native";
doCheck = false;
};
resources = deps.crane.lib.buildPackage (
resourcesCommon
// {
cargoArtifacts = deps.crane.lib.buildDepsOnly resourcesCommon;
npmDeps = pkgs.importNpmLock {
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
npmConfigScript = "setup";
makeCacheWritable = true;
nativeBuildInputs = [
pkgs.importNpmLock.npmConfigHook
pkgs.removeReferencesTo
]
++ resourcesCommon.nativeBuildInputs;
prePatch = ''
mkdir branding
cp -r ${branding}/* branding
cp ${info.src}/.branding branding/.branding
'';
buildPhase = ''
export HOME="$TMPDIR"
pushd frontend
npm run native:build-${if dev then "dev" else "production"}
popd
'';
installPhase = ''
mkdir -p $out
cp -r frontend/dist/* $out/
'';
postFixup = ''
find "$out" -type f -exec remove-references-to -t "${cargoVendorDir}" '{}' +
'';
}
);
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.openssl
pkgs.libraw
# X11 Support
pkgs.libxkbcommon
pkgs.libXcursor
pkgs.libxcb
pkgs.libX11
];
common = {
inherit (info) pname version src;
inherit cargoVendorDir;
strictDeps = true;
cargoVendorDir = deps.crane.lib.vendorCargoDepsFlatten (
deps.crane.lib.vendorMultipleCargoDeps {
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
}
);
buildInputs = libs;
nativeBuildInputs = [
pkgs.pkg-config
pkgs.cargo-about
pkgs.removeReferencesTo
];
env = deps.cef.env // {
CARGO_PROFILE = if dev then "dev" else "release";
};
cargoExtraArgs = "-p graphite-desktop";
strictDeps = true;
doCheck = false;
};
cargoArtifacts = deps.crane.lib.buildDepsOnly (
common
// {
nativeBuildInputs = [
pkgs.pkg-config
pkgs.lld
];
env.CEF_PATH = self.packages.${system}.graphite-cef;
buildPhase =
let
profile = if dev then "dev" else "release";
in
''
cargo check --profile ${profile} --locked -p graphite-desktop-platform-linux
cargo build --profile ${profile} --locked -p graphite-desktop-platform-linux
cargo check --profile ${profile} --target wasm32-unknown-unknown --locked -p graphite-wasm-wrapper --no-default-features --features native
cargo build --profile ${profile} --target wasm32-unknown-unknown --locked -p graphite-wasm-wrapper --no-default-features --features native
cargo check --locked -p third-party-licenses --features desktop
cargo build --locked -p third-party-licenses --features desktop
cargo check --profile ${profile} --locked -p graphite-desktop-bundle
cargo build --profile ${profile} --locked -p graphite-desktop-bundle
'';
}
);
in
deps.crane.lib.buildPackage (
common
// {
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
inherit cargoArtifacts;
env = common.env // {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
EMBEDDED_RESOURCES = resources;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
};
buildInputs = libs;
nativeBuildInputs = [
pkgs.pkg-config
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_121
pkgs.cargo-about
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
];
npmDeps = pkgs.importNpmLock {
npmRoot = "${info.src}/frontend";
};
npmRoot = "frontend";
nativeBuildInputs = [
pkgs.importNpmLock.npmConfigHook
pkgs.nodePackages.npm
]
++ common.nativeBuildInputs;
makeCacheWritable = true;
env = {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
CEF_PATH = self.packages.${system}.graphite-cef;
};
postPatch = ''
mkdir branding
cp -r ${branding}/* branding
cp ${info.src}/.branding branding/.branding
'';
preBuild = ''
${lib.getExe self.packages.${system}.tools.third-party-licenses}
# Prevent `cargo-run`'s frontend setup from trying to update npm dependencies
touch -r frontend/package-lock.json -d '+1 year' frontend/node_modules/.install-timestamp
export HOME="$TMPDIR"
''
+ (
if self ? rev then
@@ -143,6 +123,10 @@ deps.crane.lib.buildPackage (
""
);
buildPhaseCargoCommand = "cargo run build desktop${if dev then " debug" else ""}";
doNotPostBuildInstallCargoBinaries = true;
installPhase = ''
mkdir -p $out/bin
cp target/${if dev then "debug" else "release"}/graphite $out/bin/graphite
@@ -161,12 +145,15 @@ deps.crane.lib.buildPackage (
'';
postFixup = ''
remove-references-to -t "${cargoVendorDir}" $out/bin/graphite
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
patchelf \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${deps.cef.env.CEF_PATH}" \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
--add-needed libGL.so \
--add-needed libEGL.so \
$out/bin/graphite
'';
passthru.deps = cargoArtifacts;
}
)
-31
View File
@@ -1,31 +0,0 @@
{
info,
deps,
pkgs,
...
}:
let
cargoVendorDir = deps.crane.lib.vendorCargoDeps { inherit (info) src; };
common = {
pname = "third-party-licenses";
inherit (info) version src;
inherit cargoVendorDir;
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [ pkgs.openssl ];
strictDeps = true;
env = deps.cef.env // {
CARGO_PROFILE = "dev";
};
cargoExtraArgs = "-p third-party-licenses --features desktop";
doCheck = false;
};
in
deps.crane.lib.buildPackage (
common
// {
inherit cargoVendorDir;
cargoArtifacts = deps.crane.lib.buildDepsOnly common;
meta.mainProgram = "third-party-licenses";
}
)
+2 -1
View File
@@ -70,5 +70,6 @@
"*.graphite": "json"
},
"editor.renderWhitespace": "boundary",
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+"
"editor.minimap.markSectionHeaderRegex": "// ===+\\n\\s*//\\s*(?<label>[^\\n]{1,18})[^\\n]*(\\n\\s*//[^\\n]*)*\\n\\s*// ===+",
"git.addAICoAuthor": "off"
}
Generated
+955 -1005
View File
File diff suppressed because it is too large. Load diff
+39 -19
View File
@@ -7,10 +7,14 @@ members = [
"desktop/platform/linux",
"desktop/platform/mac",
"desktop/platform/win",
"document/graph-storage",
"document/container",
"document/document-format",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"node-graph/libraries/graphene-hash",
"node-graph/libraries/*",
"node-graph/nodes/*",
"node-graph/nodes/raster/shaders",
@@ -23,6 +27,7 @@ members = [
"node-graph/preprocessor",
"proc-macros",
"tools/cargo-run",
"tools/cargo-run/internal/*",
"tools/crate-hierarchy-viz",
"tools/third-party-licenses",
"tools/editor-message-tree",
@@ -63,9 +68,11 @@ dyn-any = { path = "libraries/dyn-any", features = [
"log-bad-types",
"rc",
] }
graphene-hash = { path = "node-graph/libraries/graphene-hash", features = ["derive"] }
preprocessor = { path = "node-graph/preprocessor" }
math-parser = { path = "libraries/math-parser" }
graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
core-types = { path = "node-graph/libraries/core-types" }
no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
@@ -83,18 +90,24 @@ repeat-nodes = { path = "node-graph/nodes/repeat" }
math-nodes = { path = "node-graph/nodes/math" }
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
graph-craft = { path = "node-graph/graph-craft" }
graph-storage = { path = "document/graph-storage", default-features = false }
document-format = { path = "document/document-format" }
document-container = { path = "document/container" }
raster-nodes = { path = "node-graph/nodes/raster" }
graphene-std = { path = "node-graph/nodes/gstd" }
interpreted-executor = { path = "node-graph/interpreted-executor" }
node-macro = { path = "node-graph/node-macro" }
wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
# Workspace dependencies
rustc-hash = "2.0"
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
rmp-serde = "1.3"
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -104,6 +117,9 @@ log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "0.2"
convert_case = "0.8"
titlecase = "3.6"
fancy-regex = "0.18.0"
unicode-segmentation = "1.13.2"
indoc = "2.0.5"
derivative = "2.2"
thiserror = "2"
@@ -113,17 +129,17 @@ quote = "1.0"
chrono = "0.4"
ron = "0.12"
fastnoise-lite = "1.1"
wgpu = { version = "27.0", features = [
wgpu = { version = "29.0", features = [
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
"fragile-send-sync-non-atomic-wasm",
"spirv",
"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.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.77"
web-sys = { version = "=0.3.77", features = [
js-sys = "=0.3.98"
web-sys = { version = "=0.3.98", features = [
"Document",
"DomRect",
"Element",
@@ -147,22 +163,25 @@ 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.7"
vello_encoding = "0.7"
vello = "0.9"
vello_encoding = "0.9"
resvg = "0.47"
usvg = "0.47"
parley = "0.6"
skrifa = "0.40"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.29", default-features = false, features = [
glam = { version = "0.32.1", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
] }
base64 = "0.22"
blake3 = "1.5"
mmap-io = { version = "0.9", features = ["hugepages"] }
image = { version = "0.25", default-features = false, features = [
"png",
"jpeg",
@@ -191,26 +210,27 @@ petgraph = { version = "0.7", default-features = false, features = ["graphmap"]
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.7", features = ["html_reports"] }
iai-callgrind = { version = "0.16" }
gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "142"
cef-dll-sys = "142"
cef = "149"
cef-dll-sys = "149"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.15"
rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
spirv-std = { git = "https://github.com/Firestar99/rust-gpu-new", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
cargo-gpu = { git = "https://github.com/Firestar99/cargo-gpu", rev = "3952a22d16edbd38689f3a876e417899f21e1fe7", default-features = false }
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
linesweeper = "0.3"
linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
@@ -236,6 +256,6 @@ 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" }
download-cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
vello = { git = "https://github.com/Keavon/vello.git", branch = "0.7.0-fix-images-rendering-blurry" }
vello_encoding = { git = "https://github.com/Keavon/vello.git", branch = "0.7.0-fix-images-rendering-blurry" }
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" }
+1
View File
@@ -1,4 +1,5 @@
accepted = [
"0BSD", # Keep this list in sync with those in `/deny.toml`
"Apache-2.0 WITH LLVM-exception", # Keep this list in sync with those in `/deny.toml`
"Apache-2.0", # Keep this list in sync with those in `/deny.toml`
"BSD-2-Clause", # Keep this list in sync with those in `/deny.toml`
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[10316247453530667000,{"inputs":[{"Node":{"node_id":9079109751490757000,"output_index":0}},{"Node":{"node_id":1250460246919467000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":false,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7954638344846060000,{"inputs":[{"Node":{"node_id":5991296268862790000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.1875,"green":0.0,"blue":0.0,"alpha":0.203125}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.19140625,"green":0.0,"blue":0.0,"alpha":0.203125}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[17021405646895729000,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientTable":{"element":[{"position":[0.0,0.5,1.0],"midpoint":[0.5,0.5,0.5],"color":[{"red":1.0,"green":0.31764707,"blue":0.15686275,"alpha":1.0},{"red":1.0,"green":0.5686275,"blue":0.25490198,"alpha":1.0},{"red":1.0,"green":0.7294118,"blue":0.16078432,"alpha":1.0}]}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::GradientValueNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[8366826746721323000,{"inputs":[{"Node":{"node_id":5591755359500854000,"output_index":0}},{"Node":{"node_id":13846904447064916285,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3Line 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":{"Fill":{"Solid":{"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":{"FillGradient":{"stops":{"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}]},"gradient_type":"Linear","start":[9.606221358397944,-69.72678572415595],"end":[9.606221358397944,-162.2641409381776],"spread_method":"Pad","absolute":true,"transform":[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":""}}],[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,"context_features":{"extract":"","inject":""}}],[1789832635968548900,{"inputs":[{"NLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[10507084483235320484,{"inputs":[{"Node":{"node_id":9157963288496356916,"output_index":0}},{"Node":{"node_id":1396768435017101055,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4741515246389989284,{"inputs":[{"Node":{"node_id":14255588039347536657,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[4105329493214975815,{"inputs":[{"Node":{"node_id":12931264630175648107,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.24355652969916,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::conteLine 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::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
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientTable":{"element":[{"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},{"red":0.23828125,"green":0.0,"blue":0.08377075,"alpha":1.0},{"red":0.92578125,"green":0.8676921,"blue":0.5569153,"alpha":1.0},{"red":0.17333984,"green":0.625,"blue":0.625,"alpha":1.0},{"red":0.106292725,"green":0.3359375,"blue":0.3359375,"alpha":1.0}]}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","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>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"Graphic":{"element":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc:Line 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":{"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
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[13353438235848911576,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[6379137305818664393,18442321214082298093,18118267825025549699,6351696498298648253,17863574903157697896,4691860614575868200,301778328144628917,10625296323957562985,533731991408535384,13357220652574593654,15992617814592812350],"remove":[],"delta":[[18442321214082298093,[565.6296296296297,122.96296296296298]],[13357220652574593654,[574.2222222222222,108.44444444444449]],[6351696498298648253,[646.8148148148149,0.0]],[6379137305818664393,[625.4814814814813,0.0]],[17863574903157697896,[606.8148151308641,95.19407372365433]],[18118267825025549699,[642.0740740740741,0.0]],[10625296323957562985,[473.4814814814815,272.5925925925926]],[533731991408535384,[501.6296296296296,175.40740740740742]],[4691860614575868200,[528.2962962962963,283.8518518518518]],[15992617814592812350,[621.0370370370368,0.0]],[301778328144628917,[493.5149940383244,200.29629629629628]]]},"segments":{"add":[13662059715350867364,3384102572540409881,12035095010819582754,10146665273368938971,318560030360358929,8462655819889292900,3303411878775644985,8661113083384527971,2035327810332855521,11346538709718766144,3710133387837274291],"remove":[],"start_point":[[3303411878775644985,301778328144628917],[13662059715350867364,6379137305818664393],[318560030360358929,17863574903157697896],[3384102572540409881,18442321214082298093],[12035095010819582754,18118267825025549699],[10146665273368938971,6351696498298648253],[11346538709718766144,13357220652574593654],[8462655819889292900,4691860614575868200],[8661113083384527971,10625296323957562985],[3710133387837274291,15992617814592812350],[2035327810332855521,533731991408535384]],"end_point":[[2035327810332855521,13357220652574593654],[12035095010819582754,6351696498298648253],[10146665273368938971,17863574903157697896],[318560030360358929,4691860614575868200],[11346538709718766144,15992617814592812350],[3303411878775644985,10625296323957562985],[3710133387837274291,6379137305818664393],[8462655819889292900,301778328144628917],[13662059715350867364,18442321214082298093],[8661113083384527971,533731991408535384],[3384102572540409881,18118267825025549699]],"handle_primary":[[8661113083384527971,[0.2962962962963047,0.2962962962963047]],[3710133387837274291,[0.0,0.0]],[10146665273368938971,[0.0,0.0]],[3303411878775644985,[0.0,0.0]],[13662059715350867364,[0.0,0.0]],[12035095010819582754,[0.0,0.0]],[11346538709718766144,[9.925839724176626,-9.951533978271286]],[8462655819889292900,[0.0,0.0]],[2035327810332855521,[42.96296296296293,-41.7777777777778]],[3384102572540409881,[0.0,0.0]],[318560030360358929,[-46.95465552079859,46.40007297527743]]],"handle_end":[[3384102572540409881,[0.5807410754567854,77.36888852918523]],[13662059715350867364,[68.68148181185177,-54.8859262904691]],[3710133387837274291,[0.0,0.0]],[11346538709718766144,[1.1377781018271662,63.71555518874077]],[8661113083384527971,[-42.34888386913234,41.180638796880466]],[2035327810332855521,[-8.299214014278164,8.32069754812484]],[12035095010819582754,[0.0,0.0]],[318560030360358929,[-97.48148148148152,-81.18518518518522]],[10146665273368938971,[48.16592595101224,-47.597037061827145]],[3303411878775644985,[-6.2222222222222285,-40.59259259259261]],[8462655819889292900,[-21.74426522093495,47.99999999999997]]],"stroke":[[3303411878775644985,0],[8661113083384527971,0],[12035095010819582754,0],[2035327810332855521,0],[3710133387837274291,0],[8462655819889292900,0],[3384102572540409881,0],[318560030360358929,0],[11346538709718766144,0],[10146665273368938971,0],[13662059715350867364,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[[{"ty":"End","segment":8661113083384527971},{"ty":"Primary","segment":2035327810332855521}],[{"ty":"End","segment":10146665273368938971},{"ty":"Primary","segment":318560030360358929}],[{"ty":"Primary","segment":11346538709718766144},{"ty":"End","segment":2035327810332855521}],[{"ty":"End","segment":12035095010819582754},{"ty":"Primary","segment":10146665273368938971}]],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine 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":{"Fill":{"Solid":{"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":{"FillGradient":{"stops":{"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}]},"gradient_type":"Linear","start":[-10.0,0.0],"end":[10.0,0.0],"spread_method":"Pad","absolute":true,"transform":[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":""}}],[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::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[17154757625902243313,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.23529412,"green":0.23529412,"blue":0.24313726,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":1670.79570439},"exposed":false}},{"Value":{"tagged_value":{"F64":24.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[11731553664207576737,{"inputs":[{"Node":{"node_id":757876048866560520,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::JitterPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[14158287945315818946,{"inputs":[{"Node":{"node_id":16943732999059587742,"output_index":0}},{"Node":{"node_id":14577956936089455769,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.6181095265062186,3.496297826945966]},"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>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"math_nodes::ToU32Node"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[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>>","alias":null}},"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":{"element":[{"red":0.99607843,"green":0.827451,"blue":0.65882355,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_valueLine truncated
{"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":{"FillGradient":{"stops":{"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}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"spread_method":"Pad","absolute":true,"transform":[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,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::contLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[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":4,"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::SourceNodeIdNode"}},"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>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[3,[45.77777777777777,145.33333333333331]],[18,[145.77777777777777,-97.7777777777778]],[9,[156.4444444444444,97.33333333333331]],[21,[76.0,-202.22222222222223]],[28,[39.111111111111086,-58.22222222222226]],[23,[19.555555555555543,-139.55555555555557]],[6,[123.99999999999994,148.4444444444444]],[30,[-9.333333333333371,0.0]],[16,[159.5555555555555,-75.55555555555557]],[29,[-32.888888888888914,-14.666666666666686]],[20,[128.4444444444444,-142.22222222222223]],[13,[153.77777777777777,-1.3333333333333712]],[27,[-11.111111111111144,-72.00000000000003]],[4,[18.66666666666663,157.77777777777771]],[25,[0.8888888888888573,-94.66666666666669]],[11,[136.88888888888886,39.111111111111086]],[8,[252.4444444444444,124.88888888888886]],[32,[9.333333333333314,38.66666666666663]],[17,[123.99999999999994,-84.00000000000003]],[15,[111.11111111111114,-60.888888888888914]],[5,[66.22222222222223,152.88888888888886]],[33,[-78.22222222222223,75.55555555555554]],[24,[57.77777777777777,-129.33333333333334]],[19,[90.66666666666664,-129.33333333333334]],[12,[199.5555555555555,10.666666666666629]],[31,[-53.33333333333337,13.777777777777771]],[34,[-5.333333333333371,99.11111111111109]],[10,[216.4444444444444,72.4444444444444]],[14,[183.11111111111103,-19.111111111111143]],[26,[22.66666666666663,-81.33333333333337]],[7,[229.33333333333331,152.4444444444444]],[2,[-67.55555555555554,158.22222222222217]],[22,[71.11111111111109,-201.7777777777778]],[1,[-103.55555555555554,126.66666666666664]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"start_point":[[1,1],[14,14],[8,8],[33,33],[30,30],[9,9],[1Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"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}]},"gradient_type":"Radial","start":[-0.22577926355610423,34.981204988590605],"end":[-0.11953019835323353,66.53737705977504],"spread_method":"Pad","absolute":true,"transform":[0.0033669629737862325,-0.9999943317641021,0.9999943317641021,0.0033669629737862325,-35.2060257800042,34.63764658282962]}}},"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":{"FillGradient":{"stops":{"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}]},"gradient_type":"Radial","start":[-0.22577926355610423,34.981204988590605],"end":[-0.11953019835323353,66.53737705977504],"spread_method":"Pad","absolute":true,"transform":[0.0033669629737862325,-0.9999943317641021,0.9999943317641021,0.0033669629737862325,-35.2060257800042,34.63764658282962]}},"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,2Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[10127467043900015225,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[1,[258.00000000000006,994.6666666666664]],[2,[644.0,726.6666666666666]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-328.66666666666674,129.33333333333337]]],"stroke":[[1,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graphene_core::table::Table<graphene_core::vector::vector_types::Vector>","alias":null}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":"graphene_core::vector::vector_modification::VectorModification","alias":null}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[15961046538654083626,{"inputs":[{"Node":{"node_id":1889157037801767612,"output_index":0}},{"Node":{"node_id":4332145463108161926,"output_index":0}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":10.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"core_types::vector::CopyToPointsNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[17378885078543074499,{"inputs":[{"Value":{"tagged_value":{"Vector":{"element":[{"style":{"stroke":{"color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},"weight":0.0,"dash_lengths":[],"dash_offset":0.0,"cap":"Butt","join":"Miter","join_miter_limit":4.0,"align":"Center","transform":[1.0,0.0,0.0,1.0,0.0,0.0],"non_scaling":false,"paint_order":"StrokeAbove"},"fill":"None"},"colinear_manipulators":[],"point_domain":{"id":[],"position":[]},"segment_domain":{"id":[],"start_point":[],"end_point":[],"handles":[],"stroke":[]},"region_domain":{"id":[],"segment_range":[],"fill":[]},"upstream_data":null}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8],"remove":[],"delta":[[5,[740.4444444444443,857.1111111111111]],[3,[707.5,1026.5]],[7,[727.5555555555554,1026.6666666666663]],[2,[745.5,826.0]],[1,[823.2222222222221,660.4444444444445]],[6,[725.7777777777779,1026.370370370371]],[4,[709.5555555555554,1026.6666666666667]],[8,[746.0000000000001,842.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8],"remove":[],"start_point":[[5,5],[2,2],[6,6],[8,8],[3,3],[4,4],[1,1],[7,7]],"end_point":[[6,7],[8,1],[2,3],[5,6],[1,2],[3,4],[4,5],[7,8]],"handle_primary":[[6,[0.0,0.0]],[8,[17.33333333333337,-84.99999999999989]],[3,[0.0,0.0]],[7,[0.0,0.0]],[5,[0.0,0.0]],[1,[0.0,0.0]],[4,[0.0,0.0]],[2,[-24.5,85.0]]],"handle_end":[[7,[-26.8034437596026,131.4399645903585]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[-23.11111111111109,Line truncated
{"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":{"Fill":{"Solid":{"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":{"FillGradient":{"stops":{"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}]},"gradient_type":"Linear","start":[604.9565968314213,108.54930650815423],"end":[607.1269623532997,108.54930650815423],"spread_method":"Pad","absolute":true,"transform":[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":""}}],[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":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_indLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[202,{"inputs":[{"Node":{"node_id":206,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Solid":{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.5058824,"green":0.26666668,"blue":0.20392157,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]},"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5]}},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[404,{"inputs":[{"Node":{"node_id":402,"output_index":0}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.24313726,"green":0.18431373,"blue":0.19215687,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"StrokeAlign":"Center"},"exposed":false}},{"Value":{"tagged_value":{"StrokeCap":"Butt"},"exposed":false}},{"Value":{"tagged_value":{"StrokeJoin":"Miter"},"exposed":false}},{"Value":{"tagged_value":{"F64":4.0},"exposed":false}},{"Value":{"tagged_value":{"PaintOrder":"StrokeAbove"},"exposed":false}},{"Value":{"tagged_value":{"VecF64":[]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::StrokeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[93,{"inputs":[{"Node":{"node_id":94,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[851.1666666666667,668.5377104806669]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[39.677869315599935,39.67786931560005]},"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>>","alias":null}},"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","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>","alias":null}},"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":""}}],[155,{"inputs":[{"Node":{"node_id":159,"output_index":0}},{"Value":{"tagged_value":{"Fill":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0},{"red":0.6431373,"green":0.31764707,"blue":0.21176471,"alpha":1.0}]},"gradient_type":"Linear","start":[0.9001916129448388,0.7881778212017586],"end":[0.8902470335613286,0.6662432828529555]}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"element":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],"transform":[[1.0,0.0,0.0,1.0,0.0,0.0]],"alpha_blending":[{"blend_mode":"Normal","opacity":1.0,"fill":1.0,"clip":false}],"source_node_id":[null]}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.7529412,"green":0.34117648,"blue":0.2,"alpha":1.0},{"red":0.6431373,"greeLine 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::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
+2 -1
View File
@@ -42,7 +42,7 @@ ignore = [
"RUSTSEC-2024-0388", # Unmaintained `derivative`, used directly by graphite-editor and graphite-desktop
"RUSTSEC-2024-0436", # Unmaintained `paste`, pulled in by dependencies `metal` and `wgpu-hal`
"RUSTSEC-2025-0134", # Unmaintained `rustls-pemfile`, pulled in by build dependency `download-cef`
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `iai-callgrind`
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `gungraun`
]
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
# lower than the range specified will be ignored. Note that ignored advisories
@@ -63,6 +63,7 @@ ignore = [
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
#
allow = [
"0BSD", # Keep this list in sync with those in `/about.toml`
"Apache-2.0 WITH LLVM-exception", # Keep this list in sync with those in `/about.toml`
"Apache-2.0", # Keep this list in sync with those in `/about.toml`
"BSD-2-Clause", # Keep this list in sync with those in `/about.toml`
+2 -1
View File
@@ -48,13 +48,14 @@ lzma-rust2 = { workspace = true }
serde = { 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]
windows = { version = "0.58.0", features = [
windows = { version = "0.62.2", features = [
"Win32_Foundation",
"Win32_Graphics_Dwm",
"Win32_Graphics_Gdi",
+95 -2
View File
@@ -13,6 +13,9 @@ const EXEC_PATH: &str = "Contents/MacOS";
const FRAMEWORKS_PATH: &str = "Contents/Frameworks";
const RESOURCES_PATH: &str = "Contents/Resources";
const CEF_FRAMEWORK: &str = "Chromium Embedded Framework.framework";
const GRAPHITE_DOCUMENT_TYPE: &str = "art.graphite.document";
const GRAPHITE_FILE_EXTENSION: &str = "graphite";
const GRAPHITE_MIME_TYPE: &str = "application/graphite+json";
pub fn main() -> Result<(), Box<dyn Error>> {
let app_bin = build_bin("graphite-desktop-platform-mac", None)?;
@@ -73,7 +76,7 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
cf_bundle_identifier: id.to_string(),
cf_bundle_display_name: exec_name.to_string(),
cf_bundle_executable: exec_name.to_string(),
cf_bundle_icon_file: ICONS_FILE_NAME.to_string(),
cf_bundle_icon_file: if is_helper { None } else { Some(ICONS_FILE_NAME.to_string()) },
cf_bundle_info_dictionary_version: "6.0".to_string(),
cf_bundle_package_type: "APPL".to_string(),
cf_bundle_signature: "????".to_string(),
@@ -85,6 +88,8 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
ls_minimum_system_version: "11.0".to_string(),
ls_ui_element: if is_helper { Some("1".to_string()) } else { None },
ns_supports_automatic_graphics_switching: true,
cf_bundle_document_types: (!is_helper).then(document_types),
ut_exported_type_declarations: (!is_helper).then(exported_type_declarations),
};
let plist_file = dir.join("Info.plist");
@@ -92,6 +97,47 @@ fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) ->
Ok(())
}
fn document_types() -> Vec<DocumentType> {
vec![
DocumentType {
cf_bundle_type_name: "Graphite Document".to_string(),
cf_bundle_type_role: "Editor".to_string(),
cf_bundle_type_extensions: Some(vec![GRAPHITE_FILE_EXTENSION.to_string()]),
cf_bundle_type_icon_file: Some(ICONS_FILE_NAME.to_string()),
ls_handler_rank: Some("Owner".to_string()),
ls_item_content_types: vec![GRAPHITE_DOCUMENT_TYPE.to_string()],
},
DocumentType {
cf_bundle_type_name: "SVG Image".to_string(),
cf_bundle_type_role: "Editor".to_string(),
cf_bundle_type_extensions: Some(vec!["svg".to_string()]),
cf_bundle_type_icon_file: None,
ls_handler_rank: Some("Alternate".to_string()),
ls_item_content_types: vec!["public.svg-image".to_string()],
},
DocumentType {
cf_bundle_type_name: "Image".to_string(),
cf_bundle_type_role: "Editor".to_string(),
cf_bundle_type_extensions: None,
cf_bundle_type_icon_file: None,
ls_handler_rank: Some("Alternate".to_string()),
ls_item_content_types: vec!["public.image".to_string()],
},
]
}
fn exported_type_declarations() -> Vec<ExportedTypeDeclaration> {
vec![ExportedTypeDeclaration {
ut_type_identifier: GRAPHITE_DOCUMENT_TYPE.to_string(),
ut_type_description: "Graphite Document".to_string(),
ut_type_conforms_to: vec!["public.json".to_string()],
ut_type_tag_specification: TypeTagSpecification {
public_filename_extension: vec![GRAPHITE_FILE_EXTENSION.to_string()],
public_mime_type: GRAPHITE_MIME_TYPE.to_string(),
},
}]
}
#[derive(serde::Serialize)]
struct InfoPlist {
#[serde(rename = "CFBundleName")]
@@ -103,7 +149,8 @@ struct InfoPlist {
#[serde(rename = "CFBundleExecutable")]
cf_bundle_executable: String,
#[serde(rename = "CFBundleIconFile")]
cf_bundle_icon_file: String,
#[serde(skip_serializing_if = "Option::is_none")]
cf_bundle_icon_file: Option<String>,
#[serde(rename = "CFBundleInfoDictionaryVersion")]
cf_bundle_info_dictionary_version: String,
#[serde(rename = "CFBundlePackageType")]
@@ -123,7 +170,53 @@ struct InfoPlist {
#[serde(rename = "LSMinimumSystemVersion")]
ls_minimum_system_version: String,
#[serde(rename = "LSUIElement")]
#[serde(skip_serializing_if = "Option::is_none")]
ls_ui_element: Option<String>,
#[serde(rename = "NSSupportsAutomaticGraphicsSwitching")]
ns_supports_automatic_graphics_switching: bool,
#[serde(rename = "CFBundleDocumentTypes")]
#[serde(skip_serializing_if = "Option::is_none")]
cf_bundle_document_types: Option<Vec<DocumentType>>,
#[serde(rename = "UTExportedTypeDeclarations")]
#[serde(skip_serializing_if = "Option::is_none")]
ut_exported_type_declarations: Option<Vec<ExportedTypeDeclaration>>,
}
#[derive(serde::Serialize)]
struct DocumentType {
#[serde(rename = "CFBundleTypeName")]
cf_bundle_type_name: String,
#[serde(rename = "CFBundleTypeRole")]
cf_bundle_type_role: String,
#[serde(rename = "CFBundleTypeExtensions")]
#[serde(skip_serializing_if = "Option::is_none")]
cf_bundle_type_extensions: Option<Vec<String>>,
#[serde(rename = "CFBundleTypeIconFile")]
#[serde(skip_serializing_if = "Option::is_none")]
cf_bundle_type_icon_file: Option<String>,
#[serde(rename = "LSHandlerRank")]
#[serde(skip_serializing_if = "Option::is_none")]
ls_handler_rank: Option<String>,
#[serde(rename = "LSItemContentTypes")]
ls_item_content_types: Vec<String>,
}
#[derive(serde::Serialize)]
struct ExportedTypeDeclaration {
#[serde(rename = "UTTypeIdentifier")]
ut_type_identifier: String,
#[serde(rename = "UTTypeDescription")]
ut_type_description: String,
#[serde(rename = "UTTypeConformsTo")]
ut_type_conforms_to: Vec<String>,
#[serde(rename = "UTTypeTagSpecification")]
ut_type_tag_specification: TypeTagSpecification,
}
#[derive(serde::Serialize)]
struct TypeTagSpecification {
#[serde(rename = "public.filename-extension")]
public_filename_extension: Vec<String>,
#[serde(rename = "public.mime-type")]
public_mime_type: String,
}
+99 -90
View File
@@ -2,6 +2,7 @@ use rand::Rng;
use rfd::AsyncFileDialog;
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, SyncSender};
@@ -14,15 +15,15 @@ use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;
use crate::cef;
use crate::cli::Cli;
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::persist::PersistentData;
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -32,6 +33,7 @@ pub(crate) struct App {
window_size: PhysicalSize<u32>,
window_maximized: bool,
window_fullscreen: bool,
window_pending_drag: bool,
pointer_position: PhysicalPosition<f64>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
ui_scale: f64,
@@ -45,10 +47,8 @@ pub(crate) struct App {
start_render_sender: SyncSender<()>,
web_communication_initialized: bool,
web_communication_startup_buffer: Vec<Vec<u8>>,
persistent_data: PersistentData,
#[cfg_attr(not(target_os = "macos"), expect(unused))]
preferences: Preferences,
cli: Cli,
launch_documents: Option<Vec<PathBuf>>,
startup_time: Option<Instant>,
exiting: Arc<AtomicBool>,
exit_reason: ExitReason,
@@ -59,6 +59,7 @@ impl App {
Window::init();
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
cef_context: Box<dyn cef::CefContext>,
cef_view_info_sender: Sender<cef::ViewInfoUpdate>,
@@ -66,7 +67,7 @@ impl App {
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
preferences: Preferences,
cli: Cli,
launch_documents: Vec<PathBuf>,
) -> Self {
let ctrlc_app_event_scheduler = app_event_scheduler.clone();
ctrlc::set_handler(move || {
@@ -92,10 +93,14 @@ impl App {
}
});
let mut persistent_data = PersistentData::default();
persistent_data.load_from_disk();
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
// Wake the winit event loop when an editor future completes.
let wake_scheduler = app_event_scheduler.clone();
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), wgpu_context.clone(), wake);
Self {
render_state: None,
@@ -105,6 +110,7 @@ impl App {
window_size: PhysicalSize { width: 0, height: 0 },
window_maximized: false,
window_fullscreen: false,
window_pending_drag: false,
pointer_position: Default::default(),
pointer_lock_position: Default::default(),
ui_scale: 1.,
@@ -118,9 +124,8 @@ impl App {
start_render_sender,
web_communication_initialized: false,
web_communication_startup_buffer: Vec::new(),
persistent_data,
preferences,
cli,
launch_documents: Some(launch_documents),
startup_time: None,
exiting,
exit_reason: ExitReason::Shutdown,
@@ -202,7 +207,7 @@ impl App {
};
self.send_or_queue_web_message(bytes);
}
DesktopFrontendMessage::OpenFileDialog { title, filters, context } => {
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
let app_event_scheduler = self.app_event_scheduler.clone();
let _ = thread::spawn(move || {
let mut dialog = AsyncFileDialog::new().set_title(title);
@@ -210,13 +215,21 @@ impl App {
dialog = dialog.add_filter(filter.name, &filter.extensions);
}
let show_dialog = async move { dialog.pick_file().await.map(|f| f.path().to_path_buf()) };
let handles = if multiple {
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
} else {
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
};
if let Some(path) = futures::executor::block_on(show_dialog)
&& let Ok(content) = fs::read(&path)
{
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
for handle in handles {
let path = handle.path().to_path_buf();
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
}
}
});
}
@@ -267,8 +280,8 @@ impl App {
let viewport_offset_y = y / window_size.height as f64;
render_state.set_viewport_offset([viewport_offset_x as f32, viewport_offset_y as f32]);
let viewport_scale_x = if width != 0.0 { window_size.width as f64 / width } else { 1.0 };
let viewport_scale_y = if height != 0.0 { window_size.height as f64 / height } else { 1.0 };
let viewport_scale_x = if width != 0. { window_size.width as f64 / width } else { 1. };
let viewport_scale_y = if height != 0. { window_size.height as f64 / height } else { 1. };
render_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
}
}
@@ -284,17 +297,24 @@ impl App {
window.request_redraw();
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document } => {
self.persistent_data.write_document(id, document);
DesktopFrontendMessage::PersistenceWriteState { state } => {
persist::write_state(state);
}
DesktopFrontendMessage::PersistenceReadState => {
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
}
DesktopFrontendMessage::PersistenceReadDocument { id } => {
if let Some(document) = persist::read_document_content(&id) {
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
} else {
tracing::error!("Failed to read document content for {id:?}");
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
persist::write_document_content(id, document_serialized_content);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
self.persistent_data.delete_document(&id);
}
DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id } => {
self.persistent_data.set_current_document(id);
}
DesktopFrontendMessage::PersistenceUpdateDocumentsList { ids } => {
self.persistent_data.set_document_order(ids);
persist::delete_document(&id);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
@@ -304,58 +324,12 @@ impl App {
let message = DesktopWrapperMessage::LoadPreferences { preferences };
responses.push(message);
}
DesktopFrontendMessage::PersistenceLoadCurrentDocument => {
if let Some((id, document)) = self.persistent_data.current_document() {
let message = DesktopWrapperMessage::LoadDocument {
id,
document,
to_front: false,
select_after_open: true,
};
responses.push(message);
}
}
DesktopFrontendMessage::PersistenceLoadRemainingDocuments => {
for (id, document) in self.persistent_data.documents_before_current().into_iter().rev() {
let message = DesktopWrapperMessage::LoadDocument {
id,
document,
to_front: true,
select_after_open: false,
};
responses.push(message);
}
for (id, document) in self.persistent_data.documents_after_current() {
let message = DesktopWrapperMessage::LoadDocument {
id,
document,
to_front: false,
select_after_open: false,
};
responses.push(message);
}
if let Some(id) = self.persistent_data.current_document_id() {
let message = DesktopWrapperMessage::SelectDocument { id };
responses.push(message);
}
}
DesktopFrontendMessage::OpenLaunchDocuments => {
if self.cli.files.is_empty() {
let Some(launch_documents) = std::mem::take(&mut self.launch_documents) else {
tracing::error!("OpenLaunchDocuments should only be sent once");
return;
}
let app_event_scheduler = self.app_event_scheduler.clone();
let launch_documents = std::mem::take(&mut self.cli.files);
let _ = thread::spawn(move || {
for path in launch_documents {
tracing::info!("Opening file from command line: {}", path.display());
if let Ok(content) = fs::read(&path) {
let message = DesktopWrapperMessage::OpenFile { path, content };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
} else {
tracing::error!("Failed to read file: {}", path.display());
}
}
});
};
self.app_event_scheduler.schedule(AppEvent::OpenFiles(launch_documents));
}
DesktopFrontendMessage::UpdateMenu { entries } => {
if let Some(window) = &self.window {
@@ -399,8 +373,11 @@ impl App {
}
}
DesktopFrontendMessage::WindowDrag => {
self.window_pending_drag = true;
}
DesktopFrontendMessage::WindowFocus => {
if let Some(window) = &self.window {
window.start_drag();
window.focus();
}
}
DesktopFrontendMessage::WindowHide => {
@@ -508,6 +485,29 @@ impl App {
tracing::info!("Exiting main event loop");
event_loop.exit();
}
AppEvent::OpenFiles(paths) => {
// Accumulate launch documents until OpenLaunchDocuments message is received
if let Some(launch_documents) = &mut self.launch_documents {
launch_documents.extend(paths);
return;
}
if paths.is_empty() {
return;
}
let app_event_scheduler = self.app_event_scheduler.clone();
let _ = thread::spawn(move || {
for path in paths {
tracing::info!("Opening file: {}", path.display());
if let Ok(content) = fs::read(&path) {
let message = DesktopWrapperMessage::OpenFile { path, content };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
} else {
tracing::error!("Failed to read file: {}", path.display());
}
}
});
}
#[cfg(target_os = "macos")]
AppEvent::MenuEvent { id } => {
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::MenuEvent { id });
@@ -534,8 +534,6 @@ impl ApplicationHandler for App {
self.resize();
self.desktop_wrapper.init(self.wgpu_context.clone());
self.startup_time = Some(Instant::now());
}
@@ -590,20 +588,16 @@ impl ApplicationHandler for App {
Err(RenderError::OutdatedUITextureError) => {
self.cef_context.notify_view_info_changed();
}
Err(RenderError::SurfaceError(wgpu::SurfaceError::Lost)) => {
Err(RenderError::SurfaceLost) => {
tracing::warn!("lost surface");
}
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
tracing::error!("GPU out of memory");
self.exit(None);
}
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
Err(other) => tracing::error!("Render error: {:?}", other),
}
let _ = self.start_render_sender.try_send(());
}
if !self.cef_init_successful
&& !self.cli.disable_ui_acceleration
&& !self.preferences.disable_ui_acceleration
&& self.web_communication_initialized
&& let Some(startup_time) = self.startup_time
&& startup_time.elapsed() > Duration::from_secs(3)
@@ -657,6 +651,21 @@ impl ApplicationHandler for App {
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();
}
}
}
WindowEvent::PointerButton {
button: ButtonSource::Mouse(MouseButton::Left),
state: ElementState::Released,
..
} => {
self.window_pending_drag = false;
}
_ => {}
-1
View File
@@ -27,7 +27,6 @@ use crate::wrapper::{WgpuContext, deserialize_editor_message};
mod consts;
mod context;
mod dirs;
mod input;
mod internal;
mod ipc;
+7 -6
View File
@@ -1,3 +1,4 @@
use graphite_desktop_wrapper::DOUBLE_CLICK_MILLISECONDS;
use std::time::Duration;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
@@ -7,16 +8,16 @@ 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.0;
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_Y: f32 = 3.0;
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_X: f32 = 1.0;
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_Y: f32 = 1.0;
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.0;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(DOUBLE_CLICK_MILLISECONDS);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
+91 -109
View File
@@ -4,15 +4,15 @@ use cef::{
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, LogSeverity, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
browser_host_create_browser_sync, execute_process,
};
use std::path::{Path, PathBuf};
use std::path::Path;
use super::CefContext;
use super::singlethreaded::SingleThreadedCefContext;
use crate::cef::CefEventHandler;
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
use crate::cef::dirs::{create_instance_dir, delete_instance_dirs};
use crate::cef::input::InputState;
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
use crate::dirs::TempDir;
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
pub(crate) args: Args,
@@ -24,14 +24,13 @@ unsafe impl<H: CefEventHandler> Send for CefContextBuilder<H> {}
impl<H: CefEventHandler> CefContextBuilder<H> {
pub(crate) fn new() -> Self {
Self::new_inner(false)
Self::new_impl(false)
}
pub(crate) fn new_helper() -> Self {
Self::new_inner(true)
Self::new_impl(true)
}
fn new_inner(helper: bool) -> Self {
fn new_impl(helper: bool) -> Self {
#[cfg(target_os = "macos")]
let _loader = {
let loader = cef::library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), helper);
@@ -42,12 +41,8 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
let _ = helper;
let _ = api_hash(CEF_API_VERSION_LAST, 0);
let args = Args::new();
let cmd = args.as_cmd_line().unwrap();
let switch = CefString::from("type");
let is_sub_process = cmd.has_switch(Some(&switch)) == 1;
let is_sub_process = args.as_cmd_line().unwrap().has_switch(Some(&"type".into())) == 1;
Self {
args,
is_sub_process,
@@ -61,8 +56,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
pub(crate) fn execute_sub_process(&self) -> SetupError {
let cmd = self.args.as_cmd_line().unwrap();
let switch = CefString::from("type");
let process_type = CefString::from(&cmd.switch_value(Some(&switch)));
let process_type = CefString::from(&cmd.switch_value(Some(&"type".into())));
let mut app = RenderProcessAppImpl::<H>::app();
let ret = execute_process(Some(self.args.as_main_args()), Some(&mut app), std::ptr::null_mut());
if ret >= 0 {
@@ -72,105 +66,96 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
}
}
fn common_settings(instance_dir: &Path) -> Settings {
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG") {
Ok(level) => match level.to_lowercase().as_str() {
"debug" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_VERBOSE),
"info" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_INFO),
"warn" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_WARNING),
"error" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_ERROR),
"none" => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_DISABLE),
_ => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
},
Err(_) => LogSeverity::from(cef_log_severity_t::LOGSEVERITY_FATAL),
};
Settings {
windowless_rendering_enabled: 1,
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
cache_path: CefString::from(""),
disable_signal_handlers: 1,
log_severity,
..Default::default()
}
}
#[cfg(target_os = "macos")]
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
delete_instance_dirs();
let instance_dir = create_instance_dir();
let exe = std::env::current_exe().expect("cannot get current exe path");
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
let settings = Settings {
main_bundle_path: CefString::from(app_root.to_str().unwrap()),
multi_threaded_message_loop: 0,
external_message_pump: 1,
no_sandbox: 1, // GPU helper crashes when running with sandbox
..Self::common_settings(&instance_dir)
};
self.initialize_inner(&event_handler, settings)?;
create_browser(event_handler, instance_dir, disable_gpu_acceleration)
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
create_browser(event_handler, instance_dir, accelerated_paint)
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
delete_instance_dirs();
let instance_dir = create_instance_dir();
let settings = Settings {
multi_threaded_message_loop: 1,
#[cfg(target_os = "linux")]
no_sandbox: 1,
..Self::common_settings(&instance_dir)
};
self.initialize_inner(&event_handler, settings)?;
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, disable_gpu_acceleration) {
Ok(context) => {
super::multithreaded::CONTEXT.with(|b| {
*b.borrow_mut() = Some(context);
});
}
Err(e) => {
panic!("Failed to initialize CEF context: {:?}", e);
}
pub(crate) fn create(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
let instance_dir = TempDir::new().expect("Failed to create temporary directory for CEF instance");
let accelerated_paint = accelerated_paint(disable_gpu_acceleration);
self.build_inner(&event_handler, instance_dir.as_ref(), accelerated_paint)?;
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, accelerated_paint) {
Ok(context) => super::multithreaded::CONTEXT.with(|b| *b.borrow_mut() = Some(context)),
Err(e) => panic!("Failed to initialize CEF context: {:?}", e),
});
Ok(super::multithreaded::MultiThreadedCefContextProxy)
}
fn initialize_inner(self, event_handler: &H, settings: Settings) -> Result<(), InitError> {
// Attention! Wrapping this in an extra App is necessary, otherwise the program still compiles but segfaults
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate()));
let result = cef::initialize(Some(self.args.as_main_args()), Some(&settings), Some(&mut cef_app), std::ptr::null_mut());
fn build_inner(self, event_handler: &H, instance_dir: &Path, accelerated_paint: bool) -> Result<(), InitError> {
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate(), accelerated_paint));
let result = cef::initialize(Some(self.args.as_main_args()), Some(&platform_settings(instance_dir)), Some(&mut cef_app), std::ptr::null_mut());
if result != 1 {
let cef_exit_code = cef::get_exit_code() as u32;
return Err(InitError::InitializationFailureCode(cef_exit_code));
return Err(InitError::InitializationFailureCode(cef::get_exit_code() as u32));
}
Ok(())
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
fn accelerated_paint(disable_gpu_acceleration: bool) -> bool {
#[cfg(feature = "accelerated_paint")]
let use_accelerated_paint = if disable_gpu_acceleration {
{
!disable_gpu_acceleration && crate::cef::platform::should_enable_hardware_acceleration()
}
#[cfg(not(feature = "accelerated_paint"))]
{
let _ = disable_gpu_acceleration;
false
} else {
crate::cef::platform::should_enable_hardware_acceleration()
}
}
fn platform_settings(instance_dir: &Path) -> Settings {
let log_severity = match std::env::var("GRAPHITE_BROWSER_LOG").unwrap_or_default().to_lowercase().as_str() {
"debug" => cef_log_severity_t::LOGSEVERITY_VERBOSE,
"info" => cef_log_severity_t::LOGSEVERITY_INFO,
"warn" => cef_log_severity_t::LOGSEVERITY_WARNING,
"error" => cef_log_severity_t::LOGSEVERITY_ERROR,
"none" => cef_log_severity_t::LOGSEVERITY_DISABLE,
_ => cef_log_severity_t::LOGSEVERITY_FATAL,
};
let base = Settings {
windowless_rendering_enabled: 1,
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
cache_path: "".into(),
disable_signal_handlers: 1,
log_severity: LogSeverity::from(log_severity),
..Default::default()
};
#[cfg(target_os = "macos")]
{
let exe = std::env::current_exe().expect("cannot get current exe path");
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
Settings {
main_bundle_path: app_root.to_str().map(CefString::from).unwrap(),
multi_threaded_message_loop: 0,
external_message_pump: 1,
no_sandbox: 1, // GPU helper crashes when running with sandbox
..base
}
}
#[cfg(not(target_os = "macos"))]
Settings {
multi_threaded_message_loop: 1,
#[cfg(target_os = "linux")]
no_sandbox: 1,
..base
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: TempDir, accelerated_paint: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
let window_info = WindowInfo {
windowless_rendering_enabled: 1,
#[cfg(feature = "accelerated_paint")]
shared_texture_enabled: use_accelerated_paint as i32,
shared_texture_enabled: accelerated_paint as i32,
..Default::default()
};
@@ -183,7 +168,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
let Some(mut incognito_request_context) = cef::request_context_create_context(
Some(&RequestContextSettings {
persist_session_cookies: 0,
cache_path: CefString::from(""),
cache_path: "".into(),
..Default::default()
}),
Option::<&mut cef::RequestContextHandler>::None,
@@ -193,30 +178,27 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, d
let mut scheme_handler_factory = SchemeHandlerFactory::new(SchemeHandlerFactoryImpl::new(event_handler.duplicate()));
incognito_request_context.clear_scheme_handler_factories();
incognito_request_context.register_scheme_handler_factory(Some(&CefString::from(RESOURCE_SCHEME)), Some(&CefString::from(RESOURCE_DOMAIN)), Some(&mut scheme_handler_factory));
incognito_request_context.register_scheme_handler_factory(Some(&RESOURCE_SCHEME.into()), Some(&RESOURCE_DOMAIN.into()), Some(&mut scheme_handler_factory));
let url = CefString::from(format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/").as_str());
let browser = browser_host_create_browser_sync(
let url = format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/");
browser_host_create_browser_sync(
Some(&window_info),
Some(&mut client),
Some(&url),
Some(&url.as_str().into()),
Some(&settings),
Option::<&mut DictionaryValue>::None,
Some(&mut incognito_request_context),
);
if let Some(browser) = browser {
Ok(SingleThreadedCefContext {
event_handler: Box::new(event_handler),
browser,
input_state: InputState::default(),
instance_dir,
})
} else {
)
.map(|browser| SingleThreadedCefContext {
event_handler: Box::new(event_handler),
browser,
input_state: InputState::default(),
_instance_dir: instance_dir,
})
.ok_or_else(|| {
tracing::error!("Failed to create browser");
Err(InitError::BrowserCreationFailed)
}
InitError::BrowserCreationFailed
})
}
#[derive(thiserror::Error, Debug)]
+6 -1
View File
@@ -54,7 +54,12 @@ impl CefContext for MultiThreadedCefContextProxy {
impl Drop for MultiThreadedCefContextProxy {
fn drop(&mut self) {
// Force dropping underlying context on the UI thread
run_on_ui_thread(move || drop(CONTEXT.take()));
let (sync_drop_tx, sync_drop_rx) = std::sync::mpsc::channel();
run_on_ui_thread(move || {
drop(CONTEXT.take());
let _ = sync_drop_tx.send(());
});
let _ = sync_drop_rx.recv();
}
}
+2 -15
View File
@@ -4,6 +4,7 @@ use winit::event::WindowEvent;
use crate::cef::input::InputState;
use crate::cef::ipc::{MessageType, SendMessage};
use crate::cef::{CefEventHandler, input};
use crate::dirs::TempDir;
use super::CefContext;
@@ -11,7 +12,7 @@ pub(super) struct SingleThreadedCefContext {
pub(super) event_handler: Box<dyn CefEventHandler>,
pub(super) browser: Browser,
pub(super) input_state: InputState,
pub(super) instance_dir: std::path::PathBuf,
pub(super) _instance_dir: TempDir,
}
impl CefContext for SingleThreadedCefContext {
@@ -46,19 +47,6 @@ impl Drop for SingleThreadedCefContext {
// CEF wants us to close the browser before shutting down, otherwise it may run longer that necessary.
self.browser.host().unwrap().close_browser(1);
cef::shutdown();
// Sometimes some CEF processes still linger at this point and hold file handles to the cache directory.
// To mitigate this, we try to remove the directory multiple times with some delay.
// TODO: find a better solution if possible.
for _ in 0..30 {
match std::fs::remove_dir_all(&self.instance_dir) {
Ok(_) => break,
Err(e) => {
tracing::warn!("Failed to remove CEF cache directory, retrying...: {e}");
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
}
}
}
@@ -68,7 +56,6 @@ impl SendMessage for SingleThreadedCefContext {
tracing::error!("Main frame is not available, cannot send message");
return;
};
frame.send_message(message_type, message);
}
}
-24
View File
@@ -1,24 +0,0 @@
use std::path::PathBuf;
use crate::dirs::{app_data_dir, ensure_dir_exists};
static CEF_DIR_NAME: &str = "browser";
pub(crate) fn delete_instance_dirs() {
let cef_dir = app_data_dir().join(CEF_DIR_NAME);
if let Ok(entries) = std::fs::read_dir(&cef_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let _ = std::fs::remove_dir_all(&path);
}
}
}
}
pub(crate) fn create_instance_dir() -> PathBuf {
let instance_id: String = (0..32).map(|_| format!("{:x}", rand::random::<u8>() % 16)).collect();
let path = app_data_dir().join(CEF_DIR_NAME).join(instance_id);
ensure_dir_exists(&path);
path
}
+29 -32
View File
@@ -133,51 +133,46 @@ impl ClickTracker {
};
let Some(record) = record else {
*record = Some(ClickRecord { position, ..Default::default() });
*record = Some(ClickRecord {
down_position: position,
up_position: position,
..Default::default()
});
return ClickCount::Single;
};
let prev_time = record.time;
let prev_position = record.position;
let prev_count: ClickCount = record.down_count;
let now = Instant::now();
record.time = now;
record.position = position;
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
match state {
ElementState::Pressed if record.down_count == ClickCount::Triple => {
*record = ClickRecord {
down_count: ClickCount::Double,
..*record
};
return ClickCount::Double;
}
ElementState::Released if record.up_count == ClickCount::Triple => {
*record = ClickRecord {
up_count: ClickCount::Double,
..*record
};
return ClickCount::Double;
}
_ => {}
}
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);
let dy = position.y.abs_diff(prev_position.y);
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let within_time = now.saturating_duration_since(prev_time) <= MULTICLICK_TIMEOUT;
let count = match (prev_count, within_time, within_dist) {
(ClickCount::Single, true, true) => ClickCount::Double,
(ClickCount::Double, true, true) => ClickCount::Triple,
(_, true, true) => ClickCount::Double,
(ClickCount::Triple, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
*record = match state {
ElementState::Pressed => ClickRecord { down_count: count, ..*record },
ElementState::Released => ClickRecord { up_count: count, ..*record },
};
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
}
}
@@ -202,7 +197,8 @@ impl From<ClickCount> for i32 {
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
position: MousePosition,
down_position: MousePosition,
up_position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
@@ -211,7 +207,8 @@ impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
position: Default::default(),
down_position: Default::default(),
up_position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
+2
View File
@@ -10,7 +10,9 @@ mod context_menu_handler;
mod display_handler;
mod life_span_handler;
mod load_handler;
mod request_handler;
mod resource_handler;
mod resource_request_handler;
mod scheme_handler_factory;
pub(super) mod render_handler;
+54 -60
View File
@@ -1,6 +1,3 @@
#[cfg(target_os = "linux")]
use std::env;
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_app_t, cef_base_ref_counted_t};
use cef::{BrowserProcessHandler, CefString, ImplApp, ImplCommandLine, SchemeRegistrar, WrapApp};
@@ -12,12 +9,14 @@ use crate::cef::CefEventHandler;
pub(crate) struct BrowserProcessAppImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_app_t, Self>,
event_handler: H,
accelerated_paint: bool,
}
impl<H: CefEventHandler> BrowserProcessAppImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
pub(crate) fn new(event_handler: H, accelerated_paint: bool) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
accelerated_paint,
}
}
}
@@ -33,81 +32,75 @@ impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
fn on_before_command_line_processing(&self, _process_type: Option<&cef::CefString>, command_line: Option<&mut cef::CommandLine>) {
if let Some(cmd) = command_line {
cmd.append_switch_with_value(Some(&CefString::from("renderer-process-limit")), Some(&CefString::from("1")));
cmd.append_switch_with_value(Some(&CefString::from("password-store")), Some(&CefString::from("basic")));
cmd.append_switch_with_value(Some(&CefString::from("disk-cache-size")), Some(&CefString::from("0")));
cmd.append_switch(Some(&CefString::from("incognito")));
cmd.append_switch(Some(&CefString::from("no-first-run")));
cmd.append_switch(Some(&CefString::from("no-default-browser-check")));
cmd.append_switch(Some(&CefString::from("disable-component-update")));
cmd.append_switch(Some(&CefString::from("disable-geolocation")));
cmd.append_switch(Some(&CefString::from("disable-notifications")));
cmd.append_switch(Some(&CefString::from("disable-audio-input")));
cmd.append_switch(Some(&CefString::from("disable-audio-output")));
cmd.append_switch(Some(&CefString::from("disable-sync")));
cmd.append_switch(Some(&CefString::from("disable-file-system")));
cmd.append_switch(Some(&CefString::from("disable-local-storage")));
cmd.append_switch(Some(&CefString::from("disable-background-networking")));
cmd.append_switch(Some(&CefString::from("disable-default-apps")));
cmd.append_switch(Some(&CefString::from("disable-breakpad")));
cmd.append_switch_with_value(Some(&CefString::from("disable-blink-features")), Some(&CefString::from("WebBluetooth,WebUSB,Serial")));
cmd.append_switch_with_value(Some(&"renderer-process-limit".into()), Some(&"1".into()));
cmd.append_switch_with_value(Some(&"password-store".into()), Some(&"basic".into()));
cmd.append_switch_with_value(Some(&"disk-cache-size".into()), Some(&"0".into()));
cmd.append_switch(Some(&"no-sandbox".into()));
cmd.append_switch(Some(&"no-first-run".into()));
cmd.append_switch(Some(&"noerrdialogs".into()));
cmd.append_switch(Some(&"no-default-browser-check".into()));
cmd.append_switch(Some(&"mute-audio".into()));
cmd.append_switch(Some(&"use-fake-device-for-media-stream".into()));
cmd.append_switch(Some(&"incognito".into()));
cmd.append_switch(Some(&"disable-sync".into()));
cmd.append_switch(Some(&"disable-file-system".into()));
cmd.append_switch(Some(&"disable-component-update".into()));
cmd.append_switch(Some(&"disable-geolocation".into()));
cmd.append_switch(Some(&"disable-notifications".into()));
cmd.append_switch(Some(&"disable-background-networking".into()));
cmd.append_switch(Some(&"disable-default-apps".into()));
cmd.append_switch(Some(&"disable-breakpad".into()));
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&CefString::from("disable-features"));
let disabled_features: String = CefString::from(&cmd.switch_value(disabled_features_switch))
let disabled_features_switch = Some(&"disable-features".into());
let mut disabled_features: Vec<String> = CefString::from(&cmd.switch_value(disabled_features_switch))
.to_string()
.split(',')
.chain(extra_disabled_features)
.collect::<Vec<_>>()
.join(",");
cmd.append_switch_with_value(disabled_features_switch, Some(&CefString::from(disabled_features.as_str())));
.filter(|feature| !feature.is_empty())
.map(ToOwned::to_owned)
.collect();
disabled_features.extend(extra_disabled_features.into_iter().map(ToOwned::to_owned));
cmd.append_switch_with_value(disabled_features_switch, Some(&disabled_features.join(",").as_str().into()));
#[cfg(not(feature = "accelerated_paint"))]
{
// Disable GPU acceleration when accelerated_paint feature is not enabled
cmd.append_switch(Some(&CefString::from("disable-gpu")));
cmd.append_switch(Some(&CefString::from("disable-gpu-compositing")));
}
if self.accelerated_paint {
cmd.append_switch(Some(&"enable-gpu".into()));
cmd.append_switch(Some(&"enable-gpu-compositing".into()));
cmd.append_switch(Some(&"enable-begin-frame-scheduling".into()));
cmd.append_switch(Some(&"off-screen-rendering-enabled".into()));
cmd.append_switch(Some(&"enable-accelerated-2d-canvas".into()));
#[cfg(feature = "accelerated_paint")]
{
// Enable GPU acceleration switches for better performance
cmd.append_switch(Some(&CefString::from("enable-gpu-rasterization")));
cmd.append_switch(Some(&CefString::from("enable-accelerated-2d-canvas")));
}
#[cfg(target_os = "linux")]
{
cmd.append_switch_with_value(Some(&"use-angle".into()), Some(&"gl-egl".into()));
#[cfg(all(feature = "accelerated_paint", target_os = "linux"))]
{
// Use Vulkan for accelerated painting
cmd.append_switch_with_value(Some(&CefString::from("use-angle")), Some(&CefString::from("vulkan")));
}
// Tell CEF to use Wayland if available
#[cfg(target_os = "linux")]
{
let use_wayland = env::var("WAYLAND_DISPLAY")
.ok()
.filter(|var| !var.is_empty())
.or_else(|| env::var("WAYLAND_SOCKET").ok())
.filter(|var| !var.is_empty())
.is_some();
if use_wayland {
cmd.append_switch_with_value(Some(&CefString::from("ozone-platform")), Some(&CefString::from("wayland")));
let use_wayland = std::env::var("WAYLAND_DISPLAY")
.ok()
.filter(|var| !var.is_empty())
.or_else(|| std::env::var("WAYLAND_SOCKET").ok())
.filter(|var| !var.is_empty())
.is_some();
if use_wayland {
cmd.append_switch_with_value(Some(&"ozone-platform".into()), Some(&"wayland".into()));
}
}
} else {
cmd.append_switch(Some(&"disable-gpu".into()));
cmd.append_switch(Some(&"disable-gpu-compositing".into()));
}
#[cfg(target_os = "macos")]
{
// Hide user prompt asking for keychain access
cmd.append_switch(Some(&CefString::from("use-mock-keychain")));
cmd.append_switch(Some(&"use-mock-keychain".into()));
}
// Enable browser debugging via environment variable
if let Some(env) = std::env::var("GRAPHITE_BROWSER_DEBUG_PORT").ok()
&& let Some(port) = env.parse::<u16>().ok()
{
cmd.append_switch_with_value(Some(&CefString::from("remote-debugging-port")), Some(&CefString::from(port.to_string().as_str())));
cmd.append_switch_with_value(Some(&CefString::from("remote-allow-origins")), Some(&CefString::from("*")));
cmd.append_switch_with_value(Some(&"remote-debugging-port".into()), Some(&port.to_string().as_str().into()));
cmd.append_switch_with_value(Some(&"remote-allow-origins".into()), Some(&"*".into()));
}
}
}
@@ -126,6 +119,7 @@ impl<H: CefEventHandler> Clone for BrowserProcessAppImpl<H> {
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
accelerated_paint: self.accelerated_paint,
}
}
}
@@ -1,6 +1,6 @@
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_client_t, cef_base_ref_counted_t};
use cef::{ContextMenuHandler, DisplayHandler, ImplClient, LifeSpanHandler, LoadHandler, RenderHandler, WrapClient};
use cef::{ContextMenuHandler, DisplayHandler, ImplClient, LifeSpanHandler, LoadHandler, RenderHandler, RequestHandler, WrapClient};
use crate::cef::CefEventHandler;
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
@@ -10,6 +10,7 @@ use super::display_handler::DisplayHandlerImpl;
use super::life_span_handler::LifeSpanHandlerImpl;
use super::load_handler::LoadHandlerImpl;
use super::render_handler::RenderHandlerImpl;
use super::request_handler::RequestHandlerImpl;
pub(crate) struct BrowserProcessClientImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_client_t, Self>,
@@ -17,6 +18,7 @@ pub(crate) struct BrowserProcessClientImpl<H: CefEventHandler> {
load_handler: LoadHandler,
render_handler: RenderHandler,
display_handler: DisplayHandler,
request_handler: RequestHandler,
}
impl<H: CefEventHandler> BrowserProcessClientImpl<H> {
pub(crate) fn new(event_handler: &H) -> Self {
@@ -26,6 +28,7 @@ impl<H: CefEventHandler> BrowserProcessClientImpl<H> {
load_handler: LoadHandler::new(LoadHandlerImpl::new(event_handler.duplicate())),
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate())),
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(event_handler.duplicate())),
request_handler: RequestHandler::new(RequestHandlerImpl::new()),
}
}
}
@@ -73,6 +76,10 @@ impl<H: CefEventHandler> ImplClient for BrowserProcessClientImpl<H> {
Some(self.display_handler.clone())
}
fn request_handler(&self) -> Option<cef::RequestHandler> {
Some(self.request_handler.clone())
}
fn context_menu_handler(&self) -> Option<cef::ContextMenuHandler> {
Some(ContextMenuHandler::new(ContextMenuHandlerImpl::new()))
}
@@ -94,6 +101,7 @@ impl<H: CefEventHandler> Clone for BrowserProcessClientImpl<H> {
load_handler: self.load_handler.clone(),
render_handler: self.render_handler.clone(),
display_handler: self.display_handler.clone(),
request_handler: self.request_handler.clone(),
}
}
}
@@ -1,6 +1,6 @@
use cef::rc::{ConvertReturnValue, Rc, RcImpl};
use cef::sys::{_cef_render_process_handler_t, cef_base_ref_counted_t, cef_render_process_handler_t, cef_v8_propertyattribute_t, cef_v8_value_create_array_buffer_with_copy};
use cef::{CefString, ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
use cef::{ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
@@ -52,14 +52,10 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
let function_call = format!("window.{function_name}(window.{property_name})");
global.set_value_bykey(
Some(&CefString::from(property_name)),
Some(&mut value),
cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result(),
);
global.set_value_bykey(Some(&property_name.into()), Some(&mut value), cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result());
if global.value_bykey(Some(&CefString::from(function_name))).is_some() {
frame.execute_java_script(Some(&CefString::from(function_call.as_str())), None, 0);
if global.value_bykey(Some(&function_name.into())).is_some() {
frame.execute_java_script(Some(&function_call.as_str().into()), None, 0);
}
if context.exit() == 0 {
@@ -78,7 +74,7 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
fn on_context_created(&self, _browser: Option<&mut cef::Browser>, _frame: Option<&mut cef::Frame>, context: Option<&mut cef::V8Context>) {
let register_js_function = |context: &mut cef::V8Context, name: &'static str| {
let mut v8_handler = V8Handler::new(RenderProcessV8HandlerImpl::new());
let Some(mut function) = v8_value_create_function(Some(&CefString::from(name)), Some(&mut v8_handler)) else {
let Some(mut function) = v8_value_create_function(Some(&name.into()), Some(&mut v8_handler)) else {
tracing::error!("Failed to create V8 function {name}");
return;
};
@@ -87,7 +83,7 @@ impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
tracing::error!("Global object is not available in V8 context");
return;
};
global.set_value_bykey(Some(&CefString::from(name)), Some(&mut function), V8Propertyattribute::default());
global.set_value_bykey(Some(&name.into()), Some(&mut function), V8Propertyattribute::default());
};
let Some(context) = context else {
@@ -0,0 +1,84 @@
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_request_handler_t, cef_base_ref_counted_t};
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, WrapRequestHandler};
use std::ffi::c_int;
use super::resource_request_handler::ResourceRequestHandlerImpl;
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
pub(crate) struct RequestHandlerImpl {
object: *mut RcImpl<_cef_request_handler_t, Self>,
}
impl RequestHandlerImpl {
pub(crate) fn new() -> Self {
Self { object: std::ptr::null_mut() }
}
}
impl ImplRequestHandler for RequestHandlerImpl {
fn on_before_browse(&self, _browser: Option<&mut Browser>, _frame: Option<&mut Frame>, request: Option<&mut Request>, _user_gesture: c_int, _is_redirect: c_int) -> c_int {
let Some(request) = request else { return 1 };
let url = CefString::from(&request.url()).to_string();
if url.starts_with(&format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/")) {
0
} else {
tracing::warn!("Blocked navigation to: {}", url);
1
}
}
fn resource_request_handler(
&self,
_browser: Option<&mut Browser>,
_frame: Option<&mut Frame>,
_request: Option<&mut Request>,
_is_navigation: c_int,
_is_download: c_int,
_request_initiator: Option<&CefString>,
_disable_default_handling: Option<&mut c_int>,
) -> Option<ResourceRequestHandler> {
Some(ResourceRequestHandler::new(ResourceRequestHandlerImpl::new()))
}
fn auth_credentials(
&self,
_browser: Option<&mut Browser>,
_origin_url: Option<&CefString>,
_is_proxy: c_int,
_host: Option<&CefString>,
_port: c_int,
_realm: Option<&CefString>,
_scheme: Option<&CefString>,
_callback: Option<&mut AuthCallback>,
) -> c_int {
0
}
fn get_raw(&self) -> *mut _cef_request_handler_t {
self.object.cast()
}
}
impl Clone for RequestHandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self { object: self.object }
}
}
impl Rc for RequestHandlerImpl {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapRequestHandler for RequestHandlerImpl {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_request_handler_t, Self>) {
self.object = object;
}
}
+2 -3
View File
@@ -46,15 +46,14 @@ impl ImplResourceHandler for ResourceHandlerImpl {
if let Some(response) = response {
if self.reader.is_some() {
if let Some(mimetype) = &self.mimetype {
let cef_mime = CefString::from(mimetype.as_str());
response.set_mime_type(Some(&cef_mime));
response.set_mime_type(Some(&mimetype.as_str().into()));
} else {
response.set_mime_type(None);
}
response.set_status(200);
} else {
response.set_status(404);
response.set_mime_type(Some(&CefString::from("text/plain")));
response.set_mime_type(Some(&"text/plain".into()));
}
}
}
@@ -0,0 +1,60 @@
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_resource_request_handler_t, cef_base_ref_counted_t};
use cef::{Browser, Callback, CefString, Frame, ImplRequest, ImplResourceRequestHandler, Request, ReturnValue, WrapResourceRequestHandler};
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
// TODO: Deny all external requests once we stop relying on google fonts for font preview
fn is_allowed_url(url: &str) -> bool {
url.starts_with(&format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/")) || url.starts_with("https://fonts.googleapis.com/css2") || url.starts_with("https://fonts.gstatic.com/")
}
pub(crate) struct ResourceRequestHandlerImpl {
object: *mut RcImpl<_cef_resource_request_handler_t, Self>,
}
impl ResourceRequestHandlerImpl {
pub(crate) fn new() -> Self {
Self { object: std::ptr::null_mut() }
}
}
impl ImplResourceRequestHandler for ResourceRequestHandlerImpl {
fn on_before_resource_load(&self, _browser: Option<&mut Browser>, _frame: Option<&mut Frame>, request: Option<&mut Request>, _callback: Option<&mut Callback>) -> ReturnValue {
let Some(request) = request else { return ReturnValue::CANCEL };
let url = CefString::from(&request.url()).to_string();
if is_allowed_url(&url) {
ReturnValue::CONTINUE
} else {
tracing::error!("Blocked resource load: {}", url);
ReturnValue::CANCEL
}
}
fn get_raw(&self) -> *mut _cef_resource_request_handler_t {
self.object.cast()
}
}
impl Clone for ResourceRequestHandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self { object: self.object }
}
}
impl Rc for ResourceRequestHandlerImpl {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapResourceRequestHandler for ResourceRequestHandlerImpl {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_resource_request_handler_t, Self>) {
self.object = object;
}
}
@@ -25,7 +25,7 @@ impl<H: CefEventHandler> SchemeHandlerFactoryImpl<H> {
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_FETCH_ENABLED as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_SECURE as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_CORS_ENABLED as i32;
registrar.add_custom_scheme(Some(&CefString::from(RESOURCE_SCHEME)), scheme_options);
registrar.add_custom_scheme(Some(&RESOURCE_SCHEME.into()), scheme_options);
}
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
use cef::{CefString, Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
use cef::{Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
pub(crate) enum MessageType {
Initialized,
@@ -67,7 +67,7 @@ impl SendMessage for Frame {
fn send_message(&self, message_type: MessageType, message: &[u8]) {
let MessageInfo { name, target } = message_type.into();
let Some(mut process_message) = cef::process_message_create(Some(&CefString::from(name.as_str()))) else {
let Some(mut process_message) = cef::process_message_create(Some(&name.as_str().into())) else {
tracing::error!("Failed to create process message: {}", name);
return;
};
+2
View File
@@ -7,9 +7,11 @@ pub(crate) const APP_DIRECTORY_NAME: &str = "graphite";
#[cfg(not(target_os = "linux"))]
pub(crate) const APP_DIRECTORY_NAME: &str = "Graphite";
pub(crate) const APP_LOCK_FILE_NAME: &str = "instance.lock";
pub(crate) const APP_SOCKET_FILE_NAME: &str = "instance.sock";
pub(crate) const APP_STATE_FILE_NAME: &str = "state.ron";
pub(crate) const APP_PREFERENCES_FILE_NAME: &str = "preferences.ron";
pub(crate) const APP_DOCUMENTS_DIRECTORY_NAME: &str = "documents";
pub(crate) const APP_RESOURCES_DIRECTORY_NAME: &str = "resources";
// CEF configuration constants
pub(crate) const CEF_WINDOWLESS_FRAME_RATE: i32 = 60;
+82 -4
View File
@@ -1,11 +1,31 @@
use std::fs::create_dir_all;
use std::path::PathBuf;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME, APP_RESOURCES_DIRECTORY_NAME};
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
if !path.exists() {
create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
fs::create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
}
}
fn clear_dir(path: &PathBuf) {
let Ok(entries) = fs::read_dir(path) else {
tracing::error!("Failed to read directory at {path:?}");
return;
};
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file() {
if let Err(e) = fs::remove_file(&entry_path) {
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
}
@@ -15,8 +35,66 @@ pub(crate) fn app_data_dir() -> PathBuf {
path
}
fn app_tmp_dir() -> PathBuf {
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
pub(crate) fn app_tmp_dir_cleanup() {
clear_dir(&app_tmp_dir());
}
pub(crate) fn app_autosave_documents_dir() -> PathBuf {
let path = app_data_dir().join(APP_DOCUMENTS_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
pub(crate) fn app_resources_dir() -> PathBuf {
let path = app_data_dir().join(APP_RESOURCES_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
/// Temporary directory that is automatically deleted when dropped.
pub struct TempDir {
path: PathBuf,
}
impl TempDir {
pub fn new() -> io::Result<Self> {
Self::new_with_parent(app_tmp_dir())
}
pub fn new_with_parent(parent: impl AsRef<Path>) -> io::Result<Self> {
let random_suffix = format!("{:032x}", rand::random::<u128>());
let name = format!("{}_{}", std::process::id(), random_suffix);
let path = parent.as_ref().join(name);
fs::create_dir_all(&path)?;
Ok(Self { path })
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let result = fs::remove_dir_all(&self.path);
if let Err(e) = result {
tracing::error!("Failed to remove temporary directory at {:?}: {}", self.path, e);
}
}
}
impl AsRef<Path> for TempDir {
fn as_ref(&self) -> &Path {
&self.path
}
}
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
pub(crate) fn delete_old_cef_browser_directory() {
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
if old_browser_dir.is_dir() {
let _ = std::fs::remove_dir_all(&old_browser_dir);
}
}
+1
View File
@@ -9,6 +9,7 @@ pub(crate) enum AppEvent {
DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult),
Exit,
OpenFiles(Vec<std::path::PathBuf>),
#[cfg(target_os = "macos")]
MenuEvent {
id: String,
+8 -10
View File
@@ -1,20 +1,18 @@
use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
pub(super) async fn create_wgpu_context() -> WgpuContext {
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::PUSH_CONSTANTS);
let mut wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES);
// TODO: make this configurable via cli flags instead
if let Some(index) = std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) {
tracing::info!("Overriding WGPU adapter selection with adapter index {index}");
wgpu_context_builder = wgpu_context_builder.with_selection(index);
}
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("\nAvailable WGPU adapters:\n{}", wgpu_context_builder.available_adapters_fmt().await);
// TODO: make this configurable via cli flags instead
let wgpu_context = match std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) {
None => wgpu_context_builder.build().await,
Some(adapter_index) => {
tracing::info!("Overriding WGPU adapter selection with adapter index {adapter_index}");
wgpu_context_builder.build_with_adapter_selection(|_| Some(adapter_index)).await
}
}
.expect("Failed to create WGPU context");
let wgpu_context = wgpu_context_builder.build().await.expect("Failed to create WGPU context");
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("Using WGPU adapter: {:?}", wgpu_context.adapter.get_info());
+22 -6
View File
@@ -19,6 +19,7 @@ mod gpu_context;
mod persist;
mod preferences;
mod render;
mod socket;
mod window;
pub(crate) mod consts;
@@ -58,11 +59,22 @@ pub fn start() {
}
Err(_) => {
tracing::error!("Another instance is already running, Exiting.");
std::process::exit(1);
if !cli.files.is_empty()
&& let Err(error) = socket::send(socket::Message::OpenFiles(cli.files))
{
tracing::error!("Failed to send socket message to running instance: {}", error);
std::process::exit(1);
}
return;
}
};
let prefs = preferences::read();
dirs::app_tmp_dir_cleanup();
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory();
let mut prefs = preferences::read();
// Must be called before event loop initialization or native window integrations will break
App::init();
@@ -73,15 +85,19 @@ pub fn start() {
let (app_event_sender, app_event_receiver) = std::sync::mpsc::channel();
let app_event_scheduler = event_loop.create_app_event_scheduler(app_event_sender);
let _socket_handle = socket::start(app_event_scheduler.clone());
let (cef_view_info_sender, cef_view_info_receiver) = std::sync::mpsc::channel();
let disable_ui_acceleration = prefs.disable_ui_acceleration || cli.disable_ui_acceleration;
if disable_ui_acceleration {
if cli.disable_ui_acceleration {
prefs.disable_ui_acceleration = true;
}
if prefs.disable_ui_acceleration {
println!("UI acceleration is disabled");
}
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.initialize(cef_handler, disable_ui_acceleration) {
let cef_context = match cef_context_builder.create(cef_handler, prefs.disable_ui_acceleration) {
Ok(context) => {
tracing::info!("CEF initialized successfully");
context
@@ -97,7 +113,7 @@ pub fn start() {
}
};
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli);
let app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, prefs, cli.files);
let exit_reason = app.run(event_loop);
+73 -173
View File
@@ -1,192 +1,92 @@
use crate::wrapper::messages::{Document, DocumentId};
use crate::wrapper::messages::{DocumentId, PersistedState};
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub(crate) struct PersistentData {
documents: DocumentStore,
current_document: Option<DocumentId>,
#[serde(skip)]
document_order: Option<Vec<DocumentId>>,
pub(crate) fn read_state() -> PersistedState {
let path = state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::info!("No persistent data file found at {path:?}, starting fresh");
return PersistedState::default();
}
Err(e) => {
tracing::error!("Failed to read persistent data from disk: {e}");
return PersistedState::default();
}
};
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
return PersistedState::default();
}
};
garbage_collect_document_files(&loaded);
loaded
}
impl PersistentData {
pub(crate) fn write_document(&mut self, id: DocumentId, document: Document) {
self.documents.write(id, document);
if let Some(order) = &self.document_order {
self.documents.force_order(order);
pub(crate) fn write_state(state: PersistedState) {
let state: &PersistedState = &state;
let data = match ron::ser::to_string_pretty(state, Default::default()) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to serialize persistent data: {e}");
return;
}
self.flush();
};
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
garbage_collect_document_files(state);
}
pub(crate) fn delete_document(&mut self, id: &DocumentId) {
if Some(*id) == self.current_document {
self.current_document = None;
}
self.documents.delete(id);
self.flush();
}
pub(crate) fn current_document_id(&self) -> Option<DocumentId> {
match self.current_document {
Some(id) => Some(id),
None => Some(*self.documents.document_ids().first()?),
}
}
pub(crate) fn current_document(&self) -> Option<(DocumentId, Document)> {
let current_id = self.current_document_id()?;
Some((current_id, self.documents.read(&current_id)?))
}
pub(crate) fn documents_before_current(&self) -> Vec<(DocumentId, Document)> {
let Some(current_id) = self.current_document_id() else {
return Vec::new();
};
self.documents
.document_ids()
.into_iter()
.take_while(|id| *id != current_id)
.filter_map(|id| Some((id, self.documents.read(&id)?)))
.collect()
}
pub(crate) fn documents_after_current(&self) -> Vec<(DocumentId, Document)> {
let Some(current_id) = self.current_document_id() else {
return Vec::new();
};
self.documents
.document_ids()
.into_iter()
.skip_while(|id| *id != current_id)
.skip(1)
.filter_map(|id| Some((id, self.documents.read(&id)?)))
.collect()
}
pub(crate) fn set_current_document(&mut self, id: DocumentId) {
self.current_document = Some(id);
self.flush();
}
pub(crate) fn set_document_order(&mut self, order: Vec<DocumentId>) {
self.document_order = Some(order);
self.flush();
}
fn flush(&self) {
let data = match ron::ser::to_string_pretty(self, Default::default()) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to serialize persistent data: {e}");
return;
}
};
if let Err(e) = std::fs::write(Self::state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
}
pub(crate) fn load_from_disk(&mut self) {
let path = Self::state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::info!("No persistent data file found at {path:?}, starting fresh");
return;
}
Err(e) => {
tracing::error!("Failed to read persistent data from disk: {e}");
return;
}
};
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
return;
}
};
*self = loaded;
}
fn state_file_path() -> std::path::PathBuf {
let mut path = crate::dirs::app_data_dir();
path.push(crate::consts::APP_STATE_FILE_NAME);
path
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct DocumentStore(Vec<DocumentInfo>);
impl DocumentStore {
fn write(&mut self, id: DocumentId, document: Document) {
let meta = DocumentInfo::new(id, &document);
if let Some(existing) = self.0.iter_mut().find(|meta| meta.id == id) {
*existing = meta;
} else {
self.0.push(meta);
}
if let Err(e) = std::fs::write(Self::document_path(&id), document.content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
fn delete(&mut self, id: &DocumentId) {
self.0.retain(|meta| meta.id != *id);
if let Err(e) = std::fs::remove_file(Self::document_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
pub(crate) fn delete_document(id: &DocumentId) {
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
}
}
fn garbage_collect_document_files(state: &PersistedState) {
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
let directory = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
tracing::error!("Failed to read autosave documents directory: {e}");
return;
}
}
};
fn read(&self, id: &DocumentId) -> Option<Document> {
let meta = self.0.iter().find(|meta| meta.id == *id)?;
let content = std::fs::read_to_string(Self::document_path(id)).ok()?;
Some(Document {
content,
name: meta.name.clone(),
path: meta.path.clone(),
is_saved: meta.is_saved,
})
}
fn force_order(&mut self, desired_order: &Vec<DocumentId>) {
let mut ordered_prefix_len = 0;
for id in desired_order {
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == *id) {
let found_index = ordered_prefix_len + offset;
if found_index != ordered_prefix_len {
self.0[ordered_prefix_len..=found_index].rotate_right(1);
}
ordered_prefix_len += 1;
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && !valid_paths.contains(&path) {
if let Err(e) = std::fs::remove_file(&path) {
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
self.0.truncate(ordered_prefix_len);
}
fn document_ids(&self) -> Vec<DocumentId> {
self.0.iter().map(|meta| meta.id).collect()
}
fn document_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
}
#[derive(serde::Serialize, serde::Deserialize)]
struct DocumentInfo {
id: DocumentId,
name: String,
path: Option<std::path::PathBuf>,
is_saved: bool,
fn state_file_path() -> std::path::PathBuf {
let mut path = crate::dirs::app_data_dir();
path.push(crate::consts::APP_STATE_FILE_NAME);
path
}
impl DocumentInfo {
fn new(id: DocumentId, Document { name, path, is_saved, .. }: &Document) -> Self {
Self {
id,
name: name.clone(),
path: path.clone(),
is_saved: *is_saved,
}
}
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
+8 -8
View File
@@ -26,14 +26,14 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
// FRAGMENT SHADER
// ===============
struct Constants {
struct Immediates {
viewport_scale: vec2<f32>,
viewport_offset: vec2<f32>,
ui_scale: vec2<f32>,
background_color: vec4<f32>,
};
var<push_constant> constants: Constants;
var<immediate> immediates: Immediates;
@group(0) @binding(0)
var t_viewport: texture_2d<f32>;
@@ -46,10 +46,10 @@ var s_diffuse: sampler;
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let ui_coordinate = in.tex_coords * constants.ui_scale;
let ui_coordinate = in.tex_coords * immediates.ui_scale;
if (ui_coordinate.x < 0.0 || ui_coordinate.x > 1.0 ||
ui_coordinate.y < 0.0 || ui_coordinate.y > 1.0) {
return srgb_to_linear(constants.background_color);
return srgb_to_linear(immediates.background_color);
}
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
@@ -60,19 +60,19 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
// UI texture is premultiplied, we need to unpremultiply before blending
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
let viewport_coordinate = (in.tex_coords - constants.viewport_offset) * constants.viewport_scale;
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
viewport_coordinate.y < 0.0 || viewport_coordinate.y > 1.0) {
return srgb_to_linear(constants.background_color);
return srgb_to_linear(immediates.background_color);
}
let overlay_srgb = textureSample(t_overlays, s_diffuse, viewport_coordinate);
var viewport_srgb = textureSample(t_viewport, s_diffuse, viewport_coordinate);
if (viewport_srgb.a < 0.001) {
viewport_srgb = constants.background_color;
viewport_srgb = immediates.background_color;
} else if (viewport_srgb.a < 0.999) {
viewport_srgb = blend(viewport_srgb, constants.background_color);
viewport_srgb = blend(viewport_srgb, immediates.background_color);
}
if (overlay_srgb.a < 0.001) {
+45 -29
View File
@@ -1,8 +1,7 @@
use std::borrow::Cow;
use wgpu::PresentMode;
use crate::window::Window;
use crate::wrapper::{TargetTexture, WgpuContext, WgpuExecutor};
use crate::wrapper::{WgpuContext, WgpuExecutor};
#[derive(derivative::Derivative)]
#[derivative(Debug)]
@@ -19,7 +18,7 @@ pub(crate) struct RenderState {
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
overlays_texture: Option<TargetTexture>,
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
@@ -30,7 +29,7 @@ pub(crate) struct RenderState {
impl RenderState {
pub(crate) fn new(window: &Window, context: WgpuContext, present_mode: Option<PresentMode>) -> Self {
let size = window.surface_size();
let surface = window.create_surface(context.instance.clone());
let surface = window.create_surface(&context.instance);
let surface_caps = surface.get_capabilities(&context.adapter);
let surface_format = surface_caps.formats.iter().find(|f| f.is_srgb()).copied().unwrap_or(surface_caps.formats[0]);
@@ -73,7 +72,7 @@ impl RenderState {
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
@@ -121,11 +120,8 @@ impl RenderState {
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&texture_bind_group_layout],
push_constant_ranges: &[wgpu::PushConstantRange {
stages: wgpu::ShaderStages::FRAGMENT,
range: 0..size_of::<Constants>() as u32,
}],
bind_group_layouts: &[Some(&texture_bind_group_layout)],
immediate_size: size_of::<Immediates>() as u32,
});
let render_pipeline = context.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
@@ -162,7 +158,7 @@ impl RenderState {
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -178,8 +174,8 @@ impl RenderState {
sampler,
desired_width: size.width,
desired_height: size.height,
viewport_scale: [1.0, 1.0],
viewport_offset: [0.0, 0.0],
viewport_scale: [1., 1.],
viewport_offset: [0., 0.],
viewport_texture: None,
overlays_texture: None,
ui_texture: None,
@@ -236,11 +232,17 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = futures::executor::block_on(self.executor.render_vello_scene_to_target_texture(&scene, size, &Default::default(), None, &mut self.overlays_texture));
if let Err(e) = result {
tracing::error!("Error rendering overlays: {:?}", e);
return;
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);
}
Err(e) => {
self.overlays_texture = None;
tracing::error!("Error rendering overlays: {:?}", e);
}
}
self.update_bindgroup();
}
@@ -260,7 +262,17 @@ impl RenderState {
self.render_overlays(scene);
}
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
let (output, suboptimal) = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
// wgpu reports the swapchain no longer matches the underlying surface; present this frame and reconfigure after present, since `Surface::configure` panics while an acquired `SurfaceTexture` is still alive
wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
// Window is minimized or behind another window: skip the frame silently and try again once it becomes visible
wgpu::CurrentSurfaceTexture::Occluded => return Ok(()),
wgpu::CurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
wgpu::CurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
wgpu::CurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
wgpu::CurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
};
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
@@ -281,13 +293,13 @@ impl RenderState {
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_push_constants(
wgpu::ShaderStages::FRAGMENT,
render_pass.set_immediates(
0,
bytemuck::bytes_of(&Constants {
bytemuck::bytes_of(&Immediates {
viewport_scale: self.viewport_scale,
viewport_offset: self.viewport_offset,
ui_scale: ui_scale.unwrap_or([1., 1.]),
@@ -306,6 +318,10 @@ impl RenderState {
window.pre_present_notify();
output.present();
if suboptimal {
self.surface.configure(&self.context.device, &self.config);
}
if ui_scale.is_some() {
return Err(RenderError::OutdatedUITextureError);
}
@@ -317,11 +333,7 @@ impl RenderState {
fn update_bindgroup(&mut self) {
self.surface_outdated = true;
let viewport_texture_view = self.viewport_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let overlays_texture_view = self
.overlays_texture
.as_ref()
.map(|target| Cow::Borrowed(target.view()))
.unwrap_or_else(|| Cow::Owned(self.transparent_texture.create_view(&wgpu::TextureViewDescriptor::default())));
let overlays_texture_view = self.overlays_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let ui_texture_view = self.ui_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let bind_group = self.context.device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -333,7 +345,7 @@ impl RenderState {
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(overlays_texture_view.as_ref()),
resource: wgpu::BindingResource::TextureView(&overlays_texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
@@ -351,14 +363,18 @@ impl RenderState {
}
}
#[derive(Debug)]
pub(crate) enum RenderError {
OutdatedUITextureError,
SurfaceError(wgpu::SurfaceError),
SurfaceLost,
SurfaceOutdated,
SurfaceTimeout,
SurfaceValidation,
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct Constants {
struct Immediates {
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
ui_scale: [f32; 2],
+126
View File
@@ -0,0 +1,126 @@
use interprocess::local_socket::{GenericFilePath, GenericNamespaced, ListenerNonblockingMode, ListenerOptions, Name, prelude::*};
use std::io::{ErrorKind, Read, Write};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use crate::consts::APP_SOCKET_FILE_NAME;
use crate::event::{AppEvent, AppEventScheduler};
// TODO: Needs to be integrated/replaced with the action system.
// TODO: At that point this should just wrap the action, meaning all actions bindable by the user can also be accessed via the socket.
#[derive(serde::Serialize, serde::Deserialize)]
pub(crate) enum Message {
OpenFiles(Vec<std::path::PathBuf>),
}
fn handle_message(message: Message, app_event_scheduler: &AppEventScheduler) {
match message {
Message::OpenFiles(paths) => {
app_event_scheduler.schedule(AppEvent::OpenFiles(paths));
}
}
}
pub(crate) fn send(message: Message) -> std::io::Result<()> {
let data = ron::ser::to_string(&message).map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
let mut connection = interprocess::local_socket::Stream::connect(socket_name())?;
connection.write_all(data.as_bytes())
}
pub(crate) struct SocketHandle {
thread: Option<thread::JoinHandle<()>>,
shutdown_sender: mpsc::Sender<()>,
}
impl Drop for SocketHandle {
fn drop(&mut self) {
let _ = self.shutdown_sender.send(());
let _ = self.thread.take().expect("SocketHandle can only be dropped once").join();
}
}
pub(crate) fn start(app_event_scheduler: AppEventScheduler) -> SocketHandle {
let (shutdown_sender, shutdown_receiver) = mpsc::channel();
let thread = thread::Builder::new()
.name("socket".to_string())
.spawn(move || run(app_event_scheduler, shutdown_receiver))
.expect("Failed to spawn socket thread");
SocketHandle {
shutdown_sender,
thread: Some(thread),
}
}
fn run(app_event_scheduler: AppEventScheduler, shutdown_receiver: mpsc::Receiver<()>) {
let listener = match ListenerOptions::new()
.name(socket_name())
.nonblocking(ListenerNonblockingMode::Accept)
.try_overwrite(true)
.max_spin_time(Duration::from_millis(100))
.create_sync()
{
Ok(listener) => listener,
Err(error) => {
tracing::error!("Failed to bind socket: {}", error);
return;
}
};
let max_backoff = Duration::from_millis(100);
let mut backoff = Duration::ZERO;
loop {
if backoff.is_zero() {
match shutdown_receiver.try_recv() {
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
Err(mpsc::TryRecvError::Empty) => {}
}
backoff = Duration::from_nanos(1);
} else {
match shutdown_receiver.recv_timeout(backoff) {
Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
Err(mpsc::RecvTimeoutError::Timeout) => {}
}
backoff = (backoff * 2).min(max_backoff);
}
match listener.accept() {
Ok(mut connection) => {
backoff = Duration::ZERO;
let app_event_scheduler = app_event_scheduler.clone();
let spawn_result = thread::Builder::new().name("socket-connection".to_string()).spawn(move || {
let mut data = String::new();
if let Err(error) = connection.read_to_string(&mut data) {
tracing::error!("Failed to read socket message: {}", error);
return;
}
match ron::de::from_str(&data) {
Ok(message) => handle_message(message, &app_event_scheduler),
Err(error) => tracing::error!("Failed to deserialize socket message: {}", error),
}
});
if let Err(error) = spawn_result {
tracing::error!("Failed to spawn socket connection thread: {}", error);
}
}
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
Err(error) => {
tracing::error!("Failed to accept socket connection: {}", error);
}
}
}
}
fn socket_name() -> Name<'static> {
if cfg!(target_os = "windows") {
let user = std::env::var("USERNAME").unwrap_or_default();
let name = format!("{user}-{app}-{APP_SOCKET_FILE_NAME}", app = crate::consts::APP_NAME);
name.to_ns_name::<GenericNamespaced>().expect("valid named pipe name")
} else {
crate::dirs::app_data_dir().join(APP_SOCKET_FILE_NAME).to_fs_name::<GenericFilePath>().expect("valid socket path")
}
}
+6 -1
View File
@@ -86,7 +86,7 @@ impl Window {
self.winit_window.request_redraw();
}
pub(crate) fn create_surface(&self, instance: Arc<wgpu::Instance>) -> wgpu::Surface<'static> {
pub(crate) fn create_surface(&self, instance: &wgpu::Instance) -> wgpu::Surface<'static> {
instance.create_surface(self.winit_window.clone()).unwrap()
}
@@ -140,6 +140,11 @@ impl Window {
let _ = self.winit_window.drag_window();
}
pub(crate) fn focus(&self) {
self.winit_window.set_minimized(false);
self.winit_window.focus_window();
}
pub(crate) fn hide(&self) {
self.native_handle.hide();
}
+1 -1
View File
@@ -26,8 +26,8 @@ impl super::NativeWindow for NativeWindowImpl {
}
fn new(_window: &dyn Window, app_event_scheduler: AppEventScheduler) -> Self {
app::setup(app_event_scheduler.clone());
let menu = menu::Menu::new(app_event_scheduler);
NativeWindowImpl { menu }
}
+97 -19
View File
@@ -1,6 +1,75 @@
use objc2::{ClassType, define_class, msg_send};
use objc2_app_kit::{NSApplication, NSEvent, NSEventType, NSResponder};
use objc2_foundation::NSObject;
use std::ffi::CStr;
use std::ffi::OsStr;
use std::ops::Deref;
use std::ops::DerefMut;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::sync::{Mutex, Once};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{ClassType, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSApplication, NSApplicationDelegate, NSEvent, NSEventType, NSResponder};
use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
use crate::event::{AppEvent, AppEventScheduler};
static APP_EVENT_SCHEDULER: Mutex<Option<AppEventScheduler>> = Mutex::new(None);
static PENDING_EVENTS: Mutex<Option<Vec<AppEvent>>> = Mutex::new(Some(Vec::new()));
fn dispatch_event(event: AppEvent) {
let app_event_scheduler_guard = APP_EVENT_SCHEDULER.lock().unwrap();
if let Some(app_event_scheduler) = app_event_scheduler_guard.deref() {
app_event_scheduler.schedule(event);
} else if let Some(pending_events) = PENDING_EVENTS.lock().unwrap().deref_mut() {
pending_events.push(event);
} else {
tracing::error!("Failed to dispatch event");
}
}
fn instance() -> objc2::rc::Retained<NSApplication> {
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
}
static INSTALL_DELEGATE: Once = Once::new();
pub(super) fn init() {
let _ = instance();
INSTALL_DELEGATE.call_once(|| {
let mtm = MainThreadMarker::new().expect("should only ever be called from main thread");
let delegate: Retained<GraphiteApplicationDelegate> = unsafe { msg_send![super(GraphiteApplicationDelegate::alloc(mtm).set_ivars(())), init] };
instance().setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
std::mem::forget(delegate);
});
}
pub(super) fn setup(app_event_scheduler: AppEventScheduler) {
let mut app_event_scheduler_guard = APP_EVENT_SCHEDULER.lock().unwrap();
if let Some(mut pending_events) = PENDING_EVENTS.lock().unwrap().take() {
pending_events.drain(..).for_each(|event| {
app_event_scheduler.schedule(event);
});
} else {
tracing::error!("Failed to take PENDING_EVENTS and schedule them. This a bug.");
}
*app_event_scheduler_guard = Some(app_event_scheduler);
}
pub(super) fn hide() {
instance().hide(None);
}
pub(super) fn hide_others() {
instance().hideOtherApplications(None);
}
pub(super) fn show_all() {
instance().unhideAllApplications(None);
}
define_class!(
#[unsafe(super(NSApplication, NSResponder, NSObject))]
@@ -20,22 +89,31 @@ define_class!(
}
);
fn instance() -> objc2::rc::Retained<NSApplication> {
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "GraphiteApplicationDelegate"]
struct GraphiteApplicationDelegate;
pub(super) fn init() {
let _ = instance();
}
unsafe impl NSObjectProtocol for GraphiteApplicationDelegate {}
pub(super) fn hide() {
instance().hide(None);
}
unsafe impl NSApplicationDelegate for GraphiteApplicationDelegate {
#[unsafe(method(application:openURLs:))]
fn application_open_urls(&self, _application: &NSApplication, urls: &NSArray<NSURL>) {
let paths = (0..urls.count())
.filter_map(|index| {
let url = urls.objectAtIndex(index);
if !url.isFileURL() {
tracing::error!("Ignoring open URL event for non-file URL: {:?}", url);
return None;
}
let cstr = unsafe { CStr::from_ptr(url.fileSystemRepresentation().as_ptr()) };
let path = PathBuf::from(OsStr::from_bytes(cstr.to_bytes()));
Some(path)
})
.collect::<Vec<_>>();
pub(super) fn hide_others() {
instance().hideOtherApplications(None);
}
pub(super) fn show_all() {
instance().unhideAllApplications(None);
}
dispatch_event(AppEvent::OpenFiles(paths));
}
}
);
+30 -12
View File
@@ -61,9 +61,9 @@ impl NativeWindowHandle {
0,
0,
0,
main,
Some(main),
None,
None,
HINSTANCE(std::ptr::null_mut()),
// Pass the main window's HWND to WM_NCCREATE so the helper can store it.
Some(&main as *const _ as _),
)
@@ -72,7 +72,7 @@ impl NativeWindowHandle {
// Subclass the main window.
// https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-setwindowlongptra
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as isize) };
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as *const () as isize) };
if prev_window_message_handler == 0 {
let _ = unsafe { DestroyWindow(helper) };
panic!("SetWindowLongPtrW failed");
@@ -103,18 +103,36 @@ impl NativeWindowHandle {
};
let _ = unsafe { DwmExtendFrameIntoClientArea(main, &margins) };
let hinst = unsafe { GetModuleHandleW(None) }.unwrap();
let hinst: HINSTANCE = unsafe { GetModuleHandleW(None) }.unwrap().into();
// Set taskbar icon
if let Ok(big) = unsafe { LoadImageW(hinst, PCWSTR(1usize as *const u16), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_SHARED) } {
if let Ok(big) = unsafe {
LoadImageW(
Some(hinst),
PCWSTR(1usize as *const u16),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON),
LR_SHARED,
)
} {
unsafe { SetClassLongPtrW(main, GCLP_HICON, big.0 as isize) };
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_BIG as usize), LPARAM(big.0 as isize)) };
unsafe { SendMessageW(main, WM_SETICON, Some(WPARAM(ICON_BIG as usize)), Some(LPARAM(big.0 as isize))) };
}
// Set window icon
if let Ok(small) = unsafe { LoadImageW(hinst, PCWSTR(1usize as *const u16), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED) } {
if let Ok(small) = unsafe {
LoadImageW(
Some(hinst),
PCWSTR(1usize as *const u16),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
LR_SHARED,
)
} {
unsafe { SetClassLongPtrW(main, GCLP_HICONSM, small.0 as isize) };
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_SMALL as usize), LPARAM(small.0 as isize)) };
unsafe { SendMessageW(main, WM_SETICON, Some(WPARAM(ICON_SMALL as usize)), Some(LPARAM(small.0 as isize))) };
}
// Force window update
@@ -197,7 +215,7 @@ unsafe fn ensure_helper_class() {
lpfnWndProc: Some(helper_window_handle_message),
hInstance: unsafe { GetModuleHandleW(None).unwrap().into() },
hIcon: HICON::default(),
hCursor: unsafe { LoadCursorW(HINSTANCE(std::ptr::null_mut()), IDC_ARROW).unwrap() },
hCursor: unsafe { LoadCursorW(None, IDC_ARROW).unwrap() },
// No painting; the ring is invisible.
hbrBackground: HBRUSH::default(),
lpszClassName: PCWSTR(class_name.as_ptr()),
@@ -292,7 +310,7 @@ unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wpa
// Extract the main window's HWND from GWLP_USERDATA that we saved earlier.
let main_ptr = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as *mut std::ffi::c_void;
let main = HWND(main_ptr);
if unsafe { IsWindow(main).as_bool() } {
if unsafe { IsWindow(Some(main)).as_bool() } {
let Some(wmsz) = (unsafe { calculate_resize_direction(hwnd, lparam) }) else {
return LRESULT(0);
};
@@ -301,7 +319,7 @@ unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wpa
let _ = unsafe { SetForegroundWindow(main) };
// Start sizing on the main window in the calculated direction. (SC_SIZE + WMSZ_*)
let _ = unsafe { PostMessageW(main, WM_SYSCOMMAND, WPARAM((SC_SIZE + wmsz) as usize), lparam) };
let _ = unsafe { PostMessageW(Some(main), WM_SYSCOMMAND, WPARAM((SC_SIZE + wmsz) as usize), lparam) };
}
return LRESULT(0);
}
@@ -325,7 +343,7 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
let w = (r.right - r.left) + RESIZE_BAND_THICKNESS * 2;
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
let _ = unsafe { SetWindowPos(helper, main, x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
+1 -4
View File
@@ -13,16 +13,13 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
graphite-editor = { path = "../../editor", features = [
"gpu",
] }
graphite-editor = { workspace = true }
graphene-std = { workspace = true }
graph-craft = { workspace = true }
wgpu-executor = { workspace = true }
wgpu = { workspace = true }
thiserror = { workspace = true }
futures = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
ron = { workspace = true}
@@ -9,6 +9,9 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
DesktopWrapperMessage::FromWeb(message) => {
dispatcher.queue_editor_message(*message);
}
DesktopWrapperMessage::Wake => {
dispatcher.queue_editor_message(EditorMessage::Future(FutureMessage::Wake));
}
DesktopWrapperMessage::Input(message) => {
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
}
@@ -49,26 +52,12 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocument {
id,
document,
to_front,
select_after_open,
} => {
let message = PortfolioMessage::OpenDocumentFileWithId {
document_id: id,
document_name: Some(document.name),
document_path: document.path,
document_serialized_content: document.content,
document_is_auto_saved: true,
document_is_saved: document.is_saved,
to_front,
select_after_open,
};
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::SelectDocument { id } => {
let message = PortfolioMessage::SelectDocument { document_id: id };
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPreferences { preferences } => {
@@ -3,7 +3,7 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
use graphite_editor::messages::prelude::FrontendMessage;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
@@ -14,6 +14,7 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Open Document".to_string(),
filters: vec![],
multiple: true,
context: OpenFileDialogContext::Open,
});
}
@@ -21,6 +22,7 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters: vec![],
multiple: false,
context: OpenFileDialogContext::Import,
});
}
@@ -67,39 +69,23 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
dispatcher.respond(DesktopFrontendMessage::UpdateUIScale { scale });
return Some(FrontendMessage::UpdateUIScale { scale });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document, details } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document: Document {
name: details.name,
path: details.path,
content: document,
is_saved: details.is_saved,
},
});
FrontendMessage::TriggerPersistenceReadState => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadState);
}
FrontendMessage::TriggerPersistenceRemoveDocument { document_id } => {
FrontendMessage::TriggerPersistenceWriteState { state } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
}
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::UpdateActiveDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id: document_id });
// Forward this to update the UI
return Some(FrontendMessage::UpdateActiveDocument { document_id });
}
FrontendMessage::UpdateOpenDocumentsList { open_documents } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateDocumentsList {
ids: open_documents.iter().map(|document| document.id).collect(),
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
});
// Forward this to update the UI
return Some(FrontendMessage::UpdateOpenDocumentsList { open_documents });
}
FrontendMessage::TriggerLoadFirstAutoSaveDocument => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadCurrentDocument);
}
FrontendMessage::TriggerLoadRestAutoSaveDocuments => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadRemainingDocuments);
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
@@ -153,6 +139,9 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::WindowDrag => {
dispatcher.respond(DesktopFrontendMessage::WindowDrag);
}
FrontendMessage::WindowFocus => {
dispatcher.respond(DesktopFrontendMessage::WindowFocus);
}
FrontendMessage::WindowHide => {
dispatcher.respond(DesktopFrontendMessage::WindowHide);
}
+11 -12
View File
@@ -1,11 +1,14 @@
use graph_craft::wasm_application_io::WasmApplicationIo;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message};
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake};
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
pub use graphite_editor::consts::FILE_EXTENSION;
pub use wgpu_executor::TargetTexture;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
pub use wgpu_executor::WgpuExecutor;
@@ -23,7 +26,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -31,17 +34,13 @@ impl DesktopWrapper {
#[cfg(target_os = "linux")]
let host = Host::Linux;
let env = Environment { platform: Platform::Desktop, host };
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed),
editor: Editor::new(env, uuid_random_seed, resource_storage, application_io, schedule_wake),
}
}
pub fn init(&self, wgpu_context: WgpuContext) {
let application_io = WasmApplicationIo::new_with_context(wgpu_context);
futures::executor::block_on(graphite_editor::node_graph_executor::replace_application_io(application_io));
}
pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec<DesktopFrontendMessage> {
let mut executor = DesktopWrapperMessageDispatcher::new(&mut self.editor);
executor.queue_desktop_wrapper_message(message);
@@ -51,7 +50,7 @@ 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(|t| t.texture)),
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
+26 -65
View File
@@ -3,6 +3,7 @@ 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::prelude::DocumentId;
@@ -15,6 +16,7 @@ pub enum DesktopFrontendMessage {
OpenFileDialog {
title: String,
filters: Vec<FileFilter>,
multiple: bool,
context: OpenFileDialogContext,
},
SaveFileDialog {
@@ -41,23 +43,22 @@ pub enum DesktopFrontendMessage {
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document: Document,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceUpdateCurrentDocument {
id: DocumentId,
},
PersistenceLoadCurrentDocument,
PersistenceLoadRemainingDocuments,
PersistenceUpdateDocumentsList {
ids: Vec<DocumentId>,
},
PersistenceWritePreferences {
preferences: Preferences,
},
PersistenceLoadPreferences,
PersistenceWriteState {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -71,6 +72,7 @@ pub enum DesktopFrontendMessage {
WindowMaximize,
WindowFullscreen,
WindowDrag,
WindowFocus,
WindowHide,
WindowHideOthers,
WindowShowAll,
@@ -80,64 +82,22 @@ pub enum DesktopFrontendMessage {
pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Wake,
Input(InputMessage),
FileDialogResult {
path: PathBuf,
content: Vec<u8>,
context: OpenFileDialogContext,
},
SaveFileDialogResult {
path: PathBuf,
context: SaveFileDialogContext,
},
OpenFile {
path: PathBuf,
content: Vec<u8>,
},
ImportFile {
path: PathBuf,
content: Vec<u8>,
},
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
OpenFile { path: PathBuf, content: Vec<u8> },
ImportFile { path: PathBuf, content: Vec<u8> },
PollNodeGraphEvaluation,
UpdateMaximized {
maximized: bool,
},
UpdateFullscreen {
fullscreen: bool,
},
LoadDocument {
id: DocumentId,
document: Document,
to_front: bool,
select_after_open: bool,
},
SelectDocument {
id: DocumentId,
},
LoadPreferences {
preferences: Preferences,
},
MenuEvent {
id: String,
},
ClipboardReadResult {
content: Option<String>,
},
PointerLockMove {
x: f64,
y: f64,
},
LoadThirdPartyLicenses {
text: String,
},
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct Document {
pub content: String,
pub name: String,
pub path: Option<PathBuf>,
pub is_saved: bool,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
LoadDocumentContent { id: DocumentId, document: String },
LoadPersistedState { state: PersistedState },
LoadPreferences { preferences: Preferences },
MenuEvent { id: String },
ClipboardReadResult { content: Option<String> },
PointerLockMove { x: f64, y: f64 },
LoadThirdPartyLicenses { text: String },
}
pub struct FileFilter {
@@ -145,6 +105,7 @@ pub struct FileFilter {
pub extensions: Vec<String>,
}
#[derive(Clone, Copy)]
pub enum OpenFileDialogContext {
Open,
Import,
+48
View File
@@ -0,0 +1,48 @@
[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
[features]
default = []
zip = ["dep:zip"]
xz = ["dep:lzma-rust2", "dep:tar"]
[dependencies]
thiserror = "2.0"
log = { workspace = true }
zip = { workspace = true, optional = true, features = ["deflate-flate2-zlib-rs"], default-features = false}
lzma-rust2 = { workspace = true, optional = true }
tar = { version = "0.4", optional = true, default-features = false }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
mmap-io = { workspace = true }
[target.'cfg(target_family = "wasm")'.dependencies]
web-sys = { workspace = true, features = [
"Navigator",
"DomException",
"Window",
"StorageManager",
"FileSystemCreateWritableOptions",
"FileSystemDirectoryHandle",
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
"WritableStream",
"Blob",
] }
js-sys = { workspace = true }
wasm-bindgen = { workspace = true }
wasm-bindgen-futures = { workspace = true }
futures = { workspace = true }
[dev-dependencies]
tempfile = "3"
futures = { workspace = true }
+114
View File
@@ -0,0 +1,114 @@
//! Archive codecs (zip, xz).
//!
//! Each codec streams entries in both directions: writers wrap an `io::Write` sink, and
//! `deserialize` reads from any `io::Read + Seek` source and streams entries into any [`Container`].
#[cfg(any(feature = "xz", feature = "zip"))]
use crate::AsyncContainer;
#[cfg(any(feature = "zip", feature = "xz"))]
use crate::ContainerError;
use crate::Result;
use std::io::{Read, Seek, Write};
/// Hard cap on the total decompressed size a codec will materialize from one archive.
/// Defends against decompression bombs at the cost of refusing legitimately huge archives.
#[cfg(any(feature = "zip", feature = "xz"))]
pub(crate) const MAX_DECOMPRESSED_SIZE: u64 = 4 * 1024 * 1024 * 1024; // 4GB
/// Fold one entry's declared `size` into the running `total` and return it as a `usize` for `write_sized`.
/// Both codecs route entries through here so the decompression-bomb cap and 32-bit-safe conversion live in
/// one place. `write_sized` pre-allocates the declared size, so an over-large one is rejected before that.
#[cfg(any(feature = "zip", feature = "xz"))]
pub(crate) fn checked_entry_size(total: &mut u64, size: u64) -> Result<usize> {
*total = total.saturating_add(size);
if *total > MAX_DECOMPRESSED_SIZE {
return Err(ContainerError::SizeLimitExceeded {
declared: *total,
limit: MAX_DECOMPRESSED_SIZE,
});
}
// `usize` is 32-bit on wasm, so convert fallibly to rule out a silent truncation into a smaller allocation.
usize::try_from(size).map_err(|_| ContainerError::SizeLimitExceeded {
declared: size,
limit: usize::MAX as u64,
})
}
#[cfg(feature = "zip")]
mod zip;
#[cfg(feature = "zip")]
pub use zip::{Zip, ZipWriter};
#[cfg(feature = "xz")]
mod xz;
#[cfg(feature = "xz")]
pub use xz::{Xz, XzWriter};
/// Streaming archive codec. The associated `Writer` type wraps a `Write + Seek` sink (zip needs
/// `Seek` for the central directory; xz doesn't but `Seek` is free on file-like sinks) and
/// accepts entries one at a time. `finish` flushes the codec's trailer and consumes the wrapper.
pub trait Archive {
type Writer<W: Write + Seek>: ArchiveWriter
where
W: Write + Seek;
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>>;
/// Read entries from `source` and write each into `dest`, streaming so neither the full
/// archive nor the full container ever sits in memory at once.
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()>;
}
pub trait ArchiveWriter: Sized {
type Sink;
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()>;
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
fn finish_into(self) -> Result<Self::Sink>;
/// Finish the archive, discarding the sink. For file-backed archives the bytes are already on disk.
fn finish(self) -> Result<()> {
self.finish_into()?;
Ok(())
}
}
/// Archive container formats distinguishable by their leading magic bytes.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ArchiveFormat {
Xz,
Zip,
}
impl ArchiveFormat {
/// Sniff the format from the leading magic bytes: xz streams start with `FD 37 7A 58 5A 00`,
/// zip archives with `50 4B 03 04` (`PK\x03\x04`). Returns `None` for anything else.
pub fn detect(bytes: &[u8]) -> Option<Self> {
if bytes.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
Some(Self::Xz)
} else if bytes.starts_with(&[0x50, 0x4B, 0x03, 0x04]) {
Some(Self::Zip)
} else {
None
}
}
}
/// Deserialize an archive into `dest`, auto-detecting the format from `bytes`' magic header.
/// Errors if the bytes are neither a recognized xz nor zip archive.
#[cfg(any(feature = "xz", feature = "zip"))]
pub fn open_auto<C: AsyncContainer>(bytes: &[u8], dest: &mut C) -> Result<()> {
let source = std::io::Cursor::new(bytes);
match ArchiveFormat::detect(bytes) {
#[cfg(feature = "xz")]
Some(ArchiveFormat::Xz) => Xz::open(source, dest),
#[cfg(feature = "zip")]
Some(ArchiveFormat::Zip) => Zip::open(source, dest),
#[allow(unreachable_patterns)]
Some(format) => Err(ContainerError::Codec(format!("tried to open {format:?}, but the binary was compiled without the feature enabled "))),
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip) ".into())),
}
}
+92
View File
@@ -0,0 +1,92 @@
//! Xz-compressed tarball archive codec.
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size};
use crate::{AsyncContainer, ContainerError, Result, validate_path};
use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter};
use std::io::{Read, Seek, Write};
pub struct Xz;
/// xz-tar writer. Held as an `Option` so `finish` can take ownership and unwind the layered
/// writers in the right order: drop the tar builder first to flush its trailer, then finish xz.
pub struct XzWriter<W: Write + Seek> {
tar: Option<tar::Builder<InnerXzWriter<W>>>,
}
impl Archive for Xz {
type Writer<W: Write + Seek> = XzWriter<W>;
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>> {
let xz_writer = InnerXzWriter::new(output, XzOptions::default()).map_err(lzma_err)?;
Ok(XzWriter {
tar: Some(tar::Builder::new(xz_writer)),
})
}
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
// `take` bounds how many bytes we decompress from the xz stream, but each tar entry's declared
// size is fed to `write_sized`, which pre-allocates from it before reading. Cap the cumulative
// declared size too so a header claiming a huge size can't trigger a giant allocation up front.
let xz_reader = XzReader::new(source, false);
let bounded = xz_reader.take(MAX_DECOMPRESSED_SIZE);
let mut tar_reader = tar::Archive::new(bounded);
let mut total_size = 0u64;
for entry in tar_reader.entries()? {
let mut entry = entry?;
if entry.header().entry_type() != tar::EntryType::Regular {
continue;
}
// Reject non-UTF8 entry names rather than lossily rewriting them, so the path we store matches
// the archive exactly.
let path = entry.path()?;
let path = path.to_str().ok_or_else(|| ContainerError::Codec(format!("tar: non-UTF8 entry name {path:?}")))?.to_owned();
validate_path(&path)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
dest.write_sized_non_blocking(&path, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(())
})?;
}
Ok(())
}
}
impl<W: Write + Seek> ArchiveWriter for XzWriter<W> {
type Sink = W;
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
let tar = self.tar.as_mut().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
let mut header = tar::Header::new_gnu();
header.set_path(path).map_err(|error| ContainerError::Codec(format!("tar: invalid path {path}: {error}")))?;
header.set_size(bytes.len() as u64);
header.set_mode(0o644);
header.set_cksum();
tar.append(&header, bytes)?;
Ok(())
}
fn finish_into(mut self) -> Result<W> {
self.finish_inner()
}
}
impl<W: Write + Seek> XzWriter<W> {
/// Unwind the layered writers in order (flush the tar trailer, then finish xz) and hand back the
/// innermost sink.
fn finish_inner(&mut self) -> Result<W> {
let mut tar = self.tar.take().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
tar.finish()?;
let xz_writer = tar.into_inner()?;
xz_writer.finish().map_err(lzma_err)
}
}
fn lzma_err(error: std::io::Error) -> ContainerError {
ContainerError::Codec(format!("lzma: {error}"))
}
+76
View File
@@ -0,0 +1,76 @@
//! Zip archive codec.
use crate::archive::{Archive, ArchiveWriter, checked_entry_size};
use crate::{AsyncContainer, ContainerError, Result, validate_path};
use std::io::{Read, Seek, Write};
use zip::ZipArchive;
use zip::write::{SimpleFileOptions, ZipWriter as InnerZipWriter};
pub struct Zip;
pub struct ZipWriter<W: Write + Seek> {
inner: InnerZipWriter<W>,
options: SimpleFileOptions,
}
impl Archive for Zip {
type Writer<W: Write + Seek> = ZipWriter<W>;
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>> {
Ok(ZipWriter {
inner: InnerZipWriter::new(output),
options: SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated),
})
}
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
let mut archive = ZipArchive::new(source).map_err(zip_err)?;
// Zip headers declare each entry's uncompressed size up front; `checked_entry_size` caps the running
// total so a malicious archive can't exhaust memory or disk before any bytes are read.
let mut total_size = 0u64;
for index in 0..archive.len() {
let mut entry = archive.by_index(index).map_err(zip_err)?;
if !entry.is_file() {
continue;
}
let name = entry.name().to_string();
validate_path(&name)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
dest.write_sized_non_blocking(&name, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(())
})?;
}
Ok(())
}
}
impl<W: Write + Seek> ArchiveWriter for ZipWriter<W> {
type Sink = W;
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.inner.start_file(path, self.options).map_err(zip_err)?;
self.inner.write_all(bytes)?;
Ok(())
}
fn finish_into(self) -> Result<W> {
self.inner.finish().map_err(zip_err)
}
}
fn zip_err(error: zip::result::ZipError) -> ContainerError {
// Preserve a real I/O failure (disk full, etc.) as a structured `Io` so callers can tell it apart from a
// corrupt-archive `Codec` error; only the genuinely archive-format errors collapse into `Codec`.
match error {
zip::result::ZipError::Io(io) => ContainerError::Io(io),
other => ContainerError::Codec(format!("zip: {other}")),
}
}
+9
View File
@@ -0,0 +1,9 @@
//! Container backend implementations.
pub mod memory;
#[cfg(not(target_family = "wasm"))]
pub mod folder;
#[cfg(target_family = "wasm")]
pub mod opfs;
+191
View File
@@ -0,0 +1,191 @@
//! Loose-folder backend.
use crate::{ByteHolder, Container, ContainerError, MmappedBytes, Result, validate_path, validate_prefix};
use mmap_io::mmap::{MemoryMappedFile, MmapMode};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
pub struct FolderBackend {
root: PathBuf,
}
impl FolderBackend {
/// Open an existing folder. Errors if `root` is not a directory.
pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
if !root.is_dir() {
return Err(ContainerError::NotFound(root.display().to_string()));
}
Ok(Self { root })
}
/// Create the folder if it does not exist, then open it.
pub fn create(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
fs::create_dir_all(&root)?;
Ok(Self { root })
}
pub fn root(&self) -> &std::path::Path {
&self.root
}
fn resolve(&self, path: &str) -> Result<PathBuf> {
validate_path(path)?;
self.reject_symlinked_components(path)?;
Ok(self.root.join(path))
}
/// Reject any existing component along `root/relative` that is a symlink. `validate_path`/`validate_prefix`
/// block `..` and absolute paths, but a symlink stored under the root could still point outside it, so every
/// path that gets joined onto the root must pass through here before it is opened or traversed.
fn reject_symlinked_components(&self, relative: &str) -> Result<()> {
let mut partial = self.root.clone();
for component in Path::new(relative).components() {
partial.push(component);
if let Ok(metadata) = fs::symlink_metadata(&partial)
&& metadata.file_type().is_symlink()
{
return Err(ContainerError::InvalidPath(relative.to_string()));
}
}
Ok(())
}
fn list_filtered(&self, prefix: &str, want_files: bool) -> Result<Vec<String>> {
validate_prefix(prefix)?;
let base = if prefix.is_empty() || prefix == "." {
self.root.clone()
} else {
self.reject_symlinked_components(prefix)?;
self.root.join(prefix)
};
// A missing prefix has no entries; a prefix that names a file is a misuse.
if base.is_file() {
return Err(ContainerError::NotADirectory(prefix.to_string()));
}
if !base.is_dir() {
return Ok(Vec::new());
}
let mut results = Vec::new();
for entry in fs::read_dir(&base)? {
let entry = entry?;
// `file_type` does not follow symlinks, unlike `is_file`/`is_dir`. Skip symlink entries so a
// listing never advertises a path that `resolve` would then reject as a container escape.
let Ok(file_type) = entry.file_type() else { continue };
let matches = if want_files { file_type.is_file() } else { file_type.is_dir() };
if !matches {
continue;
}
let path = entry.path();
let relative = path.strip_prefix(&self.root).map_err(|_| ContainerError::Backend("path escaped root".into()))?;
results.push(relative.to_string_lossy().replace('\\', "/"));
}
Ok(results)
}
}
impl Container for FolderBackend {
fn read(&self, path: &str) -> Result<ByteHolder> {
let full = self.resolve(path)?;
if !full.is_file() {
return Err(ContainerError::NotFound(path.to_string()));
}
// Mmapping a zero-length file is platform-dependent and often fails, so serve empty files as owned
// bytes and reserve mmap for files that actually have content.
if fs::metadata(&full).map(|metadata| metadata.len() == 0).unwrap_or(false) {
return Ok(ByteHolder::Owned(Vec::new()));
}
Ok(ByteHolder::Mmapped(MmappedBytes::new(open_mmap(&full)?)?))
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
let full = self.resolve(path)?;
if let Some(parent) = full.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&full, bytes)?;
Ok(())
}
fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
let full = self.resolve(path)?;
if let Some(parent) = full.parent() {
fs::create_dir_all(parent)?;
}
let mut file = OpenOptions::new().create(true).append(true).open(&full)?;
file.write_all(bytes)?;
Ok(())
}
fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
if size == 0 {
return self.write(path, &[]);
}
let full = self.resolve(path)?;
if let Some(parent) = full.parent() {
fs::create_dir_all(parent)?;
}
let file = MemoryMappedFile::create_rw(&full, size as u64).map_err(|error| ContainerError::Backend(format!("create_rw {full:?} failed: {error}")))?;
let result = {
let mut slice = file
.as_slice_mut(0, size as u64)
.map_err(|error| ContainerError::Backend(format!("as_slice_mut {full:?} failed: {error}")))?;
fill(slice.as_mut())?;
drop(slice);
file.flush().map_err(|error| ContainerError::Backend(format!("flush {full:?} failed: {error}")))
};
// `create_rw` materializes the full-size file before `fill` runs, so remove it on failure rather
// than leave a zeroed or half-written remnant.
if result.is_err() {
drop(file);
let _ = fs::remove_file(&full);
}
result
}
fn list(&self, prefix: &str) -> Result<Vec<String>> {
self.list_filtered(prefix, true)
}
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
self.list_filtered(prefix, false)
}
fn exists(&self, path: &str) -> bool {
match self.resolve(path) {
Ok(full) => full.is_file(),
Err(_) => false,
}
}
fn remove(&self, path: &str) -> Result<()> {
let full = self.resolve(path)?;
// Idempotent: a missing file is not an error. Directories are left alone.
if full.is_file() {
fs::remove_file(full)?;
}
// TODO: decide if we should remove empty parent directories
Ok(())
}
}
/// Open a memory-mapped read-only view of `path`, trying huge pages first. Callers must ensure `path`
/// is non-empty, since mmapping a zero-length file is platform-dependent.
fn open_mmap(path: &Path) -> Result<MemoryMappedFile> {
match MemoryMappedFile::builder(path).mode(MmapMode::ReadOnly).huge_pages(true).open() {
Ok(file) => Ok(file),
Err(_) => MemoryMappedFile::open_ro(path).map_err(|error| ContainerError::Backend(format!("mmap of {path:?} failed: {error}"))),
}
}
+89
View File
@@ -0,0 +1,89 @@
//! In-memory backend. Useful for tests and as the deserialize target for archive codecs.
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
#[derive(Default)]
pub struct MemoryBackend {
files: Mutex<HashMap<String, Vec<u8>>>,
}
impl MemoryBackend {
pub fn new() -> Self {
Self::default()
}
}
impl Container for MemoryBackend {
fn read(&self, path: &str) -> Result<ByteHolder> {
validate_path(path)?;
self.files
.lock()
.unwrap()
.get(path)
.map(|bytes| ByteHolder::Owned(bytes.clone()))
.ok_or_else(|| ContainerError::NotFound(path.to_string()))
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.files.lock().unwrap().insert(path.to_string(), bytes.to_vec());
Ok(())
}
fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.files.lock().unwrap().entry(path.to_string()).or_default().extend_from_slice(bytes);
Ok(())
}
fn list(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
let files = self.files.lock().unwrap();
// A prefix that is itself a stored key names a file, not a directory.
if files.contains_key(prefix) {
return Err(ContainerError::NotADirectory(prefix.to_string()));
}
let normalized = with_trailing_slash(prefix);
let results = files.keys().filter(|path| path.starts_with(&normalized) && !path[normalized.len()..].contains('/')).cloned().collect();
Ok(results)
}
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
let files = self.files.lock().unwrap();
if files.contains_key(prefix) {
return Err(ContainerError::NotADirectory(prefix.to_string()));
}
let normalized = with_trailing_slash(prefix);
let mut seen = HashSet::new();
let mut results = Vec::new();
for path in files.keys() {
if !path.starts_with(&normalized) {
continue;
}
let remainder = &path[normalized.len()..];
if let Some((segment, _)) = remainder.split_once('/') {
let dir = format!("{normalized}{segment}");
if seen.insert(dir.clone()) {
results.push(dir);
}
}
}
Ok(results)
}
fn exists(&self, path: &str) -> bool {
validate_path(path).is_ok() && self.files.lock().unwrap().contains_key(path)
}
fn remove(&self, path: &str) -> Result<()> {
validate_path(path)?;
// Idempotent: removing a missing path is not an error.
self.files.lock().unwrap().remove(path);
Ok(())
}
}
+475
View File
@@ -0,0 +1,475 @@
//! OPFS (Origin Private File System) backend for browser wasm.
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use futures::channel::oneshot;
use js_sys::Uint8Array;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{
Blob, DomException, FileSystemCreateWritableOptions, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, FileSystemWritableFileStream,
WritableStream,
};
enum Mutation {
Write {
path: String,
bytes: Vec<u8>,
},
Append {
path: String,
bytes: Vec<u8>,
},
Delete {
path: String,
},
/// In-band flush barrier. The worker fulfills the sender once it dequeues this, which (by FIFO
/// order) signals that every mutation enqueued before it has been applied to disk.
Barrier(oneshot::Sender<()>),
}
struct Inner {
directory: FileSystemDirectoryHandle,
/// Paths believed to be on disk, letting `exists_non_blocking` answer without OPFS's missing sync API.
/// Optimistic: a path is inserted when its write is queued and kept even if that write later fails, so it
/// can briefly over-report. Rebuilt from real disk state on the next `open`.
on_disk: HashSet<String>,
queue: VecDeque<Mutation>,
worker_active: bool,
}
pub struct OpfsBackend {
inner: Arc<Mutex<Inner>>,
}
// Safety: only built for browser wasm where JS handles never leave the main thread.
unsafe impl Send for OpfsBackend {}
unsafe impl Sync for OpfsBackend {}
impl OpfsBackend {
/// Open (or create) `directory_name` under the OPFS root.
pub async fn open(directory_name: &str) -> Result<Self> {
let directory = open_directory(directory_name).await.map_err(js_err)?;
let on_disk = enumerate_paths(&directory, "").await.map_err(js_err)?;
Ok(Self {
inner: Arc::new(Mutex::new(Inner {
directory,
on_disk,
queue: VecDeque::new(),
worker_active: false,
})),
})
}
fn directory(&self) -> FileSystemDirectoryHandle {
self.inner.lock().unwrap().directory.clone()
}
/// Wait until all queued non-blocking mutations have hit disk, so awaited reads observe them. Plants a
/// barrier at the back of the queue and awaits the worker reaching it; by FIFO order, everything ahead is
/// then applied. Draining stays the worker's job so it remains the sole mutator.
async fn flush(&self) {
let (sender, receiver) = oneshot::channel();
{
let mut guard = self.inner.lock().unwrap();
guard.queue.push_back(Mutation::Barrier(sender));
kick_worker(&self.inner, &mut guard);
}
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
// there is nothing left to wait for, so a receive error is treated as "already flushed".
let _ = receiver.await;
}
}
impl AsyncContainer for OpfsBackend {
async fn read(&self, path: &str) -> Result<ByteHolder> {
validate_path(path)?;
// Non-blocking writes only land on disk once the queue drains, so flush first and then treat
// disk as authoritative. Draining (rather than folding the queue against an awaited base read)
// avoids racing the background worker, which could otherwise double-apply a queued append.
self.flush().await;
let bytes = read_file(&self.directory(), path).await.map_err(js_err)?;
Ok(ByteHolder::Owned(bytes))
}
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
// Flush first so this awaited write lands after any non-blocking mutation already queued for the
// same path, then apply directly so the real disk error still propagates to the caller.
self.flush().await;
write_file(&self.directory(), path, bytes).await.map_err(js_err)?;
self.inner.lock().unwrap().on_disk.insert(path.to_string());
Ok(())
}
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
self.flush().await;
append_file(&self.directory(), path, bytes).await.map_err(js_err)?;
self.inner.lock().unwrap().on_disk.insert(path.to_string());
Ok(())
}
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
validate_path(path)?;
let mut buffer = vec![0; size];
fill(&mut buffer)?;
self.flush().await;
write_file(&self.directory(), path, &buffer).await.map_err(js_err)?;
self.inner.lock().unwrap().on_disk.insert(path.to_string());
Ok(())
}
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
self.flush().await;
list_entries(&self.directory(), prefix, EntryKind::File).await.map_err(|error| list_error(prefix, error))
}
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
validate_prefix(prefix)?;
self.flush().await;
list_entries(&self.directory(), prefix, EntryKind::Directory).await.map_err(|error| list_error(prefix, error))
}
async fn exists(&self, path: &str) -> bool {
if validate_path(path).is_err() {
return false;
}
self.flush().await;
file_exists(&self.directory(), path).await
}
async fn remove(&self, path: &str) -> Result<()> {
validate_path(path)?;
self.flush().await;
// Idempotent: a missing entry is not an error, matching the other backends.
if let Err(error) = remove_file(&self.directory(), path).await
&& !is_not_found(&error)
{
return Err(js_err(error));
}
self.inner.lock().unwrap().on_disk.remove(path);
Ok(())
}
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
let mut guard = self.inner.lock().unwrap();
guard.on_disk.insert(path.to_string());
guard.queue.push_back(Mutation::Write {
path: path.to_string(),
bytes: bytes.to_vec(),
});
kick_worker(&self.inner, &mut guard);
Ok(())
}
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
validate_path(path)?;
let mut guard = self.inner.lock().unwrap();
guard.on_disk.insert(path.to_string());
guard.queue.push_back(Mutation::Append {
path: path.to_string(),
bytes: bytes.to_vec(),
});
kick_worker(&self.inner, &mut guard);
Ok(())
}
fn remove_non_blocking(&self, path: &str) -> Result<()> {
validate_path(path)?;
let mut guard = self.inner.lock().unwrap();
guard.on_disk.remove(path);
guard.queue.push_back(Mutation::Delete { path: path.to_string() });
kick_worker(&self.inner, &mut guard);
Ok(())
}
fn exists_non_blocking(&self, path: &str) -> bool {
validate_path(path).is_ok() && self.inner.lock().unwrap().on_disk.contains(path)
}
}
fn kick_worker(inner: &Arc<Mutex<Inner>>, guard: &mut Inner) {
if guard.worker_active {
return;
}
guard.worker_active = true;
let inner = inner.clone();
spawn_local(drain_queue(inner));
}
/// Apply every queued mutation to disk, in FIFO order, until the queue is empty, then mark the worker
/// idle. Spawned once via [`kick_worker`] and runs as the sole mutator; the awaited read paths wait on
/// a [`Mutation::Barrier`] rather than draining themselves, so there is never more than one drainer.
///
/// Consecutive appends to the same path are coalesced into one combined append. Each `createWritable`
/// on OPFS copies the whole existing file, so appending N frames one at a time is O(N^2) in bytes
/// copied (every per-op autosave queues one append per hot op). Concatenating a run into a single
/// append collapses that to one file copy, while staying byte-identical to applying them in order.
async fn drain_queue(inner: Arc<Mutex<Inner>>) {
loop {
// Pop the front mutation, coalescing a run of same-path appends behind it into one batch.
let (directory, mutation) = {
let mut guard = inner.lock().unwrap();
let Some(mut mutation) = guard.queue.pop_front() else {
guard.worker_active = false;
return;
};
if let Mutation::Append { path, bytes } = &mut mutation {
while let Some(Mutation::Append { path: next_path, .. }) = guard.queue.front()
&& next_path == path
{
let Some(Mutation::Append { bytes: next_bytes, .. }) = guard.queue.pop_front() else {
unreachable!()
};
bytes.extend_from_slice(&next_bytes);
}
}
(guard.directory.clone(), mutation)
};
match mutation {
Mutation::Write { path, bytes } => {
if let Err(error) = write_file(&directory, &path, &bytes).await {
log::error!("OPFS background write for {path} failed: {error:?}");
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
log::error!("OPFS background append for {path} failed: {error:?}");
}
}
Mutation::Delete { path } => {
// Removal is idempotent, so a missing entry is the expected outcome of a redundant delete, not an error.
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
log::error!("OPFS background delete for {path} failed: {error:?}");
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
Mutation::Barrier(sender) => {
let _ = sender.send(());
}
}
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
options.set_create(true);
current = JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await?.dyn_into()?;
}
Ok(current)
}
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
let mut current = root.clone();
let mut segments = relative.split('/').filter(|s| !s.is_empty()).collect::<Vec<_>>();
let file = segments.pop().ok_or_else(|| JsValue::from_str("empty path"))?;
for segment in segments {
let options = FileSystemGetDirectoryOptions::new();
options.set_create(create_dirs);
current = JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await?.dyn_into()?;
}
Ok((current, file))
}
async fn read_file(root: &FileSystemDirectoryHandle, path: &str) -> std::result::Result<Vec<u8>, JsValue> {
let (directory, name) = descend(root, path, false).await?;
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle(name)).await?.dyn_into()?;
let file_value = JsFuture::from(handle.get_file()).await?;
let blob: Blob = file_value.dyn_into()?;
let buffer = JsFuture::from(blob.array_buffer()).await?;
Ok(Uint8Array::new(&buffer).to_vec())
}
async fn write_file(root: &FileSystemDirectoryHandle, path: &str, bytes: &[u8]) -> std::result::Result<(), JsValue> {
let (directory, name) = descend(root, path, true).await?;
let options = FileSystemGetFileOptions::new();
options.set_create(true);
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &options)).await?.dyn_into()?;
let writable: FileSystemWritableFileStream = JsFuture::from(handle.create_writable()).await?.dyn_into()?;
let stream: WritableStream = writable.clone().unchecked_into();
// Wrap in an async block so any failure, including a synchronous JS throw from `write_with_js_u8_array`,
// aborts the stream before returning instead of leaving a dangling locked writable.
let write = async {
let array = Uint8Array::from(bytes);
JsFuture::from(writable.write_with_js_u8_array(&array)?).await?;
Ok::<(), JsValue>(())
}
.await;
if let Err(error) = write {
let _ = JsFuture::from(stream.abort()).await;
return Err(error);
}
JsFuture::from(stream.close()).await?;
Ok(())
}
async fn append_file(root: &FileSystemDirectoryHandle, path: &str, bytes: &[u8]) -> std::result::Result<(), JsValue> {
let (directory, name) = descend(root, path, true).await?;
let file_options = FileSystemGetFileOptions::new();
file_options.set_create(true);
let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &file_options)).await?.dyn_into()?;
// Determine the current end-of-file so we can seek there before writing.
let file_value = JsFuture::from(handle.get_file()).await?;
let blob: Blob = file_value.dyn_into()?;
let offset = blob.size();
// `keepExistingData: true` preserves bytes outside the written range; without it OPFS truncates to the written length.
let writable_options = FileSystemCreateWritableOptions::new();
writable_options.set_keep_existing_data(true);
let writable: FileSystemWritableFileStream = JsFuture::from(handle.create_writable_with_options(&writable_options)).await?.dyn_into()?;
let stream: WritableStream = writable.clone().unchecked_into();
// Wrap in an async block so a synchronous JS throw from `seek_with_f64`/`write_with_js_u8_array`
// aborts the stream instead of bypassing the abort via `?`.
let seek_and_write = async {
JsFuture::from(writable.seek_with_f64(offset)?).await?;
let array = Uint8Array::from(bytes);
JsFuture::from(writable.write_with_js_u8_array(&array)?).await?;
Ok::<(), JsValue>(())
}
.await;
if let Err(error) = seek_and_write {
let _ = JsFuture::from(stream.abort()).await;
return Err(error);
}
JsFuture::from(stream.close()).await?;
Ok(())
}
async fn remove_file(root: &FileSystemDirectoryHandle, path: &str) -> std::result::Result<(), JsValue> {
let (directory, name) = descend(root, path, false).await?;
JsFuture::from(directory.remove_entry(name)).await?;
Ok(())
}
async fn file_exists(root: &FileSystemDirectoryHandle, path: &str) -> bool {
let Ok((directory, name)) = descend(root, path, false).await else {
return false;
};
JsFuture::from(directory.get_file_handle(name)).await.is_ok()
}
#[derive(Clone, Copy)]
enum EntryKind {
File,
Directory,
}
async fn list_entries(root: &FileSystemDirectoryHandle, prefix: &str, want: EntryKind) -> std::result::Result<Vec<String>, JsValue> {
// `.` and the empty string both name the container root.
let prefix = if prefix == "." { "" } else { prefix };
let directory = if prefix.is_empty() {
root.clone()
} else {
let mut current = root.clone();
for segment in prefix.split('/').filter(|s| !s.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
options.set_create(false);
current = match JsFuture::from(current.get_directory_handle_with_options(segment, &options)).await {
Ok(value) => value.dyn_into()?,
Err(error) if is_not_found(&error) => return Ok(Vec::new()),
Err(error) => return Err(error),
};
}
current
};
let entries = directory.entries();
let iterator: js_sys::AsyncIterator = entries.unchecked_into();
let mut results = Vec::new();
let prefix_with_slash = with_trailing_slash(prefix);
let want_kind = match want {
EntryKind::File => web_sys::FileSystemHandleKind::File,
EntryKind::Directory => web_sys::FileSystemHandleKind::Directory,
};
loop {
let next: js_sys::IteratorNext = JsFuture::from(iterator.next()?).await?.unchecked_into();
if next.done() {
break;
}
let pair: js_sys::Array = next.value().unchecked_into();
let Some(name) = pair.get(0).as_string() else { continue };
let handle: web_sys::FileSystemHandle = pair.get(1).unchecked_into();
if handle.kind() != want_kind {
continue;
}
results.push(format!("{prefix_with_slash}{name}"));
}
Ok(results)
}
/// Walk every file under `prefix` (recursively) and collect their full container paths.
/// Used at open time to populate the in-memory tracking set.
async fn enumerate_paths(root: &FileSystemDirectoryHandle, prefix: &str) -> std::result::Result<HashSet<String>, JsValue> {
let mut paths = HashSet::new();
let mut to_visit = vec![prefix.to_string()];
while let Some(current_prefix) = to_visit.pop() {
for file in list_entries(root, &current_prefix, EntryKind::File).await? {
paths.insert(file);
}
for dir in list_entries(root, &current_prefix, EntryKind::Directory).await? {
to_visit.push(dir);
}
}
Ok(paths)
}
fn is_not_found(error: &JsValue) -> bool {
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "NotFoundError")
}
/// OPFS raises `TypeMismatchError` when a path segment used as a directory is actually a file.
fn is_type_mismatch(error: &JsValue) -> bool {
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "TypeMismatchError")
}
/// Map a listing error: a prefix that names a file becomes [`ContainerError::NotADirectory`], anything
/// else passes through as a backend error.
fn list_error(prefix: &str, error: JsValue) -> ContainerError {
if is_type_mismatch(&error) {
ContainerError::NotADirectory(prefix.to_string())
} else {
js_err(error)
}
}
+512
View File
@@ -0,0 +1,512 @@
//! Container abstraction for the on-disk side of the `.gdd` document format.
//!
//! A [`Container`] is a virtual filesystem of named byte payloads.
//! Backends include a loose folder, an in-memory map, and an OPFS-backed wasm store.
//! Archive codecs ([`archive::Zip`], [`archive::Xz`]) round-trip a container's contents
//! through a compressed byte stream.
//!
//! Reads return a [`ByteHolder`], an ownership-carrying handle whose variant depends on
//! how the backend produced the bytes (mmap region, owned vector, external file mmap).
//! [`AsyncContainer`] mirrors [`Container`] for inherently async backends; every sync
//! [`Container`] is reachable from async code via a blanket impl.
pub mod archive;
pub mod backends;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
/// The only variant available on `target_family = "wasm"`.
Owned(Vec<u8>),
/// Bytes mmap'd from a file inside the container.
#[cfg(not(target_family = "wasm"))]
Mmapped(MmappedBytes),
/// Bytes mmap'd from a file outside the container (e.g. a linked resource).
#[cfg(not(target_family = "wasm"))]
External { path: std::path::PathBuf, bytes: MmappedBytes },
}
impl ByteHolder {
pub fn as_slice(&self) -> &[u8] {
match self {
ByteHolder::Owned(bytes) => bytes,
#[cfg(not(target_family = "wasm"))]
ByteHolder::Mmapped(bytes) => bytes.as_ref(),
#[cfg(not(target_family = "wasm"))]
ByteHolder::External { bytes, .. } => bytes.as_ref(),
}
}
/// If the bytes are backed by a real filesystem path, return it. Enables consumers to
/// short-circuit byte copies with `fs::copy` (CoW on supported filesystems).
#[cfg(not(target_family = "wasm"))]
pub fn source_path(&self) -> Option<&std::path::Path> {
match self {
ByteHolder::Owned(_) => None,
ByteHolder::Mmapped(bytes) => Some(bytes.path()),
ByteHolder::External { path, .. } => Some(path),
}
}
#[cfg(target_family = "wasm")]
pub fn source_path(&self) -> Option<&std::path::Path> {
None
}
/// Open an external file and produce a [`ByteHolder::External`] backed by mmap.
#[cfg(not(target_family = "wasm"))]
pub fn open_external(path: impl Into<std::path::PathBuf>) -> Result<Self> {
let path = path.into();
let file = mmap_io::mmap::MemoryMappedFile::open_ro(&path).map_err(|error| ContainerError::Backend(format!("mmap of {path:?} failed: {error}")))?;
let bytes = MmappedBytes::new(file)?;
Ok(ByteHolder::External { path, bytes })
}
}
impl AsRef<[u8]> for ByteHolder {
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl std::fmt::Debug for ByteHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ByteHolder::Owned(bytes) => f.debug_tuple("Owned").field(&format_args!("{} bytes", bytes.len())).finish(),
#[cfg(not(target_family = "wasm"))]
ByteHolder::Mmapped(bytes) => f.debug_tuple("Mmapped").field(&format_args!("{} bytes", bytes.as_ref().len())).finish(),
#[cfg(not(target_family = "wasm"))]
ByteHolder::External { path, bytes } => f.debug_struct("External").field("path", path).field("len", &bytes.as_ref().len()).finish(),
}
}
}
/// Owning wrapper around a memory-mapped file that exposes the mapped region as `&[u8]`.
#[cfg(not(target_family = "wasm"))]
pub struct MmappedBytes(mmap_io::mmap::MemoryMappedFile);
#[cfg(not(target_family = "wasm"))]
impl MmappedBytes {
/// Wrap a mapped file, probing that its region is sliceable so the failure surfaces here rather than
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
let len = file.len();
file.as_slice(0, len)
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
Ok(Self(file))
}
pub fn path(&self) -> &std::path::Path {
self.0.path()
}
}
#[cfg(not(target_family = "wasm"))]
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
&[]
}
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ContainerError {
#[error("path not found: {0}")]
NotFound(String),
#[error("invalid path: {0}")]
InvalidPath(String),
#[error("not a directory: {0}")]
NotADirectory(String),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
/// An archive declared more decompressed data (`declared` bytes) than the codec is willing to
/// materialize (`limit` bytes).
#[error("declared decompressed size {declared} exceeds the {limit}-byte limit")]
SizeLimitExceeded { declared: u64, limit: u64 },
/// Failure inside an archive codec (zip, lzma, tar). Wraps a foreign error as text since those
/// error types don't share a common Rust trait we can chain through.
#[error("codec error: {0}")]
Codec(String),
/// Failure inside a storage backend (mmap, OPFS/JS). Wraps a foreign error as text for the same reason.
#[error("backend error: {0}")]
Backend(String),
}
pub type Result<T> = std::result::Result<T, ContainerError>;
/// Normalize a listing prefix to end with a trailing slash (unless it names the container root).
/// The root (empty string or `.`) normalizes to the empty string, so backends concatenate child paths
/// as `prefix/child` without a double, missing, or `./`-rooted slash.
pub(crate) fn with_trailing_slash(prefix: &str) -> String {
if prefix.is_empty() || prefix == "." {
String::new()
} else if prefix.ends_with('/') {
prefix.to_string()
} else {
format!("{prefix}/")
}
}
/// Validate that `path` names a container-safe file: relative, no `.`/`..` segments, no backslashes,
/// no redundant separators (`a//b`, `a/b/`). Dotfile names like `.gitignore` are fine. Requiring a canonical
/// form gives a file one identity across backends, some of which key on the raw string rather than path
/// components. Used by backends to block container escapes and by archive codecs on untrusted entry names.
/// For listing prefixes, which may name the container root, use [`validate_prefix`] instead.
pub fn validate_path(path: &str) -> Result<()> {
let invalid = || ContainerError::InvalidPath(path.to_string());
if path.is_empty() || path.contains('\\') || path.starts_with('/') {
return Err(invalid());
}
// `Path::components` silently folds away `//`, trailing `/`, and interior `.` segments, but backends key
// on the raw string, so a non-canonical path would resolve to one file on a path-joining backend yet a
// different identity on a string-keyed backend. Reject the redundant segments the component loop below
// can't see (it never observes a folded-away `CurDir`/empty segment).
if path.split('/').any(|segment| segment.is_empty() || segment == ".") {
return Err(invalid());
}
// Reject Windows drive-letter prefixes (`C:foo`, `C:/foo`) that platform-agnostic Path doesn't recognize as absolute on Linux.
let bytes = path.as_bytes();
if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
return Err(invalid());
}
for component in std::path::Path::new(path).components() {
use std::path::Component;
match component {
Component::Normal(_) => {}
Component::CurDir | Component::ParentDir | Component::Prefix(_) | Component::RootDir => return Err(invalid()),
}
}
Ok(())
}
/// Validate a listing prefix. Same rules as [`validate_path`], except the container root is also a valid
/// prefix, named by either the empty string or `.`. Backends pass this to `list`/`list_dirs`.
pub fn validate_prefix(prefix: &str) -> Result<()> {
if prefix.is_empty() || prefix == "." {
return Ok(());
}
validate_path(prefix)
}
/// Synchronous virtual filesystem of named byte payloads.
pub trait Container {
/// Read the contents of `path` into a [`ByteHolder`].
fn read(&self, path: &str) -> Result<ByteHolder>;
/// Write `bytes` at `path`, creating intermediate directories as needed.
fn write(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Append `bytes` to the file at `path`, creating it (and any intermediate directories)
/// if it does not yet exist. Equivalent to `write` on a fresh path.
fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Write `size` bytes whose contents are produced by `fill`.
/// The default implementation allocates and forwards to [`Container::write`];
/// backends that can mmap a writable region may override to fill in place.
fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
let mut buffer = vec![0; size];
fill(&mut buffer)?;
self.write(path, &buffer)
}
/// List file entries directly under `prefix` (non-recursive).
/// Returned paths include the `prefix` (e.g. `list("resources")` returns
/// `["resources/abc123", ...]`). A missing prefix yields an empty list; a prefix that names a
/// file (not a directory) is an error.
fn list(&self, prefix: &str) -> Result<Vec<String>>;
/// List subdirectory entries directly under `prefix` (non-recursive).
/// Returned names include the `prefix`, without a trailing slash
/// (e.g. `list_dirs("")` returns `["resources"]`). Same missing/file-prefix semantics as [`Container::list`].
fn list_dirs(&self, prefix: &str) -> Result<Vec<String>>;
/// Whether a file exists at `path`. Directories return `false`.
fn exists(&self, path: &str) -> bool;
/// Remove the file at `path`. Idempotent: removing a missing path succeeds. Directories are never
/// removed (they exist only implicitly as parents of files).
fn remove(&self, path: &str) -> Result<()>;
}
/// Asynchronous virtual filesystem of named byte payloads. Mirrors [`Container`].
///
/// The returned futures are intentionally not `Send`: native uses `block_on` at the save seam
/// and wasm is single-threaded, so neither needs cross-thread futures. Revisit if we ever want
/// to run container I/O on a thread pool.
#[expect(async_fn_in_trait, reason = "see trait docs — Send is not required")]
pub trait AsyncContainer {
async fn read(&self, path: &str) -> Result<ByteHolder>;
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()>;
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()>;
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()>;
async fn list(&self, prefix: &str) -> Result<Vec<String>>;
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>>;
async fn exists(&self, path: &str) -> bool;
async fn remove(&self, path: &str) -> Result<()>;
/// Synchronous write. On backends with sync I/O (folder, memory) the write completes durably
/// before return and reports real errors. On OPFS the write is enqueued onto a background task
/// and `Ok` is returned eagerly; a later failure is logged.
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Synchronous write. Same eager-enqueue semantics on OPFS as [`write_non_blocking`](Self::write_non_blocking);
/// queued appends preserve order relative to earlier queued writes/appends.
fn write_sized_non_blocking(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
let mut buf = vec![0u8; size];
fill(&mut buf)?;
self.write_non_blocking(path, &buf)
}
/// Synchronous append. Same eager-enqueue semantics on OPFS as [`write_non_blocking`](Self::write_non_blocking);
/// queued appends preserve order relative to earlier queued writes/appends.
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
/// Synchronous remove. Same semantics as [`write_non_blocking`](Self::write_non_blocking).
fn remove_non_blocking(&self, path: &str) -> Result<()>;
/// Non-blocking existence check. On OPFS this reads from an in-memory tracking set populated by
/// the sync write/remove paths, since the underlying OPFS existence API is async only.
fn exists_non_blocking(&self, path: &str) -> bool;
}
impl<C: Container + ?Sized> AsyncContainer for C {
async fn read(&self, path: &str) -> Result<ByteHolder> {
Container::read(self, path)
}
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::write(self, path, bytes)
}
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::append(self, path, bytes)
}
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
Container::write_sized(self, path, size, fill)
}
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
Container::list(self, prefix)
}
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
Container::list_dirs(self, prefix)
}
async fn exists(&self, path: &str) -> bool {
Container::exists(self, path)
}
async fn remove(&self, path: &str) -> Result<()> {
Container::remove(self, path)
}
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::write(self, path, bytes)
}
fn write_sized_non_blocking(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
Container::write_sized(self, path, size, fill)
}
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
Container::append(self, path, bytes)
}
fn remove_non_blocking(&self, path: &str) -> Result<()> {
Container::remove(self, path)
}
fn exists_non_blocking(&self, path: &str) -> bool {
Container::exists(self, path)
}
}
/// Type-erased container that dispatches to one of the in-tree backends.
///
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
/// impl forwards to the active variant.
pub enum AnyContainer {
Memory(backends::memory::MemoryBackend),
#[cfg(not(target_family = "wasm"))]
Folder(backends::folder::FolderBackend),
#[cfg(target_family = "wasm")]
Opfs(backends::opfs::OpfsBackend),
}
impl AsyncContainer for AnyContainer {
async fn read(&self, path: &str) -> Result<ByteHolder> {
match self {
Self::Memory(backend) => AsyncContainer::read(backend, path).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::read(backend, path).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::read(backend, path).await,
}
}
async fn write(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::write(backend, path, bytes).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::write(backend, path, bytes).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::write(backend, path, bytes).await,
}
}
async fn append(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::append(backend, path, bytes).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::append(backend, path, bytes).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::append(backend, path, bytes).await,
}
}
async fn write_sized(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::write_sized(backend, path, size, fill).await,
}
}
async fn list(&self, prefix: &str) -> Result<Vec<String>> {
match self {
Self::Memory(backend) => AsyncContainer::list(backend, prefix).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::list(backend, prefix).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::list(backend, prefix).await,
}
}
async fn list_dirs(&self, prefix: &str) -> Result<Vec<String>> {
match self {
Self::Memory(backend) => AsyncContainer::list_dirs(backend, prefix).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::list_dirs(backend, prefix).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::list_dirs(backend, prefix).await,
}
}
async fn exists(&self, path: &str) -> bool {
match self {
Self::Memory(backend) => AsyncContainer::exists(backend, path).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::exists(backend, path).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::exists(backend, path).await,
}
}
async fn remove(&self, path: &str) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::remove(backend, path).await,
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::remove(backend, path).await,
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::remove(backend, path).await,
}
}
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::write_non_blocking(backend, path, bytes),
}
}
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::append_non_blocking(backend, path, bytes),
}
}
fn remove_non_blocking(&self, path: &str) -> Result<()> {
match self {
Self::Memory(backend) => AsyncContainer::remove_non_blocking(backend, path),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::remove_non_blocking(backend, path),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::remove_non_blocking(backend, path),
}
}
fn exists_non_blocking(&self, path: &str) -> bool {
match self {
Self::Memory(backend) => AsyncContainer::exists_non_blocking(backend, path),
#[cfg(not(target_family = "wasm"))]
Self::Folder(backend) => AsyncContainer::exists_non_blocking(backend, path),
#[cfg(target_family = "wasm")]
Self::Opfs(backend) => AsyncContainer::exists_non_blocking(backend, path),
}
}
}
#[cfg(test)]
mod tests {
use super::{ContainerError, validate_path, validate_prefix};
#[test]
fn validate_path_accepts_well_formed() {
// `..` and `.` are only rejected as whole path components; as substrings of a name they are fine.
for ok in ["manifest.json", "resources/abc", "a/b/c.bin", "my..file.txt", "..hidden", ".gitignore"] {
assert!(validate_path(ok).is_ok(), "{ok:?} should be accepted");
}
}
#[test]
fn validate_path_rejects_unsafe() {
for bad in ["", "../escape", "a/../b", ".", "./leading", "/abs", "back\\slash", "C:/win", "\\\\?\\unc"] {
let result = validate_path(bad);
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "{bad:?} should be rejected, got {result:?}");
}
}
#[test]
fn validate_prefix_accepts_root_tokens() {
// The container root is a valid listing prefix, named by either the empty string or `.`.
for root in ["", ".", "resources", "a/b"] {
assert!(validate_prefix(root).is_ok(), "{root:?} should be accepted as a prefix");
}
// Unsafe prefixes are still rejected, same as paths.
assert!(validate_prefix("../escape").is_err());
}
}
+81
View File
@@ -0,0 +1,81 @@
#![cfg(any(feature = "zip", feature = "xz"))]
use document_container::Container;
use document_container::archive::{Archive, ArchiveWriter};
use document_container::backends::folder::FolderBackend;
use document_container::backends::memory::MemoryBackend;
fn entries() -> Vec<(&'static str, &'static [u8])> {
vec![
("manifest.json", br#"{"format":"gdd"}"#),
("document.json", b"{\"registry\":\"...\"}"),
("history.jsonl", b"{\"rev\":1}\n{\"rev\":2}\n"),
("resources/abc123", &[0xDE, 0xAD, 0xBE, 0xEF]),
("resources/xyz789", b"another resource"),
]
}
fn assert_round_trip(restored: &MemoryBackend) {
assert_eq!(restored.read("manifest.json").unwrap().as_slice(), br#"{"format":"gdd"}"#);
assert_eq!(restored.read("document.json").unwrap().as_slice(), b"{\"registry\":\"...\"}");
assert_eq!(restored.read("history.jsonl").unwrap().as_slice(), b"{\"rev\":1}\n{\"rev\":2}\n");
assert_eq!(restored.read("resources/abc123").unwrap().as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
assert_eq!(restored.read("resources/xyz789").unwrap().as_slice(), b"another resource");
}
#[cfg(feature = "zip")]
#[test]
fn zip_round_trip() {
use document_container::archive::Zip;
use std::io::Cursor;
let mut buffer = Cursor::new(Vec::new());
let mut writer = Zip::writer(&mut buffer).unwrap();
for (path, bytes) in entries() {
writer.write_entry(path, bytes).unwrap();
}
writer.finish().unwrap();
let mut restored = MemoryBackend::new();
<Zip as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
assert_round_trip(&restored);
}
#[cfg(feature = "zip")]
#[test]
fn zip_deserialize_streams_into_folder_backend() {
use document_container::archive::Zip;
use std::io::Cursor;
let mut buffer = Cursor::new(Vec::new());
let mut writer = Zip::writer(&mut buffer).unwrap();
for (path, bytes) in entries() {
writer.write_entry(path, bytes).unwrap();
}
writer.finish().unwrap();
let dir = tempfile::tempdir().unwrap();
let mut restored = FolderBackend::create(dir.path()).unwrap();
<Zip as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
assert_eq!(restored.read("manifest.json").unwrap().as_slice(), br#"{"format":"gdd"}"#);
assert_eq!(restored.read("resources/abc123").unwrap().as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
}
#[cfg(feature = "xz")]
#[test]
fn xz_round_trip() {
use document_container::archive::Xz;
use std::io::Cursor;
let mut buffer = Cursor::new(Vec::new());
let mut writer = Xz::writer(&mut buffer).unwrap();
for (path, bytes) in entries() {
writer.write_entry(path, bytes).unwrap();
}
writer.finish().unwrap();
let mut restored = MemoryBackend::new();
<Xz as Archive>::open(Cursor::new(buffer.get_ref()), &mut restored).unwrap();
assert_round_trip(&restored);
}
+178
View File
@@ -0,0 +1,178 @@
use document_container::backends::folder::FolderBackend;
use document_container::backends::memory::MemoryBackend;
use document_container::{AnyContainer, Container, ContainerError};
fn run_round_trip<C: Container>(container: C) {
container.write("manifest.json", br#"{"format":"gdd"}"#).unwrap();
container.write("resources/abc123", &[0xDE, 0xAD, 0xBE, 0xEF]).unwrap();
container.write("resources/xyz789", b"another resource").unwrap();
assert!(container.exists("manifest.json"));
assert!(container.exists("resources/abc123"));
assert!(!container.exists("does-not-exist"));
let manifest = container.read("manifest.json").unwrap();
assert_eq!(manifest.as_slice(), br#"{"format":"gdd"}"#);
let blob = container.read("resources/abc123").unwrap();
assert_eq!(blob.as_slice(), &[0xDE, 0xAD, 0xBE, 0xEF]);
let top_level = container.list("").unwrap();
assert!(top_level.iter().any(|p| p == "manifest.json"));
assert!(
top_level.iter().all(|p| !p.starts_with("resources/")),
"list(\"\") must not descend into subdirectories, got {top_level:?}"
);
let mut resources = container.list("resources").unwrap();
resources.sort();
assert_eq!(resources, vec!["resources/abc123".to_string(), "resources/xyz789".to_string()]);
container.remove("resources/abc123").unwrap();
assert!(!container.exists("resources/abc123"));
assert!(matches!(container.read("resources/abc123"), Err(ContainerError::NotFound(_))));
}
#[test]
fn memory_backend_round_trip() {
run_round_trip(MemoryBackend::new());
}
#[test]
fn folder_backend_round_trip() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
run_round_trip(backend);
}
fn run_list_and_remove_semantics<C: Container>(container: C) {
container.write("dir/file", b"x").unwrap();
// Removing a missing path is idempotent.
container.remove("dir/missing").unwrap();
container.remove("dir/file").unwrap();
container.remove("dir/file").unwrap();
// Listing a missing prefix yields an empty list.
assert_eq!(container.list("nonexistent").unwrap(), Vec::<String>::new());
// Listing a prefix that names a file is an error.
container.write("manifest.json", b"{}").unwrap();
assert!(matches!(container.list("manifest.json"), Err(ContainerError::NotADirectory(_))));
assert!(matches!(container.list_dirs("manifest.json"), Err(ContainerError::NotADirectory(_))));
}
#[test]
fn memory_backend_list_and_remove_semantics() {
run_list_and_remove_semantics(MemoryBackend::new());
}
#[test]
fn folder_backend_list_and_remove_semantics() {
let dir = tempfile::tempdir().unwrap();
run_list_and_remove_semantics(FolderBackend::create(dir.path()).unwrap());
}
#[test]
#[cfg(unix)]
fn folder_backend_rejects_symlink_escape() {
let outside = tempfile::tempdir().unwrap();
std::fs::write(outside.path().join("secret"), b"sensitive").unwrap();
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
// A symlink planted inside the root pointing outside it must not be traversable.
std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
let result = backend.read("link/secret");
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "symlink escape should be rejected, got {result:?}");
// Listing must reject the symlinked prefix too, not just reads, so it can't leak entry names from outside the root.
assert!(matches!(backend.list("link"), Err(ContainerError::InvalidPath(_))), "list through symlink should be rejected");
assert!(matches!(backend.list_dirs("link"), Err(ContainerError::InvalidPath(_))), "list_dirs through symlink should be rejected");
// A symlink entry directly under root must not appear in listings, since `resolve` would reject reading it.
std::os::unix::fs::symlink(outside.path().join("secret"), dir.path().join("file_link")).unwrap();
std::fs::write(dir.path().join("real"), b"ok").unwrap();
assert_eq!(backend.list("").unwrap(), vec!["real".to_string()], "symlink entries should be omitted from file listings");
assert!(backend.list_dirs("").unwrap().is_empty(), "symlink-to-dir entries should be omitted from dir listings");
}
#[test]
fn folder_backend_rejects_path_traversal() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
for bad in ["../escape", "subdir/../escape", "/abs", "back\\slash", "a//b", "trailing/", "a/./b"] {
let result = backend.write(bad, b"nope");
assert!(matches!(result, Err(ContainerError::InvalidPath(_))), "expected InvalidPath for {bad:?}, got {result:?}");
}
}
fn run_append<C: Container>(container: C) {
// Appending to a non-existent path creates it — same semantics as `OpenOptions::append().create(true)`.
container.append("history.jsonl", b"{\"op\":1}\n").unwrap();
container.append("history.jsonl", b"{\"op\":2}\n").unwrap();
container.append("history.jsonl", b"{\"op\":3}\n").unwrap();
let log = container.read("history.jsonl").unwrap();
assert_eq!(log.as_slice(), b"{\"op\":1}\n{\"op\":2}\n{\"op\":3}\n");
}
#[test]
fn memory_backend_append() {
run_append(MemoryBackend::new());
}
#[test]
fn folder_backend_append() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
run_append(backend);
}
#[test]
fn any_container_dispatches_to_active_variant() {
use document_container::AsyncContainer;
let container = AnyContainer::Memory(MemoryBackend::new());
futures::executor::block_on(async {
container.write("manifest.json", br#"{"format":"gdd"}"#).await.unwrap();
container.append("history.jsonl", b"frame-1\n").await.unwrap();
container.append("history.jsonl", b"frame-2\n").await.unwrap();
assert!(container.exists("manifest.json").await);
let manifest = container.read("manifest.json").await.unwrap();
assert_eq!(manifest.as_slice(), br#"{"format":"gdd"}"#);
let history = container.read("history.jsonl").await.unwrap();
assert_eq!(history.as_slice(), b"frame-1\nframe-2\n");
});
}
#[test]
fn folder_backend_reads_empty_file() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
backend.write("empty.bin", &[]).unwrap();
let read_back = backend.read("empty.bin").unwrap();
assert_eq!(read_back.as_slice(), &[] as &[u8]);
}
#[test]
fn folder_backend_write_sized_fills_via_mmap() {
let dir = tempfile::tempdir().unwrap();
let backend = FolderBackend::create(dir.path()).unwrap();
let payload = b"hello world";
backend
.write_sized("resources/sized", payload.len(), &mut |buffer| {
buffer.copy_from_slice(payload);
Ok(())
})
.unwrap();
let read_back = backend.read("resources/sized").unwrap();
assert_eq!(read_back.as_slice(), payload);
}
+36
View File
@@ -0,0 +1,36 @@
[package]
name = "document-format"
description = "Typed handle for the .gdd document format, sitting over graph-storage and document-container"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
[features]
# Runtime bridge: the editor↔storage conversion methods (stage/commit from a `NodeNetwork`,
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
# or `core-types`. Forwards to `graph-storage/conversion`.
conversion = ["graph-storage/conversion", "dep:graph-craft", "dep:core-types"]
# Compressed-archive export/open. Each forwards to the matching `document-container` feature and
# 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"]
[dependencies]
document-container = { workspace = true }
graph-storage = { workspace = true, default-features = false }
graph-craft = { workspace = true, optional = true }
graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
rmp-serde = { workspace = true }
futures = { workspace = true }
thiserror = "2.0"
log = { workspace = true }
[dev-dependencies]
futures = { workspace = true }
graphene-resource = { workspace = true }
tempfile = "3"
+327
View File
@@ -0,0 +1,327 @@
//! Codec for a stream of values. Single-value writes are just streams of length one.
use serde::{Deserialize, Serialize, de::DeserializeOwned};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Codec {
/// A single JSON document. `append` to a non-empty buffer errors.
Json,
/// Newline-delimited compact JSON, one value per line.
JsonLines,
/// A single MessagePack blob. `append` to a non-empty buffer errors.
MessagePack,
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
MessagePackFrames,
}
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("MessagePack encode error: {0}")]
MessagePackEncode(#[from] rmp_serde::encode::Error),
#[error("MessagePack decode error: {0}")]
MessagePackDecode(#[from] rmp_serde::decode::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("frame length {0} exceeds u32")]
FrameTooLarge(usize),
#[error("frame length prefix truncated: need 4 bytes, have {0}")]
TruncatedLengthPrefix(usize),
#[error("declared frame length {declared} exceeds remaining buffer ({remaining} bytes)")]
TruncatedFrame { declared: usize, remaining: usize },
#[error("single-value codec cannot append to a non-empty buffer")]
SingleValueAlreadyWritten,
#[error("expected at least one value, got none")]
Empty,
#[error("expected exactly one value, got more")]
ExpectedSingle,
}
impl Codec {
pub fn extension(self) -> &'static str {
match self {
Codec::Json => "json",
Codec::JsonLines => "jsonl",
Codec::MessagePack => "bin",
Codec::MessagePackFrames => "frames",
}
}
/// Append one value to `output` in this codec's framing.
/// Single-value codecs error if `output` is non-empty.
pub fn append<T: Serialize>(self, output: &mut Vec<u8>, value: &T) -> Result<(), CodecError> {
match self {
Codec::Json => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
serde_json::to_writer_pretty(output, value)?;
Ok(())
}
Codec::JsonLines => {
serde_json::to_writer(&mut *output, value)?;
output.push(b'\n');
Ok(())
}
Codec::MessagePack => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
rmp_serde::encode::write(output, value)?;
Ok(())
}
Codec::MessagePackFrames => {
let payload = rmp_serde::to_vec(value)?;
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
output.extend_from_slice(&length.to_be_bytes());
output.extend_from_slice(&payload);
Ok(())
}
}
}
/// Iterate values from `bytes`. Single-value codecs yield exactly one item;
/// stream codecs yield however many were written.
pub fn iter<'a, T: DeserializeOwned + 'a>(self, bytes: &'a [u8]) -> Box<dyn Iterator<Item = Result<T, CodecError>> + 'a> {
match self {
Codec::Json => {
let single = serde_json::from_slice::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::JsonLines => Box::new(JsonLineIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
Codec::MessagePack => {
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
}
}
/// Serialize a single value into a fresh buffer.
pub fn write_single<T: Serialize>(self, value: &T) -> Result<Vec<u8>, CodecError> {
let mut output = Vec::new();
self.append(&mut output, value)?;
Ok(output)
}
/// Deserialize the single value in `bytes`. Errors if zero or more than one value is present.
pub fn read_single<T: DeserializeOwned>(self, bytes: &[u8]) -> Result<T, CodecError> {
let mut iter = self.iter::<T>(bytes);
let first = iter.next().ok_or(CodecError::Empty)??;
match iter.next() {
// A trailing decode error is more informative than `ExpectedSingle`, so surface it.
Some(Err(error)) => return Err(error),
Some(Ok(_)) => return Err(CodecError::ExpectedSingle),
None => {}
}
Ok(first)
}
}
struct JsonLineIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.remaining.is_empty() {
return None;
}
let (line, tail) = match self.remaining.iter().position(|&byte| byte == b'\n') {
Some(index) => (&self.remaining[..index], &self.remaining[index + 1..]),
None => (self.remaining, &[][..]),
};
self.remaining = tail;
let trimmed = trim_ascii(line);
if trimmed.is_empty() {
continue;
}
return Some(serde_json::from_slice(trimmed).map_err(CodecError::from));
}
}
}
struct MessagePackFrameIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining.is_empty() {
return None;
}
let buffer = std::mem::take(&mut self.remaining);
let Some((length_bytes, tail)) = buffer.split_first_chunk::<4>() else {
return Some(Err(CodecError::TruncatedLengthPrefix(buffer.len())));
};
let length = u32::from_be_bytes(*length_bytes) as usize;
if tail.len() < length {
return Some(Err(CodecError::TruncatedFrame {
declared: length,
remaining: tail.len(),
}));
}
let (frame, after) = tail.split_at(length);
self.remaining = after;
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
}
}
fn trim_ascii(bytes: &[u8]) -> &[u8] {
let start = bytes.iter().position(|byte| !byte.is_ascii_whitespace()).unwrap_or(bytes.len());
let end = bytes.iter().rposition(|byte| !byte.is_ascii_whitespace()).map(|index| index + 1).unwrap_or(start);
&bytes[start..end]
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Frame {
id: u32,
label: String,
}
fn frames() -> [Frame; 3] {
[Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }, Frame { id: 3, label: "gamma".into() }]
}
#[test]
fn json_round_trip_single() {
let frame = Frame { id: 7, label: "solo".into() };
let bytes = Codec::Json.write_single(&frame).unwrap();
let decoded: Frame = Codec::Json.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn json_append_to_non_empty_errors() {
let mut buffer = b"already here".to_vec();
let result = Codec::Json.append(&mut buffer, &Frame { id: 1, label: "x".into() });
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
}
#[test]
fn message_pack_round_trip_single() {
let frame = Frame { id: 99, label: "blob".into() };
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn message_pack_append_to_non_empty_errors() {
let mut buffer = vec![0xAB];
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
}
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
#[test]
fn message_pack_round_trips_serde_json_value() {
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
let bytes = Codec::MessagePack.write_single(&value).unwrap();
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, value);
}
#[test]
fn json_lines_round_trip_and_skip_blanks() {
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
let mut buffer = Vec::new();
Codec::JsonLines.append(&mut buffer, &frames[0]).unwrap();
buffer.extend_from_slice(b" \n\n");
Codec::JsonLines.append(&mut buffer, &frames[1]).unwrap();
let decoded: Vec<Frame> = Codec::JsonLines.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
#[test]
fn message_pack_frames_round_trip() {
let frames = frames();
let mut buffer = Vec::new();
for frame in &frames {
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
/// A crash mid-append leaves a torn final frame. The length prefix lets us detect that
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
/// than decoding a partial value into a plausible-but-wrong one.
#[test]
fn message_pack_frames_detect_truncation() {
let mut buffer = Vec::new();
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
buffer.truncate(buffer.len() - 1);
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
}
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
#[test]
fn message_pack_frames_detect_truncated_length_prefix() {
let buffer = vec![0x00, 0x00];
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
}
#[test]
fn write_single_then_read_with_iter_yields_one() {
let frame = Frame { id: 5, label: "one".into() };
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
let bytes = codec.write_single(&frame).unwrap();
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
}
}
#[test]
fn read_single_rejects_multi_value_stream() {
let mut buffer = Vec::new();
Codec::JsonLines.append(&mut buffer, &Frame { id: 1, label: "a".into() }).unwrap();
Codec::JsonLines.append(&mut buffer, &Frame { id: 2, label: "b".into() }).unwrap();
let result: Result<Frame, _> = Codec::JsonLines.read_single(&buffer);
assert!(matches!(result, Err(CodecError::ExpectedSingle)), "got {result:?}");
}
#[test]
fn extensions_are_distinct() {
let exts = [
Codec::Json.extension(),
Codec::JsonLines.extension(),
Codec::MessagePack.extension(),
Codec::MessagePackFrames.extension(),
];
let unique: std::collections::HashSet<_> = exts.iter().collect();
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Unified error type for the `document-format` crate.
//!
//! Every fallible [`crate::Gdd`] method returns [`Result<T>`]. Variants are grouped by failure
//! domain (container I/O, codec, CRDT, format validation, export)
use document_container::ContainerError;
#[cfg(feature = "conversion")]
use graph_storage::CommitError;
use graph_storage::CrdtError;
use graphene_resource::ResourceHash;
use crate::codec::CodecError;
use crate::io::ReadError;
/// Crate-wide result alias.
pub type Result<T> = std::result::Result<T, Error>;
/// Anything that can go wrong reading, mutating, or exporting a `.gdd` document. Per the format's
/// load-time policy, any unexpected condition is a hard error rather than a silent fallback.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Working-copy container I/O failed (read, write, or path validation).
#[error("container error: {0}")]
Container(#[from] ContainerError),
/// A typed payload could not be located or read from the container.
#[error("read error: {0}")]
Read(#[from] ReadError),
/// A payload failed to encode or decode in its recorded codec.
#[error("codec error: {0}")]
Codec(#[from] CodecError),
/// A CRDT operation was rejected while replaying a hot op or moving the undo/redo cursor.
#[error("CRDT error: {0}")]
Crdt(#[from] CrdtError),
/// Staging a runtime snapshot into the session failed (conversion or CRDT apply).
#[cfg(feature = "conversion")]
#[error("commit error: {0}")]
Commit(#[from] CommitError),
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
WrongFormat { found: String, expected: &'static str },
/// The manifest declares a format version newer than this build can open.
#[error("unsupported format version: found {found}, max supported {max_supported}")]
UnsupportedVersion { found: u32, max_supported: u32 },
/// The requested export options are incoherent (e.g. neither registry nor history included).
#[error("invalid export options: {0}")]
InvalidExportOptions(&'static str),
/// 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),
}
+310
View File
@@ -0,0 +1,310 @@
//! Export: walking the working copy through an archive codec, keeping payloads as-is.
//!
//! [`ExportFormat`] / [`ExportOptions`] are the public settings; the [`Gdd`] export methods drive a
//! [`ExportSink`] (folder / zip / xz) through the manifest → registry → history → resources sequence.
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use graphene_resource::{LoadResource, Resource, ResourceHash};
use crate::error::Error;
use crate::layout::Layout;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, io};
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
#[derive(Copy, Clone, Debug)]
pub enum ExportFormat {
/// Copy the working copy to a destination folder.
Folder,
/// Wrap as a `.gdd.zip` archive.
#[cfg(feature = "zip")]
Zip,
/// Wrap as a `.gdd.tar.xz` archive (whole-archive xz via `lzma-rust2`).
#[cfg(feature = "xz")]
Xz,
}
#[derive(Copy, Clone, Debug)]
pub struct ExportOptions {
/// Whether to include the registry snapshot. `false` produces a history-only export, useful
/// for VCS workflows where the diffable `history.jsonl` is the interesting payload and the
/// registry would rewrite whole-file on every retirement. Consumers replay history from an
/// empty registry.
pub include_registry: bool,
/// Whether to include history + hot-log. `false` produces a flat snapshot (registry only),
/// useful for sharing without revealing edit history and for cutting file size.
pub include_history: bool,
/// Materialize every non-`DataSource::Embedded` resource into `resources/<hash>` for portability.
/// Does not mutate the in-memory `Gdd`.
pub embed_all_resources: bool,
}
impl ExportOptions {
/// Returns an error description if the combination is incoherent.
pub fn validate(&self) -> Result<(), &'static str> {
if !self.include_registry && !self.include_history {
return Err("export must include at least one of: registry, history");
}
Ok(())
}
}
impl Default for ExportOptions {
fn default() -> Self {
Self {
include_registry: true,
include_history: true,
embed_all_resources: false,
}
}
}
impl<L: Layout> Gdd<L> {
/// Stream the working copy to `dest` as a folder/zip/xz archive, keeping payload codecs as-is.
/// Does not mutate `self` and does not buffer the export. Native-only (writes a filesystem path).
///
/// # Errors
/// [`Error::InvalidExportOptions`] for incoherent options, [`Error::MissingResource`] if an
/// embedded resource's bytes are absent from `byte_store`.
#[cfg(not(target_family = "wasm"))]
pub async fn export(&self, dest: &Path, format: ExportFormat, options: ExportOptions, byte_store: &dyn LoadResource, legacy_document: Option<&[u8]>) -> Result<(), Error> {
options.validate().map_err(Error::InvalidExportOptions)?;
match format {
ExportFormat::Folder => {
let mut folder = document_container::backends::folder::FolderBackend::create(dest)?;
let mut sink = FolderSink { folder: &mut folder };
self.stream_entries(options, byte_store, &mut sink).await?;
if let Some(legacy) = legacy_document {
sink.write_entry(self.layout.legacy_path(), legacy)?;
}
}
#[cfg(feature = "zip")]
ExportFormat::Zip => {
let file = std::fs::File::create(dest).map_err(document_container::ContainerError::Io)?;
self.export_archive::<document_container::archive::Zip, _>(file, options, byte_store, legacy_document).await?;
}
#[cfg(feature = "xz")]
ExportFormat::Xz => {
let file = std::fs::File::create(dest).map_err(document_container::ContainerError::Io)?;
self.export_archive::<document_container::archive::Xz, _>(file, options, byte_store, legacy_document).await?;
}
}
Ok(())
}
/// In-memory variant of [`export`](Self::export) returning the archive bytes. Available on every
/// target (no `std::fs`) but buffers the whole archive. `legacy_document` is embedded verbatim at
/// [`Layout::legacy_path`]. `ExportFormat::Folder` has no single-file form and is rejected.
#[cfg(any(feature = "zip", feature = "xz"))]
pub async fn export_to_bytes(&self, format: ExportFormat, options: ExportOptions, byte_store: &dyn LoadResource, legacy_document: Option<&[u8]>) -> Result<Vec<u8>, Error> {
options.validate().map_err(Error::InvalidExportOptions)?;
let cursor = std::io::Cursor::new(Vec::new());
let buffer = match format {
ExportFormat::Folder => return Err(Error::InvalidExportOptions("folder export has no single-file byte form")),
#[cfg(feature = "zip")]
ExportFormat::Zip => self.export_archive::<document_container::archive::Zip, _>(cursor, options, byte_store, legacy_document).await?,
#[cfg(feature = "xz")]
ExportFormat::Xz => self.export_archive::<document_container::archive::Xz, _>(cursor, options, byte_store, legacy_document).await?,
};
Ok(buffer.into_inner())
}
/// Stream entries into a fresh `A` archive over `output`, append the optional legacy blob, then
/// finalize and hand back the inner sink. The shared body of both archive export paths.
#[cfg(any(feature = "zip", feature = "xz"))]
async fn export_archive<A, W>(&self, output: W, options: ExportOptions, byte_store: &dyn LoadResource, legacy_document: Option<&[u8]>) -> Result<W, Error>
where
A: document_container::archive::Archive,
W: std::io::Write + std::io::Seek + Send,
A::Writer<W>: ExportSink + document_container::archive::ArchiveWriter<Sink = W>,
{
use document_container::archive::ArchiveWriter;
let mut writer = A::writer(output)?;
self.stream_entries(options, byte_store, &mut writer).await?;
if let Some(legacy) = legacy_document {
ExportSink::write_entry(&mut writer, self.layout.legacy_path(), legacy)?;
}
Ok(writer.finish_into()?)
}
/// Drive a sink through manifest → session → registry → history → resources, one entry at a time,
/// keeping each payload's recorded codec.
async fn stream_entries(&self, options: ExportOptions, byte_store: &dyn LoadResource, sink: &mut dyn ExportSink) -> Result<(), Error> {
use document_container::AsyncContainer;
let codecs = self.manifest.codecs;
sink.write_entry(&io::path_for(self.layout.manifest_basename(), MANIFEST_CODEC), &MANIFEST_CODEC.write_single(&self.manifest)?)?;
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_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(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
// Resources to embed as bytes: every `Embedded` entry, plus link-only ones when
// `embed_all_resources`. Bytes already in the working copy are written by the copy-through pass
// below, so only the gap is loaded from the byte store here.
let mut export_session = self.session.clone();
let mut hashes_from_store: Vec<ResourceHash> = Vec::new();
let mut links_to_promote: Vec<graph_storage::ResourceId> = Vec::new();
for (id, entry) in &export_session.registry().resources {
let Some(hash) = entry.hash else { continue };
let embed = entry.has_embedded_source() || options.embed_all_resources;
if !embed {
continue;
}
if !entry.has_embedded_source() {
links_to_promote.push(*id);
}
if !working_copy_hashes.contains(&hash) {
hashes_from_store.push(hash);
}
}
hashes_from_store.sort_unstable();
hashes_from_store.dedup();
// Fail fast if an embedded resource is missing, then promote link-only sources on the clone so
// the exported registry and history stay consistent. The live `Gdd` is untouched.
let mut embedded_bytes: Vec<(ResourceHash, Resource)> = Vec::new();
for hash in hashes_from_store {
let Some(resource) = byte_store.load(hash).await else {
return Err(Error::MissingResource(hash));
};
embedded_bytes.push((hash, resource));
}
export_session.embed_resource_sources(links_to_promote)?;
if options.include_registry {
// With history, the persisted snapshot is the retired registry and the hot log layers on top
// (mirrors `Session::load`); without history it must be the full working registry, since
// `bootstrap_from_registry` reconstructs the whole document from it alone.
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
}
if options.include_history {
let mut buffer = Vec::new();
for delta in export_session.history() {
codecs.history.append(&mut buffer, delta)?;
}
if !buffer.is_empty() {
sink.write_entry(&io::path_for(self.layout.history_basename(), codecs.history), &buffer)?;
}
// Carry the un-retired hot ops alongside history so a document exported mid-interaction (e.g. a save
// during a tool drag) isn't shipped with its pending edits dropped. `open` replays them on top of
// the retired snapshot, same as the working copy does.
let mut hot_buffer = Vec::new();
for hot_op in export_session.hot_log() {
codecs.hot_log.append(&mut hot_buffer, hot_op)?;
}
if !hot_buffer.is_empty() {
sink.write_entry(&io::path_for(self.layout.hot_log_basename(), codecs.hot_log), &hot_buffer)?;
}
}
// Copy bytes the working copy already holds, tracking covered hashes so the embed pass below
// doesn't re-emit them.
let mut emitted = std::collections::HashSet::new();
let resources_dir = self.layout.resources_dir();
if self.working.list_dirs("").await?.iter().any(|d| d == resources_dir) {
let prefix = format!("{resources_dir}/");
for path in self.working.list(resources_dir).await? {
if let Some(hash) = path.strip_prefix(&prefix).and_then(|name| name.parse::<ResourceHash>().ok()) {
emitted.insert(hash);
}
let holder = self.working.read(&path).await?;
// Native `External` (mmap'd) holders copy CoW via a source path; others write bytes.
#[cfg(not(target_family = "wasm"))]
match holder.source_path() {
Some(src_path) => sink.write_entry_from_path(&path, src_path)?,
None => sink.write_entry(&path, holder.as_slice())?,
}
#[cfg(target_family = "wasm")]
sink.write_entry(&path, holder.as_slice())?;
}
}
for (hash, resource) in &embedded_bytes {
if emitted.insert(*hash) {
sink.write_entry(&self.layout.resource_path(hash), resource.as_ref())?;
}
}
Ok(())
}
}
/// Sink an export streams entries into, so one async loop drives folder/zip/xz writes. Archive sinks
/// work on every target; the folder sink and `write_entry_from_path` are native-only. `Send` because
/// `stream_entries` holds `&mut dyn ExportSink` across `.await`s.
pub(crate) trait ExportSink: Send {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error>;
/// Copy a file from disk into the sink. Default reads it into memory; the folder sink overrides to
/// `fs::copy` (CoW). Native-only: only reachable for an `External` (mmap'd) holder.
#[cfg(not(target_family = "wasm"))]
fn write_entry_from_path(&mut self, path: &str, src: &std::path::Path) -> Result<(), Error> {
let bytes = std::fs::read(src).map_err(document_container::ContainerError::Io)?;
self.write_entry(path, &bytes)
}
}
#[cfg(not(target_family = "wasm"))]
struct FolderSink<'a> {
folder: &'a mut document_container::backends::folder::FolderBackend,
}
#[cfg(not(target_family = "wasm"))]
impl ExportSink for FolderSink<'_> {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
document_container::Container::write(self.folder, path, bytes)?;
Ok(())
}
fn write_entry_from_path(&mut self, path: &str, src: &std::path::Path) -> Result<(), Error> {
document_container::validate_path(path)?;
let dest = self.folder.root().join(path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(document_container::ContainerError::Io)?;
}
std::fs::copy(src, &dest).map_err(document_container::ContainerError::Io)?;
Ok(())
}
}
#[cfg(feature = "zip")]
impl<W: std::io::Write + std::io::Seek + Send> ExportSink for document_container::archive::ZipWriter<W> {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
use document_container::archive::ArchiveWriter;
ArchiveWriter::write_entry(self, path, bytes)?;
Ok(())
}
}
#[cfg(feature = "xz")]
impl<W: std::io::Write + std::io::Seek + Send> ExportSink for document_container::archive::XzWriter<W> {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
use document_container::archive::ArchiveWriter;
ArchiveWriter::write_entry(self, path, bytes)?;
Ok(())
}
}
+60
View File
@@ -0,0 +1,60 @@
//! Bridge between [`crate::Codec`] and [`document_container::AnyContainer`]. Each payload's codec
//! is known up front (the manifest is always JSON; every other payload's codec is recorded in the
//! manifest), so reads and writes address a fixed `{basename}.{ext}` path without probing.
use document_container::{AnyContainer, AsyncContainer};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::{Codec, CodecError};
/// Compose a container path from `basename` and `codec.extension()`.
pub fn path_for(basename: &str, codec: Codec) -> String {
format!("{basename}.{}", codec.extension())
}
#[derive(Debug, thiserror::Error)]
pub enum ReadError {
#[error("file not found for basename {basename:?} with codec {codec:?}")]
NotFound { basename: String, codec: Codec },
#[error("container error: {0}")]
Container(#[from] document_container::ContainerError),
#[error("codec error: {0}")]
Codec(#[from] CodecError),
}
/// Read `{basename}.{ext}` and decode the single value it contains.
pub async fn read_single<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<T, ReadError> {
let bytes = read_bytes(container, basename, codec).await?;
Ok(codec.read_single::<T>(bytes.as_slice())?)
}
/// Same as [`read_single`] but yields every value when `codec` is a stream codec.
pub async fn iter<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<Vec<T>, ReadError> {
let bytes = read_bytes(container, basename, codec).await?;
Ok(codec.iter::<T>(bytes.as_slice()).collect::<Result<Vec<_>, _>>()?)
}
/// Whether `{basename}.{ext}` exists for the given codec.
pub async fn exists(container: &AnyContainer, basename: &str, codec: Codec) -> bool {
container.exists(&path_for(basename, codec)).await
}
/// Encode `value` with `codec` and write to `{basename}.{ext}`. Synchronous: the write goes through
/// the container's sync write surface (durable on folder/memory, enqueued on OPFS).
pub fn write_single<T: Serialize>(container: &AnyContainer, basename: &str, codec: Codec, value: &T) -> Result<(), crate::Error> {
let bytes = codec.write_single(value)?;
container.write_non_blocking(&path_for(basename, codec), &bytes)?;
Ok(())
}
async fn read_bytes(container: &AnyContainer, basename: &str, codec: Codec) -> Result<document_container::ByteHolder, ReadError> {
let path = path_for(basename, codec);
if !container.exists(&path).await {
return Err(ReadError::NotFound {
basename: basename.to_string(),
codec,
});
}
Ok(container.read(&path).await?)
}
+51
View File
@@ -0,0 +1,51 @@
//! Path layout for a `.gdd` working copy.
//!
//! Layout owns basenames only — the codec choice for each payload is a runtime parameter at the
//! read/write call site. Working-copy creation, exports, and migrations may all hit the same
//! basename with different codecs.
use graphene_resource::ResourceHash;
pub trait Layout {
fn manifest_basename(&self) -> &str;
fn session_basename(&self) -> &str;
fn registry_basename(&self) -> &str;
fn history_basename(&self) -> &str;
fn hot_log_basename(&self) -> &str;
fn resources_dir(&self) -> &str;
fn resource_path(&self, hash: &ResourceHash) -> String;
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
/// new format can be validated against (and recovered from) the old one. Dropped once `.gdd`
/// becomes the sole source of truth.
fn legacy_path(&self) -> &str;
}
#[derive(Copy, Clone, Debug, Default)]
pub struct GddV1Layout;
impl Layout for GddV1Layout {
fn manifest_basename(&self) -> &str {
"manifest"
}
fn session_basename(&self) -> &str {
"session"
}
fn registry_basename(&self) -> &str {
"registry"
}
fn history_basename(&self) -> &str {
"history"
}
fn hot_log_basename(&self) -> &str {
"hot-log"
}
fn resources_dir(&self) -> &str {
"resources"
}
fn resource_path(&self, hash: &ResourceHash) -> String {
format!("{}/{hash}", self.resources_dir())
}
fn legacy_path(&self) -> &str {
"legacy.graphite"
}
}
+344
View File
@@ -0,0 +1,344 @@
//! Typed handle for `.gdd` documents.
//!
//! [`Gdd`] owns a [`graph_storage::Session`] plus a working-copy [`document_container::AnyContainer`].
//! Mutations flow through `Gdd` to keep the session and the on-disk working copy mirrored.
//! Export is a separate, explicit operation — see [`export::ExportFormat`].
//!
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
use std::sync::Arc;
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
// gated off wasm to avoid unused-import warnings.
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
#[cfg(feature = "conversion")]
use graph_storage::{CommitError, NodeMetadataSource};
use graph_storage::{Delta, HotOp, PeerId, Registry, Session};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
pub mod codec;
pub mod error;
pub mod export;
pub mod io;
pub mod layout;
pub mod manifest;
pub mod persist;
pub mod resource;
pub mod session_state;
pub use codec::{Codec, CodecError};
pub use error::Error;
pub use export::{ExportFormat, ExportOptions};
pub use io::ReadError;
pub use layout::{GddV1Layout, Layout};
pub use manifest::{Manifest, PayloadCodecs};
pub use resource::ResourceProxy;
pub use session_state::SessionState;
/// The default [`Layout`], so callers write `GddV1` for the common `Gdd<GddV1Layout>` handle.
pub type GddV1 = Gdd<GddV1Layout>;
/// The manifest is always JSON: it is the bootstrap file, read before any other payload's codec is
/// known, so its own codec cannot itself be configurable.
pub const MANIFEST_CODEC: Codec = Codec::Json;
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
///
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
/// 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)]
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
pub(crate) layout: L,
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
/// and synchronous.
pub(crate) manifest: Manifest,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
/// 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<graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
/// `AnyContainer` itself and uses [`Gdd::open_in`] / [`Gdd::create_in`] directly.
#[cfg(not(target_family = "wasm"))]
impl<L: Layout + Default> Gdd<L> {
/// Open an existing working copy at `path`. Validates the manifest, materializes the session
/// from `registry.bin` (fast path) or by replaying `history.jsonl` (slow path), then applies
/// the persisted hot log on top.
pub async fn open(path: &Path) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::open(path)?);
let layout = L::default();
Self::open_in(working, layout).await
}
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
}
}
impl<L: Layout> Gdd<L> {
/// Open a `.gdd` from archive bytes (xz or zip, auto-detected) by materializing it into `working`,
/// then opening it as a working copy. The archive is deserialized into an in-memory staging backend
/// (the archive reader is synchronous), then each entry is written into `working` via the sync
/// `write_non_blocking` surface — durable on folder/memory, eagerly enqueued on OPFS. `working` is
/// expected to be a fresh per-document container; entries with colliding paths are overwritten.
#[cfg(any(feature = "zip", feature = "xz"))]
pub async fn open_from_archive(bytes: &[u8], mut working: AnyContainer, layout: L) -> Result<Self, Error> {
document_container::archive::open_auto(bytes, &mut working)?;
Self::open_in(working, layout).await
}
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
let session_state: SessionState = match io::exists(&working, layout.session_basename(), codecs.session).await {
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
false => SessionState::default(),
};
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
let mut session = match (has_registry, has_history) {
(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)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, registry)?
}
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
if let Some(rev) = session_state.last_broadcast_rev {
session.publish_up_to(rev);
}
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
Ok(Self {
session,
working: Arc::new(working),
layout,
manifest,
view_settings: session_state.view_settings,
network_view_settings: session_state.network_view_settings,
})
}
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState { peer_id: peer, ..Default::default() };
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
io::write_single(&working, layout.registry_basename(), codecs.registry, session.registry())?;
Ok(Self {
session,
working: Arc::new(working),
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
})
}
}
fn validate_manifest(manifest: &Manifest) -> Result<(), Error> {
if manifest.format != manifest::FORMAT_MAGIC {
return Err(Error::WrongFormat {
found: manifest.format.clone(),
expected: manifest::FORMAT_MAGIC,
});
}
if manifest.format_version > manifest::SUPPORTED_FORMAT_VERSION {
return Err(Error::UnsupportedVersion {
found: manifest.format_version,
max_supported: manifest::SUPPORTED_FORMAT_VERSION,
});
}
Ok(())
}
async fn load_history<L: Layout>(working: &AnyContainer, layout: &L, codec: Codec) -> Result<Vec<Delta>, Error> {
if !io::exists(working, layout.history_basename(), codec).await {
return Ok(Vec::new());
}
Ok(io::iter::<Delta>(working, layout.history_basename(), codec).await?)
}
async fn replay_hot_log<L: Layout>(working: &AnyContainer, layout: &L, codec: Codec, session: &mut Session) -> Result<(), Error> {
if !io::exists(working, layout.hot_log_basename(), codec).await {
return Ok(());
}
for hot_op in io::iter::<HotOp>(working, layout.hot_log_basename(), codec).await? {
session.replay_hot_op(hot_op)?;
}
Ok(())
}
impl<L: Layout> Gdd<L> {
pub fn session(&self) -> &Session {
&self.session
}
pub fn can_undo(&self) -> bool {
self.session.can_undo()
}
pub fn can_redo(&self) -> bool {
self.session.can_redo()
}
pub fn registry(&self) -> &Registry {
self.session.registry()
}
/// The in-memory manifest. `Gdd` is its sole writer, so this is authoritative without re-reading
/// disk.
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
pub fn layout(&self) -> &L {
&self.layout
}
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
&self.view_settings
}
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
/// [`NetworkId`](graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
&self.network_view_settings
}
/// Resolve each runtime `network_path` to its stable [`NetworkId`](graph_storage::NetworkId), so the
/// editor can key per-network, per-peer view state by a stable id. See [`Session::network_ids`].
#[cfg(feature = "conversion")]
pub fn network_ids<M: NodeMetadataSource>(
&self,
network: &graph_craft::document::NodeNetwork,
metadata: &M,
) -> Result<std::collections::HashMap<Vec<core_types::uuid::NodeId>, graph_storage::NetworkId>, CommitError> {
self.session.network_ids(network, metadata)
}
/// Every resource hash referenced by the current registry or anywhere in history, so resource GC keeps
/// redoable/re-undoable interactions' resources (notably proto-node declaration bytes) alive even when an
/// undo has dropped them from the current registry.
pub fn all_referenced_resource_hashes(&self) -> std::collections::HashSet<ResourceHash> {
self.session.all_referenced_resource_hashes()
}
/// Drop the session and return the working-copy container + layout.
/// Intended for test code that needs to reopen against the same container; panics if the container
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
pub fn into_storage(self) -> (AnyContainer, L) {
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
(working, self.layout)
}
/// Resolve the proto-node declarations referenced by the registry into a [`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.
#[cfg(feature = "conversion")]
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> graph_storage::Declarations {
use graph_storage::Implementation;
let registry = self.session.registry();
let mut declarations = 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 {
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
continue;
};
let Some(resource) = byte_store.load(hash).await else {
log::error!("Declaration bytes for {id} (hash {hash}) missing from byte store");
continue;
};
match graph_storage::decode_declaration(resource.as_ref()) {
Ok(proto) => {
declarations.insert(*id, proto);
}
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
}
}
declarations
}
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
// TODO: Add feature gate for legacy embedding
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
}
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
self.working.read(self.layout.legacy_path()).await.ok()
}
}
+63
View File
@@ -0,0 +1,63 @@
//! Bootstrap file for a `.gdd` document. Always JSON regardless of payload codec choice.
use serde::{Deserialize, Serialize};
use crate::Codec;
use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_REGISTRY_CODEC, DEFAULT_SESSION_CODEC};
/// Magic string carried in [`Manifest::format`] to identify a `.gdd` document.
pub const FORMAT_MAGIC: &str = "gdd";
/// Maximum manifest version this build can open. Bumped when manifest layout changes
/// in a way that older builds can't safely read.
pub const SUPPORTED_FORMAT_VERSION: u32 = 1;
/// The on-disk codec for each working-copy payload, recorded so reads/writes never have to probe
/// the filesystem to discover it. The manifest itself is excluded: it is always JSON, since it must
/// be parsed before any other codec is known.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct PayloadCodecs {
pub registry: Codec,
pub history: Codec,
pub hot_log: Codec,
pub session: Codec,
}
impl Default for PayloadCodecs {
fn default() -> Self {
Self {
registry: DEFAULT_REGISTRY_CODEC,
history: DEFAULT_HISTORY_CODEC,
hot_log: DEFAULT_HOT_LOG_CODEC,
session: DEFAULT_SESSION_CODEC,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Manifest {
pub format: String,
pub format_version: u32,
pub editor_version: String,
pub stdlib_version: String,
pub document_id: u64,
/// Codec used for each non-manifest payload on disk. Authoritative — never inferred from which
/// file extension is present.
#[serde(default)]
pub codecs: PayloadCodecs,
}
impl Manifest {
pub fn new(document_id: u64, editor_version: String, stdlib_version: String) -> Self {
Self {
format: FORMAT_MAGIC.to_string(),
format_version: SUPPORTED_FORMAT_VERSION,
document_id,
editor_version,
stdlib_version,
codecs: PayloadCodecs::default(),
}
}
}
+259
View File
@@ -0,0 +1,259 @@
//! The per-edit persist path on the [`Gdd`] handle: stage/retire/commit, hot-log and history
//! append, registry snapshots, session-state and manifest writes, plus view-settings setters.
//! Synchronous and read-free (the manifest is cached on the handle); the container's `*_non_blocking`
//! surface absorbs durability.
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use graph_storage::NodeMetadataSource;
use graph_storage::{HotOp, Rev, TimeStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
use crate::error::Error;
use crate::layout::Layout;
use crate::manifest::Manifest;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, io};
impl<L: Layout> Gdd<L> {
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
/// the undone `Rev`. The working registry is rewound in place by the reverse delta, so re-snapshot it
/// (alongside `head`) or a reopen would read a `registry.bin` inconsistent with the persisted cursor.
pub fn undo(&mut self) -> Result<Rev, Error> {
let rev = self.session.undo()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
Ok(rev)
}
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry.
pub fn redo(&mut self) -> Result<Rev, Error> {
let rev = self.session.redo()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
Ok(rev)
}
/// Edit the cached manifest and persist it. Always JSON, synchronous.
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
edit(&mut self.manifest);
io::write_single(&self.working, self.layout.manifest_basename(), MANIFEST_CODEC, &self.manifest)?;
Ok(())
}
/// Stage a runtime snapshot as hot ops without retiring: diff the runtime against the working
/// registry, append the hot frames (so a crash recovers the work), and persist proto-node
/// 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.
///
/// # Errors
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
/// [`Error::Codec`] from persisting the hot frames, the session has already advanced past what the
/// working copy reflects, so the caller should treat the document as needing re-persist.
#[cfg(feature = "conversion")]
pub fn stage_runtime_snapshot<M: NodeMetadataSource>(
&mut self,
network: &graph_craft::document::NodeNetwork,
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)?;
}
// 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() {
byte_store.store(bytes);
}
Ok(())
}
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
/// are no pending hot ops.
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
return Ok(Vec::new());
};
self.retire_inner(up_to, true)
}
/// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into
/// durable history. Convenience for callers that produce a whole interaction atomically (tests, and any
/// one-shot commit). Equivalent to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot) followed
/// by [`retire_pending_interaction`](Self::retire_pending_interaction).
#[cfg(feature = "conversion")]
pub fn commit_from_runtime<M: NodeMetadataSource>(
&mut self,
network: &graph_craft::document::NodeNetwork,
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<Vec<Rev>, Error> {
self.stage_runtime_snapshot(network, metadata, resources, byte_store)?;
self.retire_pending_interaction()
}
/// Apply a hot op from the broadcast stream, appending one frame to the hot log.
///
/// # Errors
/// Returns [`Error::Crdt`] if the op is rejected by the session, or an [`Error::Container`] /
/// [`Error::Codec`] if persisting the hot frame fails. On a persist failure the session has already
/// advanced past what the working copy reflects, so the caller should treat the document as needing
/// re-persist (mirrors [`stage_runtime_snapshot`](Self::stage_runtime_snapshot)).
pub fn apply_hot_op(&mut self, op: HotOp) -> Result<(), Error> {
self.session.apply_hot_op(op.clone())?;
self.append_hot_frame(&op)?;
Ok(())
}
/// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each
/// hot frame (so a crash before retirement still recovers the work), then retires up to the last
/// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the
/// retired `Rev`s. A no-op when nothing was staged.
pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result<Vec<Rev>, Error> {
let Some(last) = hot_ops.last() else { return Ok(Vec::new()) };
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
self.retire_inner(last.timestamp, interaction_end)
}
/// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes
/// from `Session::retire` in append order, which is a valid replay order, so a direct per-rev lookup
/// preserves replay order without scanning the whole history.
fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
let mut buffer = Vec::new();
for &rev in revs {
let Some(delta) = self.session.delta(rev) else {
log::error!("Retired rev {rev:?} missing from history; skipping its history frame");
continue;
};
self.manifest.codecs.history.append(&mut buffer, delta)?;
}
self.working.append_non_blocking(&io::path_for(self.layout.history_basename(), self.manifest.codecs.history), &buffer)?;
Ok(())
}
/// Set a local annotation (e.g. a commit message) on an existing retired delta and re-persist it.
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
self.rewrite_history()?;
}
Ok(())
}
/// 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> {
let mut buffer = Vec::new();
for delta in self.session.history() {
self.manifest.codecs.history.append(&mut buffer, delta)?;
}
self.working.write_non_blocking(&io::path_for(self.layout.history_basename(), self.manifest.codecs.history), &buffer)?;
Ok(())
}
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(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
io::write_single(&self.working, self.layout.session_basename(), self.manifest.codecs.session, &state)?;
Ok(())
}
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
/// 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> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
Ok(())
}
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
self.view_settings = view_settings;
self.persist_session_state()
}
/// Advance the published frontier to `rev` and persist it to `session.json`, so the silent/published
/// undo boundary survives a reopen. Called by the (future) broadcast transport as commits are shared.
pub fn publish_up_to(&mut self, rev: graph_storage::Rev) -> Result<(), Error> {
self.session.publish_up_to(rev);
self.persist_session_state()
}
/// Replace the per-network view settings and persist them to `session.json`. Per-peer, per-network; never
/// enters the registry, history, or CRDT.
pub fn set_network_view_settings(
&mut self,
network_view_settings: std::collections::BTreeMap<graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
) -> Result<(), Error> {
self.network_view_settings = network_view_settings;
self.persist_session_state()
}
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)?;
Ok(())
}
/// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas,
/// append them to the history file, rewrite the hot log with remaining (unretired) ops, and
/// re-snapshot the registry. Synchronous.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
self.retire_inner(up_to, false)
}
/// `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> {
let new_revs = self.session.retire(up_to)?;
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
if interaction_end && let Some(&last) = new_revs.last() {
self.session.mark_interaction_end(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.persist_registry_snapshot()?;
self.persist_session_state()?;
Ok(new_revs)
}
}
+159
View File
@@ -0,0 +1,159 @@
//! Resource I/O on the [`Gdd`] handle: the content-addressed byte store that backs raster images,
//! fonts, embedded WASM, and proto-node declarations. Registration goes through the session as an
//! `AddResource` delta; the bytes live in the working copy's `resources/<hash>` directory.
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use graphene_resource::ResourceFuture;
use graphene_resource::{LoadResource, Resource, ResourceHash, ResourceStorage};
use crate::Gdd;
use crate::error::Error;
use crate::layout::Layout;
impl<L: Layout> Gdd<L> {
pub async fn read_resource(&self, hash: &ResourceHash) -> Result<ByteHolder, ContainerError> {
self.working.read(&self.layout.resource_path(hash)).await
}
/// Register a resource under `id` and store its bytes. Commits an `AddResource` delta (a single
/// `DataSource::Embedded` source resolved to the content hash) through the session so the registry
/// records the resource and the entry replicates, then writes the bytes into the working copy's
/// content-addressed store. The caller owns `id` allocation.
pub fn add_resource(&mut self, id: graph_storage::ResourceId, bytes: &[u8]) -> Result<(), Error> {
let hash = ResourceHash::from(bytes);
self.working.write_non_blocking(&self.layout.resource_path(&hash), bytes)?;
let hot_ops = self.session.stage_embedded_resource(id, hash)?;
self.append_and_retire(&hot_ops, false)?;
Ok(())
}
/// Like [`add_resource`](Self::add_resource) but copies the bytes from a filesystem `src` rather
/// than buffering them. Folder backends use `fs::copy` (CoW on supported filesystems); other
/// backends fall back to read-then-write. Native-only: there is no filesystem source path on wasm.
#[cfg(not(target_family = "wasm"))]
pub fn add_resource_from_path(&mut self, id: graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
let dest_path = self.layout.resource_path(&hash);
if let AnyContainer::Folder(folder) = self.working.as_ref() {
let full = folder.root().join(&dest_path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
}
std::fs::copy(src, &full).map_err(ContainerError::Io)?;
} else {
let bytes = std::fs::read(src).map_err(ContainerError::Io)?;
// The folder fast path trusts the caller's hash to avoid reading the file; here we've read
// the bytes anyway, so verify the hash matches and flag a content-addressing bug in debug.
debug_assert_eq!(hash, ResourceHash::from(bytes.as_slice()), "add_resource_from_path hash does not match the file at {src:?}");
self.working.write_non_blocking(&dest_path, &bytes)?;
}
let hot_ops = self.session.stage_embedded_resource(id, hash)?;
self.append_and_retire(&hot_ops, false)?;
Ok(())
}
pub async fn has_resource(&self, hash: &ResourceHash) -> bool {
self.working.exists(&self.layout.resource_path(hash)).await
}
pub fn remove_resource(&self, hash: &ResourceHash) -> Result<(), ContainerError> {
self.working.remove_non_blocking(&self.layout.resource_path(hash))
}
/// Enumerate every resource currently in the working copy. Paths that don't parse as a
/// `ResourceHash` (foreign files dropped into the resources directory) are silently skipped.
pub async fn resource_hashes(&self) -> Result<Vec<ResourceHash>, ContainerError> {
let dir = self.layout.resources_dir();
if !self.working.list_dirs("").await?.iter().any(|d| d == dir) {
return Ok(Vec::new());
}
let entries = self.working.list(dir).await?;
let prefix = format!("{dir}/");
let mut hashes = Vec::with_capacity(entries.len());
for entry in entries {
let Some(name) = entry.strip_prefix(&prefix) else { continue };
if let Ok(hash) = name.parse::<ResourceHash>() {
hashes.push(hash);
}
}
Ok(hashes)
}
pub fn resource_proxy(&self) -> ResourceProxy<L>
where
L: Clone,
{
ResourceProxy(self.working.clone(), self.layout.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
let bytes = self.working.read(&self.layout.resource_path(&hash)).await.ok()?;
Some(Resource::new(bytes))
})
}
}
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
let bytes = self.0.read(&self.1.resource_path(&hash)).await.ok()?;
Some(Resource::new(bytes))
})
}
}
impl<L: Layout + Send + Sync> ResourceStorage for Gdd<L> {
fn store(&self, data: &[u8]) -> ResourceHash {
let hash = ResourceHash::from(data);
if let Err(error) = self.working.write_non_blocking(&self.layout.resource_path(&hash), data) {
log::error!("ResourceStorage::store failed for {hash}: {error}");
}
hash
}
fn contains(&self, hash: &ResourceHash) -> bool {
self.working.exists_non_blocking(&self.layout.resource_path(hash))
}
fn garbage_collect(&self, used: &[ResourceHash]) {
// `garbage_collect` is synchronous but listing resources is async, so the native path blocks on
// it. That's unavailable on wasm (single-threaded; `block_on` would deadlock). The editor never
// uses `Gdd` as the runtime `ResourceStorage` on wasm (it GCs the app-global cache instead), so
// this is an unreachable configuration there rather than a missing feature.
#[cfg(target_family = "wasm")]
{
let _ = used;
log::error!("ResourceStorage::garbage_collect is not supported for Gdd on wasm");
}
#[cfg(not(target_family = "wasm"))]
{
let kept: std::collections::HashSet<&ResourceHash> = used.iter().collect();
let hashes = match futures::executor::block_on(self.resource_hashes()) {
Ok(hashes) => hashes,
Err(error) => {
log::error!("Failed to list resources during garbage_collect: {error}");
return;
}
};
for hash in hashes {
if kept.contains(&hash) {
continue;
}
if let Err(error) = self.working.remove_non_blocking(&self.layout.resource_path(&hash)) {
log::error!("ResourceStorage::garbage_collect failed to remove {hash}: {error}");
}
}
}
}
}
@@ -0,0 +1,42 @@
//! Persistent cursor state for the local peer. Separate from [`crate::Manifest`] because the
//! manifest describes document identity (what this document *is*), while [`SessionState`]
//! describes where the local peer's cursor sits inside it.
//!
//! Lives in `session.json`. Rewritten on retirement.
use graph_storage::{NetworkId, PeerId, Rev};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SessionState {
/// This peer's identity for the document, stable per (device, document). Per-peer rather than
/// document identity, so it lives with the cursor here, not in the manifest. Used for CRDT
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
pub head_rev: Option<Rev>,
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_broadcast_rev: Option<Rev>,
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
#[serde(default)]
pub redo_stack: Vec<Rev>,
/// Shared-monotonic counter feeding `Document::next_node_id`. Persisted so reopens don't
/// collide on minted IDs.
#[serde(default)]
pub next_node_counter: 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")]
pub view_settings: BTreeMap<String, serde_json::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
}
@@ -0,0 +1,722 @@
// Exercises the runtime-conversion bridge and the zip archive round-trip, so it only compiles with
// both features. A minimal-dependency build (e.g. `--no-default-features`) skips it entirely.
#![cfg(all(feature = "conversion", feature = "zip"))]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
}
/// A resource byte store for export calls. Empty unless a test pre-populates it; only consulted when
/// `embed_all_resources` is set.
fn empty_byte_store() -> graph_craft::application_io::resource::HashMapResourceStorage {
graph_craft::application_io::resource::HashMapResourceStorage::new()
}
/// A one-node network referencing `id` via a `TaggedValue::Resource` input. Conversion only snapshots
/// resources the network references, so a resource needs a referencing node to survive into storage.
fn network_referencing_resource(id: graphene_resource::ResourceId) -> graph_craft::document::NodeNetwork {
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
NodeNetwork {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Resource(id), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
}
}
#[test]
fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
let (working, layout) = created.into_storage();
let reopened = match GddV1::open_in(working, layout).await {
Ok(gdd) => gdd,
Err(error) => panic!("open_in failed: {error:?}"),
};
assert_eq!(reopened.session().peer(), PeerId(7));
assert!(reopened.registry().node_instances.is_empty());
assert!(reopened.registry().networks.is_empty());
});
}
#[test]
fn open_in_rejects_wrong_format_magic() {
futures::executor::block_on(async {
let container = empty_container();
let layout = GddV1Layout;
let mut bogus = Manifest::new(0xC0DE, "ed".into(), "std".into());
bogus.format = "not-gdd".into();
io::write_single(&container, layout.manifest_basename(), Codec::Json, &bogus).unwrap();
match GddV1::open_in(container, layout).await {
Err(Error::WrongFormat { .. }) => {}
Ok(_) => panic!("expected WrongFormat, got Ok"),
Err(other) => panic!("expected WrongFormat, got {other:?}"),
}
});
}
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
let manifest = gdd.manifest();
assert_eq!(manifest.document_id, 0xC0FFEE);
assert_eq!(manifest.editor_version, "ed-1.2");
assert_eq!(manifest.stdlib_version, "std-0.7");
assert_eq!(manifest.format, manifest::FORMAT_MAGIC);
});
}
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
let manifest = reopened.manifest();
assert_eq!(manifest.editor_version, "ed-NEW");
});
}
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
// produces one network in the registry.
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
assert!(gdd.registry().networks.contains_key(&ROOT_NETWORK), "hot op should have created the root network in memory");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert!(reopened.registry().networks.contains_key(&ROOT_NETWORK), "hot op should have been replayed from the hot log on reopen");
});
}
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
let early = HotOp {
op: RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
id: NetworkId(42),
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
assert_eq!(gdd.session().hot_log().len(), 2);
// Retire only up to timestamp 5 → drains the early op, leaves the late one.
let cutoff = TimeStamp { counter: 5, peer: PeerId(5) };
gdd.retire(cutoff).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
assert_eq!(gdd.session().hot_log().len(), 1, "late hot op should still be in hot log");
assert_eq!(gdd.session().history().count(), 1, "early hot op should be in retired history");
// Reopen and confirm survival: hot log has the late op (replayed), history has the early op.
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert!(reopened.registry().networks.contains_key(&ROOT_NETWORK), "retired op's effect should be in registry");
assert!(reopened.registry().networks.contains_key(&NetworkId(42)), "hot op's effect should be replayed");
assert_eq!(reopened.session().history().count(), 1);
assert_eq!(reopened.session().hot_log().len(), 1);
});
}
/// The published frontier (`last_broadcast_rev`, the silent/published undo boundary) persists in
/// `session.json` and is restored on reopen.
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Retire one op so there is a real retired rev to mark as published.
let op = HotOp {
op: RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
let published = *retired.last().expect("one retired rev");
assert_eq!(gdd.session().last_broadcast_rev(), None, "nothing is published before publish_up_to");
gdd.publish_up_to(published).unwrap_or_else(|error| panic!("publish_up_to failed: {error:?}"));
assert_eq!(gdd.session().last_broadcast_rev(), Some(published));
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.session().last_broadcast_rev(), Some(published), "published frontier should survive reopen");
});
}
#[test]
fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
gdd.export(&dest, ExportFormat::Folder, ExportOptions::default(), &empty_byte_store(), None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
assert!(dest.join("registry.bin").exists());
assert!(dest.join("manifest.json").exists());
assert!(dest.join("session.json").exists());
assert!(!dest.join("hot-log.bin").exists());
assert!(!dest.join("hot-log.frames").exists());
// And the export is itself openable.
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open failed: {error:?}"));
assert_eq!(reopened.session().peer(), PeerId(3));
});
}
#[test]
fn export_zip_round_trips_via_deserialize() {
use document_container::archive::{Archive, Zip};
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
gdd.export(&dest, ExportFormat::Zip, ExportOptions::default(), &empty_byte_store(), None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let bytes = std::fs::read(&dest).unwrap();
let mut restored = document_container::backends::memory::MemoryBackend::new();
Zip::open(std::io::Cursor::new(&bytes), &mut restored).unwrap();
use document_container::Container;
assert!(restored.exists("manifest.json"));
assert!(restored.exists("registry.bin"));
assert!(restored.exists("session.json"));
assert!(!restored.exists("hot-log.frames"));
});
}
#[test]
fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
let options = ExportOptions {
include_registry: false,
include_history: false,
embed_all_resources: false,
};
match gdd.export(&dest, ExportFormat::Folder, options, &empty_byte_store(), None).await {
Err(Error::InvalidExportOptions(_)) => {}
Ok(_) => panic!("expected InvalidOptions, got Ok"),
Err(other) => panic!("expected InvalidOptions, got {other:?}"),
}
});
}
#[test]
fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
let id = ResourceId::new();
assert!(!gdd.has_resource(&hash).await);
gdd.add_resource(id, payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
assert!(gdd.has_resource(&hash).await);
let read_back = gdd.read_resource(&hash).await.unwrap();
assert_eq!(read_back.as_slice(), payload);
// The registry records the resource (entry keyed by id, resolved to the content hash).
let entry = gdd.registry().resources.get(&id).expect("registry records the added resource");
assert_eq!(entry.hash, Some(hash));
let hashes = gdd.resource_hashes().await.unwrap();
assert_eq!(hashes, vec![hash]);
gdd.remove_resource(&hash).unwrap();
assert!(!gdd.has_resource(&hash).await);
});
}
#[test]
fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
let id = ResourceId::new();
gdd.add_resource(id, payload).unwrap();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert!(reopened.has_resource(&hash).await);
assert_eq!(reopened.read_resource(&hash).await.unwrap().as_slice(), payload);
// The registry entry replicated through the history file and survives reopen.
let entry = reopened.registry().resources.get(&id).expect("reopened registry records the resource");
assert_eq!(entry.hash, Some(hash));
});
}
#[test]
fn resource_from_path_uses_fs_copy_on_folder_backend() {
use document_container::AnyContainer;
use document_container::backends::folder::FolderBackend;
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Source file outside the working copy.
let payload = b"external resource bytes";
let src_dir = tempfile::tempdir().unwrap();
let src_path = src_dir.path().join("blob");
std::fs::write(&src_path, payload).unwrap();
let hash = ResourceHash::from(&payload[..]);
let id = ResourceId::new();
gdd.add_resource_from_path(id, hash, &src_path)
.unwrap_or_else(|error| panic!("add_resource_from_path failed: {error:?}"));
assert!(gdd.has_resource(&hash).await);
assert_eq!(gdd.read_resource(&hash).await.unwrap().as_slice(), payload);
});
}
#[test]
fn export_carries_resources() {
use document_format::{ExportFormat, ExportOptions};
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
let id = ResourceId::new();
gdd.add_resource(id, payload).unwrap();
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
gdd.export(&dest, ExportFormat::Folder, ExportOptions::default(), &empty_byte_store(), None).await.unwrap();
let resource_file = dest.join("resources").join(format!("{hash}"));
assert!(resource_file.exists(), "exported resource file should exist at {resource_file:?}");
assert_eq!(std::fs::read(&resource_file).unwrap(), payload);
});
}
/// `embed_all_resources` makes a link-only resource self-contained: the bytes (which live only in
/// the byte store, not the working copy) are written into the export, the exported registry's chain
/// gains a leading `Embedded` source ahead of the original `Url`, and the export reopens with both.
#[test]
fn embed_all_resources_materializes_link_only_resource() {
use document_format::{ExportFormat, ExportOptions};
use graph_craft::application_io::resource::ResourceStorage;
use graph_storage::NoMetadata;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
// byte store; the working copy never holds them.
let payload = b"bytes behind a url";
let hash = ResourceHash::from(&payload[..]);
let byte_store = empty_byte_store();
byte_store.store(payload);
let mut resources = ResourceRegistry::new();
let id = ResourceId::new();
resources.push_source_back(&id, DataSource::Url("https://example.com/r.bin".parse().unwrap()));
resources.resolve(&id, hash);
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
// The working copy holds no resource bytes (URL source, nothing embedded yet).
assert!(!gdd.has_resource(&hash).await);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("embedded");
gdd.export(
&dest,
ExportFormat::Folder,
ExportOptions {
embed_all_resources: true,
..Default::default()
},
&byte_store,
None,
)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
// Bytes materialized into the export.
let resource_file = dest.join("resources").join(format!("{hash}"));
assert!(resource_file.exists(), "embedded resource bytes should be written to {resource_file:?}");
assert_eq!(std::fs::read(&resource_file).unwrap(), payload);
// Reopen the export: the registry chain now leads with Embedded, keeping the URL as fallback,
// and the bytes are resolvable from the export itself with no byte store.
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open export failed: {error:?}"));
assert!(reopened.has_resource(&hash).await, "embedded bytes should be resolvable from the export");
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
assert_eq!(entry.hash, Some(hash));
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
});
}
/// A plain export (no `embed_all_resources`) still materializes the bytes of an already-`Embedded`
/// resource, pulling from the byte store when the working copy doesn't hold them (the editor case
/// where bytes live in the app-global cache, not the per-document working copy).
#[test]
fn export_materializes_embedded_resource_from_byte_store() {
use document_format::{ExportFormat, ExportOptions};
use graph_craft::application_io::resource::ResourceStorage;
use graph_storage::NoMetadata;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// An Embedded resource whose bytes live only in the byte store, not the working copy.
let payload = b"embedded bytes in the cache";
let hash = ResourceHash::from(&payload[..]);
let byte_store = empty_byte_store();
byte_store.store(payload);
let mut resources = ResourceRegistry::new();
let id = ResourceId::new();
resources.push_source_back(&id, DataSource::Embedded);
resources.resolve(&id, hash);
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("plain");
// Default options: embed_all_resources is false.
gdd.export(&dest, ExportFormat::Folder, ExportOptions::default(), &byte_store, None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let resource_file = dest.join("resources").join(format!("{hash}"));
assert!(resource_file.exists(), "embedded resource bytes should be pulled from the store into {resource_file:?}");
assert_eq!(std::fs::read(&resource_file).unwrap(), payload);
});
}
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
/// export, which previously failed at `embed_resource_sources` and fell back to the legacy blob.
#[test]
fn export_round_trips_unretired_hot_ops() {
use graph_craft::application_io::resource::ResourceStorage;
use graph_storage::NoMetadata;
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
let byte_store = empty_byte_store();
byte_store.store(payload);
let mut resources = ResourceRegistry::new();
let id = ResourceId::new();
resources.push_source_back(&id, DataSource::Embedded);
resources.resolve(&id, hash);
// Stage into the working copy without retiring, leaving the conversion in the hot log.
gdd.stage_runtime_snapshot(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
.unwrap_or_else(|error| panic!("stage_runtime_snapshot failed: {error:?}"));
assert!(!gdd.session().hot_log().is_empty(), "staging without retiring should leave hot ops");
assert!(gdd.registry().resources.contains_key(&id), "working registry should reflect the staged resource");
// Export to an archive and reopen it from scratch: the staged (hot) state must survive.
let archive = gdd
.export_to_bytes(document_format::ExportFormat::Zip, document_format::ExportOptions::default(), &byte_store, None)
.await
.unwrap_or_else(|error| panic!("export_to_bytes failed: {error:?}"));
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
.await
.unwrap_or_else(|error| panic!("open_from_archive failed: {error:?}"));
assert!(reopened.registry().resources.contains_key(&id), "the staged resource must survive export and reopen");
});
}
#[test]
fn open_in_rejects_future_format_version() {
futures::executor::block_on(async {
let container = empty_container();
let layout = GddV1Layout;
let mut future_version = Manifest::new(0xC0DE, "ed".into(), "std".into());
future_version.format_version = manifest::SUPPORTED_FORMAT_VERSION + 1;
io::write_single(&container, layout.manifest_basename(), Codec::Json, &future_version).unwrap();
match GddV1::open_in(container, layout).await {
Err(Error::UnsupportedVersion { .. }) => {}
Ok(_) => panic!("expected UnsupportedVersion, got Ok"),
Err(other) => panic!("expected UnsupportedVersion, got {other:?}"),
}
});
}
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::MessagePack);
assert_eq!(codecs.history, Codec::MessagePackFrames);
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
assert_eq!(codecs.session, Codec::Json);
});
}
/// The `RegisterPeer` op auto-emitted on the first commit rides the hot-op pipeline through
/// persistence and retirement, so the `peer_users` mapping survives a reopen.
#[test]
fn first_commit_registers_peer_and_survives_reopen() {
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graph_storage::{NoMetadata, UserId};
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
nodes: [(
core_types::uuid::NodeId(0),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(u32), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
});
}
#[test]
fn persist_path_writes_at_manifest_declared_codec_paths() {
// The manifest declares the on-disk codec for each payload; the persist path must write at the
// extension that codec implies, and reopen (which reads the codec from the manifest) must find them.
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
let (working, layout) = gdd.into_storage();
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert!(reopened.registry().networks.contains_key(&ROOT_NETWORK));
});
}
/// Complete declaration round-trip through the byte store: committing a runtime network with a
/// proto-node persists its `ProtoNode` content into a `ResourceStorage`, and resolving declarations
/// back through that store reconstructs the proto-node identifier in `to_runtime`. This is the
/// editor-shaped path (declaration bytes live in the resource store, not the Gdd container).
#[test]
fn declarations_round_trip_through_byte_store() {
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graph_storage::NoMetadata;
use graphene_resource::ResourceRegistry;
const PROTO: &str = "graphene_core::ops::identity::IdentityNode";
futures::executor::block_on(async {
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
nodes: [(
core_types::uuid::NodeId(0),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(u32), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(PROTO)),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Commit: declaration bytes flow into the byte store, not the Gdd container.
let byte_store = HashMapResourceStorage::new();
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
// Resolve declarations back through the store and convert to a runtime network.
let declarations = gdd.declarations(&byte_store).await;
assert_eq!(declarations.len(), 1, "expected one proto-node declaration resolved from the byte store");
let (converted, _entries) = gdd.registry().to_runtime_with_metadata(&declarations).unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
let node = converted.nodes.values().next().expect("converted network has the node");
match &node.implementation {
DocumentNodeImplementation::ProtoNode(identifier) => assert_eq!(identifier.as_str(), PROTO, "proto-node identifier survived the byte-store round-trip"),
other => panic!("expected a ProtoNode implementation, got {other:?}"),
}
});
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "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
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
default = ["conversion"]
[dependencies]
graph-craft = { workspace = true, optional = true }
core-types = { workspace = true, optional = true }
graphene-resource = { workspace = true }
thiserror = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
blake3 = { workspace = true }
rustc-hash = { workspace = true }
rmp-serde = { workspace = true }
[dev-dependencies]
graph-craft = { workspace = true, features = ["loading"] }
core-types = { workspace = true }
+71
View File
@@ -0,0 +1,71 @@
use crate::TimeStamp;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
///
/// `ui::*` keys are namespaced per CRDT design so each value gets its own LWW timestamp. Per-input
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
}
}
pub type Attributes = BTreeMap<String, Value>;
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
/// Serializes `value` and inserts it under `key`.
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
self.set(key, serde_json::to_value(value)?, timestamp);
Ok(())
}
/// Inserts only when `value != default`, so the read side falls back to the same default.
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
Ok(())
}
}
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
}
}
/// Typed read helpers for `Attributes`.
pub trait AttributesRead {
/// Deserializes the value under `key`, or `None` if missing or undecodable.
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T>;
/// Same as `get_typed`, falling back to `default`.
fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
self.get_typed(key).unwrap_or(default)
}
/// Same as `get_typed`, falling back to `T::default()`.
fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
self.get_typed(key).unwrap_or_default()
}
}
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
@@ -0,0 +1,68 @@
pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument";
pub const CONTEXT_FEATURES: &str = "context_features";
pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata";
pub const ORIGINAL_NODE_ID: &str = "original_node_id";
pub mod input {
pub const IMPORT_TYPE: &str = "import_type";
pub mod ui {
pub const NAME: &str = "ui::name";
pub const DESCRIPTION: &str = "ui::description";
pub const WIDGET_OVERRIDE: &str = "ui::widget_override";
/// Prefix for `InputPersistentMetadata::data` entries. Full key: `ui::data::<sub_key>`.
pub const DATA_PREFIX: &str = "ui::data::"; // TODO: Remove and make runtime strongly typed again
}
}
pub mod ui {
pub const POSITION: &str = "ui::position";
pub const IS_LAYER: &str = "ui::is_layer";
pub const DISPLAY_NAME: &str = "ui::display_name";
pub const LOCKED: &str = "ui::locked";
pub const PINNED: &str = "ui::pinned";
pub const OUTPUT_NAMES: &str = "ui::output_names";
pub const REFERENCE: &str = "ui::reference"; // TODO: Remove?
}
}
pub mod session {
pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
pub const NAV_WIDTH: &str = "ui::nav::width";
}
pub mod doc {
// Document-level editor chrome, stored in `Registry.attributes` (document scope). Each setting is
// its own key so concurrent edits to one don't clobber another.
pub const PTZ: &str = "ui::ptz";
pub const RENDER_MODE: &str = "ui::render_mode";
pub const OVERLAYS: &str = "ui::overlays";
pub const RULERS_VISIBLE: &str = "ui::rulers_visible";
pub const SNAPPING: &str = "ui::snapping";
pub const COLLAPSED: &str = "ui::collapsed";
}
}
pub mod registry {
pub const EXPORTED_NODES: &str = "exported_nodes";
}
pub mod network {
/// Whole-map LWW of a network's `scope_injections` (`key -> (storage NodeId, Type)`), stored as a
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
pub const SCOPE_INJECTIONS: &str = "scope_injections";
}
pub mod delta {
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta.
pub const INTERACTION_END: &str = "interaction_end";
}
+226
View File
@@ -0,0 +1,226 @@
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
/// observing the same forward delta against different local states would otherwise compute
/// different Revs for the same logical op.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
/// Primary parent; `None` for the root delta.
pub parent: Option<Rev>,
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
pub reverse: RegistryDelta,
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
pub attributes: Attributes,
}
impl Delta {
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
let id = compute_rev(parent, author, timestamp, &kind);
Self {
id,
parent,
author,
timestamp,
kind,
reverse,
attributes: Attributes::default(),
}
}
/// Build a merge delta joining `tips` into one node. See [`RegistryDelta::Merge`] for the semantics.
pub fn merge(tips: impl IntoIterator<Item = Rev>, author: PeerId, timestamp: TimeStamp) -> Self {
let mut parents: Vec<Rev> = tips.into_iter().collect();
parents.sort_unstable();
parents.dedup();
let parent = parents.first().copied();
let extra_parents = parents.split_first().map(|(_, rest)| rest.to_vec()).unwrap_or_default();
let kind = RegistryDelta::Merge { extra_parents };
let id = compute_rev(parent, author, timestamp, &kind);
Self {
id,
parent,
author,
timestamp,
reverse: kind.clone(),
kind,
attributes: Attributes::default(),
}
}
/// Every parent: the primary `parent` (absent for the root) plus a merge's `extra_parents`.
pub fn all_parents(&self) -> impl Iterator<Item = Rev> + '_ {
let extras = match &self.kind {
RegistryDelta::Merge { extra_parents } => extra_parents.as_slice(),
_ => &[],
};
self.parent.into_iter().chain(extras.iter().copied())
}
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
}
pub fn is_interaction_end(&self) -> bool {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
pub fn recomputed_id(&self) -> Rev {
compute_rev(self.parent, self.author, self.timestamp, &self.kind)
}
/// Whether `id` matches the recomputed content hash. `Delta` deserializes without checking this
/// (the hash is not cheap over a large history); callers verify explicitly when they don't trust
/// the source via [`Session::verify_history`].
pub fn has_valid_id(&self) -> bool {
self.id == self.recomputed_id()
}
}
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
node: Node,
},
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
RemoveNode {
id: NodeId,
snapshot: Node,
},
ChangeNodeInput {
id: NodeId,
index: u32,
new_input: NodeInput,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
},
ChangeNodeInputAttribute {
id: NodeId,
index: u32,
delta: AttributeDelta,
},
/// LWW per slot. `export == None` removes the slot.
SetNetworkExport {
id: NetworkId,
index: u32,
export: Option<NodeInput>,
},
/// Per-network attribute change, LWW per key. Mirrors `ChangeDocumentAttribute`.
ChangeNetworkAttribute {
id: NetworkId,
delta: AttributeDelta,
},
AddNetwork {
id: NetworkId,
network: Network,
},
/// `snapshot` lets the reverse delta rebuild without re-walking history.
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
},
/// LWW on a resource's resolved content hash. Creates the resource entry if absent.
/// Concurrent resolves agree by construction (the hash is content-derived), so LWW is safe.
SetResourceHash {
id: ResourceId,
hash: Option<ResourceHash>,
},
/// Remove a whole resource entry. `snapshot` is the state of the resource before it was removed.
RemoveResource {
id: ResourceId,
snapshot: ResourceEntry,
},
/// Add (or LWW-overwrite) one entry in a resource's source fallback chain. The source body is
/// type-erased; `key` carries the fractional priority + peer that order it. Add-wins: concurrent
/// adds at distinct keys all survive. Creates the resource entry if absent.
AddSource {
id: ResourceId,
key: SourceKey,
source: serde_json::Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
/// First write wins; conflicting re-registration errors. Duplicate identical registration
/// is a no-op. Not LWW — the mapping is forever.
RegisterPeer {
peer: PeerId,
user: UserId,
},
ChangeDocumentAttribute {
delta: AttributeDelta,
},
/// Joins divergent history tips into one shared node. A registry no-op on replay (it only collapses
/// tips so `head` stays a single `Rev`); the joined tips are `Delta::parent` (the lowest `Rev`) plus
/// these `extra_parents` (sorted). Identity is the parent set alone, so two peers merging the same
/// tips mint the identical delta and it dedups.
Merge {
extra_parents: Vec<Rev>,
},
// Allow for future delta types without a model change
Other(serde_json::Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
}
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
let AttributeDelta { key, value } = delta;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
}
}
+425
View File
@@ -0,0 +1,425 @@
use std::collections::HashSet;
use crate::{AttributeDelta, NetworkId, Node, NodeId, Registry, RegistryDelta, ResourceEntry, ResourceId};
/// Collect a `HashSet` walk (difference/intersection) into ascending order. The sets iterate in
/// random order, so sorting keeps `compute_deltas` emitting a deterministic delta sequence.
fn sorted<'a, T: Ord + Copy + 'a>(ids: impl Iterator<Item = &'a T>) -> Vec<T> {
let mut ids: Vec<T> = ids.copied().collect();
ids.sort_unstable();
ids
}
/// Minimal set of deltas to transform `from` into `to`.
///
/// Emits timestamp-less op shapes; the caller (`Document::commit_local` or equivalent) wraps each
/// in a `Delta` with a fresh clock tick.
pub fn compute_deltas(from: &Registry, to: &Registry) -> Vec<RegistryDelta> {
let mut deltas = Vec::new();
let from_network_ids: HashSet<NetworkId> = from.networks.keys().copied().collect();
let to_network_ids: HashSet<NetworkId> = to.networks.keys().copied().collect();
// AddNetwork before any AddNode that references it. `HashSet` difference/intersection iterate in
// random order, so every set walk below is sorted to keep the emitted delta sequence (and thus the
// resulting `Rev` chain) deterministic across runs.
for network_id in sorted(to_network_ids.difference(&from_network_ids)) {
deltas.push(RegistryDelta::AddNetwork {
id: network_id,
network: to.networks[&network_id].clone(),
});
}
let from_node_ids: HashSet<NodeId> = from.node_instances.keys().copied().collect();
let to_node_ids: HashSet<NodeId> = to.node_instances.keys().copied().collect();
for node_id in sorted(from_node_ids.difference(&to_node_ids)) {
deltas.push(RegistryDelta::RemoveNode {
id: node_id,
snapshot: from.node_instances[&node_id].clone(),
});
}
for node_id in sorted(to_node_ids.difference(&from_node_ids)) {
deltas.push(RegistryDelta::AddNode {
id: node_id,
node: to.node_instances[&node_id].clone(),
});
}
for node_id in sorted(from_node_ids.intersection(&to_node_ids)) {
let from_node = &from.node_instances[&node_id];
let to_node = &to.node_instances[&node_id];
// No `ChangeImplementation` op; the only path is remove + re-add. Same for input-count and
// containing-network changes (a moved node has no in-place op either). `inputs_attributes` is
// checked too: the per-slot loops below `zip` only the shared prefix, so a length change there
// must force a remove + re-add rather than silently dropping the extra slots.
let structural_change = !nodes_have_same_implementation(from_node, to_node) || from_node.inputs.len() != to_node.inputs.len() || from_node.network != to_node.network;
if structural_change {
deltas.push(RegistryDelta::RemoveNode {
id: node_id,
snapshot: from_node.clone(),
});
deltas.push(RegistryDelta::AddNode { id: node_id, node: to_node.clone() });
continue;
}
// Compare by value, ignoring the per-slot timestamp. Timestamps are derived from the diff
// (assigned by the caller via clock.tick), not part of the diff itself: a slot whose value
// is unchanged but whose timestamp differs should not emit a delta.
for (input_idx, (from_slot, to_slot)) in from_node.inputs.iter().zip(&to_node.inputs).enumerate() {
if from_slot.input != to_slot.input {
deltas.push(RegistryDelta::ChangeNodeInput {
id: node_id,
index: input_idx as u32,
new_input: to_slot.input.clone(),
});
}
}
for delta in compute_attribute_deltas(&from_node.attributes, &to_node.attributes) {
deltas.push(RegistryDelta::ChangeNodeAttribute { id: node_id, delta });
}
for (input_idx, (from_input, to_input)) in from_node.inputs.iter().zip(&to_node.inputs).enumerate() {
for delta in compute_attribute_deltas(&from_input.attributes, &to_input.attributes) {
deltas.push(RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: input_idx as u32,
delta,
});
}
}
}
for network_id in sorted(from_network_ids.difference(&to_network_ids)) {
deltas.push(RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: from.networks[&network_id].clone(),
});
}
for network_id in sorted(from_network_ids.intersection(&to_network_ids)) {
let from_network = &from.networks[&network_id];
let to_network = &to.networks[&network_id];
let max_len = from_network.exports.len().max(to_network.exports.len());
for slot_idx in 0..max_len {
let from_slot = from_network.exports.get(slot_idx);
let to_slot = to_network.exports.get(slot_idx);
let from_target = from_slot.and_then(|s| s.target.as_ref());
let to_target = to_slot.and_then(|s| s.target.as_ref());
if from_target != to_target {
deltas.push(RegistryDelta::SetNetworkExport {
id: network_id,
index: slot_idx as u32,
export: to_target.cloned(),
});
}
}
// Per-network attributes.
for delta in compute_attribute_deltas(&from_network.attributes, &to_network.attributes) {
deltas.push(RegistryDelta::ChangeNetworkAttribute { id: network_id, delta });
}
}
// Document-level attributes (`ui::doc::*`, format version, ...).
for delta in compute_attribute_deltas(&from.attributes, &to.attributes) {
deltas.push(RegistryDelta::ChangeDocumentAttribute { delta });
}
compute_resource_deltas(from, to, &mut deltas);
deltas
}
/// Diff the resource store, emitting whole-entry add/remove for resources that appear or vanish and
/// fine-grained hash/source ops for resources present in both. Value-only: per-entry and per-source
/// timestamps are derived by the caller, so an unchanged resource emits nothing.
fn compute_resource_deltas(from: &Registry, to: &Registry, deltas: &mut Vec<RegistryDelta>) {
let from_ids: HashSet<ResourceId> = from.resources.keys().copied().collect();
let to_ids: HashSet<ResourceId> = to.resources.keys().copied().collect();
for id in sorted(from_ids.difference(&to_ids)) {
deltas.push(RegistryDelta::RemoveResource {
id,
snapshot: from.resources[&id].clone(),
});
}
for id in sorted(to_ids.difference(&from_ids)) {
deltas.push(RegistryDelta::AddResource { id, entry: to.resources[&id].clone() });
}
for id in sorted(from_ids.intersection(&to_ids)) {
diff_resource_entry(id, &from.resources[&id], &to.resources[&id], deltas);
}
}
/// Per-entry diff for a resource present in both registries: hash change, then source chain
/// additions/changes/removals.
fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry, deltas: &mut Vec<RegistryDelta>) {
if from.hash != to.hash {
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in &from.sources {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in &to.sources {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
key: *key,
source: to_source.source.clone(),
});
}
}
}
fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
use crate::Implementation::*;
match (&a.implementation, &b.implementation) {
(ProtoNode(a_id), ProtoNode(b_id)) => a_id == b_id,
(Network(a_id), Network(b_id)) => a_id == b_id,
_ => false,
}
}
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for key in from.keys() {
if !to.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
});
}
}
deltas
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
#[test]
fn test_compute_deltas_empty() {
let registry = Registry::default();
let deltas = compute_deltas(&registry, &registry);
assert_eq!(deltas.len(), 0, "No deltas should be generated for identical registries");
}
/// The emitted delta sequence must not depend on `HashMap`/`HashSet` iteration order, which varies
/// per run and per compiler version. Building the same registry repeatedly (each `HashMap` gets a
/// fresh random seed) must yield identical `AddNode` order, since the diff sorts its set walks.
#[test]
fn compute_deltas_emits_nodes_in_deterministic_order() {
let make_registry = || {
let mut registry = Registry::default();
registry.networks.insert(NetworkId(0), Network::default());
for node_id in [50, 3, 17, 999, 1, 42, 8, 256, 100, 7] {
registry.node_instances.insert(NodeId(node_id), Node::dummy());
}
registry
};
let empty = Registry::default();
let add_node_ids = |registry: &Registry| -> Vec<NodeId> {
compute_deltas(&empty, registry)
.into_iter()
.filter_map(|delta| match delta {
RegistryDelta::AddNode { id: node_id, .. } => Some(node_id),
_ => None,
})
.collect()
};
let expected = vec![1, 3, 7, 8, 17, 42, 50, 100, 256, 999].into_iter().map(NodeId).collect::<Vec<_>>();
for _ in 0..16 {
assert_eq!(add_node_ids(&make_registry()), expected, "AddNode order must be deterministic (ascending)");
}
}
#[test]
fn test_compute_deltas_add_node() {
let from = Registry::default();
let mut to = from.clone();
let node = Node::dummy();
to.node_instances.insert(NodeId(42), node);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1);
assert!(matches!(deltas[0], RegistryDelta::AddNode { id: NodeId(42), .. }));
}
/// A change in `inputs_attributes` length is structural: the per-slot diff only `zip`s the shared
/// prefix, so it must force a remove + re-add rather than dropping the extra attribute slots.
#[test]
fn compute_deltas_treats_inputs_attributes_length_change_as_structural() {
// Same implementation/inputs/network in both registries; only `inputs_attributes` length differs.
let base = Node::dummy();
let mut from = Registry::default();
from.node_instances.insert(NodeId(42), base.clone());
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().inputs.push(crate::InputSlot {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
});
let deltas = compute_deltas(&from, &to);
assert!(
deltas.iter().any(|delta| matches!(delta, RegistryDelta::RemoveNode { id: NodeId(42), .. })) && deltas.iter().any(|delta| matches!(delta, RegistryDelta::AddNode { id: NodeId(42), .. })),
"an inputs_attributes length change must emit RemoveNode + AddNode, got {deltas:?}"
);
}
#[test]
fn test_compute_deltas_change_network_attribute() {
use crate::{AttributesWrite, TimeStamp};
let mut from = Registry::default();
from.networks.insert(NetworkId(0), Network::default());
let mut to = from.clone();
to.networks
.get_mut(&NetworkId(0))
.unwrap()
.attributes
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
assert!(
matches!(&deltas[0], RegistryDelta::ChangeNetworkAttribute { id: NetworkId(0), delta } if delta.key == "ui::nav::width"),
"expected ChangeNetworkAttribute for ui::nav::width, got {:?}",
deltas[0]
);
}
#[test]
fn test_compute_deltas_remove_node() {
let mut from = Registry::default();
let node = Node::dummy();
from.node_instances.insert(NodeId(42), node);
let to = Registry::default();
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1);
assert!(matches!(deltas[0], RegistryDelta::RemoveNode { id: NodeId(42), .. }));
}
#[test]
fn test_compute_deltas_modify_attribute() {
let mut from = Registry::default();
let mut node = Node::dummy();
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
node.attributes.insert(
"test".to_string(),
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
},
);
from.node_instances.insert(NodeId(42), node);
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
"test".to_string(),
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
},
);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1);
assert!(matches!(
&deltas[0],
RegistryDelta::ChangeNodeAttribute { id: NodeId(42), delta: AttributeDelta { key, value: Some(_) } } if key == "test"
));
}
/// Document-level attributes (the `Registry.attributes` bucket) must diff into
/// `ChangeDocumentAttribute` deltas, so a document-scoped attribute change reaches the commit path.
/// (Per-peer `ui::doc::*` view settings live in `session.json`, not here.)
#[test]
fn test_compute_deltas_document_attribute() {
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
let from = Registry::default();
let mut to = from.clone();
to.attributes.insert(
"doc::test_attribute".to_string(),
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
},
);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1);
assert!(matches!(
&deltas[0],
RegistryDelta::ChangeDocumentAttribute { delta: AttributeDelta { key, value: Some(_) } } if key == "doc::test_attribute"
));
}
#[test]
fn test_compute_deltas_network_changes() {
let make_slot = |id: u64| ExportSlot {
target: Some(NodeInput::Node { id: NodeId(id), index: 0 }),
timestamp: TimeStamp::ORIGIN,
};
let mut from = Registry::default();
from.networks.insert(
NetworkId(0),
Network {
exports: vec![make_slot(1), make_slot(2)],
..Default::default()
},
);
let mut to = from.clone();
to.networks.get_mut(&NetworkId(0)).unwrap().exports.push(make_slot(3));
let deltas = compute_deltas(&from, &to);
// Only slot 2 changed (added). Slots 0 and 1 are unchanged so they don't emit ops.
assert_eq!(deltas.len(), 1);
assert!(matches!(
&deltas[0],
RegistryDelta::SetNetworkExport {
id: NetworkId(0),
index: 2,
export: Some(NodeInput::Node { id: NodeId(3), .. }),
..
}
));
}
}
+451
View File
@@ -0,0 +1,451 @@
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,
};
#[derive(Clone, Debug)]
pub struct Document {
/// Working registry: retired state with the current hot ops applied on top. This is what live
/// reads and `registry()` observe, and what undo/redo force-apply against.
pub(crate) working_registry: Registry,
/// 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>,
/// 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
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
/// new edits win
pub(crate) retired_snapshot: Registry,
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
pub(crate) head: Option<Rev>,
/// Retired delta DAG in topological (append) order. See [`History`](crate::History).
pub(crate) history: History,
/// Revs undone past (most-recent last), so `redo` can re-apply them. Local-view state the DAG can't
/// recover (a parent may have several children). A new edit while non-empty clears it.
pub(crate) redo_stack: Vec<Rev>,
pub(crate) clock: LamportClock,
pub(crate) peer: PeerId,
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
/// Commits after this can be rewritten silently; commits at or before this are published
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
pub(crate) last_broadcast_rev: Option<Rev>,
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
/// 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,
}
impl Document {
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
/// truncated; the counter is shared across peers and persisted with the document.
pub fn next_node_id(&mut self) -> NodeId {
self.next_node_counter += 1;
let bytes = rmp_serde::to_vec(&(self.peer, self.next_node_counter)).expect("(PeerId, counter) must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
NodeId(u64::from_le_bytes(truncated))
}
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
self.revert_delta(target, delta)
}
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
// which is what we want to re-apply.
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
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.
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
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
/// the same timestamp as the forward op it undoes.
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
std::mem::swap(&mut delta.kind, &mut delta.reverse);
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
}
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
/// Doesn't touch history or `head` — hot ops are transient.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_log.push(hot_op);
Ok(())
}
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
/// 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> {
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_log.push(hot_op);
Ok(())
}
/// 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.
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
self.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
self.history.push(delta);
Ok(())
}
/// The registry an apply reads and writes, resolved from the explicit [`RegistryTarget`].
fn registry_mut(&mut self, target: RegistryTarget) -> &mut Registry {
match target {
RegistryTarget::Working => &mut self.working_registry,
RegistryTarget::Snapshot => &mut self.retired_snapshot,
}
}
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
match target {
RegistryTarget::Working => &self.working_registry,
RegistryTarget::Snapshot => &self.retired_snapshot,
}
}
/// New local/remote op against the working registry: add ops error on duplicate targets and
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
}
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
}
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
}
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
// Advance the local clock past every observed op, including ones that subsequently no-op or
// error. Observation is about causality knowledge, not about whether the op took effect.
self.clock.observe(timestamp);
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
// LWW arms assign unconditionally only under `Force`.
let idempotent = mode != ApplyMode::Live;
let force = mode == ApplyMode::Force;
// Resurrect any concurrently-removed targets the op references before binding the registry
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
self.ensure_referenced_exist(target, &op)?;
let registry = self.registry_mut(target);
match op {
RegistryDelta::AddNode { id, node } => {
if registry.node_instances.contains_key(&id) {
if idempotent {
// Hot ops already created this node; skip rather than error.
return Ok(());
}
return Err(CrdtError::NodeAlreadyExists(id));
}
registry.node_instances.insert(id, node);
}
RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id);
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
if force || timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
}
}
RegistryDelta::ChangeNodeAttribute { id, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
}
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
}
RegistryDelta::SetNetworkExport { id, index, export } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
}
net.exports.resize(
slot_idx + 1,
ExportSlot {
target: None,
timestamp: TimeStamp::ORIGIN,
},
);
}
let existing = &mut net.exports[slot_idx];
if force || timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
}
}
RegistryDelta::AddNetwork { id, network: contents } => {
if registry.networks.contains_key(&id) {
if idempotent {
return Ok(());
}
return Err(CrdtError::NetworkAlreadyExists(id));
}
registry.networks.insert(id, contents);
}
RegistryDelta::RemoveNetwork { id, .. } => {
registry.networks.remove(&id);
}
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
}
RegistryDelta::SetResourceHash { id, hash } => {
let entry = registry.resources.entry(id).or_default();
if force || timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
}
RegistryDelta::AddSource { id, key, source } => {
let entry = registry.resources.entry(id).or_default();
let value = SourceValue { source, timestamp };
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
}
RegistryDelta::RemoveSource { id, key } => {
if let Some(entry) = registry.resources.get_mut(&id) {
if force {
entry.force_remove_source(&key);
} else {
entry.remove_source(&key, timestamp);
}
}
}
RegistryDelta::AddResource { id, entry } => {
registry.resources.insert(id, entry);
}
RegistryDelta::RemoveResource { id, .. } => {
registry.resources.remove(&id);
}
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
Some(_) => {}
None => {
registry.peer_users.insert(peer, user);
}
},
RegistryDelta::ChangeDocumentAttribute { delta } => {
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
}
// Merge is a structural sync point only; it mutates no registry state.
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
}
Ok(())
}
/// 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> {
match op {
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
if let NodeInput::Node { id: referenced, .. } = new_input {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_node_exists(target, *id)?;
}
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
RegistryDelta::SetNetworkExport {
id: network, export: export_target, ..
} => {
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_network_exists(target, *network)?;
}
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
_ => {}
}
Ok(())
}
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)?;
}
Ok(())
}
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)?;
}
Ok(())
}
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
/// capture the true pre-op value rather than the hot-polluted working state.
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
let registry = self.registry_ref(target);
Ok(match delta {
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
RegistryDelta::ChangeNodeInput {
id,
index: input_idx,
new_input: slot.input.clone(),
}
}
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::ChangeNodeAttribute {
id,
delta: reverse_attribute_delta(delta, node.attributes()),
}
}
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
RegistryDelta::ChangeNodeInputAttribute {
id,
index,
delta: reverse_attribute_delta(delta, &input.attributes),
}
}
&RegistryDelta::SetNetworkExport { id, index, .. } => {
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
// since pre-forward there was no export to point at.
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
RegistryDelta::SetNetworkExport { id, index, export: export_target }
}
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
RegistryDelta::ChangeNetworkAttribute {
id,
delta: reverse_attribute_delta(delta, current),
}
}
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
delta: reverse_attribute_delta(delta, &registry.attributes),
},
// Registrations are append-only and not user-undoable; reverse is the same op,
// which applies as a no-op on the already-registered PeerId.
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
id,
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
},
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
// The slot already held a source: undo restores it.
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// The slot was empty: undo removes what this op added.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
Some(existing) => RegistryDelta::AddSource {
id,
key,
source: existing.source.clone(),
},
// Nothing to restore; reverse is a no-op removal.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
// Overwrote an existing entry: undo restores it.
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
None => RegistryDelta::RemoveResource {
id,
snapshot: ResourceEntry::default(),
},
},
&RegistryDelta::RemoveResource { id, .. } => {
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
RegistryDelta::AddResource { id, entry: snapshot }
}
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
&RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null),
})
}
}
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
/// live hot ops) or the retired snapshot (retired deltas only). Retirement targets the snapshot so
/// reverses capture pre-op values; the hot path and undo/redo target the working copy.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RegistryTarget {
Working,
Snapshot,
}
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApplyMode {
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
Live,
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
Idempotent,
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
Force,
}
+573
View File
@@ -0,0 +1,573 @@
use std::collections::HashMap;
use core_types::Context;
use core_types::context::ContextDependencies;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput as GraphCraftNodeInput, NodeNetwork};
use serde::Serialize;
use crate::attr::*;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
}
/// Path to a node, used to mint stable global IDs by hashing.
///
/// Hashing uses blake3 truncated to 64 bits with the document's `PeerId` mixed in, so two peers
/// converting runtime states that happen to share local IDs (e.g. both editors seeded the same
/// UUID RNG) still produce distinct global IDs. Determinism: same `(peer, path, local_id)` always
/// yields the same global ID, so a peer re-converting its own runtime state preserves IDs.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
struct NodePath {
path: Vec<(RuntimeNodeId, NetworkId)>,
local_id: RuntimeNodeId,
}
impl NodePath {
fn root(node_id: RuntimeNodeId) -> Self {
Self { path: vec![], local_id: node_id }
}
fn nested(parent_path: &NodePath, parent_node_id: RuntimeNodeId, network_id: NetworkId, local_id: RuntimeNodeId) -> Self {
let mut path = parent_path.path.clone();
path.push((parent_node_id, network_id));
Self { path, local_id }
}
fn to_global_id(&self, peer: PeerId) -> NodeId {
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
NodeId(u64::from_le_bytes(truncated))
}
/// Stable id of the network owned by the node at this path, derived purely from the (structural)
/// path and peer so it reproduces across `to_runtime` -> `from_runtime` round trips rather than
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
let bytes = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
NetworkId(u64::from_le_bytes(truncated))
}
}
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
#[error("Failed to serialize value: {0}")]
SerializationError(String),
#[error("Unsupported node implementation type")]
UnsupportedImplementation,
#[error("Invalid network structure: {0}")]
InvalidNetwork(String),
#[error("Index {0} exceeds the storage format's u32 range")]
IndexOverflow(usize),
}
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
/// editor round-trips.
impl TryFrom<&NodeNetwork> for Registry {
type Error = ConversionError;
/// Test/utility entry point: scopes IDs under `PeerId(0)`. Real editor conversions go through
/// `from_runtime_with_metadata` and pass the document's actual peer.
fn try_from(node_network: &NodeNetwork) -> Result<Self, Self::Error> {
Registry::from_runtime_with_metadata(node_network, &NoMetadata, &graphene_resource::ResourceRegistry::new(), PeerId(0))
}
}
/// Proto-node declaration bytes extracted during conversion, keyed by content hash, for the caller
/// to persist into its byte store.
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. `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.
pub struct RuntimeConversion {
pub registry: Registry,
pub declaration_bytes: DeclarationBytes,
/// 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`].
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
serde_json::from_value(value).map_err(|error| error.to_string())
}
impl Registry {
/// Convenience wrapper returning only the registry (declaration bytes discarded). For callers
/// that don't persist a byte store — e.g. the graph-only `TryFrom` and value-comparison tests.
pub fn from_runtime_with_metadata<M: NodeMetadataSource>(node_network: &NodeNetwork, metadata: &M, resources: &graphene_resource::ResourceRegistry, peer: PeerId) -> Result<Self, ConversionError> {
Ok(Self::convert_from_runtime(node_network, metadata, resources, peer)?.registry)
}
/// Full conversion: returns the registry and the extracted declaration bytes for the caller to
/// persist. See [`RuntimeConversion`].
pub fn convert_from_runtime<M: NodeMetadataSource>(
node_network: &NodeNetwork,
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
peer: PeerId,
) -> Result<RuntimeConversion, ConversionError> {
let mut registry = Registry::default();
let mut ctx = ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
};
convert_network(node_network, ROOT_NETWORK, None, &[], &mut registry, &mut ctx)?;
// Only snapshot resources the network actually references. The runtime resource cache also keeps
// resources alive across undo (so legacy redo can restore them), so it can contain orphans whose
// node was removed by an undo. Snapshotting those would re-introduce an `AddResource` on the next
// diff and let an undone resource resurface as a phantom edit. Declaration resources are added
// separately by `convert_network` and are always referenced, so they're unaffected by this filter.
let referenced = collect_referenced_resources(node_network);
convert_resources(resources, &referenced, peer, &mut registry)?;
Ok(RuntimeConversion {
registry,
declaration_bytes: ctx.declaration_bytes,
network_ids: ctx.network_ids,
})
}
}
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
/// stored type-erased as `serde_json::Value` so its on-disk shape can migrate freely. All
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
for id in resources.ids() {
if !referenced.contains(&id) {
continue;
}
let Some(info) = resources.info(&id) else { continue };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
registry.resources.insert(id, entry);
}
Ok(())
}
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
/// (recursively through nested networks). These are the resources the document actually uses; the
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
fn collect_referenced_resources(network: &NodeNetwork) -> std::collections::HashSet<ResourceId> {
let mut referenced = std::collections::HashSet::new();
collect_referenced_resources_inner(network, &mut referenced);
referenced
}
fn collect_referenced_resources_inner(network: &NodeNetwork, referenced: &mut std::collections::HashSet<ResourceId>) {
for export in &network.exports {
collect_input_resource(export, referenced);
}
for node in network.nodes.values() {
for input in &node.inputs {
collect_input_resource(input, referenced);
}
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
collect_referenced_resources_inner(nested, referenced);
}
}
}
fn collect_input_resource(input: &GraphCraftNodeInput, referenced: &mut std::collections::HashSet<ResourceId>) {
if let GraphCraftNodeInput::Value { tagged_value, .. } = input
&& let TaggedValue::Resource(id) = &**tagged_value
{
referenced.insert(*id);
}
}
/// Register a proto-node declaration as a content-addressed resource: a single `DataSource::Embedded`
/// source resolved to `hash`. The bytes themselves are persisted by the caller's byte store.
fn register_declaration_resource(registry: &mut Registry, id: ResourceId, hash: ResourceHash, peer: PeerId) {
registry.resources.insert(id, crate::ResourceEntry::embedded(hash, peer, TimeStamp::ORIGIN));
}
struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
/// Cache from proto-node identifier to its derived `ResourceId`, so repeated proto-nodes reuse
/// one id without re-serializing. (Identical content hashes to the same id anyway; this just
/// skips the work.)
declaration_ids: HashMap<String, ResourceId>,
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
declaration_bytes: DeclarationBytes,
/// 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>,
metadata: &'m M,
peer: PeerId,
}
fn convert_network<M: NodeMetadataSource + ?Sized>(
node_network: &NodeNetwork,
network_id: NetworkId,
parent_path: Option<&NodePath>,
metadata_path: &[RuntimeNodeId],
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
) -> Result<(), ConversionError> {
for (runtime_node_id, doc_node) in &node_network.nodes {
let node_path = child_path(parent_path, network_id, *runtime_node_id);
let global_id = node_path.to_global_id(ctx.peer);
let location = NodeLocation {
network_id,
parent_path,
metadata_path,
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
let exports = node_network
.exports
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
}
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
/// each runtime-local node reference to its stable storage global ID so the reference survives a
/// round trip even if runtime IDs are later reshuffled.
fn write_scope_injections(
attributes: &mut crate::Attributes,
node_network: &NodeNetwork,
parent_path: Option<&NodePath>,
network_id: NetworkId,
peer: PeerId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
if node_network.scope_injections.is_empty() {
return Ok(());
}
let stored: HashMap<String, (NodeId, core_types::Type)> = node_network
.scope_injections
.iter()
.map(|(key, (runtime_id, ty))| {
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer);
(key.clone(), (storage_id, ty.clone()))
})
.collect();
attributes
.set_serialized(network::SCOPE_INJECTIONS, &stored, timestamp)
.map_err(map_serialization_error(network::SCOPE_INJECTIONS))
}
fn child_path(parent_path: Option<&NodePath>, network_id: NetworkId, local_id: RuntimeNodeId) -> NodePath {
match parent_path {
None => NodePath::root(local_id),
Some(parent) => NodePath::nested(parent, parent.local_id, network_id, local_id),
}
}
/// Where a node sits in both the storage tree (`network_id`, `parent_path`) and the runtime tree
/// (`metadata_path`, `runtime_node_id`). `metadata_path` is the chain of runtime IDs from the root
/// down to (but not including) this node.
struct NodeLocation<'a> {
network_id: NetworkId,
parent_path: Option<&'a NodePath>,
metadata_path: &'a [RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
}
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
let NodeLocation {
network_id,
parent_path,
metadata_path,
runtime_node_id,
} = location;
let node_path = child_path(parent_path, network_id, runtime_node_id);
let timestamp = TimeStamp::ORIGIN;
let mut inputs = Vec::with_capacity(doc_node.inputs.len());
for (input_index, input) in doc_node.inputs.iter().enumerate() {
let mut input_attrs = convert_input_attributes(input)?;
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
inputs.push(InputSlot {
input: convert_input(input, parent_path, network_id, ctx.peer)?,
timestamp,
attributes: input_attrs,
});
}
// For nested networks, append this node onto the metadata path.
let mut extended_path = Vec::new();
let child_metadata_path = if matches!(doc_node.implementation, DocumentNodeImplementation::Network(_)) {
extended_path.extend_from_slice(metadata_path);
extended_path.push(runtime_node_id);
extended_path.as_slice()
} else {
metadata_path
};
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new();
attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
attributes
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?;
attributes
.set_if_not_default(node::SKIP_DEDUPLICATION, &doc_node.skip_deduplication, &false, timestamp)
.map_err(map_serialization_error(node::SKIP_DEDUPLICATION))?;
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
implementation,
inputs,
attributes,
network: network_id,
})
}
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
if let Some(position) = metadata.position(metadata_path, runtime_node_id) {
attributes
.set_serialized(node::ui::POSITION, &position, timestamp)
.map_err(map_serialization_error(node::ui::POSITION))?;
}
// Bool flags are only emitted when true; absence reads as false.
for (key, value) in [
(node::ui::IS_LAYER, metadata.is_layer(metadata_path, runtime_node_id)),
(node::ui::LOCKED, metadata.locked(metadata_path, runtime_node_id)),
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
] {
if value {
attributes.set(key, serde_json::Value::Bool(true), timestamp);
}
}
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
&& !name.is_empty()
{
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
}
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
let output_names = metadata.output_names(metadata_path, runtime_node_id);
if !output_names.is_empty() {
attributes
.set_serialized(node::ui::OUTPUT_NAMES, &output_names, timestamp)
.map_err(map_serialization_error(node::ui::OUTPUT_NAMES))?;
}
Ok(())
}
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> {
if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
}
Ok(())
}
/// Empty strings (the runtime's "unset" sentinel) and absent values are both skipped.
/// `input_data` entries each get their own `ui::input_data::<sub_key>` attribute for per-key LWW.
fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
input_index: usize,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
if let Some(value) = value.filter(|s| !s.is_empty()) {
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
}
};
non_empty_string(node::input::ui::NAME, metadata.input_name(metadata_path, runtime_node_id, input_index), attributes);
non_empty_string(node::input::ui::DESCRIPTION, metadata.input_description(metadata_path, runtime_node_id, input_index), attributes);
non_empty_string(node::input::ui::WIDGET_OVERRIDE, metadata.widget_override(metadata_path, runtime_node_id, input_index), attributes);
for (sub_key, value) in metadata.input_data(metadata_path, runtime_node_id, input_index) {
attributes.set(&format!("{prefix}{sub_key}", prefix = node::input::ui::DATA_PREFIX), value, timestamp);
}
Ok(())
}
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> {
Ok(match input {
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
id: child_path(parent_path, network_id, *node_id).to_global_id(peer),
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
NodeInput::Value { value, exposed: *exposed }
}
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
GraphCraftNodeInput::Import { import_index, .. } => NodeInput::Import {
index: (*import_index).try_into().map_err(|_| ConversionError::IndexOverflow(*import_index))?,
},
GraphCraftNodeInput::Reflection(_) => NodeInput::Reflection,
// GPU-specific; not modeled in the Registry format.
GraphCraftNodeInput::Inline(_) => return Err(ConversionError::UnsupportedImplementation),
})
}
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN;
match input {
GraphCraftNodeInput::Import { import_type, .. } => {
attributes
.set_serialized(node::input::IMPORT_TYPE, import_type, timestamp)
.map_err(map_serialization_error(node::input::IMPORT_TYPE))?;
}
GraphCraftNodeInput::Reflection(metadata) => {
attributes
.set_serialized(node::REFLECTION_METADATA, metadata, timestamp)
.map_err(map_serialization_error(node::REFLECTION_METADATA))?;
}
_ => {}
}
Ok(attributes)
}
fn convert_implementation<M: NodeMetadataSource + ?Sized>(
implementation: &DocumentNodeImplementation,
current_node_path: &NodePath,
child_metadata_path: &[RuntimeNodeId],
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
) -> Result<Implementation, ConversionError> {
Ok(match implementation {
DocumentNodeImplementation::ProtoNode(identifier) => {
let identifier_str = identifier.as_str().to_string();
// Reuse a previously-converted proto-node's id; identical content hashes to the same id
// anyway, so this only skips re-serializing.
if let Some(id) = ctx.declaration_ids.get(&identifier_str) {
return Ok(Implementation::ProtoNode(*id));
}
let proto = ProtoNode {
identifier: identifier_str.clone(),
attributes: Default::default(),
};
// Content-address the declaration: serialize, hash, derive a deterministic id.
let bytes = encode_declaration(&proto).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
let hash = ResourceHash::from(bytes.as_slice());
let id = ResourceId::from_hash(&hash);
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
ctx.declaration_ids.insert(identifier_str, id);
Implementation::ProtoNode(id)
}
DocumentNodeImplementation::Network(nested_network) => {
// Stable, traversal-order-independent id derived from the owning node's path, so a
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
// same node-path hashes underneath it).
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
Implementation::Network(nested_network_id)
}
// TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
})
}
+180
View File
@@ -0,0 +1,180 @@
//! Retired delta history: the durable, append-only DAG of committed deltas.
//!
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
//! collaboration where the leader serializes retired commits), so appending preserves the order by
//! 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 crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
}
impl History {
pub fn new() -> Self {
Self::default()
}
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
self.index.get(&rev).map(|&position| &self.deltas[position])
}
pub fn contains(&self, rev: Rev) -> bool {
self.index.contains_key(&rev)
}
pub fn len(&self) -> usize {
self.deltas.len()
}
pub fn is_empty(&self) -> bool {
self.deltas.is_empty()
}
/// Append a delta after its parents, keeping `deltas` and `index` in sync. A duplicate `Rev`
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
/// Deltas in topological order (a valid replay order).
pub fn iter(&self) -> impl Iterator<Item = &Delta> + '_ {
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) {
// 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();
for delta in &self.deltas {
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
pending_parents.insert(delta.id, in_history_parents);
for parent in delta.all_parents() {
if self.index.contains_key(&parent) {
children.entry(parent).or_default().push(delta.id);
}
}
}
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
order.push(rev);
for child in children.get(&rev).into_iter().flatten() {
let count = pending_parents.get_mut(child).expect("child is in history");
*count -= 1;
if *count == 0 {
ready.push(std::cmp::Reverse(*child));
}
}
}
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
self.index.clear();
for (position, rev) in order.iter().enumerate() {
if let Some(delta) = by_rev.remove(rev) {
self.index.insert(*rev, position);
self.deltas.push(delta);
}
}
}
/// 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> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
/// Mark a retired delta as the end of a user interaction. Mutates only the delta's attributes
/// (excluded from its `Rev`), so the index stays valid. Returns whether the delta was found.
pub fn mark_interaction_end(&mut self, rev: Rev, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].mark_interaction_end(timestamp);
true
}
None => false,
}
}
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].attributes.set(key, value, timestamp);
true
}
None => false,
}
}
/// Test-only mutable access to the first stored delta, for corrupting it to exercise `verify`.
#[cfg(test)]
pub(crate) fn first_mut(&mut self) -> Option<&mut Delta> {
self.deltas.first_mut()
}
/// Verify the two stored invariants for history loaded from an untrusted source: every delta's
/// content-addressed `id` matches its recomputed hash, and the deltas are in topological order
/// (each delta's in-history parents precede it). Returns the first violation found.
pub fn verify(&self) -> Result<(), CrdtError> {
let mut seen: std::collections::HashSet<Rev> = std::collections::HashSet::with_capacity(self.deltas.len());
for delta in &self.deltas {
let expected = delta.recomputed_id();
if delta.id != expected {
return Err(CrdtError::RevMismatch { stored: delta.id, expected });
}
for parent in delta.all_parents() {
if self.index.contains_key(&parent) && !seen.contains(&parent) {
return Err(CrdtError::NotFoundInHistory(parent));
}
}
seen.insert(delta.id);
}
Ok(())
}
}
Loaded 100 of 548 files, more files were not shown because too many files have changed in this diff. Show more