Compare commits

...
Author SHA1 Message Date
firestar99 953a9312f0 GPU: add support for N-many input images and not just exactly one 2026-06-07 20:39:30 -07: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
135 changed files with 6101 additions and 1331 deletions

No files matched your search

+1 -1
View File
@@ -123,7 +123,7 @@ jobs:
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="master" --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"
Generated
+147 -8
View File
@@ -304,6 +304,20 @@ dependencies = [
"serde_core",
]
[[package]]
name = "blake3"
version = "1.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce"
dependencies = [
"arrayref",
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq",
"cpufeatures 0.3.0",
]
[[package]]
name = "blending-nodes"
version = "0.1.0"
@@ -812,6 +826,12 @@ dependencies = [
"windows-sys 0.60.2",
]
[[package]]
name = "constant_time_eq"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "convert_case"
version = "0.8.0"
@@ -928,6 +948,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
dependencies = [
"libc",
]
[[package]]
name = "crate-hierarchy-viz"
version = "0.0.0"
@@ -1213,6 +1242,24 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359"
[[package]]
name = "document-container"
version = "0.0.0"
dependencies = [
"futures",
"js-sys",
"log",
"lzma-rust2",
"mmap-io",
"tar",
"tempfile",
"thiserror 2.0.18",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"zip",
]
[[package]]
name = "document-features"
version = "0.2.11"
@@ -1474,6 +1521,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d"
dependencies = [
"crc32fast",
"libz-rs-sys",
"miniz_oxide",
]
@@ -1527,7 +1575,7 @@ checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
dependencies = [
"fontconfig-parser",
"log",
"memmap2",
"memmap2 0.9.10",
"slotmap",
"tinyvec",
"ttf-parser",
@@ -1541,7 +1589,7 @@ checksum = "7c20b425addb8661e97fe1d51c4d8bcec3ec29ed6ad0db983976a7521276b8f7"
dependencies = [
"hashbrown 0.17.1",
"linebender_resource_handle",
"memmap2",
"memmap2 0.9.10",
"parlance",
"read-fonts",
"smallvec",
@@ -1853,6 +1901,7 @@ dependencies = [
"gungraun",
"js-sys",
"log",
"mmap-io",
"pretty_assertions",
"raster-nodes",
"rendering",
@@ -1866,6 +1915,7 @@ dependencies = [
"url",
"vector-nodes",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wgpu-executor",
"winit",
@@ -1875,9 +1925,11 @@ dependencies = [
name = "graphene-application-io"
version = "0.1.0"
dependencies = [
"blake3",
"core-types",
"dyn-any",
"glam",
"graphene-resource",
"log",
"serde",
"text-nodes",
@@ -1957,6 +2009,17 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "graphene-resource"
version = "0.1.0"
dependencies = [
"blake3",
"core-types",
"dyn-any",
"serde",
"url",
]
[[package]]
name = "graphene-std"
version = "0.1.0"
@@ -2108,7 +2171,6 @@ version = "0.1.0"
dependencies = [
"base64",
"dirs",
"futures",
"graph-craft",
"graphene-std",
"graphite-editor",
@@ -2148,6 +2210,7 @@ dependencies = [
"num_enum",
"once_cell",
"preprocessor",
"reqwest",
"serde",
"serde_bytes",
"serde_json",
@@ -2155,11 +2218,14 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tsify",
"url",
"usvg",
"vello",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wgpu-executor",
"zip",
]
[[package]]
@@ -2958,6 +3024,15 @@ dependencies = [
"redox_syscall",
]
[[package]]
name = "libz-rs-sys"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c10501e7805cee23da17c7790e59df2870c0d4043ec6d03f67d31e2b53e77415"
dependencies = [
"zlib-rs",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -3105,6 +3180,15 @@ version = "2.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
[[package]]
name = "memmap2"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f49388d20533534cd19360ad3d6a7dadc885944aa802ba3995040c5ec11288c6"
dependencies = [
"libc",
]
[[package]]
name = "memmap2"
version = "0.9.10"
@@ -3141,6 +3225,21 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "mmap-io"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a34b926fd173419d630eb9d8ee3a485345237bf699d6f7ea6e5c1ee97cf1fa47"
dependencies = [
"anyhow",
"cfg-if",
"libc",
"log",
"memmap2 0.7.1",
"parking_lot",
"thiserror 1.0.69",
]
[[package]]
name = "muda"
version = "0.17.1"
@@ -4292,6 +4391,7 @@ dependencies = [
"futures",
"glam",
"graphene-hash",
"graphene-resource",
"image",
"kurbo",
"ndarray",
@@ -4852,7 +4952,7 @@ checksum = "1dd3accc0f3f4bbaf2c9e1957a030dc582028130c67660d44c0a0345a22ca69b"
dependencies = [
"ab_glyph",
"log",
"memmap2",
"memmap2 0.9.10",
"smithay-client-toolkit",
"tiny-skia",
]
@@ -5034,7 +5134,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -5120,7 +5220,7 @@ dependencies = [
"cursor-icon",
"libc",
"log",
"memmap2",
"memmap2 0.9.10",
"rustix",
"thiserror 2.0.18",
"wayland-backend",
@@ -5423,6 +5523,19 @@ dependencies = [
"xattr",
]
[[package]]
name = "tempfile"
version = "3.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
dependencies = [
"fastrand",
"getrandom 0.3.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "tendril"
version = "0.4.3"
@@ -5453,6 +5566,7 @@ dependencies = [
"fancy-regex",
"glam",
"graphene-hash",
"graphene-resource",
"log",
"node-macro",
"parley",
@@ -5901,6 +6015,12 @@ dependencies = [
"core_maths",
]
[[package]]
name = "typed-path"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
[[package]]
name = "typeid"
version = "1.0.3"
@@ -7230,7 +7350,7 @@ name = "winit-common"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
dependencies = [
"memmap2",
"memmap2 0.9.10",
"objc2 0.6.4",
"objc2-core-foundation",
"smol_str",
@@ -7302,7 +7422,7 @@ dependencies = [
"cursor-icon",
"dpi",
"libc",
"memmap2",
"memmap2 0.9.10",
"raw-window-handle",
"rustix",
"sctk-adwaita",
@@ -7599,6 +7719,25 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "zip"
version = "8.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
dependencies = [
"crc32fast",
"flate2",
"indexmap",
"memchr",
"typed-path",
]
[[package]]
name = "zlib-rs"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40990edd51aae2c2b6907af74ffb635029d5788228222c4bb811e9351c0caad3"
[[package]]
name = "zune-core"
version = "0.4.12"
+5
View File
@@ -7,6 +7,7 @@ members = [
"desktop/platform/linux",
"desktop/platform/mac",
"desktop/platform/win",
"document/container",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -68,6 +69,7 @@ graphene-hash = { path = "node-graph/libraries/graphene-hash", features = ["deri
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" }
@@ -171,6 +173,8 @@ glam = { version = "0.32.1", default-features = false, features = [
"bytemuck",
] }
base64 = "0.22"
blake3 = "1.5"
mmap-io = { version = "0.9", features = ["hugepages"] }
image = { version = "0.25", default-features = false, features = [
"png",
"jpeg",
@@ -219,6 +223,7 @@ lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "e
scraper = "0.25"
linesweeper = "0.3"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
+10 -4
View File
@@ -16,13 +16,14 @@ use winit::window::WindowId;
use crate::cef;
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
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>,
@@ -91,7 +92,14 @@ impl App {
}
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
// 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,
@@ -526,8 +534,6 @@ impl ApplicationHandler for App {
self.resize();
self.desktop_wrapper.init(self.wgpu_context.clone());
self.startup_time = Some(Instant::now());
}
+1
View File
@@ -11,6 +11,7 @@ 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;
+7 -1
View File
@@ -2,7 +2,7 @@ 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() {
@@ -51,6 +51,12 @@ pub(crate) fn app_autosave_documents_dir() -> PathBuf {
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,
-1
View File
@@ -20,7 +20,6 @@ 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));
}
+7 -8
View File
@@ -1,9 +1,12 @@
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 graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
@@ -22,7 +25,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")]
@@ -30,17 +33,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 = PlatformApplicationIo::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);
+1
View File
@@ -82,6 +82,7 @@ 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 },
+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 }
+97
View File
@@ -0,0 +1,97 @@
//! 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 = "zip", feature = "xz"))]
use crate::ContainerError;
use crate::{Container, 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: Container>(source: R, dest: &mut C) -> Result<()>;
}
pub trait ArchiveWriter {
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()>;
fn finish(self) -> Result<()>;
}
/// 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(all(feature = "xz", feature = "zip"))]
pub fn open_auto<C: Container>(bytes: &[u8], dest: &mut C) -> Result<()> {
let source = std::io::Cursor::new(bytes);
match ArchiveFormat::detect(bytes) {
Some(ArchiveFormat::Xz) => Xz::open(source, dest),
Some(ArchiveFormat::Zip) => Zip::open(source, dest),
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip)".into())),
}
}
+97
View File
@@ -0,0 +1,97 @@
//! Xz-compressed tarball archive codec.
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size};
use crate::{Container, 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: Container>(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(&path, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(())
})?;
}
Ok(())
}
}
impl<W: Write + Seek> ArchiveWriter for XzWriter<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(mut self) -> Result<()> {
self.finish_inner()?;
Ok(())
}
}
impl<W: Write + Seek> XzWriter<W> {
/// 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.
pub fn finish_into(mut self) -> Result<W> {
self.finish_inner()
}
/// Unwind the layered writers in order (flush the tar trailer, then finish xz) and hand back the
/// innermost sink. Shared by `finish` and `finish_into`.
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}"))
}
+83
View File
@@ -0,0 +1,83 @@
//! Zip archive codec.
use crate::archive::{Archive, ArchiveWriter, checked_entry_size};
use crate::{Container, 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: Container>(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(&name, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(())
})?;
}
Ok(())
}
}
impl<W: Write + Seek> ArchiveWriter for ZipWriter<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(self) -> Result<()> {
self.inner.finish().map_err(zip_err)?;
Ok(())
}
}
impl<W: Write + Seek> ZipWriter<W> {
/// 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.
pub 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)
}
}
+500
View File
@@ -0,0 +1,500 @@
//! 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 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 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);
}
+9 -1
View File
@@ -47,6 +47,9 @@ base64 = { workspace = true }
spin = { workspace = true }
image = { workspace = true }
color = { workspace = true }
zip = { workspace = true }
reqwest = { workspace = true }
url = { workspace = true }
# Optional local dependencies
wgpu-executor = { workspace = true, optional = true }
@@ -54,8 +57,13 @@ wgpu-executor = { workspace = true, optional = true }
# Optional workspace dependencies
wasm-bindgen = { workspace = true, optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
tokio = { workspace = true }
[target.'cfg(target_family = "wasm")'.dependencies]
wasm-bindgen-futures = { workspace = true }
[dev-dependencies]
# Workspace dependencies
env_logger = { workspace = true }
futures = { workspace = true }
tokio = { workspace = true }
+15 -4
View File
@@ -1,18 +1,25 @@
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
pub use graphene_std::uuid::*;
use std::sync::OnceLock;
use std::sync::{Arc, OnceLock};
pub struct Editor {
pub dispatcher: Dispatcher,
}
impl Editor {
pub fn new(environment: Environment, uuid_random_seed: u64) -> Self {
pub fn new(environment: Environment, uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, mut application_io: PlatformApplicationIo, wake: Wake) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
Self { dispatcher: Dispatcher::new() }
let mut dispatcher = Dispatcher::new(resource_storage);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
Self { dispatcher }
}
#[cfg(test)]
@@ -20,11 +27,15 @@ impl Editor {
let _ = ENVIRONMENT.set(*Editor::environment());
graphene_std::uuid::set_uuid_seed(0);
let (runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
let editor = Self {
dispatcher: Dispatcher::with_executor(executor),
};
let mut application_io = PlatformApplicationIo::default();
application_io.inject_resource_proxy(editor.dispatcher.message_handlers.resource_storage_message_handler.resources());
runtime.replace_application_io(application_io);
(editor, runtime)
}
+41 -20
View File
@@ -6,6 +6,8 @@ use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
use graph_craft::application_io::resource::ResourceStorage;
use std::sync::Arc;
#[derive(Debug, Default)]
pub struct Dispatcher {
@@ -19,6 +21,7 @@ pub struct Dispatcher {
pub struct DispatcherMessageHandlers {
animation_message_handler: AnimationMessageHandler,
app_window_message_handler: AppWindowMessageHandler,
pub(crate) future_message_handler: FutureMessageHandler,
broadcast_message_handler: BroadcastMessageHandler,
clipboard_message_handler: ClipboardMessageHandler,
color_picker_message_handler: ColorPickerMessageHandler,
@@ -29,17 +32,26 @@ pub struct DispatcherMessageHandlers {
key_mapping_message_handler: KeyMappingMessageHandler,
layout_message_handler: LayoutMessageHandler,
menu_bar_message_handler: MenuBarMessageHandler,
network_message_handler: NetworkMessageHandler,
pub(crate) portfolio_message_handler: PortfolioMessageHandler,
preferences_message_handler: PreferencesMessageHandler,
pub(crate) resource_storage_message_handler: ResourceStorageMessageHandler,
tool_message_handler: ToolMessageHandler,
viewport_message_handler: ViewportMessageHandler,
}
impl DispatcherMessageHandlers {
pub fn with_resource_storage(resource_storage: Arc<dyn ResourceStorage>) -> Self {
Self {
resource_storage_message_handler: ResourceStorageMessageHandler::new(resource_storage),
..Self::default()
}
}
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
Self {
portfolio_message_handler: PortfolioMessageHandler::with_executor(executor),
..Default::default()
..Self::default()
}
}
}
@@ -54,7 +66,6 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontDataLoad),
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
];
/// Since we don't need to update the frontend multiple times per frame,
@@ -78,15 +89,16 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
impl Dispatcher {
pub fn new() -> Self {
Self::default()
pub fn new(resource_storage: Arc<dyn ResourceStorage>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s
}
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
Self {
message_handlers: DispatcherMessageHandlers::with_executor(executor),
..Default::default()
}
let mut s = Self::default();
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
// If the deepest queues (higher index in queues list) are now empty (after being popped from) then remove them
@@ -114,6 +126,13 @@ impl Dispatcher {
pub fn handle_message<T: Into<Message>>(&mut self, message: T, process_after_all_current: bool) {
let message = message.into();
// Drain async results into the queue before processing the new message.
let mut async_results = VecDeque::new();
self.message_handlers.future_message_handler.drain_results(&mut async_results);
if !async_results.is_empty() {
Self::schedule_execution(&mut self.message_queues, true, async_results);
}
// If we are not maintaining the buffer, simply add to the current queue
Self::schedule_execution(&mut self.message_queues, process_after_all_current, [message]);
@@ -163,6 +182,9 @@ impl Dispatcher {
Message::AppWindow(message) => {
self.message_handlers.app_window_message_handler.process_message(message, &mut queue, ());
}
Message::Future(message) => {
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
}
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
Message::Clipboard(message) => self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, ()),
Message::ColorPicker(message) => self.message_handlers.color_picker_message_handler.process_message(message, &mut queue, ()),
@@ -183,17 +205,7 @@ impl Dispatcher {
self.message_handlers.dialog_message_handler.process_message(message, &mut queue, context);
}
Message::Frontend(message) => {
// Handle these messages immediately by returning early
if let FrontendMessage::TriggerFontDataLoad { .. } | FrontendMessage::TriggerFontCatalogLoad = message {
self.responses.push(message);
self.cleanup_queues(false);
// Return early to avoid running the code after the match block
return;
} else {
// `FrontendMessage`s are saved and will be sent to the frontend after the message queue is done being processed
self.responses.push(message);
}
self.responses.push(message);
}
Message::InputPreprocessor(message) => {
self.message_handlers.input_preprocessor_message_handler.process_message(
@@ -218,6 +230,14 @@ impl Dispatcher {
self.message_handlers.layout_message_handler.process_message(message, &mut queue, context);
}
Message::Network(message) => {
self.message_handlers.network_message_handler.process_message(message, &mut queue, NetworkMessageContext {});
}
Message::ResourceStorage(message) => {
self.message_handlers
.resource_storage_message_handler
.process_message(message, &mut queue, ResourceStorageMessageContext {});
}
Message::Portfolio(message) => {
self.message_handlers.portfolio_message_handler.process_message(
message,
@@ -230,6 +250,7 @@ impl Dispatcher {
timing_information: self.message_handlers.animation_message_handler.timing_information(),
animation: &self.message_handlers.animation_message_handler,
viewport: &self.message_handlers.viewport_message_handler,
resource_storage: &self.message_handlers.resource_storage_message_handler,
},
);
}
@@ -297,7 +318,7 @@ impl Dispatcher {
document_id,
document,
input: &self.message_handlers.input_preprocessor_message_handler,
cached_data: &self.message_handlers.portfolio_message_handler.cached_data,
fonts: &self.message_handlers.portfolio_message_handler.fonts,
node_graph: &self.message_handlers.portfolio_message_handler.executor,
preferences: &self.message_handlers.preferences_message_handler,
viewport: &self.message_handlers.viewport_message_handler,
@@ -3,7 +3,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use graphene_std::render_node::{EditorPreferences, wgpu_available};
use graph_craft::application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> {
@@ -307,7 +307,7 @@ impl PreferencesDialogMessageHandler {
// COMPATIBILITY
// =============
{
let wgpu_available = wgpu_available().unwrap_or(false);
let wgpu_available = graph_craft::application_io::wgpu_available().unwrap_or(false);
let is_desktop = cfg!(not(target_family = "wasm"));
if wgpu_available || is_desktop {
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
@@ -0,0 +1,113 @@
// TODO: Eventually remove this document upgrade code
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
pub struct FailedToLoadDocumentsDialog {
pub failed_document_names: Vec<String>,
}
impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Failed to Open Documents";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("Download")
.emphasized(true)
.tooltip_description("Save the raw document data to disk so it can be recovered later.")
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::DownloadFailedToLoadDocuments.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Discard")
.tooltip_description("Permanently delete the autosaved data for these documents.")
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::DiscardFailedToLoadDocuments.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Dismiss")
.tooltip_description("Close this dialog. The autosaved data is kept and this dialog will reappear on next launch.")
.on_update(|_| FrontendMessage::DialogClose.into())
.widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for FailedToLoadDocumentsDialog {
fn layout(&self) -> Layout {
let count = self.failed_document_names.len();
let header = format!("{count} document{} couldn't be reopened.", if count == 1 { "" } else { "s" });
let list = "• ".to_string() + &self.failed_document_names.join("\n• ");
let plural_s = if count == 1 { "" } else { "s" };
let plural_it_them = if count == 1 { "it" } else { "them" };
Layout(vec![
LayoutGroup::row(vec![TextLabel::new(header).bold(true).multiline(true).widget_instance()]),
LayoutGroup::row(vec![
TextLabel::new(format!(
"Sorry about that!\n\
This shouldn't happen, and we'd like to help.\n\
\n\
Click \"Download\" to save a copy of the affected file{plural_s},\n\
then please share {plural_it_them} with us so we can investigate:"
))
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Ask on Discord")
.icon("Volunteer")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://discord.graphite.art".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Report on GitHub")
.icon("Bug")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextLabel::new(
"In the meantime, you can keep working in the\n\
previous version of Graphite:",
)
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Sept. 2025 Release")
.icon("GraphiteLogo")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://57130155.graphite.pages.dev/".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![TextLabel::new(format!("Affected document{plural_s}:\n{list}")).multiline(true).widget_instance()]),
])
}
}
@@ -0,0 +1,84 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
pub struct FailedToOpenDocumentDialog {
pub document_name: String,
}
impl DialogLayoutHolder for FailedToOpenDocumentDialog {
const ICON: &'static str = "Warning";
const TITLE: &'static str = "Failed to Open Document";
fn layout_buttons(&self) -> Layout {
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DialogClose.into()).widget_instance()];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for FailedToOpenDocumentDialog {
fn layout(&self) -> Layout {
let header = if self.document_name.trim().is_empty() {
"The document couldn't be opened.".to_string()
} else {
format!("\"{}\" couldn't be opened.", self.document_name)
};
Layout(vec![
LayoutGroup::row(vec![TextLabel::new(header).bold(true).multiline(true).widget_instance()]),
LayoutGroup::row(vec![
TextLabel::new(
"Sorry about that!\n\
This shouldn't happen, and we'd like to help.\n\
\n\
Please share the file with us so we can investigate:",
)
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Ask on Discord")
.icon("Volunteer")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://discord.graphite.art".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Report on GitHub")
.icon("Bug")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://github.com/GraphiteEditor/Graphite/issues/new".into(),
}
.into()
})
.widget_instance(),
]),
LayoutGroup::row(vec![
TextLabel::new(
"In the meantime, you can keep working in the\n\
previous version of Graphite:",
)
.multiline(true)
.widget_instance(),
]),
LayoutGroup::row(vec![
TextButton::new("Sept. 2025 Release")
.icon("GraphiteLogo")
.flush(true)
.on_update(|_| {
FrontendMessage::TriggerVisitLink {
url: "https://57130155.graphite.pages.dev/".into(),
}
.into()
})
.widget_instance(),
]),
])
}
}
@@ -4,6 +4,8 @@ mod close_document_dialog;
mod confirm_restart_dialog;
mod demo_artwork_dialog;
mod error_dialog;
mod failed_to_load_documents_dialog;
mod failed_to_open_document_dialog;
mod licenses_dialog;
mod licenses_third_party_dialog;
@@ -14,5 +16,7 @@ pub use confirm_restart_dialog::ConfirmRestartDialog;
pub use demo_artwork_dialog::ARTWORK;
pub use demo_artwork_dialog::DemoArtworkDialog;
pub use error_dialog::ErrorDialog;
pub use failed_to_load_documents_dialog::FailedToLoadDocumentsDialog;
pub use failed_to_open_document_dialog::FailedToOpenDocumentDialog;
pub use licenses_dialog::LicensesDialog;
pub use licenses_third_party_dialog::LicensesThirdPartyDialog;
@@ -15,7 +15,6 @@ use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use graphene_std::text::Font;
use graphene_std::vector::style::FillChoiceUI;
use std::path::PathBuf;
@@ -111,11 +110,6 @@ pub enum FrontendMessage {
name: String,
filename: String,
},
TriggerFontCatalogLoad,
TriggerFontDataLoad {
font: Font,
url: String,
},
TriggerPersistenceReadState,
TriggerPersistenceReadDocument {
#[serde(rename = "documentId")]
@@ -1,5 +1,7 @@
use std::path::PathBuf;
use graph_craft::application_io::resource::ResourceHash;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*;
@@ -10,6 +12,9 @@ pub struct DocumentInfo {
pub id: DocumentId,
pub name: String,
#[serde(default)]
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
pub resources: Option<Box<[ResourceHash]>>,
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
}
@@ -0,0 +1,16 @@
use crate::messages::future::MessageFuture;
use crate::messages::prelude::*;
#[impl_message(Message, Future)]
#[derive(derivative::Derivative, Clone, serde::Serialize, serde::Deserialize)]
#[derivative(Debug, PartialEq)]
pub enum FutureMessage {
/// Spawn `future`; its resolved [`Message`] re-enters the dispatcher on the next tick.
Await {
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
future: MessageFuture,
},
/// Sent by a wake callback to nudge an idle event loop into a dispatch tick.
Wake,
}
@@ -0,0 +1,193 @@
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use dyn_any::WasmNotSend;
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
use crate::messages::prelude::*;
#[cfg(not(target_family = "wasm"))]
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
#[cfg(target_family = "wasm")]
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + 'static>>;
/// Invoked by the spawner after a result is sent, to wake the platform event loop.
pub type Wake = Arc<dyn Fn() + Send + Sync>;
fn noop_wake() -> Wake {
Arc::new(|| {})
}
/// One-shot async work whose result re-enters the dispatcher as a [`Message`].
/// Resolves to [`Message::NoOp`] if polled after the inner future has already been taken.
#[derive(Clone, Default)]
pub struct MessageFuture {
inner: Arc<Mutex<Option<InnerMessageFuture>>>,
}
impl MessageFuture {
pub fn new(future: impl Future<Output = Message> + WasmNotSend + 'static) -> Self {
Self {
inner: Arc::new(Mutex::new(Some(Box::pin(future)))),
}
}
}
impl IntoFuture for MessageFuture {
type Output = Message;
type IntoFuture = InnerMessageFuture;
fn into_future(self) -> Self::IntoFuture {
let taken = self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take();
match taken {
Some(future) => future,
None => Box::pin(async { Message::NoOp }),
}
}
}
impl From<MessageFuture> for Message {
fn from(future: MessageFuture) -> Self {
FutureMessage::Await { future }.into()
}
}
impl<T> From<T> for Message
where
T: Future<Output = Message> + WasmNotSend + 'static,
{
fn from(future: T) -> Self {
MessageFuture::new(future).into()
}
}
/// Platform-specific async-task executor.
/// Runs `future`, sends the resolved message on `results`, then calls `wake`.
pub trait MessageSpawner: Send + Sync {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake);
}
#[derive(ExtractField)]
pub struct FutureMessageContext {}
#[derive(ExtractField)]
pub struct FutureMessageHandler {
spawner: Arc<dyn MessageSpawner>,
wake: Wake,
results_sender: UnboundedSender<Message>,
results_receiver: UnboundedReceiver<Message>,
}
impl FutureMessageHandler {
pub fn with_wake(wake: Wake) -> Self {
let (results_sender, results_receiver) = unbounded();
Self {
spawner: default_spawner(),
wake,
results_sender,
results_receiver,
}
}
pub fn set_wake(&mut self, wake: Wake) {
self.wake = wake;
}
/// Pull every resolved async result into `out`.
pub fn drain_results(&mut self, out: &mut VecDeque<Message>) {
while let Ok(Some(message)) = self.results_receiver.try_next() {
out.push_back(message);
}
}
}
impl Default for FutureMessageHandler {
fn default() -> Self {
Self::with_wake(noop_wake())
}
}
impl std::fmt::Debug for FutureMessageHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FutureMessageHandler").finish_non_exhaustive()
}
}
#[message_handler_data]
impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandler {
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
match message {
FutureMessage::Await { future } => {
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
}
FutureMessage::Wake => {
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
}
}
}
advertise_actions!(FutureMessageDiscriminant;);
}
#[cfg(not(target_family = "wasm"))]
fn default_spawner() -> Arc<dyn MessageSpawner> {
Arc::new(TokioSpawner::default())
}
#[cfg(target_family = "wasm")]
fn default_spawner() -> Arc<dyn MessageSpawner> {
Arc::new(WasmSpawner)
}
#[cfg(not(target_family = "wasm"))]
struct TokioSpawner {
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
}
#[cfg(not(target_family = "wasm"))]
impl Default for TokioSpawner {
fn default() -> Self {
Self { runtime: std::sync::OnceLock::new() }
}
}
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
fn runtime(&self) -> &tokio::runtime::Runtime {
self.runtime.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("graphite-async")
.enable_all()
.build()
.expect("failed to construct async-message tokio runtime")
})
}
}
#[cfg(not(target_family = "wasm"))]
impl MessageSpawner for TokioSpawner {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
self.runtime().spawn(async move {
let message = future.await;
let _ = results.unbounded_send(message);
wake();
});
}
}
#[cfg(target_family = "wasm")]
struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl MessageSpawner for WasmSpawner {
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
wasm_bindgen_futures::spawn_local(async move {
let message = future.await;
let _ = results.unbounded_send(message);
wake();
});
}
}
+7
View File
@@ -0,0 +1,7 @@
mod future_message;
mod future_message_handler;
#[doc(inline)]
pub use future_message::{FutureMessage, FutureMessageDiscriminant};
#[doc(inline)]
pub use future_message_handler::{FutureMessageContext, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
+6
View File
@@ -24,6 +24,8 @@ pub enum Message {
#[child]
Frontend(FrontendMessage),
#[child]
Future(FutureMessage),
#[child]
InputPreprocessor(InputPreprocessorMessage),
#[child]
KeyMapping(KeyMappingMessage),
@@ -32,10 +34,14 @@ pub enum Message {
#[child]
MenuBar(MenuBarMessage),
#[child]
Network(NetworkMessage),
#[child]
Portfolio(PortfolioMessage),
#[child]
Preferences(PreferencesMessage),
#[child]
ResourceStorage(ResourceStorageMessage),
#[child]
Tool(ToolMessage),
#[child]
Viewport(ViewportMessage),
+3
View File
@@ -9,13 +9,16 @@ pub mod debug;
pub mod defer;
pub mod dialog;
pub mod frontend;
pub mod future;
pub mod input_mapper;
pub mod input_preprocessor;
pub mod layout;
pub mod menu_bar;
pub mod message;
pub mod network;
pub mod portfolio;
pub mod preferences;
pub mod prelude;
pub mod resource_storage;
pub mod tool;
pub mod viewport;
+10
View File
@@ -0,0 +1,10 @@
mod network_message;
mod network_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use network_message::{NetworkMessage, NetworkMessageDiscriminant};
#[doc(inline)]
pub use network_message_handler::{NetworkMessageContext, NetworkMessageHandler};
#[doc(inline)]
pub use utility_types::Client;
@@ -0,0 +1,49 @@
use std::pin::Pin;
use dyn_any::WasmNotSend;
use crate::messages::network::utility_types::Client;
use crate::messages::prelude::*;
#[impl_message(Message, Network)]
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize)]
#[derivative(Debug, PartialEq)]
pub enum NetworkMessage {
Request {
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
request: Option<RequestFn>,
},
}
impl NetworkMessage {
pub fn request<F, Fut>(f: F) -> Self
where
F: FnOnce(Client) -> Fut + WasmNotSend + 'static,
Fut: Future<Output = Message> + WasmNotSend + 'static,
{
NetworkMessage::Request {
request: Some(Box::new(move |c| Box::pin(f(c)))),
}
}
}
#[cfg(not(target_family = "wasm"))]
type RequestFuture = Pin<Box<dyn Future<Output = Message> + Send>>;
#[cfg(target_family = "wasm")]
type RequestFuture = Pin<Box<dyn Future<Output = Message>>>;
#[cfg(not(target_family = "wasm"))]
type RequestFn = Box<dyn FnOnce(Client) -> RequestFuture + Send>;
#[cfg(target_family = "wasm")]
type RequestFn = Box<dyn FnOnce(Client) -> RequestFuture>;
impl Clone for NetworkMessage {
fn clone(&self) -> Self {
match self {
NetworkMessage::Request { .. } => {
log::error!("Cloning a NetworkMessage::Request is not supported");
NetworkMessage::Request { request: None }
}
}
}
}
@@ -0,0 +1,27 @@
use crate::messages::network::utility_types::Client;
use crate::messages::prelude::*;
#[derive(ExtractField)]
pub struct NetworkMessageContext {}
#[derive(Debug, Default, ExtractField)]
pub struct NetworkMessageHandler {
client: Client,
}
#[message_handler_data]
impl MessageHandler<NetworkMessage, NetworkMessageContext> for NetworkMessageHandler {
fn process_message(&mut self, message: NetworkMessage, responses: &mut VecDeque<Message>, _context: NetworkMessageContext) {
match message {
NetworkMessage::Request { request } => {
if let Some(request) = request {
responses.add(request(self.client.clone()));
} else {
log::error!("received a empty NetworkMessage::Request");
}
}
}
}
advertise_actions!(NetworkMessageDiscriminant;
);
}
@@ -0,0 +1,30 @@
use reqwest::IntoUrl;
#[derive(Debug, Clone)]
pub struct Client {
inner: Option<reqwest::Client>,
}
impl Default for Client {
fn default() -> Self {
Self {
#[cfg(not(target_family = "wasm"))]
inner: reqwest::Client::builder().timeout(std::time::Duration::from_secs(100)).build().ok(),
#[cfg(target_family = "wasm")]
inner: reqwest::Client::builder().build().ok(),
}
}
}
impl Client {
pub async fn fetch<U: IntoUrl>(&self, url: U) -> Option<Box<[u8]>> {
let Some(client) = &self.inner else {
log::error!("HTTP client failed to initialize, cannot fetch");
return None;
};
let response = client.get(url).send().await;
let response = response.and_then(|r| r.error_for_status()).map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
let bytes = response.bytes().await.map_err(|err| log::error!("failed to read response body: {err}")).ok()?;
Some(bytes.to_vec().into_boxed_slice())
}
}
@@ -37,6 +37,8 @@ pub enum DocumentMessage {
PropertiesPanel(PropertiesPanelMessage),
#[child]
DataPanel(DataPanelMessage),
#[child]
Resource(ResourceMessage),
// Messages
AlignSelectedLayers {
@@ -21,7 +21,7 @@ use crate::messages::portfolio::document::properties_panel::properties_panel_mes
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::utility_types::{CachedData, PanelType};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
@@ -29,13 +29,14 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
use graphene_std::raster::BlendMode;
use graphene_std::render_node::wgpu_available;
use graphene_std::subpath::Subpath;
use graphene_std::vector::PointId;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
@@ -51,7 +52,6 @@ use std::time::Duration;
pub struct DocumentMessageContext<'a> {
pub document_id: DocumentId,
pub ipp: &'a InputPreprocessorMessageHandler,
pub cached_data: &'a CachedData,
pub executor: &'a mut NodeGraphExecutor,
pub current_tool: &'a ToolType,
pub preferences: &'a PreferencesMessageHandler,
@@ -59,6 +59,8 @@ pub struct DocumentMessageContext<'a> {
pub layers_panel_open: bool,
pub properties_panel_open: bool,
pub viewport: &'a ViewportMessageHandler,
pub resource_storage: &'a ResourceStorageMessageHandler,
pub fonts: &'a FontsMessageHandler,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
@@ -85,6 +87,9 @@ pub struct DocumentMessageHandler {
//
// Contains the NodeNetwork and acts an an interface to manipulate the NodeNetwork with custom setters in order to keep NetworkMetadata in sync
pub network_interface: NodeNetworkInterface,
/// Resources embedded in the document.
#[serde(default, skip_serializing_if = "ResourceMessageHandler::is_empty")]
pub resources: ResourceMessageHandler,
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree path.
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
pub collapsed: CollapsedLayers,
@@ -160,6 +165,7 @@ impl Default for DocumentMessageHandler {
// Fields that are saved in the document format
// ============================================
network_interface: default_document_network_interface(),
resources: ResourceMessageHandler::default(),
collapsed: CollapsedLayers::default(),
commit_hash: GRAPHITE_GIT_COMMIT_HASH.to_string(),
document_ptz: PTZ::default(),
@@ -192,7 +198,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let DocumentMessageContext {
document_id,
ipp,
cached_data,
executor,
viewport,
current_tool,
@@ -200,6 +205,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
data_panel_open,
layers_panel_open,
properties_panel_open,
resource_storage,
fonts,
} = context;
match message {
@@ -226,11 +233,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
DocumentMessage::PropertiesPanel(message) => {
let context = PropertiesPanelMessageContext {
executor,
network_interface: &mut self.network_interface,
resources: &self.resources,
selection_network_path: &self.selection_network_path,
document_name: self.name.as_str(),
executor,
cached_data,
fonts,
properties_panel_open,
};
self.properties_panel_message_handler.process_message(message, responses, context);
@@ -274,6 +282,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let mut graph_operation_message_handler = GraphOperationMessageHandler {};
graph_operation_message_handler.process_message(message, responses, context);
}
DocumentMessage::Resource(message) => {
let context = ResourceMessageContext { document_id, fonts };
self.resources.process_message(message, responses, context);
}
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
let axis = match axis {
AlignAxis::X => DVec2::X,
@@ -912,19 +924,29 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
responses.add(PortfolioMessage::AutoSaveActiveDocument);
let name = format!("{}.{}", self.name.clone(), FILE_EXTENSION);
let path = if let DocumentMessage::SaveDocumentAs = message { None } else { self.path.clone() };
if path.is_some() {
responses.add(DocumentMessage::MarkAsSaved);
}
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
responses.add(FrontendMessage::TriggerSaveDocument {
document_id,
name: format!("{}.{}", self.name.clone(), FILE_EXTENSION),
path,
folder,
content: self.serialize_document().into_bytes().into(),
let mut document = self.clone();
let resources_load_handle = resource_storage.resources();
responses.add(async move {
document.resources.collect_garbage(document.used_resources(false).as_ref());
document.resources.embed_resources(resources_load_handle).await;
let content = document.serialize_document().into_bytes().into();
Message::Frontend(FrontendMessage::TriggerSaveDocument {
document_id,
name,
path,
folder,
content,
})
});
}
DocumentMessage::SavedDocument { path } => {
@@ -1306,11 +1328,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_text_frames = text_frames
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, frame)| {
self.network_interface.is_layer(&node_id, &[]).then(|| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, frame)
})
.filter(|&(node_id, _)| self.network_interface.is_layer(&node_id, &[]))
.map(|(node_id, frame)| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, frame)
})
.collect();
self.network_interface.update_text_frames(layer_text_frames);
@@ -2546,6 +2567,7 @@ impl DocumentMessageHandler {
/// Helper method for NudgeSelectedLayers message.
/// Handles keyboard nudging of selected layers with optional resize mode.
#[allow(clippy::too_many_arguments)]
fn handle_nudge_selected_layers(
&mut self,
delta_x: f64,
@@ -2635,23 +2657,6 @@ impl DocumentMessageHandler {
}
}
/// Loads all of the fonts in the document.
pub fn load_layer_resources(&self, responses: &mut VecDeque<Message>) {
let mut fonts_to_load = HashSet::new();
for (_, node, _) in self.document_network().recursive_nodes() {
for input in &node.inputs {
if let Some(TaggedValue::Font(font)) = input.as_value() {
fonts_to_load.insert(font.clone());
}
}
}
for font in fonts_to_load {
responses.add(PortfolioMessage::LoadFontData { font });
}
}
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
let mut snapping_state = self.snapping_state.clone();
let mut snapping_state2 = self.snapping_state.clone();
@@ -3444,6 +3449,21 @@ impl DocumentMessageHandler {
pub fn graph_view_overlay_open(&self) -> bool {
self.graph_view_overlay_open
}
pub fn garbage_collect_resources(&mut self) {
let used_resources = self.used_resources(true);
self.resources.collect_garbage(&used_resources);
}
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
if include_history {
self.document_undo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
self.document_redo_history.iter().for_each(|interface| interface.collect_used_resources(&mut resources));
}
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
}
}
/// Create a network interface with a single export
@@ -32,7 +32,7 @@ pub struct GraphOperationMessageHandler {}
#[message_handler_data]
impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for GraphOperationMessageHandler {
fn process_message(&mut self, message: GraphOperationMessage, responses: &mut VecDeque<Message>, context: GraphOperationMessageContext) {
let network_interface = context.network_interface;
let GraphOperationMessageContext { network_interface, .. } = context;
match message {
GraphOperationMessage::FillSet { layer, fill } => {
@@ -1,9 +1,11 @@
use super::transform_utils;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{self, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
@@ -248,12 +250,13 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn insert_text(&mut self, text: String, font: Font, typesetting: TypesettingConfig, layer: LayerNodeIdentifier) {
let font_resource_id = ResourceId::new();
let text = resolve_proto_node_type(graphene_std::text::text::IDENTIFIER)
.expect("Text node does not exist")
.node_template_input_override([
Some(NodeInput::scope("editor-api")),
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Font(font), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
@@ -263,6 +266,7 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
Some(NodeInput::value(TaggedValue::Bool(false), false)),
]);
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
@@ -275,6 +279,8 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.insert_node(text_id, text, &[]);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
@@ -298,13 +304,20 @@ impl<'a> ModifyInputsContext<'a> {
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
.default_node_template();
let resource_id = ResourceId::new();
self.responses.add(ResourceMessage::StoreEmbedded {
resource_id,
data: image.to_png().into(),
});
let image_node = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER)
.expect("Image node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::ImageData(image), false))]);
.node_template_input_override([Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
let image_id = NodeId::new();
self.network_interface.insert_node(image_id, image_node, &[]);
self.network_interface.move_node_to_chain_start(&image_id, layer, &[], self.import);
let image_node_id = NodeId::new();
self.network_interface.insert_node(image_node_id, image_node, &[]);
self.network_interface.move_node_to_chain_start(&image_node_id, layer, &[], self.import);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
@@ -327,6 +340,37 @@ impl<'a> ModifyInputsContext<'a> {
self.existing_node_id(&DefinitionIdentifier::Network(reference.into()), create_if_nonexistent)
}
/// Like `existing_proto_node_id`, but walks/inserts at `target_input` instead of the layer's content input.
/// Used when a chain lives on a non-layer input.
pub fn existing_proto_node_id_at(&mut self, target_input: &InputConnector, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
let identifier = DefinitionIdentifier::ProtoNode(reference.clone());
// Walk upstream from whatever is currently connected to target_input
let walk_start = self.network_interface.upstream_output_connector(target_input, &[]).and_then(|out| out.node_id());
let existing = walk_start.and_then(|start| {
self.network_interface
.upstream_flow_back_from_nodes(vec![start], &[], FlowType::HorizontalFlow)
.take_while(|id| !self.network_interface.is_layer(id, &[]))
.find(|id| self.network_interface.reference(id, &[]).as_ref() == Some(&identifier) && self.network_interface.is_visible(id, &[]))
});
if let Some(id) = existing {
return Some(id);
}
if !create_if_nonexistent {
return None;
}
// Splice a new node onto the wire feeding `target_input`, positioning it sensibly within the chain.
let node_definition = resolve_proto_node_type(reference)?;
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
self.network_interface.insert_node_before_input(&node_id, target_input, &[]);
Some(node_id)
}
/// Gets the node id of a proto node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
pub fn existing_proto_node_id(&mut self, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
self.existing_node_id(&DefinitionIdentifier::ProtoNode(reference), create_if_nonexistent)
@@ -482,12 +526,14 @@ impl<'a> ModifyInputsContext<'a> {
);
}
/// Set the GradientStops list on the 'Gradient Value' node, creating it if necessary.
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
let Some(gradient_node_id) = self.existing_proto_node_id(graphene_std::math_nodes::gradient_value::IDENTIFIER, true) else {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
};
let input_connector = InputConnector::node(gradient_node_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
}
@@ -497,13 +543,21 @@ impl<'a> ModifyInputsContext<'a> {
pub fn gradient_line_set(&mut self, new_start: DVec2, new_end: DVec2) {
let Some(output_layer) = self.get_output_layer() else { return };
let walk_from = if let Some(fill_input_node_id) = get_fill_input_node_id(output_layer, self.network_interface) {
// Some nodes are connected to a Fill node, this means that the primary path is a `List<Vector>`, so we need to traverse it
fill_input_node_id
} else {
// No Fill node found, we will traverse the primary path to find transforms
output_layer.to_node()
};
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let upstream_transforms: Vec<NodeId> = self
.network_interface
.upstream_flow_back_from_nodes(vec![output_layer.to_node()], &[], network_interface::FlowType::HorizontalFlow)
.skip(1)
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
.skip_while(|node_id| self.network_interface.is_layer(node_id, &[]))
.take_while(|node_id| !self.network_interface.is_layer(node_id, &[]))
.filter(|node_id| self.network_interface.reference(node_id, &[]).as_ref() == Some(&transform_reference))
.filter(|id| self.network_interface.reference(id, &[]).as_ref() == Some(&transform_reference))
.collect();
// Upstream walk yields downstream-to-upstream order, so the first hit is the chain's last `Transform`
@@ -528,15 +582,10 @@ impl<'a> ModifyInputsContext<'a> {
// Rebuild the y-axis from the new x-axis using the old (parallel, perpendicular) decomposition and length ratio,
// so the gradient's aspect ratio and skew survive an endpoint drag (so an ellipse stays the same ellipse) instead of
// the old y-axis vector remaining fixed while x changes
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(composed_old.matrix2.x_axis, composed_old.matrix2.y_axis, new_x_axis);
let new_composed = DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
};
let new_composed = build_transform_with_y_preservation(composed_old, new_start, new_end);
let last_transform_value = new_composed * prior_combined.inverse();
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let transform_node_id = if let Some(id) = last_transform_node_id {
id
} else {
@@ -544,7 +593,7 @@ impl<'a> ModifyInputsContext<'a> {
if last_transform_value.abs_diff_eq(DAffine2::IDENTITY, 1e-6) {
return;
}
let Some(id) = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
let Some(id) = self.existing_proto_node_id_at(&target_input, graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
return;
};
id
@@ -558,9 +607,13 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the gradient type to the last 'Gradient Type' node in the chain, inserting one only when the value differs
/// from the default (`Linear`).
pub fn gradient_type_set(&mut self, gradient_type: GradientType) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
let create_if_nonexistent = gradient_type != GradientType::default();
let Some(node_id) = self.existing_proto_node_id(identifier, create_if_nonexistent) else { return };
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_type::GradientTypeInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientType(gradient_type), false), false);
@@ -569,9 +622,13 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the spread method to the last 'Spread Method' node in the chain, inserting one only when the value differs
/// from the default (`Pad`).
pub fn gradient_spread_method_set(&mut self, spread_method: GradientSpreadMethod) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
let Some(node_id) = self.existing_proto_node_id(identifier, create_if_nonexistent) else { return };
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::spread_method::SpreadMethodInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false), false);
@@ -766,3 +823,14 @@ fn scale_y_axis_to_match_new_x(old_x: DVec2, old_y: DVec2, new_x: DVec2) -> DVec
scale * (parallel * ex_new + perpendicular * ey_new)
}
/// Build a new affine that maps canonical (0,0) -> (1,0) to (new_start, new_end), preserving the y-axis
/// shape of `old` proportionally to the x-axis length change.
fn build_transform_with_y_preservation(old: DAffine2, new_start: DVec2, new_end: DVec2) -> DAffine2 {
let new_x_axis = new_end - new_start;
let preserved_y_axis = scale_y_axis_to_match_new_x(old.matrix2.x_axis, old.matrix2.y_axis, new_x_axis);
DAffine2 {
matrix2: glam::DMat2::from_cols(new_x_axis, preserved_y_axis),
translation: new_start,
}
}
@@ -7,6 +7,7 @@ pub mod navigation;
pub mod node_graph;
pub mod overlays;
pub mod properties_panel;
pub mod resource;
pub mod utility_types;
#[doc(inline)]
@@ -8,8 +8,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::{
DocumentNodeMetadata, DocumentNodePersistentMetadata, InputMetadata, NodeNetworkInterface, NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodeTemplate, NodeTypePersistentMetadata,
Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::Message;
use crate::messages::prelude::{FontsMessageHandler, Message, ResourceMessageHandler};
use crate::node_graph_executor::NodeGraphExecutor;
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
@@ -28,10 +27,11 @@ use serde_json::Value;
use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> {
pub cached_data: &'a CachedData,
pub responses: &'a mut VecDeque<Message>,
pub executor: &'a mut NodeGraphExecutor,
pub network_interface: &'a mut NodeNetworkInterface,
pub resources: &'a ResourceMessageHandler,
pub fonts: &'a FontsMessageHandler,
pub selection_network_path: &'a [NodeId],
pub document_name: &'a str,
}
@@ -876,6 +876,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.context_menu = Some(ContextMenuInformation {
context_menu_coordinates: (node_graph_point + node_graph_shift).as_ivec2().into(),
node_creation_coordinates: node_graph_point.as_ivec2().into(),
context_menu_data,
});
@@ -1315,6 +1316,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.context_menu = Some(ContextMenuInformation {
context_menu_coordinates: (point + node_graph_shift).as_ivec2().into(),
node_creation_coordinates: point.as_ivec2().into(),
context_menu_data: ContextMenuData::CreateNode { compatible_type },
});
@@ -1557,7 +1559,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Only disconnect inputs to non selected nodes
if network_interface
.upstream_output_connector(&input_connector, selection_network_path)
.is_some_and(|connector| connector.node_id().map_or(true, |node_id| !all_selected_nodes.contains(&node_id)))
.is_some_and(|connector| connector.node_id().is_none_or(|node_id| !all_selected_nodes.contains(&node_id)))
{
responses.add(NodeGraphMessage::DisconnectInput { input_connector });
}
@@ -6,12 +6,13 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::portfolio::utility_types::{CachedData, FontCatalogStyle};
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use choice::enum_choice;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete};
@@ -822,11 +823,27 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
}
pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetInstance>, Option<Vec<WidgetInstance>>) {
pub fn assign_font_message(node_id: NodeId, font: Font) -> Message {
let resource_id = ResourceId::new();
Message::Batched {
messages: Box::new([
DocumentMessage::Resource(ResourceMessage::AddFont { resource_id, font }).into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id),
}
.into(),
]),
}
}
let ParameterWidgetsInfo {
cached_data,
document_node,
node_id,
index,
resources,
fonts,
..
} = parameter_widgets_info;
@@ -839,66 +856,32 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
return (vec![], None);
};
if let Some(TaggedValue::Font(font)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::Resource(resource_id)) = input.as_non_exposed_value() {
let font = fonts.id_font(resources, *resource_id).unwrap_or_default();
first_widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(vec![
cached_data
fonts
.font_catalog
.0
.iter()
.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
let new_font = Font::new(family.name.clone(), family.closest_style(weight, italic).to_named_style());
let commit_font = new_font.clone();
MenuListEntry::new(family.name.clone())
.label(family.name.clone())
.font(family.closest_style(400, false).preview_url(&family.name))
.on_update({
// Construct the new font using the new family and the initial or previous style, although this style might not exist in the catalog
let mut new_font = Font::new(family.name.clone(), font.font_style_to_restore.clone().unwrap_or_else(|| font.font_style.clone()));
new_font.font_style_to_restore = font.font_style_to_restore.clone();
// If not already, store the initial style so it can be restored if the user switches to another family
if new_font.font_style_to_restore.is_none() {
new_font.font_style_to_restore = Some(new_font.font_style.clone());
}
// Use the closest style available in the family for the new font to ensure the style exists
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&new_font.font_style, "");
new_font.font_style = family.closest_style(weight, italic).to_named_style();
move |_| {
let new_font = new_font.clone();
Message::Batched {
messages: Box::new([
PortfolioMessage::LoadFontData { font: new_font.clone() }.into(),
update_value(move |_| TaggedValue::Font(new_font.clone()), node_id, index)(&()),
]),
}
}
})
.on_commit({
// Use the new value from the user selection
let font_family = family.name.clone();
// Use the previous style selection and extract its weight and italic properties, then find the closest style in the new family
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
let font_style = family.closest_style(weight, italic).to_named_style();
move |_| {
// Intentionally drop `font_style_to_restore` on commit so the committed style becomes the new basis
// for subsequent family switches. Preserving the original style intent is hover-only behavior.
let new_font = Font::new(font_family.clone(), font_style.clone());
DeferMessage::AfterGraphRun {
messages: vec![update_value(move |_| TaggedValue::Font(new_font.clone()), node_id, index)(&()), commit_value(&())],
}
.into()
.on_update(move |_| assign_font_message(node_id, new_font.clone()))
.on_commit(move |_| {
DeferMessage::AfterGraphRun {
messages: vec![assign_font_message(node_id, commit_font.clone()), commit_value(&())],
}
.into()
})
})
.collect::<Vec<_>>(),
])
.selected_index(cached_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.virtual_scrolling(true)
.widget_instance(),
]);
@@ -908,32 +891,18 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
second_row.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new({
cached_data
fonts
.font_catalog
.0
.iter()
.find(|family| family.name == font.font_family)
.map(|family| {
let build_entry = |style: &FontCatalogStyle| {
let font_style = style.to_named_style();
let font_family = font.font_family.clone();
let new_font = Font::new(font_family, font_style.clone());
MenuListEntry::new(font_style.clone())
.label(font_style.clone())
.on_update({
let font_family = font.font_family.clone();
let font_style = font_style.clone();
move |_| {
// Keep the existing family
let new_font = Font::new(font_family.clone(), font_style.clone());
Message::Batched {
messages: Box::new([
PortfolioMessage::LoadFontData { font: new_font.clone() }.into(),
update_value(move |_| TaggedValue::Font(new_font.clone()), node_id, index)(&()),
]),
}
}
})
.label(font_style)
.on_update(move |_| assign_font_message(node_id, new_font.clone()))
.on_commit(commit_value)
};
@@ -946,9 +915,8 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
.unwrap_or_default()
})
.selected_index(
cached_data
fonts
.font_catalog
.0
.iter()
.find(|family| family.name == font.font_family)
.and_then(|family| {
@@ -2813,8 +2781,8 @@ pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) ->
}
pub struct ParameterWidgetsInfo<'a> {
cached_data: &'a CachedData,
network_interface: &'a NodeNetworkInterface,
resources: &'a ResourceMessageHandler,
selection_network_path: &'a [NodeId],
document_node: Option<&'a DocumentNode>,
node_id: NodeId,
@@ -2824,6 +2792,7 @@ pub struct ParameterWidgetsInfo<'a> {
input_type: FrontendGraphDataType,
blank_assist: bool,
exposable: bool,
fonts: &'a FontsMessageHandler,
}
impl<'a> ParameterWidgetsInfo<'a> {
@@ -2836,9 +2805,10 @@ impl<'a> ParameterWidgetsInfo<'a> {
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
ParameterWidgetsInfo {
cached_data: context.cached_data,
network_interface: context.network_interface,
resources: context.resources,
selection_network_path: context.selection_network_path,
fonts: context.fonts,
document_node,
node_id,
index,
@@ -162,9 +162,12 @@ pub enum ContextMenuData {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ContextMenuInformation {
// Stores whether the context menu is open and its position in graph coordinates
// The menu's display position in graph coordinates, which may be shifted from the click point to keep the menu on-screen
#[serde(rename = "contextMenuCoordinates")]
pub context_menu_coordinates: (i32, i32),
// The click point in graph coordinates, where a node created from the menu is placed (unshifted, unlike the display position)
#[serde(rename = "nodeCreationCoordinates")]
pub node_creation_coordinates: (i32, i32),
#[serde(rename = "contextMenuData")]
pub context_menu_data: ContextMenuData,
}
@@ -2,11 +2,12 @@ use super::utility_types::{DrawHandles, OverlayContext};
use crate::consts::HIDE_HANDLE_DISTANCE;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::text::{Font, FontCache, TextAlign, TextContext, TypesettingConfig};
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::{PointId, SegmentId, Vector};
use std::collections::HashMap;
@@ -221,16 +222,6 @@ pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &
}
}
// Global lazy initialized font cache and text context
pub static GLOBAL_FONT_CACHE: LazyLock<FontCache> = LazyLock::new(|| {
let mut font_cache = FontCache::default();
// Initialize with the hardcoded font used by overlay text
const FONT_DATA: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
let font = Font::new("Source Sans Pro".to_string(), "Regular".to_string());
font_cache.insert(font, FONT_DATA.to_vec());
font_cache
});
pub static GLOBAL_TEXT_CONTEXT: LazyLock<Mutex<TextContext>> = LazyLock::new(|| Mutex::new(TextContext::default()));
pub fn text_width(text: &str, font_size: f64) -> f64 {
@@ -244,12 +235,8 @@ pub fn text_width(text: &str, font_size: f64) -> f64 {
align: TextAlign::AlignLeft,
};
// Load Source Sans Pro font data
// TODO: Grab this from the node_modules folder (either with `include_bytes!` or ideally at runtime) instead of checking the font file into the repo.
// TODO: And maybe use the WOFF2 version (if it's supported) for its smaller, compressed file size.
let font = Font::new("Source Sans Pro".to_string(), "Regular".to_string());
let mut text_context = GLOBAL_TEXT_CONTEXT.lock().expect("Failed to lock global text context");
let bounds = text_context.bounding_box(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
let bounds = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
bounds.x
}
@@ -3,8 +3,9 @@ use crate::consts::{
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS,
GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_FONT_CACHE, GLOBAL_TEXT_CONTEXT, hex_to_rgba_u8};
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_TEXT_CONTEXT, hex_to_rgba_u8};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::prelude::Message;
use crate::messages::prelude::ViewportMessageHandler;
use core::borrow::Borrow;
@@ -14,7 +15,7 @@ use graphene_std::ATTR_TRANSFORM;
use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::{self, Subpath};
use graphene_std::text::{Font, TextAlign, TypesettingConfig};
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector};
@@ -1115,21 +1116,16 @@ impl OverlayContextInternal {
align: TextAlign::AlignLeft,
};
// Load Source Sans Pro font data
// TODO: Grab this from the node_modules folder (either with `include_bytes!` or ideally at runtime) instead of checking the font file into the repo.
// TODO: And maybe use the WOFF2 version (if it's supported) for its smaller, compressed file size.
let font = Font::new("Source Sans Pro".to_string(), "Regular".to_string());
// Get text dimensions directly from layout
let mut text_context = GLOBAL_TEXT_CONTEXT.lock().expect("Failed to lock global text context");
let text_size = text_context.bounding_box(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_width = text_size.x;
let text_height = text_size.y;
// Create a rect from the size (assuming text starts at origin)
let text_bounds = kurbo::Rect::new(0., 0., text_width, text_height);
// Convert text to vector paths for rendering
let text_list = text_context.to_path(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
// Calculate position based on pivot
let mut position = DVec2::ZERO;
@@ -3,17 +3,17 @@ use graphene_std::uuid::NodeId;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::NodePropertiesContext;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::*;
use crate::node_graph_executor::NodeGraphExecutor;
#[derive(ExtractField)]
pub struct PropertiesPanelMessageContext<'a> {
pub executor: &'a mut NodeGraphExecutor,
pub network_interface: &'a mut NodeNetworkInterface,
pub resources: &'a ResourceMessageHandler,
pub selection_network_path: &'a [NodeId],
pub document_name: &'a str,
pub executor: &'a mut NodeGraphExecutor,
pub cached_data: &'a CachedData,
pub fonts: &'a FontsMessageHandler,
pub properties_panel_open: bool,
}
@@ -24,11 +24,12 @@ pub struct PropertiesPanelMessageHandler {}
impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> for PropertiesPanelMessageHandler {
fn process_message(&mut self, message: PropertiesPanelMessage, responses: &mut VecDeque<Message>, context: PropertiesPanelMessageContext) {
let PropertiesPanelMessageContext {
executor,
network_interface,
resources,
selection_network_path,
document_name,
executor,
cached_data,
fonts,
properties_panel_open,
} = context;
@@ -46,12 +47,13 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
}
let mut node_properties_context = NodePropertiesContext {
cached_data,
responses,
executor,
network_interface,
resources,
selection_network_path,
document_name,
executor,
fonts,
};
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
@@ -0,0 +1,8 @@
mod resource_message;
mod resource_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use resource_message::{ResourceMessage, ResourceMessageDiscriminant};
#[doc(inline)]
pub use resource_message_handler::{ResourceMessageContext, ResourceMessageHandler};
@@ -0,0 +1,15 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
use graphene_std::text::Font;
use std::sync::Arc;
#[impl_message(Message, DocumentMessage, Resource)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ResourceMessage {
StoreEmbedded { resource_id: ResourceId, data: Arc<[u8]> },
AddFont { resource_id: ResourceId, font: Font },
ResolveAll,
Resolve { resource_id: ResourceId },
Resolved { resource_id: ResourceId, source: DataSource, hash: ResourceHash },
ResolveFailed { resource_id: ResourceId },
}
@@ -0,0 +1,299 @@
use crate::messages::network::Client;
use crate::messages::portfolio::{document::resource::utility_types::EmbeddedResources, fonts::utility_types::FontCatalog};
use crate::messages::prelude::*;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graph_craft::application_io::resource::{DataSource, LoadResource, Resource, ResourceHash, ResourceId, ResourceRegistry};
use graphene_std::text::Font;
use std::sync::Arc;
use url::Url;
#[derive(ExtractField)]
pub struct ResourceMessageContext<'a> {
pub document_id: DocumentId,
pub fonts: &'a FontsMessageHandler,
}
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, ExtractField)]
pub struct ResourceMessageHandler {
pub registry: ResourceRegistry,
pub embedded: EmbeddedResources,
#[serde(skip)]
pending_resolves: HashSet<ResourceId>,
}
#[message_handler_data]
impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMessageHandler {
fn process_message(&mut self, message: ResourceMessage, responses: &mut VecDeque<Message>, context: ResourceMessageContext) {
let ResourceMessageContext { document_id, fonts } = context;
match message {
ResourceMessage::StoreEmbedded { resource_id, data } => {
let hash = ResourceHash::from(data.as_ref());
self.registry.push_source_back(&resource_id, DataSource::Embedded);
self.registry.resolve(&resource_id, hash);
responses.add(ResourceStorageMessage::Store { data });
}
ResourceMessage::AddFont { resource_id, font } => {
let style = fonts.font_catalog.find_font_style_in_catalog(&font);
let style_name = style.map(|style| style.to_named_style()).unwrap_or_else(|| font.font_style.clone());
self.registry.push_source_back(&resource_id, DataSource::Embedded);
self.registry.push_source_back(
&resource_id,
DataSource::Font {
family: font.font_family,
style: Some(style_name),
},
);
responses.add(ResourceMessage::Resolve { resource_id });
}
ResourceMessage::ResolveAll => {
let unresolved_ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).collect();
for id in unresolved_ids {
if self.pending_resolves.contains(&id) {
continue;
}
responses.add(ResourceMessage::Resolve { resource_id: id });
}
}
ResourceMessage::Resolve { resource_id } => {
if self.pending_resolves.contains(&resource_id) {
log::warn!("Already pending resolve for {resource_id}; skipping");
return;
}
let Some(info) = self.registry.info(&resource_id) else {
log::error!("Resolve for {resource_id}: no registry entry");
return;
};
if info.hash.is_some() {
log::warn!("Resource {resource_id} already resolved");
return;
}
self.pending_resolves.insert(resource_id);
let font_catalog = fonts.font_catalog.clone();
let sources = info
.sources
.iter()
.map(|source| match source {
DataSource::Font { family, style } => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
};
let hash = fonts.cached_hash(&font);
(source.clone(), hash)
}
source => (source.clone(), None),
})
.collect::<Vec<(DataSource, Option<ResourceHash>)>>();
async fn resolve_to_message(document_id: DocumentId, resource_id: ResourceId, source: DataSource, url: Url, client: &Client) -> Option<Message> {
let result = client.fetch(url.clone()).await;
match result {
Some(data) => {
let hash = ResourceHash::from(data.as_ref());
Some(Message::Batched {
messages: Box::new([
PortfolioMessage::DocumentPassMessage {
document_id,
message: ResourceMessage::Resolved { resource_id, source, hash }.into(),
}
.into(),
ResourceStorageMessage::Store { data: Arc::from(data) }.into(),
]),
})
}
None => {
log::warn!("Failed to fetch resource {resource_id} from {url}");
None
}
}
}
responses.add(NetworkMessage::request(async move |client| {
let mut loaded_catalog = None;
let mut response: Option<Message> = None;
for (source, hash) in sources {
if let Some(hash) = hash {
response = Some(ResourceMessage::Resolved { resource_id, source, hash }.into());
break;
}
match &source {
DataSource::Embedded => continue,
DataSource::Url(url) => {
response = resolve_to_message(document_id, resource_id, source.clone(), url.clone(), &client).await;
}
DataSource::Font { family, style } => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
};
if font_catalog.is_empty() && loaded_catalog.as_ref().is_none() {
loaded_catalog = FontCatalog::load_from_api(&client).await;
}
let url = loaded_catalog.as_ref().and_then(|catalog| catalog.download_url(&font)).or_else(|| font_catalog.download_url(&font));
if let Some(url) = url {
let Ok(url) = Url::parse(&url) else {
log::warn!("Invalid URL {url} for font resource {resource_id}");
continue;
};
response = resolve_to_message(document_id, resource_id, source.clone(), url, &client).await;
} else {
log::warn!("No download URL found for font resource {resource_id}");
}
}
}
if response.is_some() {
break;
}
}
let mut response = response.unwrap_or_else(|| {
log::error!("Resolve for {resource_id}: all sources exhausted");
PortfolioMessage::DocumentPassMessage {
document_id,
message: ResourceMessage::ResolveFailed { resource_id }.into(),
}
.into()
});
if let Some(catalog) = loaded_catalog.take() {
response = Message::Batched {
messages: Box::new([response, FontsMessage::CatalogLoaded { catalog }.into()]),
};
}
response
}))
}
ResourceMessage::Resolved { resource_id, source, hash } => {
self.pending_resolves.remove(&resource_id);
if self.registry.info(&resource_id).is_none() {
// Resource was removed from registry after the fetch started.
return;
}
self.registry.resolve(&resource_id, hash);
if let DataSource::Font { family, style } = source {
let font = match style {
Some(style) => Font::new(family, style),
None => Font::new_with_default_style(family),
};
responses.add(FontsMessage::ResourceResolved { font, hash });
}
responses.add(NodeGraphMessage::RunDocumentGraph);
}
ResourceMessage::ResolveFailed { resource_id } => {
self.pending_resolves.remove(&resource_id);
}
}
}
fn actions(&self) -> ActionList {
actions!(ResourceMessageDiscriminant;)
}
}
impl ResourceMessageHandler {
pub fn is_empty(&self) -> bool {
self.registry.is_empty() && self.embedded.is_empty()
}
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
let embedded = self
.registry
.resolved()
.filter(|info| info.sources.contains(&DataSource::Embedded))
.filter_map(|info| {
if let Some(hash) = info.hash {
let resource = resources_load_handle.load(*hash);
Some(async move { resource.await.map(|resource| (*hash, resource)) })
} else {
None
}
})
.collect::<Vec<_>>();
self.embedded = EmbeddedResources::from_iter(futures::future::join_all(embedded).await.into_iter().flatten());
}
pub fn collect_garbage(&mut self, used: &[ResourceId]) {
let used = HashSet::<ResourceId>::from_iter(used.iter().cloned());
let unused = self.registry.ids().filter(|id| !used.contains(id)).collect::<Vec<_>>();
unused.into_iter().for_each(|id| {
self.registry.delete(&id);
});
}
}
// TODO: Eventually remove this document upgrade code
impl<'de> serde::Deserialize<'de> for ResourceMessageHandler {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
enum Key {
Registry,
Embedded,
Hash(ResourceHash),
}
impl<'de> serde::Deserialize<'de> for Key {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Ok(match raw.as_str() {
"registry" => Key::Registry,
"embedded" => Key::Embedded,
_ => Key::Hash(raw.parse().map_err(serde::de::Error::custom)?),
})
}
}
struct EmbeddedResourcesVisitor {
human_readable: bool,
}
impl<'de> serde::de::Visitor<'de> for EmbeddedResourcesVisitor {
type Value = ResourceMessageHandler;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("an EmbeddedResources struct or a legacy EmbeddedResourceData map")
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut output = ResourceMessageHandler::default();
while let Some(key) = map.next_key::<Key>()? {
match key {
Key::Registry => output.registry = map.next_value()?,
Key::Embedded => output.embedded = map.next_value()?,
Key::Hash(hash) => {
let bytes = if self.human_readable {
let encoded: String = map.next_value()?;
BASE64.decode(&encoded).map_err(serde::de::Error::custom)?
} else {
let raw: serde_bytes::ByteBuf = map.next_value()?;
raw.into_vec()
};
let data_hash = output.embedded.store(Resource::new(bytes));
if data_hash != hash {
return Err(serde::de::Error::custom(format!("EmbeddedResource hash mismatch: expected {hash}, got {data_hash}")));
}
}
}
}
Ok(output)
}
}
let human_readable = deserializer.is_human_readable();
deserializer.deserialize_map(EmbeddedResourcesVisitor { human_readable })
}
}
@@ -0,0 +1,92 @@
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graph_craft::application_io::resource::{Resource, ResourceHash};
use std::collections::HashMap;
use std::fmt;
#[derive(Clone, Default, Debug, PartialEq)]
pub struct EmbeddedResources {
resources: HashMap<ResourceHash, Resource>,
}
impl EmbeddedResources {
pub fn is_empty(&self) -> bool {
self.resources.is_empty()
}
pub fn store(&mut self, resource: Resource) -> ResourceHash {
let hash = ResourceHash::from(resource.as_ref());
self.resources.insert(hash, resource);
hash
}
}
impl FromIterator<(ResourceHash, Resource)> for EmbeddedResources {
fn from_iter<T: IntoIterator<Item = (ResourceHash, Resource)>>(iter: T) -> Self {
Self {
resources: iter.into_iter().collect(),
}
}
}
impl IntoIterator for EmbeddedResources {
type Item = (ResourceHash, Resource);
type IntoIter = std::collections::hash_map::IntoIter<ResourceHash, Resource>;
fn into_iter(self) -> Self::IntoIter {
self.resources.into_iter()
}
}
impl serde::Serialize for EmbeddedResources {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let human_readable = serializer.is_human_readable();
let mut map = serializer.serialize_map(Some(self.resources.len()))?;
for (hash, resource) in &self.resources {
let bytes: &[u8] = resource.as_ref();
if human_readable {
map.serialize_entry(hash, &BASE64.encode(bytes))?;
} else {
map.serialize_entry(hash, serde_bytes::Bytes::new(bytes))?;
}
}
map.end()
}
}
impl<'de> serde::Deserialize<'de> for EmbeddedResources {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct EmbeddedResourcesVisitor {
human_readable: bool,
}
impl<'de> serde::de::Visitor<'de> for EmbeddedResourcesVisitor {
type Value = EmbeddedResources;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a map of ResourceHash to resource bytes")
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut resources = HashMap::with_capacity(map.size_hint().unwrap_or(0));
while let Some(hash) = map.next_key::<ResourceHash>()? {
let resource = if self.human_readable {
let encoded: String = map.next_value()?;
let bytes = BASE64.decode(&encoded).map_err(serde::de::Error::custom)?;
Resource::new(bytes)
} else {
let bytes: serde_bytes::ByteBuf = map.next_value()?;
Resource::new(bytes.into_vec())
};
resources.insert(hash, resource);
}
Ok(EmbeddedResources { resources })
}
}
let human_readable = deserializer.is_human_readable();
deserializer.deserialize_map(EmbeddedResourcesVisitor { human_readable })
}
}
@@ -16,13 +16,7 @@ pub enum EditorError {
#[error("The operation caused a document error:\n{0:?}")]
Document(String),
#[error(
"This document was created in an older version of the editor.\n\
\n\
Full backwards compatibility is not guaranteed in the current alpha release.\n\
\n\
If this document is critical, ask for support in Graphite's Discord community."
)]
#[error("Failed to deserialize document: {0}")]
DocumentDeserialization(String),
#[error("{0}")]
@@ -20,6 +20,7 @@ use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::ContextDependencies;
@@ -510,6 +511,10 @@ impl NodeNetworkInterface {
})
}
pub fn collect_used_resources(&self, target: &mut HashSet<ResourceId>) {
collect_network_resources(self.document_network(), target);
}
pub fn frontend_imports(&mut self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
@@ -5906,6 +5911,46 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node(*node_id, insert_node_input_index), network_path);
}
/// Inserts the freshly-created `node_id` onto the wire feeding `input_connector`: the previous upstream becomes the
/// new node's primary (index 0) input, and the new node feeds `input_connector`.
///
/// When the wire is part of a layer's encapsulated primary chain, `set_input` chain-positions the new node
/// automatically. On an unencapsulated secondary-input branch (e.g. a 'Fill' node's fill input) chain positioning
/// doesn't apply, so the node would otherwise land at the graph origin; instead it's placed on the displaced
/// upstream node's spot and that whole branch is shifted left (in absolute graph space) to make room.
pub fn insert_node_before_input(&mut self, node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) {
let feeder = self.upstream_output_connector(input_connector, network_path).and_then(|output| output.node_id());
let Some(current_input) = self.input_from_connector(input_connector, network_path).cloned() else {
log::error!("Could not get input in insert_node_before_input");
return;
};
if self.input_from_connector(&InputConnector::node(*node_id, 0), network_path).is_none() {
return;
}
self.set_input(&InputConnector::node(*node_id, 0), current_input, network_path);
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do.
if !self.is_absolute(node_id, network_path) {
return;
}
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room.
let Some(feeder) = feeder else { return };
let Some(node_position) = self.position(node_id, network_path) else { return };
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
self.shift_node(node_id, feeder_position - node_position, network_path);
// Deduplicate, since `UpstreamFlow` can yield a shared node more than once and we must shift each node only once.
let upstream_nodes: HashSet<NodeId> = self.upstream_flow_back_from_nodes(vec![feeder], network_path, FlowType::UpstreamFlow).collect();
for upstream_node in &upstream_nodes {
self.shift_node(upstream_node, IVec2::new(-NODE_CHAIN_WIDTH, 0), network_path);
}
}
/// Moves a node to the start of a layer chain (feeding into the secondary input of the layer).
/// When `import` is true, uses lightweight wiring that skips `is_acyclic` checks and per-node cache invalidation.
pub fn move_node_to_chain_start(&mut self, node_id: &NodeId, parent: LayerNodeIdentifier, network_path: &[NodeId], import: bool) {
@@ -6769,6 +6814,21 @@ pub enum TransactionStatus {
Finished,
}
fn collect_network_resources(network: &NodeNetwork, out: &mut HashSet<ResourceId>) {
for node in network.nodes.values() {
for input in &node.inputs {
if let NodeInput::Value { tagged_value, .. } = input
&& let TaggedValue::Resource(id) = &**tagged_value
{
out.insert(*id);
}
}
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
collect_network_resources(nested, out);
}
}
}
#[cfg(test)]
mod network_interface_tests {
use crate::test_utils::test_prelude::*;
@@ -6,6 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::descriptor;
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
@@ -16,6 +17,7 @@ use graphene_std::uuid::NodeId;
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
use std::collections::HashMap;
use std::f64::consts::PI;
use std::ops::Range;
const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
("graphene_core::vector::vector_nodes::SamplePointsNode", "graphene_core::vector::SamplePolylineNode"),
@@ -1034,6 +1036,77 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
false
}
pub fn document_migration_replace_resources_referenced_by_hash(document_serialized_content: String) -> (String, HashMap<ResourceHash, ResourceId>) {
fn collect_resources_referenced_by_hash(s: &str) -> HashMap<ResourceHash, Vec<Range<usize>>> {
let mut out: HashMap<ResourceHash, Vec<Range<usize>>> = HashMap::new();
let mut offset = 0;
while let Some(i) = s[offset..].find("\"Resource\":") {
let abs = offset + i + 11; // pos after `"Resource":`
offset = abs;
if let Some(j) = s[offset..].find('}') {
let chunk_start = offset;
let chunk = &s[chunk_start..chunk_start + j];
let quotes: Vec<_> = chunk.match_indices('"').collect();
if quotes.len() == 2 {
let q0 = chunk_start + quotes[0].0;
let q1 = chunk_start + quotes[1].0;
let hash = &s[q0 + 1..q1];
if hash.len() == 64
&& hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
&& let Ok(hash) = hash.parse::<ResourceHash>()
{
out.entry(hash).or_default().push(q0..q1 + 1);
}
}
offset = chunk_start + j + 1;
} else {
break;
}
}
out
}
let resources_by_hash = collect_resources_referenced_by_hash(&document_serialized_content);
// Require each referenced hash to also appear as an embedded resource map key (more than ranges.len() occurrences).
if resources_by_hash.is_empty()
|| !resources_by_hash
.iter()
.all(|(hash, ranges)| document_serialized_content.matches(&hash.to_string()).count() > ranges.len())
{
return (document_serialized_content, HashMap::new());
}
// Assign a new ResourceId for each hash
let mut hash_to_id: HashMap<ResourceHash, ResourceId> = HashMap::new();
for hash in resources_by_hash.keys() {
#[allow(clippy::unwrap_or_default)]
hash_to_id.entry(*hash).or_insert_with(ResourceId::new);
}
// Each range is 66 bytes (64 hex + 2 quotes) and a ResourceId serializes to at most 20 ASCII digits, so the ID always fits.
// Overwrite each hash in place with its ID and pad the leftover bytes with spaces, which JSON deserialization discards.
let mut bytes = document_serialized_content.into_bytes();
for (hash, ranges) in &resources_by_hash {
let id_str = format!("{}", hash_to_id[hash]);
let id_bytes = id_str.as_bytes();
for range in ranges {
bytes[range.start..range.start + id_bytes.len()].copy_from_slice(id_bytes);
bytes[range.start + id_bytes.len()..range.end].fill(b' ');
}
}
let out = String::from_utf8(bytes).expect("in-place hash-to-ID rewrite produced invalid UTF-8");
(out, hash_to_id)
}
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node();
@@ -1588,12 +1661,51 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[3].clone(), network_path);
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
// Upgrade `image` nodes that stored image data as `Image<Color>`` to `image` nodes that store a reference to the image data as a resource.
// Encodes the image data as PNG and stores it in the document's embedded resources and rewires the node to reference that resource.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER) {
let image = node.inputs.iter().find_map(|input| match input.as_value()? {
TaggedValue::ImageData(image) => Some(image.clone()),
_ => None,
});
// Insert a new empty input for the image
document.network_interface.add_import(TaggedValue::None, false, 0, "Empty", "", &[*node_id]);
if let Some(image) = image {
let hash = document.resources.embedded.store(Resource::new(image.to_png()));
let resource_id = ResourceId::new();
document.resources.registry.push_source_back(&resource_id, DataSource::Embedded);
document.resources.registry.resolve(&resource_id, hash);
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let _ = document.network_interface.replace_inputs(node_id, network_path, &mut node_template);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 0), NodeInput::value(TaggedValue::Resource(resource_id), false), network_path);
}
}
// Convert text nodes from the old `editor-api` scope + `Font` input to a single font `Resource` input.
// The chosen typeface is recorded as a `DataSource::Font` in the document's resource registry and loaded on open.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) && inputs_count == 13 && matches!(node.inputs.first(), Some(NodeInput::Scope(_))) {
document
.network_interface
.set_input(&InputConnector::node(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
if let Some(TaggedValue::Font(font)) = node.inputs.get(2).and_then(|input| input.as_value()) {
let resource_id = ResourceId::new();
document.resources.registry.push_source_back(&resource_id, DataSource::Embedded);
document.resources.registry.push_source_back(
&resource_id,
DataSource::Font {
family: font.font_family.clone(),
style: Some(font.font_style.clone()),
},
);
document
.network_interface
.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::Resource(resource_id), false), network_path);
}
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
@@ -0,0 +1,5 @@
use graph_craft::application_io::resource::Resource;
use std::sync::LazyLock;
const FALLBACK_FONT_BYTES: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
pub static FALLBACK_FONT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| Resource::new(FALLBACK_FONT_BYTES));
@@ -0,0 +1,26 @@
use crate::messages::portfolio::fonts::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{Resource, ResourceHash};
use graphene_std::text::Font;
#[impl_message(Message, PortfolioMessage, Fonts)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum FontsMessage {
LoadCatalog,
CatalogLoaded {
catalog: FontCatalog,
},
ResourceResolved {
font: Font,
hash: ResourceHash,
},
Load {
font: Font,
response: Box<Message>,
},
Cached {
hash: ResourceHash,
#[serde(skip, default = "Resource::empty")]
resource: Resource,
},
}
@@ -0,0 +1,116 @@
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::portfolio::fonts::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graphene_std::text::Font;
use std::sync::Arc;
#[derive(ExtractField)]
pub struct FontsMessageContext<'a> {
pub resource_storage: &'a ResourceStorageMessageHandler,
}
#[derive(Debug, Default, ExtractField)]
pub struct FontsMessageHandler {
pub font_catalog: Arc<FontCatalog>,
font_hashes: HashMap<Font, ResourceHash>,
font_data: HashMap<ResourceHash, Resource>,
}
#[message_handler_data]
impl MessageHandler<FontsMessage, FontsMessageContext<'_>> for FontsMessageHandler {
fn process_message(&mut self, message: FontsMessage, responses: &mut VecDeque<Message>, context: FontsMessageContext) {
let FontsMessageContext { resource_storage } = context;
match message {
FontsMessage::LoadCatalog => {
responses.add(NetworkMessage::request(async move |client| {
let Some(catalog) = FontCatalog::load_from_api(&client).await else {
log::error!("failed to load font catalog");
return Message::NoOp;
};
FontsMessage::CatalogLoaded { catalog }.into()
}));
}
FontsMessage::CatalogLoaded { catalog } => {
self.font_catalog = Arc::new(catalog);
responses.add(PortfolioMessage::ResolveResources);
responses.add(ToolMessage::RefreshToolOptions);
responses.add(PropertiesPanelMessage::Refresh);
}
FontsMessage::ResourceResolved { font, hash } => {
let font = self.normalize(font);
self.font_hashes.insert(font, hash);
}
FontsMessage::Load { font, response } => {
let font = self.normalize(font);
let Some(hash) = self.font_hashes.get(&font).copied() else {
log::warn!("FontsMessage::Load for {font:?} with no known hash; ignoring");
return;
};
if self.font_data.contains_key(&hash) {
responses.add(*response);
return;
}
let loader = resource_storage.resources();
responses.add(async move {
let resource = loader.load(hash).await;
match resource {
Some(resource) => Message::Batched {
messages: Box::new([FontsMessage::Cached { hash, resource }.into(), *response]),
},
None => {
log::warn!("Storage missing data for font hash {hash}");
*response
}
}
});
}
FontsMessage::Cached { hash, resource } => {
self.font_data.insert(hash, resource);
}
}
}
advertise_actions!(FontsMessageDiscriminant;);
}
impl FontsMessageHandler {
pub fn cached_hash(&self, font: &Font) -> Option<ResourceHash> {
let font = self.normalize(font.clone());
self.font_hashes.get(&font).copied()
}
pub fn get_resource_or_queue_load(&self, font: &Font, responses: &mut VecDeque<Message>) -> Resource {
let font = self.normalize(font.clone());
if let Some(hash) = self.font_hashes.get(&font) {
if let Some(resource) = self.font_data.get(hash) {
return resource.clone();
}
responses.add(FontsMessage::Load {
font: font.clone(),
response: Message::NoOp.into(),
});
}
FALLBACK_FONT_RESOURCE.clone()
}
pub fn id_font(&self, resources: &ResourceMessageHandler, resource_id: ResourceId) -> Option<Font> {
let info = resources.registry.info(&resource_id)?;
info.sources.iter().find_map(|source| match source {
DataSource::Font { family, style } => Some(match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
}),
_ => None,
})
}
pub fn used_resources(&self) -> impl Iterator<Item = ResourceHash> + '_ {
self.font_hashes.values().copied().chain(self.font_data.keys().copied())
}
fn normalize(&self, font: Font) -> Font {
self.font_catalog.normalize(font)
}
}
@@ -0,0 +1,12 @@
mod fallback;
mod fonts_message;
mod fonts_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use fallback::FALLBACK_FONT_RESOURCE;
#[doc(inline)]
pub use fonts_message::{FontsMessage, FontsMessageDiscriminant};
#[doc(inline)]
pub use fonts_message_handler::{FontsMessageContext, FontsMessageHandler};
@@ -0,0 +1,164 @@
use crate::messages::network::Client;
use graphene_std::text::Font;
use std::collections::HashMap;
const FONT_LIST_API: &str = "https://api.graphite.art/font-list";
#[derive(serde::Deserialize)]
struct FontListApiResponse {
items: Vec<FontListApiFamily>,
}
#[derive(serde::Deserialize)]
struct FontListApiFamily {
family: String,
variants: Vec<String>,
files: HashMap<String, String>,
}
impl FontCatalog {
pub async fn load_from_api(client: &Client) -> Option<Self> {
let Some(bytes) = client.fetch(FONT_LIST_API).await else {
log::error!("failed to fetch font catalog from API");
return None;
};
let response: FontListApiResponse = match serde_json::from_slice(&bytes) {
Ok(response) => response,
Err(err) => {
log::error!("failed to parse font catalog response: {err}");
return None;
}
};
let families = response
.items
.into_iter()
.map(|family| {
let styles = family
.variants
.iter()
.filter_map(|variant| {
let weight = variant.chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse::<u32>().unwrap_or(400);
let italic = variant.ends_with("italic");
let url = family.files.get(variant)?.replacen("http://", "https://", 1);
Some(FontCatalogStyle { weight, italic, url })
})
.collect();
FontCatalogFamily { name: family.family, styles }
})
.collect();
Some(Self(families))
}
}
// TODO: Should this be a BTreeMap instead?
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog(Vec<FontCatalogFamily>);
impl FontCatalog {
pub fn find_font_style_in_catalog(&self, font: &Font) -> Option<FontCatalogStyle> {
let family = self.0.iter().find(|family| family.name == font.font_family);
let found_style = family.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
family.closest_style(weight, italic).clone()
});
if found_style.is_none() {
log::warn!("Font not found in catalog: {:?}", font);
}
found_style
}
pub fn download_url(&self, font: &Font) -> Option<String> {
let catalog_family = self.0.iter().find(|catalog_family| catalog_family.name == font.font_family)?;
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
Some(catalog_family.closest_style(weight, italic).url.clone())
}
pub fn normalize(&self, font: Font) -> Font {
match self.find_font_style_in_catalog(&font) {
Some(style) => Font::new(font.font_family, style.to_named_style()),
None => font,
}
}
pub fn iter(&self) -> impl Iterator<Item = &FontCatalogFamily> {
self.0.iter()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<Vec<FontCatalogFamily>> for FontCatalog {
fn from(value: Vec<FontCatalogFamily>) -> Self {
Self(value)
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogFamily {
/// The font family name.
pub name: String,
/// The font styles (variants) available for the font family.
pub styles: Vec<FontCatalogStyle>,
}
impl FontCatalogFamily {
/// Finds the closest style to the given weight and italic setting.
/// Aims to find the nearest weight while maintaining the italic setting if possible, but italic may change if no other option is available.
pub fn closest_style(&self, weight: u32, italic: bool) -> &FontCatalogStyle {
static FALLBACK_STYLE: FontCatalogStyle = FontCatalogStyle {
weight: 400,
italic: false,
url: String::new(),
};
self.styles
.iter()
.map(|style| ((style.weight as i32 - weight as i32).unsigned_abs() + 10000 * (style.italic != italic) as u32, style))
.min_by_key(|(distance, _)| *distance)
.map(|(_, style)| style)
.unwrap_or(self.styles.first().unwrap_or(&FALLBACK_STYLE))
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogStyle {
pub weight: u32,
pub italic: bool,
pub url: String,
}
impl FontCatalogStyle {
pub fn to_named_style(&self) -> String {
let weight = self.weight;
let italic = self.italic;
let named_weight = Font::named_weight(weight);
let maybe_italic = if italic { " Italic" } else { "" };
format!("{named_weight}{maybe_italic} ({weight})")
}
pub fn from_named_style(named_style: &str, url: impl Into<String>) -> FontCatalogStyle {
let weight = named_style.split_terminator(['(', ')']).next_back().and_then(|x| x.parse::<u32>().ok()).unwrap_or(400);
let italic = named_style.contains("Italic (");
FontCatalogStyle { weight, italic, url: url.into() }
}
/// Get the URL for the stylesheet for loading a font preview for this style of the given family name, subsetted to only the letters in the family name.
pub fn preview_url(&self, family: impl Into<String>) -> String {
let name = family.into().replace(' ', "+");
let italic = if self.italic { "ital," } else { "" };
let weight = self.weight;
format!("https://fonts.googleapis.com/css2?display=swap&family={name}:{italic}wght@{weight}&text={name}")
}
}
+3
View File
@@ -3,9 +3,12 @@ mod portfolio_message_handler;
pub mod document;
pub mod document_migration;
pub mod fonts;
pub mod persistent_state;
pub mod utility_types;
#[doc(inline)]
pub use fonts::{FontsMessage, FontsMessageContext, FontsMessageHandler};
#[doc(inline)]
pub use persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
#[doc(inline)]
@@ -52,3 +52,9 @@ impl MessageHandler<PersistentStateMessage, PersistentStateMessageContext> for P
advertise_actions!(PersistentStateMessageDiscriminant;);
}
impl PersistentStateMessageHandler {
pub fn loaded(&self) -> bool {
self.loaded
}
}
@@ -3,11 +3,9 @@ use super::persistent_state::PersistentStateMessage;
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
use crate::messages::portfolio::utility_types::FontCatalog;
use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::text::Font;
use std::path::PathBuf;
#[impl_message(Message, Portfolio)]
@@ -17,6 +15,8 @@ pub enum PortfolioMessage {
#[child]
Document(DocumentMessage),
#[child]
Fonts(FontsMessage),
#[child]
PersistentState(PersistentStateMessage),
// Messages
@@ -50,20 +50,11 @@ pub enum PortfolioMessage {
},
DestroyAllDocuments,
EditorPreferences,
FontCatalogLoaded {
catalog: FontCatalog,
},
LoadFontData {
font: Font,
},
FontLoaded {
font_family: String,
font_style: String,
data: Vec<u8>,
},
LoadDocumentResources {
GarbageCollectResources,
ResolveDocumentResources {
document_id: DocumentId,
},
ResolveResources,
LoadPersistedState {
state: PersistedState,
},
@@ -71,6 +62,12 @@ pub enum PortfolioMessage {
document_id: DocumentId,
document_serialized_content: String,
},
// TODO: Eventually remove this document upgrade code
ShowFailedToLoadDocumentsDialog,
// TODO: Eventually remove this document upgrade code
DiscardFailedToLoadDocuments,
// TODO: Eventually remove this document upgrade code
DownloadFailedToLoadDocuments,
MoveAllPanelTabs {
source_group: PanelGroupId,
target_group: PanelGroupId,
@@ -1,7 +1,7 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::document::utility_types::network_interface;
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
use super::utility_types::{CachedData, PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
use super::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
use crate::application::{Editor, generate_uuid};
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
@@ -26,15 +26,16 @@ use crate::messages::tool::utility_types::{HintData, ToolType};
use crate::messages::viewport::ToPhysical;
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster_types::Image;
use graphene_std::renderer::Quad;
use graphene_std::subpath::BezierHandles;
use graphene_std::text::Font;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
use std::path::PathBuf;
use std::sync::Arc;
use std::vec;
#[derive(ExtractField)]
@@ -46,16 +47,27 @@ pub struct PortfolioMessageContext<'a> {
pub reset_node_definitions_on_open: bool,
pub timing_information: TimingInformation,
pub viewport: &'a ViewportMessageHandler,
pub resource_storage: &'a ResourceStorageMessageHandler,
}
#[derive(Debug, Default, ExtractField)]
pub struct PortfolioMessageHandler {
pub documents: HashMap<DocumentId, DocumentMessageHandler>,
unloaded_documents: HashMap<DocumentId, DocumentInfo>,
/// Pairs of `(info, raw serialized content)` for autosaved documents that failed to deserialize.
/// The info entries are folded back into `persisted_state_snapshot` so their on-disk autosave files survive garbage collection.
// TODO: Eventually remove this document upgrade code
failed_to_load_documents: HashMap<DocumentId, (DocumentInfo, String)>,
/// In-flight count of autosaved-document loads from the initial startup batch; the batched failure dialog fires when this hits 0.
// TODO: Eventually remove this document upgrade code
pending_initial_autosave_loads: usize,
/// Background eager loads whose trailing `SelectDocument` should be suppressed to keep focus on the user's active doc.
// TODO: Eventually remove this document upgrade code
pending_eager_loads: HashSet<DocumentId>,
document_ids: VecDeque<DocumentId>,
pub(crate) active_document_id: Option<DocumentId>,
persistent_state: PersistentStateMessageHandler,
pub cached_data: CachedData,
pub fonts: FontsMessageHandler,
copy_buffer: [Vec<CopyBufferEntry>; INTERNAL_CLIPBOARD_COUNT as usize],
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
@@ -74,6 +86,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
reset_node_definitions_on_open,
timing_information,
viewport,
resource_storage,
} = context;
match message {
@@ -85,11 +98,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let document_inputs = DocumentMessageContext {
document_id,
ipp,
cached_data: &self.cached_data,
fonts: &self.fonts,
executor: &mut self.executor,
current_tool,
preferences,
viewport,
resource_storage,
data_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Data) && !self.workspace_panel_layout.focus_document,
layers_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace_panel_layout.focus_document,
properties_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace_panel_layout.focus_document,
@@ -103,6 +117,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
self.persistent_state.process_message(message, responses, context);
}
PortfolioMessage::Fonts(message) => {
let context = FontsMessageContext { resource_storage };
self.fonts.process_message(message, responses, context);
}
// Messages
PortfolioMessage::Init => {
@@ -154,11 +172,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let document_inputs = DocumentMessageContext {
document_id,
ipp,
cached_data: &self.cached_data,
fonts: &self.fonts,
executor: &mut self.executor,
current_tool,
preferences,
viewport,
resource_storage,
data_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Data) && !self.workspace_panel_layout.focus_document,
layers_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Layers) && !self.workspace_panel_layout.focus_document,
properties_panel_open: self.workspace_panel_layout.is_panel_visible(PanelType::Properties) && !self.workspace_panel_layout.focus_document,
@@ -183,6 +202,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::AutoSaveDocument { document_id: *document_id });
}
}
responses.add(PortfolioMessage::GarbageCollectResources);
}
PortfolioMessage::AutoSaveDocument { document_id } => {
let Some(document) = self.document(document_id) else { return };
@@ -190,6 +211,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_id,
document: document.serialize_document(),
});
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
if let Some(document_id) = self.active_document_id {
@@ -368,86 +390,41 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(MenuBarMessage::SendLayout);
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::FontCatalogLoaded { catalog } => {
self.cached_data.font_catalog = catalog;
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::LoadDocumentResources { document_id });
}
// Load the default font
let font = Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into());
responses.add(PortfolioMessage::LoadFontData { font });
}
PortfolioMessage::LoadFontData { font } => {
if let Some(style) = self.cached_data.font_catalog.find_font_style_in_catalog(&font) {
let font = Font::new(font.font_family, style.to_named_style());
if !self.cached_data.font_cache.loaded_font(&font) {
responses.add(FrontendMessage::TriggerFontDataLoad { font, url: style.url });
}
}
}
PortfolioMessage::FontLoaded { font_family, font_style, data } => {
let font = Font::new(font_family, font_style);
self.cached_data.font_cache.insert(font, data);
self.executor.update_font_cache(self.cached_data.font_cache.clone());
for document_id in self.document_ids.iter() {
let node_to_inspect = self.node_to_inspect();
let Some(document) = self.documents.get_mut(document_id) else {
if self.unloaded_documents.contains_key(document_id) {
continue;
}
log::error!("Tried to render non-existent document");
continue;
};
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(viewport.center_in_viewport_space().into(), &document.document_ptz);
let pointer_position = document_to_viewport.inverse().transform_point2(ipp.mouse.position);
let scale = viewport.scale();
// Use exact physical dimensions from browser (via ResizeObserver's devicePixelContentBoxSize)
let physical_resolution = viewport.size().to_physical().into_dvec2().round().as_uvec2();
// TODO: Remove this when we do the SVG rendering with a separate library on desktop, thus avoiding a need for the hole punch.
// TODO: See #3796. There is a second instance of this todo comment and code block (be sure to remove both).
#[cfg(not(target_family = "wasm"))]
responses.add_front(FrontendMessage::UpdateViewportHolePunch {
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview,
});
if let Ok(message) = self
.executor
.submit_node_graph_evaluation(document, *document_id, physical_resolution, scale, timing_information, node_to_inspect, true, pointer_position)
{
responses.add_front(message);
}
}
if self.active_document_mut().is_some() {
responses.add(NodeGraphMessage::RunDocumentGraph);
}
if current_tool == &ToolType::Text {
responses.add(TextToolMessage::RefreshEditingFontData);
}
}
PortfolioMessage::EditorPreferences => self.executor.update_editor_preferences(preferences.editor_preferences()),
PortfolioMessage::LoadDocumentResources { document_id } => {
let catalog = &self.cached_data.font_catalog;
if catalog.0.is_empty() {
responses.add_front(FrontendMessage::TriggerFontCatalogLoad);
PortfolioMessage::GarbageCollectResources => {
if !self.persistent_state.loaded() {
// We don't know what can be safely garbage collected
return;
}
if let Some(document) = self.documents.get_mut(&document_id) {
document.load_layer_resources(responses);
let mut used_resources = HashSet::new();
for (id, info) in self.unloaded_documents.iter() {
if let Some(resources) = &info.resources {
used_resources.extend(resources.iter());
} else {
responses.add(PersistentStateMessage::ReadDocument { document_id: *id });
return;
}
}
for document in self.documents.values_mut() {
document.garbage_collect_resources();
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
}
used_resources.extend(self.fonts.used_resources());
responses.add(ResourceStorageMessage::GarbageCollect {
used: Vec::from_iter(used_resources).into_boxed_slice(),
});
}
PortfolioMessage::ResolveResources => {
for document_id in self.document_ids.iter().copied().collect::<Vec<_>>() {
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
}
PortfolioMessage::ResolveDocumentResources { document_id } => {
responses.add(PortfolioMessage::DocumentPassMessage {
document_id,
message: DocumentMessage::Resource(ResourceMessage::ResolveAll),
});
}
PortfolioMessage::LoadPersistedState { state } => {
if let Some(layout) = state.workspace_layout {
@@ -468,11 +445,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
workspace_layout: _,
} = state;
// TODO: Eventually remove this document upgrade code
let mut newly_unloaded_ids = Vec::new();
for info in documents {
if !self.document_ids.contains(&info.id) {
self.document_ids.push_back(info.id);
}
if !self.documents.contains_key(&info.id) {
if !self.documents.contains_key(&info.id) && !self.unloaded_documents.contains_key(&info.id) {
// TODO: Eventually remove this document upgrade code
newly_unloaded_ids.push(info.id);
self.unloaded_documents.insert(info.id, info);
}
}
@@ -480,9 +463,27 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
let select_document_id = current_document.filter(|id| self.document_ids.contains(id)).or_else(|| self.document_ids.front().copied());
// Eagerly load every autosaved doc on startup so deserialization failures can be reported in one batched dialog at the end.
// The active doc's read is deferred to the `SelectDocument` below, but is still counted.
// TODO: Eventually remove this document upgrade code
self.pending_initial_autosave_loads = self.pending_initial_autosave_loads.saturating_add(newly_unloaded_ids.len());
// TODO: Eventually remove this document upgrade code
for document_id in &newly_unloaded_ids {
if Some(*document_id) != select_document_id {
self.pending_eager_loads.insert(*document_id);
responses.add(PersistentStateMessage::ReadDocument { document_id: *document_id });
}
}
if let Some(document_id) = select_document_id {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
// TODO: Eventually remove this document upgrade code
else if self.pending_initial_autosave_loads == 0 && !self.failed_to_load_documents.is_empty() {
responses.add(PortfolioMessage::ShowFailedToLoadDocumentsDialog);
}
}
PortfolioMessage::LoadDocumentContent {
document_id,
@@ -501,7 +502,85 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_is_saved: info.is_saved,
document_serialized_content,
});
responses.add(PortfolioMessage::SelectDocument { document_id });
// Suppress auto-select for startup eager loads to keep focus on the user's active doc
// TODO: Eventually remove this document upgrade code
// TODO: (But keep the inner logic unconditionally, just remove the condition)
if !self.pending_eager_loads.remove(&document_id) {
responses.add(PortfolioMessage::SelectDocument { document_id });
}
}
// TODO: Eventually remove this document upgrade code
PortfolioMessage::ShowFailedToLoadDocumentsDialog => {
if self.failed_to_load_documents.is_empty() {
return;
}
let failed_document_names = self.failed_to_load_documents.values().map(|(info, _)| display_name_with_fallback(info)).collect();
let dialog = simple_dialogs::FailedToLoadDocumentsDialog { failed_document_names };
dialog.send_dialog_to_frontend(responses);
}
// TODO: Eventually remove this document upgrade code
PortfolioMessage::DiscardFailedToLoadDocuments => {
let failed = std::mem::take(&mut self.failed_to_load_documents);
for document_id in failed.keys() {
self.document_ids.retain(|id| id != document_id);
responses.add(PersistentStateMessage::DeleteDocument { document_id: *document_id });
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(PersistentStateMessage::WriteState);
}
// TODO: Eventually remove this document upgrade code
PortfolioMessage::DownloadFailedToLoadDocuments => {
if self.failed_to_load_documents.is_empty() {
return;
}
let mut used_names: HashMap<String, u32> = HashMap::new();
let files: Vec<(String, Vec<u8>)> = self
.failed_to_load_documents
.values()
.map(|(info, content)| {
let stem = sanitize_filename_stem(&info.name).unwrap_or_else(|| format!("document-{:x}", info.id.0));
let base = format!("{stem}.{FILE_EXTENSION}");
let unique = match used_names.get(&base).copied() {
None => {
used_names.insert(base.clone(), 1);
base
}
Some(n) => {
used_names.insert(base.clone(), n + 1);
format!("{stem} ({n}).{FILE_EXTENSION}")
}
};
(unique, content.as_bytes().to_vec())
})
.collect();
const FOLDER_NAME: &str = "Graphite Recovered Documents";
if files.len() == 1 {
let (filename, content) = files.into_iter().next().expect("just checked there's one entry");
responses.add(FrontendMessage::TriggerSaveFile {
name: filename,
folder: None,
content: serde_bytes::ByteBuf::from(content),
});
} else {
match build_recovery_zip(&files) {
Ok(zip_bytes) => responses.add(FrontendMessage::TriggerSaveFile {
name: format!("{FOLDER_NAME}.zip"),
folder: None,
content: serde_bytes::ByteBuf::from(zip_bytes),
}),
Err(e) => {
log::error!("Failed to build recovery zip: {e}");
responses.add(DialogMessage::DisplayDialogError {
title: "Failed to download".to_string(),
description: format!("Could not bundle the failed documents for download.\n\n{e}"),
});
}
}
}
}
PortfolioMessage::NewDocumentWithName { name } => {
let mut new_document = DocumentMessageHandler::default();
@@ -736,6 +815,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let reset_node_definitions_on_open = reset_node_definitions_on_open || document_migration_reset_node_definition(&document_serialized_content);
// Upgrade the document being opened with string replacements on the original JSON
let document_serialized_content = document_migration_string_preprocessing(document_serialized_content);
// Upgrade resources from being referend by hash to beeing referened by ID
let (document_serialized_content, resource_hash_to_id_migration_map) = document_migration_replace_resources_referenced_by_hash(document_serialized_content);
// Deserialize the document
let document = DocumentMessageHandler::deserialize_document(&document_serialized_content);
@@ -744,11 +825,37 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let mut document = match document {
Ok(document) => document,
Err(e) => {
if !document_is_auto_saved {
responses.add(DialogMessage::DisplayDialogError {
title: "Failed to open document".to_string(),
description: e.to_string(),
});
log::error!("{e}");
// TODO: Eventually remove this document upgrade code
// TODO: (Only the `if` branch, the `else` branch's manual-open dialog stays)
if document_is_auto_saved {
let name = document_name.unwrap_or_default();
let info = DocumentInfo {
id: document_id,
name,
resources: None,
path: document_path,
is_saved: document_is_saved,
};
self.document_ids.retain(|id| id != &document_id);
self.failed_to_load_documents.insert(document_id, (info, document_serialized_content));
if self.active_document_id == Some(document_id) {
self.active_document_id = None;
if let Some(next_id) = self.document_ids.front().copied() {
responses.add(PortfolioMessage::SelectDocument { document_id: next_id });
}
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
self.tick_autosave_load_progress(responses, true);
} else {
let name = document_name
.filter(|n| !n.trim().is_empty())
.or_else(|| document_path.as_ref().and_then(|p| p.file_stem()).map(|s| s.to_string_lossy().into_owned()))
.unwrap_or_default();
let dialog = simple_dialogs::FailedToOpenDocumentDialog { document_name: name };
dialog.send_dialog_to_frontend(responses);
}
return;
@@ -758,6 +865,25 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Upgrade the document's nodes to be compatible with the latest version
document_migration_upgrades(&mut document, reset_node_definitions_on_open);
// Load the document's embedded resources into the resource storage
std::mem::take(&mut document.resources.embedded).into_iter().for_each(|(hash, resource)| {
let data: Arc<[u8]> = Arc::from(resource.as_ref());
if ResourceHash::from(data.as_ref()) != hash {
log::error!("Resource hash mismatch for resource with hash {hash}");
return;
}
responses.add(ResourceStorageMessage::Store { data });
// TODO: Eventually remove this document upgrade code
// Register any resources that were previously referenced by hash
if let Some(id) = resource_hash_to_id_migration_map.get(&hash)
&& !document.resources.registry.contains(id)
{
document.resources.registry.resolve(id, hash);
document.resources.registry.push_source_back(id, DataSource::Embedded);
}
});
// Ensure each node has the metadata for its inputs
for (node_id, node, path) in document.network_interface.document_network().clone().recursive_nodes() {
document.network_interface.validate_input_metadata(node_id, node, &path);
@@ -821,6 +947,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.load_document(document, document_id, responses);
responses.add(AppWindowMessage::Focus);
// TODO: Eventually remove this document upgrade code
if document_is_auto_saved {
self.tick_autosave_load_progress(responses, false);
}
}
PortfolioMessage::OpenImage { name, image } => {
// `NewDocumentWithName`'s handler routes empty/None-equivalent names through `resolve_document_name` which assigns the next available "Untitled Document {N}".
@@ -944,7 +1075,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
added_nodes = true;
}
document.load_layer_resources(responses);
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
all_new_ids.extend(new_ids.values().cloned());
@@ -1429,7 +1559,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
if !document.is_loaded {
document.is_loaded = true;
responses.add(PortfolioMessage::LoadDocumentResources { document_id });
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
responses.add(PortfolioMessage::UpdateDocumentWidgets);
responses.add(PropertiesPanelMessage::Clear);
}
@@ -1475,6 +1605,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
// Skip rendering while any resource is still unresolved — the preprocessor would otherwise fail with
// `ResourceNotFound`. `ResourceMessage::Resolved` queues `RunDocumentGraph` once each id resolves,
// so the render fires automatically once the registry is complete.
if document.resources.registry.unresolved().next().is_some() {
return;
}
let document_to_viewport = document
.navigation_handler
.calculate_offset_transform(viewport.center_in_viewport_space().into(), &document.document_ptz);
@@ -1730,7 +1867,13 @@ impl PortfolioMessageHandler {
}
pub fn persisted_state_snapshot(&self) -> PersistedState {
let documents = self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect::<Vec<_>>();
let mut documents = self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect::<Vec<_>>();
// Keep failed-to-load docs referenced in `state.documents` so their autosave files survive `garbage_collect_document_files`
// TODO: Eventually remove this document upgrade code
for (info, _) in self.failed_to_load_documents.values() {
documents.push(info.clone());
}
PersistedState {
documents,
@@ -1774,6 +1917,18 @@ impl PortfolioMessageHandler {
}
}
// TODO: Eventually remove this document upgrade code
fn tick_autosave_load_progress(&mut self, responses: &mut VecDeque<Message>, failed: bool) {
if self.pending_initial_autosave_loads > 0 {
self.pending_initial_autosave_loads -= 1;
if self.pending_initial_autosave_loads == 0 && !self.failed_to_load_documents.is_empty() {
responses.add(PortfolioMessage::ShowFailedToLoadDocumentsDialog);
}
} else if failed {
responses.add(PortfolioMessage::ShowFailedToLoadDocumentsDialog);
}
}
fn read_file(path: &PathBuf, content: Vec<u8>) -> FileContent {
let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or_default().to_lowercase();
match extension.as_str() {
@@ -1869,6 +2024,7 @@ impl PortfolioMessageHandler {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
resources: Some(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()).collect::<Vec<_>>().into_boxed_slice()),
})
} else {
self.unloaded_documents.get(&document_id).cloned()
@@ -1982,3 +2138,76 @@ impl PortfolioMessageHandler {
}
}
}
// TODO: Eventually remove this document upgrade code
fn display_name_with_fallback(info: &DocumentInfo) -> String {
if info.name.trim().is_empty() {
format!("Untitled Document ({:x})", info.id.0)
} else {
info.name.clone()
}
}
/// Returns `None` if the name has no safe filename characters left or matches a Windows reserved device name, so callers fall back to an ID-based stem.
// TODO: Eventually remove this document upgrade code
fn sanitize_filename_stem(name: &str) -> Option<String> {
let replaced: String = name
.chars()
.map(|c| {
if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() {
'_'
} else {
c
}
})
.collect();
// Trim dots to avoid `.` / `..` resolving against the parent directory, and to dodge Windows' trailing-dot/space quirks
let trimmed = replaced.trim().trim_matches('.').trim();
if trimmed.is_empty() {
return None;
}
// Windows rejects these regardless of extension; superscript digits are normalized equivalently by some path APIs
let first_segment = trimmed.split('.').next().unwrap_or("").to_ascii_uppercase();
if matches!(
first_segment.as_str(),
"CON"
| "PRN" | "AUX"
| "NUL" | "COM1"
| "COM2" | "COM3"
| "COM4" | "COM5"
| "COM6" | "COM7"
| "COM8" | "COM9"
| "COM¹" | "COM²"
| "COM³" | "LPT1"
| "LPT2" | "LPT3"
| "LPT4" | "LPT5"
| "LPT6" | "LPT7"
| "LPT8" | "LPT9"
| "LPT¹" | "LPT²"
| "LPT³"
) {
return None;
}
Some(trimmed.to_string())
}
// TODO: Eventually remove this document upgrade code
fn build_recovery_zip(entries: &[(String, Vec<u8>)]) -> Result<Vec<u8>, String> {
use std::io::{Cursor, Write};
use zip::write::{SimpleFileOptions, ZipWriter};
let mut buffer = Cursor::new(Vec::<u8>::new());
let mut writer = ZipWriter::new(&mut buffer);
let options: SimpleFileOptions = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o644);
for (filename, content) in entries {
writer.start_file(filename, options).map_err(|e| format!("start_file: {e}"))?;
writer.write_all(content).map_err(|e| format!("write_all: {e}"))?;
}
writer.finish().map_err(|e| format!("finish: {e}"))?;
Ok(buffer.into_inner())
}
@@ -1,95 +1,11 @@
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::text::{Font, FontCache};
/// Proportional share (0-1) for the document panel's side when splitting adjacent to non-document panels.
const DOCUMENT_PANEL_SHARE: f64 = 0.8;
/// Proportional share for each side when neither (or both) contain the document panel.
const EQUAL_PANEL_SHARE: f64 = 0.5;
#[derive(Debug, Default)]
pub struct CachedData {
pub font_cache: FontCache,
pub font_catalog: FontCatalog,
}
// TODO: Should this be a BTreeMap instead?
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog(pub Vec<FontCatalogFamily>);
impl FontCatalog {
pub fn find_font_style_in_catalog(&self, font: &Font) -> Option<FontCatalogStyle> {
let family = self.0.iter().find(|family| family.name == font.font_family);
let found_style = family.map(|family| {
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&font.font_style, "");
family.closest_style(weight, italic).clone()
});
if found_style.is_none() {
log::warn!("Font not found in catalog: {:?}", font);
}
found_style
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogFamily {
/// The font family name.
pub name: String,
/// The font styles (variants) available for the font family.
pub styles: Vec<FontCatalogStyle>,
}
impl FontCatalogFamily {
/// Finds the closest style to the given weight and italic setting.
/// Aims to find the nearest weight while maintaining the italic setting if possible, but italic may change if no other option is available.
pub fn closest_style(&self, weight: u32, italic: bool) -> &FontCatalogStyle {
self.styles
.iter()
.map(|style| ((style.weight as i32 - weight as i32).unsigned_abs() + 10000 * (style.italic != italic) as u32, style))
.min_by_key(|(distance, _)| *distance)
.map(|(_, style)| style)
.unwrap_or(&self.styles[0])
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FontCatalogStyle {
pub weight: u32,
pub italic: bool,
pub url: String,
}
impl FontCatalogStyle {
pub fn to_named_style(&self) -> String {
let weight = self.weight;
let italic = self.italic;
let named_weight = Font::named_weight(weight);
let maybe_italic = if italic { " Italic" } else { "" };
format!("{named_weight}{maybe_italic} ({weight})")
}
pub fn from_named_style(named_style: &str, url: impl Into<String>) -> FontCatalogStyle {
let weight = named_style.split_terminator(['(', ')']).next_back().and_then(|x| x.parse::<u32>().ok()).unwrap_or(400);
let italic = named_style.contains("Italic (");
FontCatalogStyle { weight, italic, url: url.into() }
}
/// Get the URL for the stylesheet for loading a font preview for this style of the given family name, subsetted to only the letters in the family name.
pub fn preview_url(&self, family: impl Into<String>) -> String {
let name = family.into().replace(' ', "+");
let italic = if self.italic { "ital," } else { "" };
let weight = self.weight;
format!("https://fonts.googleapis.com/css2?display=swap&family={name}:{italic}wght@{weight}&text={name}")
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
@@ -65,7 +65,7 @@ impl Default for PreferencesMessageHandler {
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT,
max_render_region_size: EditorPreferences::default().max_render_region_size,
disable_ui_acceleration: false,
disable_ui_acceleration: cfg!(target_os = "linux"), // TODO: Set this back to false once we have ui acceleration working more reliably on linux
#[cfg(target_os = "macos")]
vsync: false,
}
+5
View File
@@ -16,21 +16,26 @@ pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage,
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler};
pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant};
pub use crate::messages::future::{FutureMessage, FutureMessageContext, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
pub use crate::messages::input_mapper::key_mapping::{KeyMappingMessage, KeyMappingMessageContext, KeyMappingMessageDiscriminant, KeyMappingMessageHandler};
pub use crate::messages::input_mapper::{InputMapperMessage, InputMapperMessageContext, InputMapperMessageDiscriminant, InputMapperMessageHandler};
pub use crate::messages::input_preprocessor::{InputPreprocessorMessage, InputPreprocessorMessageContext, InputPreprocessorMessageDiscriminant, InputPreprocessorMessageHandler};
pub use crate::messages::layout::{LayoutMessage, LayoutMessageDiscriminant, LayoutMessageHandler};
pub use crate::messages::menu_bar::{MenuBarMessage, MenuBarMessageDiscriminant, MenuBarMessageHandler};
pub use crate::messages::network::{NetworkMessage, NetworkMessageContext, NetworkMessageDiscriminant, NetworkMessageHandler};
pub use crate::messages::portfolio::document::data_panel::{DataPanelMessage, DataPanelMessageDiscriminant};
pub use crate::messages::portfolio::document::graph_operation::{GraphOperationMessage, GraphOperationMessageContext, GraphOperationMessageDiscriminant, GraphOperationMessageHandler};
pub use crate::messages::portfolio::document::navigation::{NavigationMessage, NavigationMessageContext, NavigationMessageDiscriminant, NavigationMessageHandler};
pub use crate::messages::portfolio::document::node_graph::{NodeGraphMessage, NodeGraphMessageDiscriminant, NodeGraphMessageHandler};
pub use crate::messages::portfolio::document::overlays::{OverlaysMessage, OverlaysMessageContext, OverlaysMessageDiscriminant, OverlaysMessageHandler};
pub use crate::messages::portfolio::document::properties_panel::{PropertiesPanelMessage, PropertiesPanelMessageDiscriminant, PropertiesPanelMessageHandler};
pub use crate::messages::portfolio::document::resource::{ResourceMessage, ResourceMessageContext, ResourceMessageDiscriminant, ResourceMessageHandler};
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
pub use crate::messages::resource_storage::{ResourceStorageMessage, ResourceStorageMessageContext, ResourceStorageMessageDiscriminant, ResourceStorageMessageHandler};
pub use crate::messages::tool::transform_layer::{TransformLayerMessage, TransformLayerMessageDiscriminant, TransformLayerMessageHandler};
pub use crate::messages::tool::{ToolMessage, ToolMessageContext, ToolMessageDiscriminant, ToolMessageHandler};
pub use crate::messages::viewport::{ViewportMessage, ViewportMessageDiscriminant, ViewportMessageHandler};
@@ -0,0 +1,7 @@
mod resource_storage_message;
mod resource_storage_message_handler;
#[doc(inline)]
pub use resource_storage_message::{ResourceStorageMessage, ResourceStorageMessageDiscriminant};
#[doc(inline)]
pub use resource_storage_message_handler::{ResourceStorageMessageContext, ResourceStorageMessageHandler, ResourcesHandle};
@@ -0,0 +1,10 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::ResourceHash;
use std::sync::Arc;
#[impl_message(Message, ResourceStorage)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ResourceStorageMessage {
Store { data: Arc<[u8]> },
GarbageCollect { used: Box<[ResourceHash]> },
}
@@ -0,0 +1,75 @@
use crate::messages::prelude::*;
use graph_craft::application_io::resource::{LoadResource, ResourceFuture, ResourceHash, ResourceStorage};
use std::sync::Arc;
#[derive(Clone)]
pub struct ResourcesHandle {
inner: Arc<dyn ResourceStorage>,
}
impl LoadResource for ResourcesHandle {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
self.inner.load(hash)
}
}
#[derive(ExtractField)]
pub struct ResourceStorageMessageHandler {
storage: Option<Arc<dyn ResourceStorage>>,
}
impl ResourceStorageMessageHandler {
pub fn new(resource_storage: Arc<dyn ResourceStorage>) -> Self {
Self { storage: Some(resource_storage) }
}
pub fn resources(&self) -> Box<dyn LoadResource> {
Box::new(ResourcesHandle {
inner: self.storage.clone().expect("Resource storage not initialized"),
})
}
}
impl std::fmt::Debug for ResourceStorageMessageHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResourceStorageMessageHandler").finish_non_exhaustive()
}
}
impl Default for ResourceStorageMessageHandler {
#[cfg(not(test))]
fn default() -> Self {
Self { storage: None }
}
#[cfg(test)]
fn default() -> Self {
Self {
storage: Some(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new())),
}
}
}
#[derive(ExtractField)]
pub struct ResourceStorageMessageContext {}
#[message_handler_data]
impl MessageHandler<ResourceStorageMessage, ResourceStorageMessageContext> for ResourceStorageMessageHandler {
fn process_message(&mut self, message: ResourceStorageMessage, _responses: &mut VecDeque<Message>, _context: ResourceStorageMessageContext) {
let Some(storage) = &self.storage else {
log::error!("Received resource message but storage is not initialized");
return;
};
match message {
ResourceStorageMessage::Store { data } => {
let _hash = storage.store(data.as_ref());
}
ResourceStorageMessage::GarbageCollect { used } => {
storage.garbage_collect(&used);
}
}
}
advertise_actions!(ResourceStorageMessageDiscriminant;);
}
@@ -271,6 +271,35 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
network_interface.document_metadata().transform_to_viewport(layer).transform_point2(min + (max - min) * center)
}
/// Determine the input connector where the gradient chain enters the layer.
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<Fill>::INDEX)
} else {
InputConnector::node(layer.to_node(), 1)
}
}
/// Try to find a "Gradient Value" node that is connected to a "Fill" node, or to a layer directly.
pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
network_interface
.upstream_flow_back_from_nodes(vec![layer.to_node()], &[], FlowType::UpstreamFlow)
.skip(1)
.take_while(|node_id| !network_interface.is_layer(node_id, &[]))
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)))
}
/// Get the node connected to Fill's fill input, if any.
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<Fill>::INDEX)? else {
return None;
};
Some(*node_id)
}
/// Get the current gradient of a layer from the closest "Fill" node.
pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
let fill_index = 1;
@@ -284,8 +313,8 @@ pub fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER))?;
let TaggedValue::Gradient(stops) = inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
let TaggedValue::Gradient(stops) = gradient_value_node.inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
return None;
};
Some(stops.clone())
@@ -431,15 +460,21 @@ pub fn get_grid_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkIn
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::grid::IDENTIFIER))
}
/// Gets properties from the Text node
pub fn get_text(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(&String, &Font, TypesettingConfig, bool)> {
/// Gets properties from the Text node. Resolves the font selection by reading the resource id and lookup via the fonts message handler.
pub fn get_text<'a>(
layer: LayerNodeIdentifier,
network_interface: &'a NodeNetworkInterface,
fonts: &FontsMessageHandler,
resources: &ResourceMessageHandler,
) -> Option<(&'a String, Font, TypesettingConfig, bool)> {
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER))?;
let Some(TaggedValue::String(text)) = &inputs[graphene_std::text::text::TextInput::INDEX].as_value() else {
return None;
};
let Some(TaggedValue::Font(font)) = &inputs[graphene_std::text::text::FontInput::INDEX].as_value() else {
return None;
let font = match &inputs[graphene_std::text::text::FontInput::INDEX].as_value() {
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
_ => Font::default(),
};
let Some(&TaggedValue::F64(font_size)) = inputs[graphene_std::text::text::SizeInput::INDEX].as_value() else {
return None;
@@ -16,7 +16,6 @@ use graph_craft::document::value::TaggedValue;
use graphene_std::list::List;
use graphene_std::renderer::Quad;
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::text::FontCache;
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModification, VectorModificationType};
@@ -63,17 +62,18 @@ where
}
/// Calculates the bounding box of the layer's text, based on the settings for max width and height specified in the typesetting config.
pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, font_cache: &FontCache) -> Quad {
pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) -> Quad {
// Use the `editor:text_frame` attribute if available (handles multi-item glyphs and the 'Index Elements' node)
if let Some(&frame) = document.metadata().text_frames.get(&layer) {
return frame * Quad::from_box([DVec2::ZERO, DVec2::ONE]);
}
// Fallback: recompute from text content (e.g. layer hasn't rendered yet)
let Some((text, font, typesetting, _)) = get_text(layer, &document.network_interface) else {
let Some((text, font, typesetting, _)) = get_text(layer, &document.network_interface, fonts, &document.resources) else {
return Quad::from_box([DVec2::ZERO, DVec2::ZERO]);
};
let far = graphene_std::text::bounding_box(text, font, font_cache, typesetting, false);
let font = fonts.get_resource_or_queue_load(&font, responses);
let far = graphene_std::text::bounding_box(text, &font, typesetting, false);
Quad::from_box([DVec2::ZERO, far])
}
@@ -4,7 +4,6 @@ use super::utility_types::{ToolActionMessageContext, ToolFsmState, tool_message_
use crate::application::generate_uuid;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::prelude::*;
use crate::messages::tool::transform_layer::transform_layer_message_handler::TransformLayerMessageContext;
use crate::messages::tool::utility_types::{HintData, ToolType};
@@ -19,7 +18,7 @@ pub struct ToolMessageContext<'a> {
pub document_id: DocumentId,
pub document: &'a mut DocumentMessageHandler,
pub input: &'a InputPreprocessorMessageHandler,
pub cached_data: &'a CachedData,
pub fonts: &'a FontsMessageHandler,
pub node_graph: &'a NodeGraphExecutor,
pub preferences: &'a PreferencesMessageHandler,
pub viewport: &'a ViewportMessageHandler,
@@ -40,7 +39,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
document_id,
document,
input,
cached_data,
fonts,
node_graph,
preferences,
viewport,
@@ -127,7 +126,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
cached_data,
fonts,
};
if let Some(tool_abort_message) = tool.event_to_message_map().tool_abort {
@@ -218,7 +217,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
tool_data.tools.get(active_tool).unwrap().activate(responses);
// Register initial properties
tool_data.tools.get(active_tool).unwrap().refresh_options(responses, cached_data);
tool_data.tools.get(active_tool).unwrap().refresh_options(responses);
// Notify the frontend about the initial active tool
tool_data.send_layout(responses, LayoutTarget::ToolShelf, preferences.brush_tool);
@@ -235,7 +234,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
cached_data,
fonts,
};
// Set initial hints and cursor
@@ -259,7 +258,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
ToolMessage::RefreshToolOptions => {
let tool_data = &mut self.tool_state.tool_data;
tool_data.tools.get(&tool_data.active_tool_type).unwrap().refresh_options(responses, cached_data);
tool_data.tools.get(&tool_data.active_tool_type).unwrap().refresh_options(responses);
}
ToolMessage::RefreshToolShelf => {
let tool_data = &mut self.tool_state.tool_data;
@@ -347,7 +346,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
node_graph,
preferences,
viewport,
cached_data,
fonts,
};
if matches!(tool_message, ToolMessage::UpdateHints) {
if graph_view_overlay_open {
@@ -8,7 +8,7 @@ use crate::messages::portfolio::document::overlays::utility_types::{GizmoEmphasi
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeNetworkInterface};
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer, get_gradient_stops};
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer, get_gradient_stops, gradient_chain_target_input};
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
use graph_craft::document::value::TaggedValue;
use graphene_std::color::SRGBA8;
@@ -347,20 +347,19 @@ fn gradient_space_transform(layer: LayerNodeIdentifier, document: &DocumentMessa
// TODO: Remove this whole function once all gradients are stored via the modern `Gradient(GradientStops)` slot
fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
if let Some(stops) = get_gradient_stops(layer, network_interface) {
let GradientChainState {
transform,
gradient_type,
spread_method,
} = read_gradient_chain_state(layer, network_interface);
return Some(Gradient {
// Try to construct a gradient out of a chain, which is directly connected to a layer
let chain_state = read_gradient_chain_state(layer, network_interface);
Some(Gradient {
stops,
gradient_type,
spread_method,
start: transform.transform_point2(DVec2::ZERO),
end: transform.transform_point2(DVec2::X),
});
gradient_type: chain_state.gradient_type,
spread_method: chain_state.spread_method,
start: chain_state.transform.transform_point2(DVec2::ZERO),
end: chain_state.transform.transform_point2(DVec2::X),
})
} else {
// Try to find a legacy Fill::Gradient that is selected in a Fill node
graph_modification_utils::get_gradient(layer, network_interface)
}
graph_modification_utils::get_gradient(layer, network_interface)
}
#[derive(Clone, Copy, Debug)]
@@ -373,6 +372,9 @@ struct GradientChainState {
/// Resolve the gradient transform, type, and spread method by walking the chain feeding the layer. Transform composes all
/// 'Transform' nodes. Type and spread method come from the closest-to-layer node of each kind, or the type default.
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientChainState {
let target_input = gradient_chain_target_input(layer, network_interface);
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_type_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_type::IDENTIFIER);
let spread_method_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::spread_method::IDENTIFIER);
@@ -382,8 +384,8 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
let mut spread_method: Option<GradientSpreadMethod> = None;
for node_id in network_interface
.upstream_flow_back_from_nodes(vec![layer.to_node()], &[], FlowType::HorizontalFlow)
.skip(1)
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
.skip_while(|node_id| network_interface.is_layer(node_id, &[]))
.take_while(|node_id| !network_interface.is_layer(node_id, &[]))
{
let Some(reference) = network_interface.reference(&node_id, &[]) else { continue };
@@ -512,14 +514,13 @@ fn calculate_insertion(start: DVec2, end: DVec2, stops: &GradientStops, mouse: D
impl SelectedGradient {
pub fn new(gradient: Gradient, layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Self {
let transform = gradient_space_transform(layer, document);
let is_gradient_list = get_gradient_stops(layer, &document.network_interface).is_some();
Self {
layer: Some(layer),
transform,
gradient: gradient.clone(),
dragging: GradientDragTarget::End,
initial_gradient: gradient,
is_gradient_list,
is_gradient_list: get_gradient_stops(layer, &document.network_interface).is_some(),
}
}
@@ -2501,4 +2502,98 @@ mod test_gradient {
assert_eq!(SRGBA8::from(updated.stops.color[1]), SRGBA8::from(Color::GREEN), "Middle stop color should be preserved");
assert_eq!(SRGBA8::from(updated.stops.color[2]), SRGBA8::from(Color::BLUE), "Last stop color should be preserved");
}
// When the gradient chain feeds a 'Fill' node's secondary input it's an unencapsulated side-branch (no layer
// background to lay it out), so a node inserted there must be placed onto the displaced feeder's spot in absolute
// graph space rather than stranded at the origin.
#[tokio::test]
async fn gradient_chain_node_on_fill_secondary_input_takes_feeder_slot() {
use graphene_std::vector::style::GradientSpreadMethod;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Ellipse, 0., 0., 100., 100., ModifierKeys::empty()).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
// Find the 'Fill' node in the layer's primary chain.
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let fill_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&fill_reference))
.expect("Fill node should exist")
};
// Feed a 'Gradient Value' node into the Fill node's secondary (fill) input.
let gradient_value_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::node(gradient_value_id, 0),
input_connector: InputConnector::node(fill_node_id, 1),
})
.await;
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_value_id,
input_index: 1,
value: TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
color: Color::RED,
},
GradientStop {
position: 1.,
midpoint: 0.5,
color: Color::BLUE,
},
])),
})
.await;
// Move the feeder off the origin so its slot is unambiguous, then record where it sits.
editor
.handle_message(NodeGraphMessage::ShiftNodePosition {
node_id: gradient_value_id,
x: 4,
y: 6,
})
.await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the spread method through the tool, which splices a 'Spread Method' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::SetSpreadMethod(GradientSpreadMethod::Reflect),
})
.await;
let spread_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::spread_method::IDENTIFIER);
let spread_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&spread_reference))
.expect("Spread Method node should have been inserted")
};
let spread_position = editor.active_document_mut().network_interface.position(&spread_node_id, &[]).expect("Spread Method position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(spread_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
assert_eq!(
feeder_position_after,
feeder_position - glam::IVec2::new(crate::consts::NODE_CHAIN_WIDTH, 0),
"the feeder's branch should shift one chain-width left to make room"
);
}
}
@@ -720,13 +720,7 @@ impl Fsm for SelectToolFsmState {
type ToolOptions = ();
fn transition(self, event: ToolMessage, tool_data: &mut Self::ToolData, tool_action_data: &mut ToolActionMessageContext, _tool_options: &(), responses: &mut VecDeque<Message>) -> Self {
let ToolActionMessageContext {
document,
input,
viewport,
cached_data,
..
} = tool_action_data;
let ToolActionMessageContext { document, input, viewport, fonts, .. } = tool_action_data;
let ToolMessage::Select(event) = event else { return self };
match (self, event) {
@@ -751,7 +745,7 @@ impl Fsm for SelectToolFsmState {
if document.metadata().is_text_layer(layer) {
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, &cached_data.font_cache);
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, fonts, responses);
overlay_context.dashed_quad(transformed_quad, None, None, Some(7.), Some(5.), None);
}
}
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Transf
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::utility_types::{CachedData, FontCatalog, FontCatalogStyle};
use crate::messages::portfolio::fonts::utility_types::{FontCatalog, FontCatalogStyle};
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::color_selector::{
ToolColorOptions, apply_fill_only_color_pick, apply_fill_only_enabled, refresh_slot_working_color, selection_changed_since_last_sync, solid, sync_fill_only,
@@ -17,12 +17,13 @@ use crate::messages::tool::common_functionality::snapping::{self, SnapCandidateP
use crate::messages::tool::common_functionality::transformation_cage::*;
use crate::messages::tool::common_functionality::utility_functions::text_bounding_box;
use crate::messages::tool::utility_types::ToolRefreshOptions;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::choice_type::ChoiceTypeStatic;
use graphene_std::color::SRGBA8;
use graphene_std::renderer::Quad;
use graphene_std::text::{Font, FontCache, TextAlign, TypesettingConfig, lines_clipping};
use graphene_std::text::{Font, TextAlign, TypesettingConfig, lines_clipping};
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI};
use graphene_std::{Color, NodeInputDecleration};
@@ -105,31 +106,30 @@ impl ToolMetadata for TextTool {
}
fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &DocumentMessageHandler) -> Vec<WidgetInstance> {
// If a single text layer is selected, the control bar's font/style menus drive that layer's text node directly, going through the
// same code path as the Properties panel (LoadFontData + SetInputValue, with closest_style and font_style_to_restore bookkeeping).
// Otherwise the menus only update the control bar option for the next created text.
let text_node_id = can_edit_selected(document).and_then(|layer| graph_modification_utils::get_text_id(layer, &document.network_interface));
let font_input_index = graphene_std::text::text::FontInput::INDEX;
let apply_font = move |new_font: Font| -> Message {
let apply_font = move |font: Font| -> Message {
match text_node_id {
Some(node_id) => NodeGraphMessage::SetInputValue {
node_id,
input_index: font_input_index,
value: TaggedValue::Font(new_font),
Some(node_id) => {
let resource_id = ResourceId::new();
Message::Batched {
messages: Box::new([
DocumentMessage::Resource(ResourceMessage::AddFont { resource_id, font }).into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id),
}
.into(),
]),
}
}
.into(),
None => TextToolMessage::UpdateOptions {
options: TextOptionsUpdate::Font { font: new_font },
options: TextOptionsUpdate::Font { font },
}
.into(),
}
};
let preview_font = move |new_font: Font| -> Message {
Message::Batched {
messages: Box::new([PortfolioMessage::LoadFontData { font: new_font.clone() }.into(), apply_font(new_font)]),
}
};
let commit_font = move |new_font: Font| -> Message {
match text_node_id {
Some(_) => DeferMessage::AfterGraphRun {
@@ -142,35 +142,27 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
let font = DropdownInput::new(vec![
font_catalog
.0
.iter()
.map(|family| {
let current_font = &tool.options.font;
let mut new_font = Font::new(family.name.clone(), current_font.font_style_to_restore.clone().unwrap_or_else(|| current_font.font_style.clone()));
new_font.font_style_to_restore = current_font.font_style_to_restore.clone().or_else(|| Some(new_font.font_style.clone()));
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&new_font.font_style, "");
new_font.font_style = family.closest_style(weight, italic).to_named_style();
// Intentionally drop `font_style_to_restore` on commit so the committed style becomes the new basis for
// subsequent family switches. Preserving the original style intent is hover-only behavior (handled by `new_font`).
let FontCatalogStyle { weight, italic, .. } = FontCatalogStyle::from_named_style(&current_font.font_style, "");
let commit_only_font = Font::new(family.name.clone(), family.closest_style(weight, italic).to_named_style());
let new_font = Font::new(family.name.clone(), family.closest_style(weight, italic).to_named_style());
let commit_only_font = new_font.clone();
MenuListEntry::new(family.name.clone())
.label(family.name.clone())
.font(family.closest_style(400, false).preview_url(&family.name))
.on_update(move |_| preview_font(new_font.clone()))
.on_update(move |_| apply_font(new_font.clone()))
.on_commit(move |_| commit_font(commit_only_font.clone()))
})
.collect::<Vec<_>>(),
])
.selected_index(font_catalog.0.iter().position(|family| family.name == tool.options.font.font_family).map(|i| i as u32))
.selected_index(font_catalog.iter().position(|family| family.name == tool.options.font.font_family).map(|i| i as u32))
.virtual_scrolling(true)
.widget_instance();
let style = DropdownInput::new({
font_catalog
.0
.iter()
.find(|family| family.name == tool.options.font.font_family)
.map(|family| {
@@ -182,7 +174,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
MenuListEntry::new(font_style.clone())
.label(font_style)
.on_update(move |_| preview_font(new_font.clone()))
.on_update(move |_| apply_font(new_font.clone()))
.on_commit(move |_| commit_font(new_font_for_commit.clone()))
};
@@ -196,7 +188,6 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
})
.selected_index(
font_catalog
.0
.iter()
.find(|family| family.name == tool.options.font.font_family)
.and_then(|family| {
@@ -253,7 +244,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
}
impl ToolRefreshOptions for TextTool {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData) {
fn refresh_options(&self, responses: &mut VecDeque<Message>) {
// Defer to the SelectionChanged handler which has document context, required for the font/style
// dropdowns to bind to the selected text layer's node graph inputs
responses.add(TextToolMessage::SelectionChanged);
@@ -299,11 +290,15 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
self.options.fill.fill_choice = Some(solid(context.global_tool_data.primary_color));
}
if context.fonts.font_catalog.is_empty() {
responses.add_front(FontsMessage::LoadCatalog);
}
let options = match message {
ToolMessage::Text(TextToolMessage::UpdateOptions { options }) => options,
ToolMessage::Text(TextToolMessage::SelectionChanged) => {
if let Some(layer) = can_edit_selected(context.document)
&& let Some((_, font, typesetting, _)) = graph_modification_utils::get_text(layer, &context.document.network_interface)
&& let Some((_, font, typesetting, _)) = graph_modification_utils::get_text(layer, &context.document.network_interface, context.fonts, &context.document.resources)
{
self.options.align = typesetting.align;
self.options.font_size = typesetting.font_size;
@@ -311,7 +306,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
if let Some(editing_text) = self.tool_data.editing_text.as_mut() {
editing_text.typesetting.align = typesetting.align;
editing_text.typesetting.font_size = typesetting.font_size;
editing_text.font = font.clone();
editing_text.font = font;
}
}
@@ -326,7 +321,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
// Text tool has no fill checkbox; keep enabled so new text never starts with `None`
self.options.fill.enabled = Some(true);
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog, context.document);
self.send_layout(responses, LayoutTarget::ToolOptions, &context.fonts.font_catalog, context.document);
return;
}
_ => {
@@ -385,7 +380,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
}
}
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog, context.document);
self.send_layout(responses, LayoutTarget::ToolOptions, &context.fonts.font_catalog, context.document);
}
fn actions(&self) -> ActionList {
@@ -476,9 +471,9 @@ struct TextToolData {
}
impl TextToolData {
fn delete_empty_layer(&mut self, font_cache: &FontCache, responses: &mut VecDeque<Message>) -> TextToolFsmState {
fn delete_empty_layer(&mut self, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) -> TextToolFsmState {
// Remove the editable textbox UI first
self.set_editing(false, font_cache, responses);
self.set_editing(false, fonts, responses);
// Delete the empty text layer and update the graph
responses.add(NodeGraphMessage::DeleteNodes {
@@ -491,15 +486,16 @@ impl TextToolData {
}
/// Set the editing state of the currently modifying layer
fn set_editing(&self, editable: bool, font_cache: &FontCache, responses: &mut VecDeque<Message>) {
fn set_editing(&self, editable: bool, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
if let Some(editing_text) = self.editing_text.as_ref().filter(|_| editable) {
let (align, align_last) = editing_text.typesetting.align.css();
let font_data = fonts.get_resource_or_queue_load(&editing_text.font, responses).as_ref().to_vec().into();
responses.add(FrontendMessage::DisplayEditableTextbox {
text: editing_text.text.clone(),
line_height_ratio: editing_text.typesetting.line_height_ratio,
font_size: editing_text.typesetting.font_size,
color: editing_text.color.map_or("#000000".to_string(), |color| SRGBA8::from(color).to_css_hex()),
font_data: font_cache.get(&editing_text.font).map(|(data, _)| data.clone()).unwrap_or_default().into(),
font_data,
transform: editing_text.transform.to_cols_array(),
max_width: editing_text.typesetting.max_width,
max_height: editing_text.typesetting.max_height,
@@ -517,13 +513,13 @@ impl TextToolData {
}
}
fn load_layer_text_node(&mut self, document: &DocumentMessageHandler) -> Option<()> {
fn load_layer_text_node(&mut self, document: &DocumentMessageHandler, fonts: &FontsMessageHandler) -> Option<()> {
let transform = document.metadata().transform_to_viewport(self.layer);
let color = graph_modification_utils::get_fill_color(self.layer, &document.network_interface).unwrap_or(Color::BLACK);
let (text, font, typesetting, _) = graph_modification_utils::get_text(self.layer, &document.network_interface)?;
let (text, font, typesetting, _) = graph_modification_utils::get_text(self.layer, &document.network_interface, fonts, &document.resources)?;
self.editing_text = Some(EditingText {
text: text.clone(),
font: font.clone(),
font,
typesetting,
color: Some(color),
transform,
@@ -532,20 +528,20 @@ impl TextToolData {
Some(())
}
fn start_editing_layer(&mut self, layer: LayerNodeIdentifier, tool_state: TextToolFsmState, document: &DocumentMessageHandler, font_cache: &FontCache, responses: &mut VecDeque<Message>) {
fn start_editing_layer(&mut self, layer: LayerNodeIdentifier, tool_state: TextToolFsmState, document: &DocumentMessageHandler, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
if layer == LayerNodeIdentifier::ROOT_PARENT {
log::error!("Cannot edit ROOT_PARENT in TextTooLData")
}
if tool_state == TextToolFsmState::Editing {
self.set_editing(false, font_cache, responses);
self.set_editing(false, fonts, responses);
}
self.layer = layer;
if self.load_layer_text_node(document).is_some() {
if self.load_layer_text_node(document, fonts).is_some() {
responses.add(DocumentMessage::AddTransaction);
self.set_editing(true, font_cache, responses);
self.set_editing(true, fonts, responses);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![self.layer.to_node()] });
// Make the rendered text invisible while editing
@@ -557,14 +553,16 @@ impl TextToolData {
};
}
fn new_text(&mut self, document: &DocumentMessageHandler, editing_text: EditingText, font_cache: &FontCache, responses: &mut VecDeque<Message>) {
// Create new text
fn new_text(&mut self, document: &DocumentMessageHandler, editing_text: EditingText, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
self.new_text = String::new();
responses.add(DocumentMessage::AddTransaction);
self.layer = LayerNodeIdentifier::new_unchecked(NodeId::new());
responses.add(PortfolioMessage::LoadFontData { font: editing_text.font.clone() });
responses.add(FontsMessage::Load {
font: editing_text.font.clone(),
response: Box::new(NodeGraphMessage::RunDocumentGraph.into()),
});
responses.add(GraphOperationMessage::NewTextLayer {
id: self.layer.to_node(),
text: String::new(),
@@ -580,7 +578,7 @@ impl TextToolData {
let transform = editing_text.transform;
self.editing_text = Some(editing_text);
self.set_editing(true, font_cache, responses);
self.set_editing(true, fonts, responses);
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![self.layer.to_node()] });
@@ -602,20 +600,19 @@ impl TextToolData {
});
}
fn check_click(document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, font_cache: &FontCache) -> Option<LayerNodeIdentifier> {
fn check_click(document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) -> Option<LayerNodeIdentifier> {
let mouse = DVec2::new(input.mouse.position.x, input.mouse.position.y);
document.metadata().all_layers().filter(|&layer| document.metadata().is_text_layer(layer)).find(|&layer| {
let transformed_quad = document.metadata().transform_to_viewport(layer) * text_bounding_box(layer, document, font_cache);
let mouse = DVec2::new(input.mouse.position.x, input.mouse.position.y);
let transformed_quad = document.metadata().transform_to_viewport(layer) * text_bounding_box(layer, document, fonts, responses);
transformed_quad.contains(mouse)
})
}
fn get_snap_candidates(&mut self, document: &DocumentMessageHandler, font_cache: &FontCache) {
fn get_snap_candidates(&mut self, document: &DocumentMessageHandler, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
self.snap_candidates.clear();
if let Some(ResizingLayer { id, .. }) = self.layer_dragging {
let quad = document.metadata().transform_to_document(id) * text_bounding_box(id, document, font_cache);
let quad = document.metadata().transform_to_document(id) * text_bounding_box(id, document, fonts, responses);
snapping::get_bbox_points(quad, &mut self.snap_candidates, snapping::BBoxSnapValues::BOUNDING_BOX, document);
}
}
@@ -651,14 +648,7 @@ impl Fsm for TextToolFsmState {
tool_options: &Self::ToolOptions,
responses: &mut VecDeque<Message>,
) -> Self {
let ToolActionMessageContext {
document,
input,
cached_data,
viewport,
..
} = transition_data;
let font_cache = &cached_data.font_cache;
let ToolActionMessageContext { document, input, fonts, viewport, .. } = transition_data;
let fill_color = COLOR_OVERLAY_BLUE_05;
let ToolMessage::Text(event) = event else { return self };
@@ -667,7 +657,8 @@ impl Fsm for TextToolFsmState {
let transform = document.metadata().transform_to_viewport(tool_data.layer).to_cols_array();
responses.add(FrontendMessage::DisplayEditableTextboxTransform { transform });
if let Some(editing_text) = tool_data.editing_text.as_mut() {
let far = graphene_std::text::bounding_box(&tool_data.new_text, &editing_text.font, font_cache, editing_text.typesetting, false);
let font_resource = fonts.get_resource_or_queue_load(&editing_text.font, responses);
let far = graphene_std::text::bounding_box(&tool_data.new_text, &font_resource, editing_text.typesetting, false);
if far.x != 0. && far.y != 0. {
let quad = Quad::from_box([DVec2::ZERO, far]);
let transformed_quad = document.metadata().transform_to_viewport(tool_data.layer) * quad;
@@ -694,7 +685,7 @@ impl Fsm for TextToolFsmState {
let selected = document.network_interface.selected_nodes();
let mut all_layers = selected.selected_visible_and_unlocked_layers(&document.network_interface);
let layer = all_layers.find(|&layer| document.metadata().is_text_layer(layer));
let bounds = layer.map(|layer| text_bounding_box(layer, document, font_cache));
let bounds = layer.map(|layer| text_bounding_box(layer, document, fonts, responses));
let layer_transform = layer.map(|layer| document.metadata().transform_to_viewport(layer)).unwrap_or(DAffine2::IDENTITY);
if layer.is_none() || bounds.is_none() || layer_transform.matrix2.determinant() == 0. {
@@ -710,10 +701,11 @@ impl Fsm for TextToolFsmState {
bounding_box_manager.render_quad(&mut overlay_context);
// Draw red overlay if text is clipped
let transformed_quad = layer_transform * bounds;
if let Some((text, font, typesetting, _)) = graph_modification_utils::get_text(layer.unwrap(), &document.network_interface)
&& lines_clipping(text.as_str(), font, font_cache, typesetting)
{
overlay_context.line(transformed_quad.0[2], transformed_quad.0[3], Some(COLOR_OVERLAY_RED), Some(3.));
if let Some((text, font, typesetting, _)) = graph_modification_utils::get_text(layer.unwrap(), &document.network_interface, fonts, &document.resources) {
let font_resource = fonts.get_resource_or_queue_load(&font, responses);
if lines_clipping(text.as_str(), &font_resource, typesetting) {
overlay_context.line(transformed_quad.0[2], transformed_quad.0[3], Some(COLOR_OVERLAY_RED), Some(3.));
}
}
bounding_box_manager.render_overlays(&mut overlay_context, false);
@@ -728,7 +720,7 @@ impl Fsm for TextToolFsmState {
}
(state, TextToolMessage::EditSelected) => {
if let Some(layer) = can_edit_selected(document) {
tool_data.start_editing_layer(layer, state, document, font_cache, responses);
tool_data.start_editing_layer(layer, state, document, fonts, responses);
return TextToolFsmState::Editing;
}
@@ -769,10 +761,10 @@ impl Fsm for TextToolFsmState {
bounds.original_bound_transform = bounds.transform;
bounds.center_of_transformation = bounds.transform.transform_point2((bounds.bounds[0] + bounds.bounds[1]) / 2.);
}
tool_data.get_snap_candidates(document, font_cache);
tool_data.get_snap_candidates(document, fonts, responses);
return TextToolFsmState::ResizingBounds;
} else if let Some(clicked_layer) = TextToolData::check_click(document, input, font_cache) {
} else if let Some(clicked_layer) = TextToolData::check_click(document, input, fonts, responses) {
responses.add(DocumentMessage::StartTransaction);
if selected != Some(clicked_layer) {
@@ -784,7 +776,7 @@ impl Fsm for TextToolFsmState {
id: clicked_layer,
original_transform,
});
tool_data.get_snap_candidates(document, font_cache);
tool_data.get_snap_candidates(document, fonts, responses);
return TextToolFsmState::Dragging;
}
TextToolFsmState::Placing
@@ -967,8 +959,8 @@ impl Fsm for TextToolFsmState {
let has_dragged = (start - end).length_squared() > DRAG_THRESHOLD * DRAG_THRESHOLD;
// Check if the user has clicked (no dragging) on some existing text
if !has_dragged && let Some(clicked_text_layer_path) = TextToolData::check_click(document, input, font_cache) {
tool_data.start_editing_layer(clicked_text_layer_path, self, document, font_cache, responses);
if !has_dragged && let Some(clicked_text_layer_path) = TextToolData::check_click(document, input, fonts, responses) {
tool_data.start_editing_layer(clicked_text_layer_path, self, document, fonts, responses);
return TextToolFsmState::Editing;
}
@@ -989,7 +981,7 @@ impl Fsm for TextToolFsmState {
font: Font::new(tool_options.font.font_family.clone(), tool_options.font.font_style.clone()),
color: tool_options.fill.active_color(),
};
tool_data.new_text(document, editing_text, font_cache, responses);
tool_data.new_text(document, editing_text, fonts, responses);
TextToolFsmState::Editing
}
(TextToolFsmState::Dragging, TextToolMessage::DragStop) => {
@@ -1004,7 +996,7 @@ impl Fsm for TextToolFsmState {
}
if drag_too_small && let Some(layer_info) = &tool_data.layer_dragging {
tool_data.start_editing_layer(layer_info.id, self, document, font_cache, responses);
tool_data.start_editing_layer(layer_info.id, self, document, fonts, responses);
return TextToolFsmState::Editing;
}
tool_data.layer_dragging.take();
@@ -1013,8 +1005,9 @@ impl Fsm for TextToolFsmState {
}
(TextToolFsmState::Editing, TextToolMessage::RefreshEditingFontData) => {
let font = Font::new(tool_options.font.font_family.clone(), tool_options.font.font_style.clone());
let font_resource = fonts.get_resource_or_queue_load(&font, responses);
responses.add(FrontendMessage::DisplayEditableTextboxUpdateFontData {
font_data: font_cache.get(&font).map(|(data, _)| data.clone()).unwrap_or_default().into(),
font_data: font_resource.as_ref().to_vec().into(),
});
TextToolFsmState::Editing
@@ -1023,7 +1016,7 @@ impl Fsm for TextToolFsmState {
tool_data.new_text = new_text;
if !is_left_or_right_click {
tool_data.set_editing(false, font_cache, responses);
tool_data.set_editing(false, fonts, responses);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(graph_modification_utils::get_text_id(tool_data.layer, &document.network_interface).unwrap(), 1),
@@ -1034,7 +1027,7 @@ impl Fsm for TextToolFsmState {
TextToolFsmState::Ready
} else {
if tool_data.new_text.is_empty() {
return tool_data.delete_empty_layer(font_cache, responses);
return tool_data.delete_empty_layer(fonts, responses);
}
responses.add(FrontendMessage::TriggerTextCommit);
@@ -1055,7 +1048,7 @@ impl Fsm for TextToolFsmState {
}
(TextToolFsmState::Editing, TextToolMessage::Abort) => {
if tool_data.new_text.is_empty() {
return tool_data.delete_empty_layer(font_cache, responses);
return tool_data.delete_empty_layer(fonts, responses);
}
responses.add(FrontendMessage::TriggerTextCommit);
+3 -4
View File
@@ -9,7 +9,6 @@ use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayProvider;
use crate::messages::portfolio::utility_types::CachedData;
use crate::messages::preferences::PreferencesMessageHandler;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeType;
@@ -25,7 +24,7 @@ pub struct ToolActionMessageContext<'a> {
pub document_id: DocumentId,
pub global_tool_data: &'a DocumentToolData,
pub input: &'a InputPreprocessorMessageHandler,
pub cached_data: &'a CachedData,
pub fonts: &'a FontsMessageHandler,
pub shape_editor: &'a mut ShapeState,
pub node_graph: &'a NodeGraphExecutor,
pub preferences: &'a PreferencesMessageHandler,
@@ -38,11 +37,11 @@ impl<T> ToolCommon for T where T: for<'a, 'b> MessageHandler<ToolMessage, &'b mu
type Tool = dyn ToolCommon + Send + Sync;
pub trait ToolRefreshOptions {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData);
fn refresh_options(&self, responses: &mut VecDeque<Message>);
}
impl<T: LayoutHolder> ToolRefreshOptions for T {
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData) {
fn refresh_options(&self, responses: &mut VecDeque<Message>) {
self.send_layout(responses, LayoutTarget::ToolOptions);
}
}
+16 -8
View File
@@ -9,7 +9,6 @@ use graphene_std::application_io::{NodeGraphUpdateMessage, RenderConfig, TimingI
use graphene_std::color::SRGBA8;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::RenderMetadata;
use graphene_std::text::FontCache;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
@@ -95,10 +94,6 @@ impl NodeGraphExecutor {
execution_id
}
pub fn update_font_cache(&self, font_cache: FontCache) {
self.runtime_io.send(GraphRuntimeRequest::FontCacheUpdate(font_cache)).expect("Failed to send font cache update");
}
pub fn update_editor_preferences(&self, editor_preferences: EditorPreferences) {
self.runtime_io
.send(GraphRuntimeRequest::EditorPreferencesUpdate(editor_preferences))
@@ -113,8 +108,14 @@ impl NodeGraphExecutor {
let mut network = document.network_interface.document_network().clone();
let instrumented = Instrumented::new(&mut network);
let resources = document.resources.registry.clone();
self.runtime_io
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect: Vec::new() }))
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
}
@@ -128,8 +129,10 @@ impl NodeGraphExecutor {
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.node_graph_hash = network_hash;
let resources = document.resources.registry.clone();
self.runtime_io
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect }))
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, node_to_inspect }))
.map_err(|e| e.to_string())?;
}
@@ -237,6 +240,7 @@ impl NodeGraphExecutor {
/// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, mut export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone();
let resources = document.resources.registry.clone();
let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg
@@ -278,7 +282,11 @@ impl NodeGraphExecutor {
// Execute the node graph
self.runtime_io
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect: Vec::new() }))
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
+31 -43
View File
@@ -1,6 +1,7 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
@@ -16,7 +17,6 @@ use graphene_std::ops::Convert;
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::text::FontCache;
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode;
@@ -42,6 +42,7 @@ pub struct NodeRuntime {
update_thumbnails: bool,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
monitor_nodes: Vec<Vec<NodeId>>,
@@ -69,13 +70,13 @@ pub struct NodeRuntime {
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
FontCacheUpdate(FontCache),
EditorPreferencesUpdate(EditorPreferences),
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
/// Full path from the root network to the node that should be temporarily inspected during execution.
/// The last element is the inspect target; preceding elements identify the nested subnetwork it lives in,
/// so the runtime can splice its monitor node alongside the target instead of only at the top level.
@@ -97,7 +98,7 @@ pub struct ExportConfig {
struct InternalNodeGraphUpdateSender(Sender<NodeGraphUpdate>);
impl InternalNodeGraphUpdateSender {
fn send_generation_response(&self, response: CompilationResponse) {
fn send_compilation_response(&self, response: CompilationResponse) {
self.0.send(NodeGraphUpdate::CompilationResponse(response)).expect("Failed to send response")
}
@@ -127,14 +128,18 @@ impl NodeRuntime {
sender: InternalNodeGraphUpdateSender(sender.clone()),
editor_preferences: EditorPreferences::default(),
old_graph: None,
resources: ResourceRegistry::default(),
update_thumbnails: true,
editor_api: PlatformEditorApi {
font_cache: FontCache::default(),
editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
#[cfg(not(test))]
application_io: None,
#[cfg(test)]
application_io: Some(PlatformApplicationIo::default().into()),
}
.into(),
@@ -154,20 +159,6 @@ impl NodeRuntime {
}
pub async fn run(&mut self) -> Option<ImageTexture> {
if self.editor_api.application_io.is_none() {
self.editor_api = PlatformEditorApi {
#[cfg(all(not(test), target_family = "wasm"))]
application_io: Some(PlatformApplicationIo::new().await.into()),
#[cfg(any(test, not(target_family = "wasm")))]
application_io: Some(PlatformApplicationIo::new().await.into()),
font_cache: self.editor_api.font_cache.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
}
.into();
}
let mut font = None;
let mut preferences = None;
let mut graph = None;
let mut eyedropper = None;
@@ -191,7 +182,6 @@ impl NodeRuntime {
break;
}
}
GraphRuntimeRequest::FontCacheUpdate(_) => font = Some(request),
GraphRuntimeRequest::EditorPreferencesUpdate(_) => preferences = Some(request),
}
}
@@ -204,27 +194,13 @@ impl NodeRuntime {
eyedropper.render_config.pointer = execution.render_config.pointer;
}
let requests = [font, preferences, graph, eyedropper, execution].into_iter().flatten();
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
for request in requests {
match request {
GraphRuntimeRequest::FontCacheUpdate(font_cache) => {
self.editor_api = PlatformEditorApi {
font_cache,
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
}
.into();
if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph).await;
}
}
GraphRuntimeRequest::EditorPreferencesUpdate(preferences) => {
self.editor_preferences = preferences.clone();
self.editor_api = PlatformEditorApi {
font_cache: self.editor_api.font_cache.clone(),
application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(preferences),
@@ -235,11 +211,16 @@ impl NodeRuntime {
let _ = self.update_network(graph).await;
}
}
GraphRuntimeRequest::GraphUpdate(GraphUpdate { mut network, node_to_inspect }) => {
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
mut network,
resources,
node_to_inspect,
}) => {
// Insert the monitor node to manage the inspection
self.inspect_state = InspectState::monitor_inspect_node(&mut network, &node_to_inspect);
self.old_graph = Some(network.clone());
self.resources = resources;
self.node_graph_errors.clear();
let result = self.update_network(network).await;
@@ -247,7 +228,7 @@ impl NodeRuntime {
self.update_thumbnails = true;
self.sender.send_generation_response(CompilationResponse { result, node_graph_errors });
self.sender.send_compilation_response(CompilationResponse { result, node_graph_errors });
}
GraphRuntimeRequest::ExecutionRequest(ExecutionRequest { execution_id, mut render_config, .. }) => {
// We may want to render via the SVG pipeline even though raster was requested, if SVG Preview render mode is active or WebGPU/Vello is unavailable
@@ -366,7 +347,9 @@ impl NodeRuntime {
}
async fn update_network(&mut self, mut graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
preprocessor::expand_network(&mut graph, &self.substitutions);
if let Err(e) = preprocessor::expand_network(&mut graph, &self.substitutions, &self.resources) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
}
let scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
@@ -571,18 +554,23 @@ pub async fn run_node_graph() -> (bool, Option<ImageTexture>) {
(false, None)
}
pub async fn replace_node_runtime(runtime: NodeRuntime) -> Option<NodeRuntime> {
pub fn replace_node_runtime(runtime: NodeRuntime) -> Option<NodeRuntime> {
let mut node_runtime = NODE_RUNTIME.lock();
node_runtime.replace(runtime)
}
pub async fn replace_application_io(application_io: PlatformApplicationIo) {
pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
let mut node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &mut *node_runtime {
node_runtime.editor_api = PlatformEditorApi {
font_cache: node_runtime.editor_api.font_cache.clone(),
node_runtime.replace_application_io(application_io);
}
}
impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi {
application_io: Some(application_io.into()),
node_graph_message_sender: Box::new(node_runtime.sender.clone()),
editor_preferences: Box::new(node_runtime.editor_preferences.clone()),
node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()),
}
.into();
}
+1 -1
View File
@@ -20,7 +20,7 @@ impl NodeRuntimeIO {
pub fn new() -> Self {
let (response_sender, response_receiver) = std::sync::mpsc::channel();
let (request_sender, request_receiver) = std::sync::mpsc::channel();
futures::executor::block_on(replace_node_runtime(NodeRuntime::new(request_receiver, response_sender)));
replace_node_runtime(NodeRuntime::new(request_receiver, response_sender));
Self {
sender: request_sender,
+1 -1
View File
@@ -23,7 +23,7 @@
// Create the editor and subscriptions router
const randomSeed = BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER));
subscriptions = createSubscriptionsRouter();
editor = EditorWrapper.create(operatingSystem(), randomSeed, (messageType: MessageName, messageData: FrontendMessage) => {
editor = await EditorWrapper.create(operatingSystem(), randomSeed, (messageType: MessageName, messageData: FrontendMessage) => {
subscriptions?.handleFrontendMessage(messageType, messageData);
});
-3
View File
@@ -2,7 +2,6 @@
import { onMount, onDestroy, setContext } from "svelte";
import MainWindow from "/src/components/window/MainWindow.svelte";
import { createClipboardManager, destroyClipboardManager } from "/src/managers/clipboard";
import { createFontsManager, destroyFontsManager } from "/src/managers/fonts";
import { createHyperlinkManager, destroyHyperlinkManager } from "/src/managers/hyperlink";
import { createInputManager, destroyInputManager } from "/src/managers/input";
import { createLocalizationManager, destroyLocalizationManager } from "/src/managers/localization";
@@ -43,7 +42,6 @@
createLocalizationManager(subscriptions, editor);
createPanicManager(subscriptions);
createPersistenceManager(subscriptions, editor, stores.portfolio);
createFontsManager(subscriptions, editor);
createInputManager(subscriptions, editor, stores.dialog, stores.portfolio, stores.document);
// Initialize certain setup tasks required by the editor backend to be ready for the user now that the frontend is ready.
@@ -71,7 +69,6 @@
destroyLocalizationManager();
destroyPanicManager();
destroyPersistenceManager();
destroyFontsManager();
destroyInputManager();
});
</script>
@@ -97,7 +97,7 @@
await tick();
const flattened = filteredEntries.flat();
const highlightedFound = highlighted?.label && flattened.map((entry) => entry.label).includes(highlighted.label);
const highlightedFound = flattened.map((entry) => entry.value).includes(highlighted.value);
const newHighlighted = highlightedFound ? highlighted : flattened[0];
setHighlighted(newHighlighted);
}
@@ -335,7 +335,7 @@
if ((menuOpen || interactive) && (e.key === "ArrowUp" || e.key === "ArrowDown")) {
let newIndex = e.key === "ArrowUp" ? flatEntries.length - 1 : 0;
if (highlighted) {
const index = highlighted ? flatEntries.map((entry) => entry.label).indexOf(highlighted.label) : 0;
const index = flatEntries.map((entry) => entry.value).indexOf(highlighted.value);
newIndex = index + (e.key === "ArrowUp" ? -1 : 1);
// Interactive dropdowns should lock at the end whereas other dropdowns should loop
@@ -482,7 +482,7 @@
{#each currentEntries(section, virtualScrollingEntryHeight, virtualScrollingStartIndex, virtualScrollingEndIndex, search) as entry, entryIndex (entryIndex + startIndex)}
<LayoutRow
class="row"
classes={{ open: openChildValue === entry.value, active: entry.label === highlighted?.label, disabled: Boolean(entry.disabled) }}
classes={{ open: openChildValue === entry.value, active: entry.value === highlighted?.value, disabled: Boolean(entry.disabled) }}
styles={{ height: virtualScrollingEntryHeight || "20px" }}
tooltipLabel={entry.tooltipLabel}
tooltipDescription={entry.tooltipDescription}
+39 -1
View File
@@ -7,6 +7,7 @@
import Graph from "/src/components/views/Graph.svelte";
import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte";
import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { AppWindowStore } from "/src/stores/app-window";
import type { DocumentStore } from "/src/stores/document";
@@ -16,7 +17,7 @@
import { pasteFile } from "/src/utility-functions/files";
import { textInputCleanup } from "/src/utility-functions/keyboard-entry";
import { rasterizeSVGCanvas } from "/src/utility-functions/rasterization";
import { setupViewportResizeObserver } from "/src/utility-functions/viewports";
import { setupViewportResizeObserver, hasFirstArtworkBeenReceived, markFirstArtworkReceived } from "/src/utility-functions/viewports";
import type { EditorWrapper, MenuDirection, MouseCursorIcon, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
let rulerHorizontal: RulerInput | undefined;
@@ -53,6 +54,10 @@
// Rendered SVG viewport data
let artworkSvg = "";
// Web-only "Initializing Renderer…" overlay shown until the first Vello-rendered artwork arrives
const isWeb = import.meta.env.MODE !== "native";
let firstArtworkReceived = hasFirstArtworkBeenReceived();
// Rasterized SVG viewport data, or none if it's not up-to-date
let rasterizedCanvas: HTMLCanvasElement | undefined = undefined;
let rasterizedContext: CanvasRenderingContext2D | undefined = undefined;
@@ -470,6 +475,11 @@
subscriptions.subscribeFrontendMessage("UpdateDocumentArtwork", async (data) => {
await tick();
if (!firstArtworkReceived) {
firstArtworkReceived = true;
markFirstArtworkReceived();
}
updateDocumentArtwork(data.svg);
});
subscriptions.subscribeFrontendMessage("UpdateEyedropperSamplingState", async (data) => {
@@ -708,6 +718,9 @@
>
</canvas>
{/if}
{#if isWeb}
<TextLabel class="shader-compiling-overlay" italic={true} classes={{ show: !firstArtworkReceived }}>Initializing Renderer…</TextLabel>
{/if}
</div>
<div class="graph-view" class:open={$document.graphViewOverlayOpen} style:--fade-artwork={`${$document.fadeArtwork}%`} data-graph>
@@ -944,6 +957,31 @@
unicode-bidi: plaintext;
}
.shader-compiling-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
opacity: 0;
transition: opacity 0.5s ease;
&.show {
opacity: 1;
animation: shader-compiling-overlay-fade-in 0.5s ease 0.5s both;
}
@keyframes shader-compiling-overlay-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
}
.text-input div {
cursor: text;
background: none;
+10 -4
View File
@@ -33,11 +33,17 @@
</LayoutCol>
</LayoutCol>
<LayoutCol class="bottom-message">
<TextLabel italic={true} disabled={true}>
{#if import.meta.env.MODE === "native"}
{#if import.meta.env.MODE === "native"}
<TextLabel italic={true} disabled={true}>
You are testing Release Candidate 5 of the 1.0 desktop release. Please regularly check Discord for the next testing build and report issues you encounter.
{/if}
</TextLabel>
</TextLabel>
{:else if new Date() < new Date(2026, 10, 1)}
<TextLabel italic={true} disabled={true}>
May 2026 release — <a href="https://youtube.com/watch?v=U3E-sWo2H_M" target="_blank">What's new? (video)</a>
— Note: Some nodes are renamed; Some older documents may render differently and require manual fixes.
<a href="https://57130155.graphite.pages.dev/" target="_blank">Need the old version?</a>
</TextLabel>
{/if}
</LayoutCol>
</LayoutCol>
+1 -1
View File
@@ -139,7 +139,7 @@
function createNode(identifier: string) {
if ($nodeGraph.contextMenuInformation === undefined) return;
editor.createNode(identifier, $nodeGraph.contextMenuInformation.contextMenuCoordinates[0], $nodeGraph.contextMenuInformation.contextMenuCoordinates[1]);
editor.createNode(identifier, $nodeGraph.contextMenuInformation.nodeCreationCoordinates[0], $nodeGraph.contextMenuInformation.nodeCreationCoordinates[1]);
}
function nodeBorderMask(nodeWidth: number, primaryInputExists: boolean, exposedSecondaryInputs: number, primaryOutputExists: boolean, exposedSecondaryOutputs: number): string {
-75
View File
@@ -1,75 +0,0 @@
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
type ApiResponse = { family: string; variants: string[]; files: Record<string, string> }[];
const FONT_LIST_API = "https://api.graphite.art/font-list";
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
let editorWrapper: EditorWrapper | undefined = undefined;
let abortController: AbortController | undefined = undefined;
export function createFontsManager(subscriptions: SubscriptionsRouter, editor: EditorWrapper) {
destroyFontsManager();
subscriptionsRouter = subscriptions;
editorWrapper = editor;
abortController = new AbortController();
subscriptions.subscribeFrontendMessage("TriggerFontCatalogLoad", async () => {
try {
const response = await fetch(FONT_LIST_API, abortController ? { signal: abortController.signal } : undefined);
if (!response.ok) throw new Error(`Font catalog request failed with status ${response.status}`);
const fontListResponse: { items: ApiResponse } = await response.json();
const fontListData = fontListResponse.items;
const catalog = fontListData.map((font) => {
const styles = font.variants.map((variant) => {
const weight = variant === "regular" || variant === "italic" ? 400 : parseInt(variant, 10);
const italic = variant.endsWith("italic");
const url = font.files[variant].replace("http://", "https://");
return { weight, italic, url };
});
return { name: font.family, styles };
});
editor.onFontCatalogLoad(catalog);
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return;
throw error;
}
});
subscriptions.subscribeFrontendMessage("TriggerFontDataLoad", async (data) => {
const { fontFamily, fontStyle } = data.font;
try {
if (!data.url) throw new Error("No URL provided for font data load");
const response = await fetch(data.url, abortController ? { signal: abortController.signal } : undefined);
if (!response.ok) throw new Error(`Font data request failed with status ${response.status}`);
const buffer = await response.arrayBuffer();
const bytes = new Uint8Array(buffer);
editor.onFontLoad(fontFamily, fontStyle, bytes);
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return;
// eslint-disable-next-line no-console
console.error("Failed to load font:", error);
}
});
}
export function destroyFontsManager() {
const subscriptions = subscriptionsRouter;
if (!subscriptions) return;
abortController?.abort();
subscriptions.unsubscribeFrontendMessage("TriggerFontCatalogLoad");
subscriptions.unsubscribeFrontendMessage("TriggerFontDataLoad");
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => {
if (subscriptionsRouter && editorWrapper) newModule?.createFontsManager(subscriptionsRouter, editorWrapper);
});
@@ -1,5 +1,15 @@
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
// Tracks whether any document has produced its first frame of rendered artwork yet during this app session.
// Used to show the one-time "Initializing Renderer…" overlay only on the very first document open.
let firstArtworkEverReceived = false;
export function hasFirstArtworkBeenReceived(): boolean {
return firstArtworkEverReceived;
}
export function markFirstArtworkReceived(): void {
firstArtworkEverReceived = true;
}
export function setupViewportResizeObserver(editor: EditorWrapper): () => void {
const viewports = Array.from(window.document.querySelectorAll("[data-viewport-container]"));
if (viewports.length <= 0) return () => {};
+30 -32
View File
@@ -9,8 +9,9 @@ use crate::EDITOR;
#[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation;
use crate::helpers::{auto_save_all_documents, calculate_hash, render_image_data_to_canvases, request_animation_frame, set_timeout, translate_key, wrapper};
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER, Error, FRONTEND_READY, MESSAGE_BUFFER, PANIC_DIALOG_MESSAGE_CALLBACK};
use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER};
#[cfg(not(feature = "native"))]
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::application::{Editor, Environment, Host, Platform};
use editor::consts::FILE_EXTENSION;
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
@@ -19,7 +20,7 @@ use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseStat
use editor::messages::layout::utility_types::layout_widget::LayoutTarget;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::{DockingSplitDirection, FontCatalog, FontCatalogFamily, PanelGroupId, PanelType};
use editor::messages::portfolio::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
use graph_craft::document::NodeId;
@@ -52,7 +53,10 @@ impl EditorWrapper {
self.send_frontend_message_to_js(message);
}
#[cfg(any(feature = "native", target_family = "wasm"))]
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
let panic_callback = frontend_message_handler_callback.clone();
let editor_wrapper = EditorWrapper { frontend_message_handler_callback };
if EDITOR_WRAPPER.with(|wrapper| wrapper.lock().ok().map(|mut guard| *guard = Some(editor_wrapper.clone()))).is_none() {
@@ -69,22 +73,31 @@ impl EditorWrapper {
// Editor wrapper machinery
// ========================
#[cfg(not(feature = "native"))]
pub fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
let editor = Editor::new(
Environment {
platform: Platform::Web,
host: match platform.as_str() {
"Linux" => Host::Linux,
"Mac" => Host::Mac,
"Windows" => Host::Windows,
_ => unreachable!(),
},
},
uuid_random_seed,
);
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::*;
if EDITOR.with(|wrapper| wrapper.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() {
let host = match platform.as_str() {
"Linux" => Host::Linux,
"Mac" => Host::Mac,
"Windows" => Host::Windows,
_ => unreachable!(),
};
let storage: std::sync::Arc<dyn ResourceStorage> = match OpfsResourceStorage::load("resources").await {
Ok(storage) => std::sync::Arc::new(storage),
Err(error) => {
log::error!("Failed to open OPFS resource storage, falling back to in-memory: {error:?}");
std::sync::Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new())
}
};
let application_io = PlatformApplicationIo::new().await;
let wake = crate::helpers::async_wake_callback();
let editor = Editor::new(Environment { platform: Platform::Web, host }, uuid_random_seed, storage, application_io, wake);
if EDITOR.with(|slot| slot.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() {
log::error!("Attempted to initialize the editor more than once");
}
@@ -634,21 +647,6 @@ impl EditorWrapper {
Ok(())
}
/// The font catalog has been loaded
#[wasm_bindgen(js_name = onFontCatalogLoad)]
pub fn on_font_catalog_load(&self, catalog: Vec<FontCatalogFamily>) {
self.dispatch(PortfolioMessage::FontCatalogLoaded { catalog: FontCatalog(catalog) });
}
/// A font has been downloaded
#[wasm_bindgen(js_name = onFontLoad)]
pub fn on_font_load(&self, font_family: String, font_style: String, data: Vec<u8>) -> Result<(), JsValue> {
let message = PortfolioMessage::FontLoaded { font_family, font_style, data };
self.dispatch(message);
Ok(())
}
/// Dialog got dismissed
#[wasm_bindgen(js_name = onDialogDismiss)]
pub fn on_dialog_dismiss(&self) {
+11
View File
@@ -108,6 +108,17 @@ pub(crate) async fn poll_node_graph_evaluation() {
});
}
/// Web wake callback: queues a microtask that dispatches [`FutureMessage::Wake`].
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) fn async_wake_callback() -> Wake {
use std::sync::Arc;
Arc::new(|| {
wasm_bindgen_futures::spawn_local(async {
wrapper(|wrapper| wrapper.dispatch(FutureMessage::Wake));
});
})
}
pub(crate) fn auto_save_all_documents() {
// Process no further messages after a crash to avoid spamming the console
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
+15 -1
View File
@@ -50,12 +50,26 @@ wasm-bindgen = { workspace = true, optional = true }
# Workspace dependencies
[target.'cfg(target_family = "wasm")'.dependencies]
web-sys = { workspace = true, features = ["Navigator", "Gpu"] }
web-sys = { workspace = true, features = [
"Navigator",
"DomException",
"Window",
"StorageManager",
"FileSystemDirectoryHandle",
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemWritableFileStream",
"WritableStream",
"Blob",
] }
js-sys = { workspace = true }
wasm-bindgen = { workspace = true }
wasm-bindgen-futures = { workspace = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
winit = { workspace = true }
mmap-io = { workspace = true }
[dev-dependencies]
# Workspace dependencies
+79 -8
View File
@@ -1,14 +1,85 @@
use dyn_any::StaticType;
#[cfg(feature = "wgpu")]
use wgpu_executor::WgpuExecutor;
#[cfg(not(target_family = "wasm"))]
mod native;
#[cfg(target_family = "wasm")]
mod wasm;
pub mod resource;
#[cfg(not(target_family = "wasm"))]
pub type PlatformApplicationIo = native::NativeApplicationIo;
#[cfg(target_family = "wasm")]
pub type PlatformApplicationIo = wasm::WasmApplicationIo;
pub use graphene_application_io::ApplicationIo;
#[derive(Default)]
pub struct PlatformApplicationIo {
#[cfg(feature = "wgpu")]
pub(crate) gpu_executor: Option<WgpuExecutor>,
resources: Option<Box<dyn resource::LoadResource>>,
}
impl PlatformApplicationIo {
pub async fn new() -> Self {
#[cfg(feature = "wgpu")]
let executor = WgpuExecutor::new().await;
#[cfg(not(feature = "wgpu"))]
let wgpu_available = false;
#[cfg(feature = "wgpu")]
let wgpu_available = executor.is_some();
set_wgpu_available(wgpu_available);
Self {
#[cfg(feature = "wgpu")]
gpu_executor: executor,
resources: None,
}
}
#[cfg(feature = "wgpu")]
pub fn new_with_context(context: wgpu_executor::WgpuContext) -> Self {
let executor = WgpuExecutor::with_context(context);
let wgpu_available = executor.is_some();
set_wgpu_available(wgpu_available);
Self {
gpu_executor: executor,
resources: None,
}
}
pub fn inject_resource_proxy(&mut self, resources: Box<dyn resource::LoadResource>) {
self.resources = Some(resources);
}
}
impl ApplicationIo for PlatformApplicationIo {
#[cfg(feature = "wgpu")]
type Executor = WgpuExecutor;
#[cfg(not(feature = "wgpu"))]
type Executor = ();
#[cfg(feature = "wgpu")]
fn gpu_executor(&self) -> Option<&Self::Executor> {
self.gpu_executor.as_ref()
}
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
match self.resources.as_ref() {
Some(resources) => resources.load(hash),
None => {
log::error!("load_resource called before resource storage was initialized");
Box::pin(std::future::ready(None))
}
}
}
}
impl std::fmt::Debug for PlatformApplicationIo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PlatformApplicationIo").finish_non_exhaustive()
}
}
unsafe impl StaticType for PlatformApplicationIo {
type Static = PlatformApplicationIo;
}
pub type PlatformEditorApi = graphene_application_io::EditorApi<PlatformApplicationIo>;
@@ -1,113 +0,0 @@
use dyn_any::StaticType;
use graphene_application_io::{ApplicationError, ApplicationIo, ResourceFuture};
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "tokio")]
use tokio::io::AsyncReadExt;
#[cfg(target_family = "wasm")]
use wasm_bindgen::JsCast;
#[cfg(feature = "wgpu")]
use wgpu_executor::WgpuExecutor;
#[derive(Debug, Default)]
pub struct NativeApplicationIo {
#[cfg(feature = "wgpu")]
pub(crate) gpu_executor: Option<WgpuExecutor>,
pub resources: HashMap<String, Arc<[u8]>>,
}
impl NativeApplicationIo {
pub async fn new() -> Self {
#[cfg(feature = "wgpu")]
let executor = WgpuExecutor::new().await;
#[cfg(not(feature = "wgpu"))]
let wgpu_available = false;
#[cfg(feature = "wgpu")]
let wgpu_available = executor.is_some();
super::set_wgpu_available(wgpu_available);
let mut io = Self {
#[cfg(feature = "wgpu")]
gpu_executor: executor,
resources: HashMap::new(),
};
io.resources.insert("null".to_string(), Arc::from(include_bytes!("../null.png").to_vec()));
io
}
#[cfg(feature = "wgpu")]
pub fn new_with_context(context: wgpu_executor::WgpuContext) -> Self {
#[cfg(feature = "wgpu")]
let executor = WgpuExecutor::with_context(context);
#[cfg(not(feature = "wgpu"))]
let wgpu_available = false;
#[cfg(feature = "wgpu")]
let wgpu_available = executor.is_some();
super::set_wgpu_available(wgpu_available);
let mut io = Self {
gpu_executor: executor,
resources: HashMap::new(),
};
io.resources.insert("null".to_string(), Arc::from(include_bytes!("../null.png").to_vec()));
io
}
}
impl ApplicationIo for NativeApplicationIo {
#[cfg(feature = "wgpu")]
type Executor = WgpuExecutor;
#[cfg(not(feature = "wgpu"))]
type Executor = ();
#[cfg(feature = "wgpu")]
fn gpu_executor(&self) -> Option<&Self::Executor> {
self.gpu_executor.as_ref()
}
fn load_resource(&self, url: impl AsRef<str>) -> Result<ResourceFuture, ApplicationError> {
let url = url::Url::parse(url.as_ref()).map_err(|_| ApplicationError::InvalidUrl)?;
log::trace!("Loading resource: {url:?}");
match url.scheme() {
#[cfg(feature = "tokio")]
"file" => {
let path = url.to_file_path().map_err(|_| ApplicationError::NotFound)?;
let path = path.to_str().ok_or(ApplicationError::NotFound)?;
let path = path.to_owned();
Ok(Box::pin(async move {
let file = tokio::fs::File::open(path).await.map_err(|_| ApplicationError::NotFound)?;
let mut reader = tokio::io::BufReader::new(file);
let mut data = Vec::new();
reader.read_to_end(&mut data).await.map_err(|_| ApplicationError::NotFound)?;
Ok(Arc::from(data))
}) as ResourceFuture)
}
"http" | "https" => {
let url = url.to_string();
Ok(Box::pin(async move {
let client = reqwest::Client::new();
let response = client.get(url).send().await.map_err(|_| ApplicationError::NotFound)?;
let data = response.bytes().await.map_err(|_| ApplicationError::NotFound)?;
Ok(Arc::from(data.to_vec()))
}) as ResourceFuture)
}
"graphite" => {
let path = url.path();
let path = path.to_owned();
log::trace!("Loading local resource: {path}");
let data = self.resources.get(&path).ok_or(ApplicationError::NotFound)?.clone();
Ok(Box::pin(async move { Ok(data.clone()) }) as ResourceFuture)
}
_ => Err(ApplicationError::NotFound),
}
}
}
unsafe impl StaticType for NativeApplicationIo {
type Static = NativeApplicationIo;
}
@@ -0,0 +1,47 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub use graphene_application_io::resource::*;
#[cfg(not(target_family = "wasm"))]
pub mod mmap;
#[cfg(not(target_family = "wasm"))]
pub use mmap::MmapResourceStorage;
#[cfg(target_family = "wasm")]
pub mod opfs;
#[cfg(target_family = "wasm")]
pub use opfs::OpfsResourceStorage;
#[derive(Debug, Default)]
pub struct HashMapResourceStorage {
resources: Mutex<HashMap<ResourceHash, Resource>>,
}
impl HashMapResourceStorage {
pub fn new() -> Self {
Self::default()
}
}
impl LoadResource for HashMapResourceStorage {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
let result = self.resources.lock().unwrap().get(&hash).cloned();
Box::pin(async move { result })
}
}
impl ResourceStorage for HashMapResourceStorage {
fn store(&self, data: &[u8]) -> ResourceHash {
let hash = ResourceHash::from(data);
self.resources.lock().unwrap().insert(hash, Resource::new(Arc::<[u8]>::from(data)));
hash
}
fn contains(&self, hash: &ResourceHash) -> bool {
self.resources.lock().unwrap().contains_key(hash)
}
fn garbage_collect(&self, used: &[ResourceHash]) {
let used_set: std::collections::HashSet<&ResourceHash> = used.iter().collect();
self.resources.lock().unwrap().retain(|hash, _| used_set.contains(hash));
}
}
@@ -0,0 +1,160 @@
use graphene_application_io::resource::{LoadResource, Resource, ResourceFuture, ResourceHash, ResourceStorage};
use mmap_io::mmap::{MemoryMappedFile, MmapMode};
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::RwLock;
pub struct MmapResourceStorage {
root: PathBuf,
cache: RwLock<HashMap<ResourceHash, Resource>>,
}
impl MmapResourceStorage {
pub fn new(root: impl Into<PathBuf>) -> std::io::Result<Self> {
let root = root.into();
fs::create_dir_all(&root)?;
Ok(Self {
root,
cache: RwLock::new(HashMap::new()),
})
}
fn path_for(&self, hash: &ResourceHash) -> PathBuf {
let hash = String::from(hash);
let mut path = self.root.clone();
path.push(&hash[..2]);
path.push(&hash[2..]);
path
}
fn open_mmap(path: &Path) -> Option<MemoryMappedFile> {
match MemoryMappedFile::builder(path).mode(MmapMode::ReadOnly).huge_pages(true).open() {
Ok(file) => Some(file),
Err(error) => {
log::warn!("Failed to mmap {path:?} retrying without huge pages: {error}");
match MemoryMappedFile::open_ro(path) {
Ok(file) => Some(file),
Err(error) => {
log::error!("Failed to mmap {path:?}: {error}");
None
}
}
}
}
}
fn lookup(&self, hash: &ResourceHash) -> Option<Resource> {
if let Some(resource) = self.cache.read().unwrap_or_else(|poisoned| poisoned.into_inner()).get(hash) {
return Some(resource.clone());
}
let path = self.path_for(hash);
let mmap = Self::open_mmap(&path)?;
let resource = Resource::new_unchecked(MmappedBytes(mmap), *hash);
self.cache.write().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(*hash, resource.clone());
Some(resource)
}
}
impl LoadResource for MmapResourceStorage {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
let result = self.lookup(&hash);
Box::pin(async move { result })
}
}
impl ResourceStorage for MmapResourceStorage {
fn store(&self, data: &[u8]) -> ResourceHash {
let hash = ResourceHash::from(data);
let path = self.path_for(&hash);
if path.exists() {
return hash;
}
let Some(parent) = path.parent() else {
log::error!("Resource path {path:?} has no parent directory");
return hash;
};
if let Err(error) = fs::create_dir_all(parent) {
log::error!("Failed to create resource subdirectory {parent:?}: {error}");
return hash;
}
let tmp = parent.join(format!(
"tmp.{}.{}.{}",
path.file_name().and_then(|n| n.to_str()).unwrap_or(""),
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0),
));
let write_result = (|| -> std::io::Result<()> {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
file.write_all(data)?;
file.sync_all()?;
fs::rename(&tmp, &path)
})();
if let Err(error) = write_result {
let _ = fs::remove_file(&tmp);
if !path.exists() {
log::error!("Failed to write resource to {path:?}: {error}");
}
}
hash
}
fn contains(&self, hash: &ResourceHash) -> bool {
self.cache.read().unwrap_or_else(|poisoned| poisoned.into_inner()).contains_key(hash) || self.path_for(hash).exists()
}
fn garbage_collect(&self, used: &[ResourceHash]) {
let used_set: std::collections::HashSet<ResourceHash> = used.iter().cloned().collect();
self.cache.write().unwrap_or_else(|poisoned| poisoned.into_inner()).retain(|hash, _| used_set.contains(hash));
let Ok(top_entries) = fs::read_dir(&self.root) else { return };
for top_entry in top_entries.flatten() {
let top_path = top_entry.path();
if !top_path.is_dir() {
continue;
}
let Ok(entries) = fs::read_dir(&top_path) else { continue };
for entry in entries.flatten() {
let path = entry.path();
let Some(prefix) = top_path.file_name().and_then(|n| n.to_str()) else { continue };
let Some(suffix) = path.file_name().and_then(|n| n.to_str()) else { continue };
if suffix.starts_with("tmp.") {
continue;
}
let hex = format!("{prefix}{suffix}");
let Ok(hash) = ResourceHash::try_from(hex.as_str()) else { continue };
if !used_set.contains(&hash)
&& let Err(error) = fs::remove_file(&path)
{
log::error!("Failed to remove unused resource {path:?}: {error}");
}
}
let _ = fs::remove_dir(&top_path);
}
}
}
struct MmappedBytes(MemoryMappedFile);
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}");
&[]
}
}
}
}
@@ -0,0 +1,366 @@
use graphene_application_io::resource::{LoadResource, Resource, ResourceFuture, ResourceHash, ResourceStorage};
use js_sys::Uint8Array;
use std::collections::{HashMap, HashSet, VecDeque};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{Blob, DomException, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, FileSystemWritableFileStream, WritableStream};
enum Mutation {
Write { hash: ResourceHash, bytes: Arc<[u8]> },
Delete { hash: ResourceHash },
}
struct Inner {
directory: FileSystemDirectoryHandle,
cache: HashMap<ResourceHash, Resource>,
on_disk: HashSet<ResourceHash>,
queue: VecDeque<Mutation>,
worker_active: bool,
persist_requested: bool,
}
pub struct OpfsResourceStorage {
inner: Arc<Mutex<Inner>>,
}
// SAFETY: This is only compiled for browser wasm, where JS handles remain on the main thread.
unsafe impl Send for OpfsResourceStorage {}
unsafe impl Sync for OpfsResourceStorage {}
impl OpfsResourceStorage {
pub async fn load(directory_name: &str) -> Result<Self, JsValue> {
let directory = open_resource_directory(directory_name).await?;
let on_disk = enumerate_hashes(&directory).await?;
Ok(Self {
inner: Arc::new(Mutex::new(Inner {
directory,
cache: HashMap::new(),
on_disk,
queue: VecDeque::new(),
worker_active: false,
persist_requested: false,
})),
})
}
}
impl LoadResource for OpfsResourceStorage {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
let inner = self.inner.clone();
{
let guard = inner.lock().unwrap();
if let Some(resource) = guard.cache.get(&hash) {
let resource = resource.clone();
return Box::pin(async move { Some(resource) });
}
if !guard.on_disk.contains(&hash) {
return Box::pin(async move { None });
}
}
let (sender, receiver) = oneshot();
spawn_local(async move {
sender.send(read_from_opfs(inner, hash).await);
});
Box::pin(receiver)
}
}
impl ResourceStorage for OpfsResourceStorage {
fn store(&self, data: &[u8]) -> ResourceHash {
let hash = ResourceHash::from(data);
let mut guard = self.inner.lock().unwrap();
let mut bytes = None;
if !guard.cache.contains_key(&hash) {
let resource_bytes = Arc::<[u8]>::from(data);
guard.cache.insert(hash, Resource::new_unchecked(resource_bytes.clone(), hash));
bytes = Some(resource_bytes);
}
if !guard.on_disk.contains(&hash) {
let bytes = bytes.unwrap_or_else(|| Arc::<[u8]>::from(data));
guard.on_disk.insert(hash);
guard.queue.push_back(Mutation::Write { hash, bytes });
kick_worker(&self.inner, &mut guard);
}
hash
}
fn contains(&self, hash: &ResourceHash) -> bool {
let guard = self.inner.lock().unwrap();
guard.cache.contains_key(hash) || guard.on_disk.contains(hash)
}
fn garbage_collect(&self, used: &[ResourceHash]) {
let used: HashSet<ResourceHash> = used.iter().copied().collect();
let mut guard = self.inner.lock().unwrap();
guard.cache.retain(|hash, _| used.contains(hash));
let unused: Vec<ResourceHash> = guard.on_disk.iter().copied().filter(|hash| !used.contains(hash)).collect();
for hash in unused {
guard.on_disk.remove(&hash);
guard.queue.push_back(Mutation::Delete { hash });
}
if !guard.queue.is_empty() {
kick_worker(&self.inner, &mut guard);
}
}
}
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));
}
async fn drain_queue(inner: Arc<Mutex<Inner>>) {
loop {
let (directory, mutation, persist_requested) = {
let mut guard = inner.lock().unwrap();
let Some(mutation) = guard.queue.pop_front() else {
guard.worker_active = false;
return;
};
let persist_requested = matches!(mutation, Mutation::Write { .. }) && !guard.persist_requested;
if persist_requested {
guard.persist_requested = true;
}
(guard.directory.clone(), mutation, persist_requested)
};
if persist_requested {
request_persistence().await;
}
match mutation {
Mutation::Write { hash, bytes } => {
if let Err(error) = write_file(&directory, &hash, &bytes).await {
log::error!("OPFS write for {hash} failed: {error:?}");
}
}
Mutation::Delete { hash } => {
if let Err(error) = delete_file(&directory, &hash).await {
log::error!("OPFS delete for {hash} failed: {error:?}");
}
}
}
}
}
async fn request_persistence() {
let Some(window) = web_sys::window() else {
log::warn!("OPFS persist() skipped: no window");
return;
};
let storage = window.navigator().storage();
match storage.persist() {
Ok(promise) => match JsFuture::from(promise).await {
Ok(value) if value.as_bool() == Some(true) => {}
Ok(_) => log::warn!("OPFS persistence was not granted; browser may evict resources under storage pressure"),
Err(error) => log::warn!("OPFS persist() rejected: {error:?}"),
},
Err(error) => log::warn!("OPFS persist() threw: {error:?}"),
}
}
async fn open_resource_directory(directory_name: &str) -> Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let root: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
let options = FileSystemGetDirectoryOptions::new();
options.set_create(true);
JsFuture::from(root.get_directory_handle_with_options(directory_name, &options)).await?.dyn_into()
}
async fn enumerate_hashes(directory: &FileSystemDirectoryHandle) -> Result<HashSet<ResourceHash>, JsValue> {
let iterator = directory.keys();
let mut hashes = HashSet::new();
loop {
let next: js_sys::IteratorNext = JsFuture::from(iterator.next()?).await?.unchecked_into();
if next.done() {
break;
}
let Some(name) = next.value().as_string() else {
log::warn!("Skipping non-string OPFS resource entry");
continue;
};
match ResourceHash::try_from(name.as_str()) {
Ok(hash) => {
hashes.insert(hash);
}
Err(error) => log::warn!("Skipping non-resource OPFS entry {name:?}: {error}"),
}
}
Ok(hashes)
}
async fn write_file(directory: &FileSystemDirectoryHandle, hash: &ResourceHash, bytes: &[u8]) -> Result<(), JsValue> {
let options = FileSystemGetFileOptions::new();
options.set_create(true);
let name = file_name(hash);
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();
let bytes = Uint8Array::from(bytes);
if let Err(error) = JsFuture::from(writable.write_with_js_u8_array(&bytes)?).await {
let _ = JsFuture::from(stream.abort()).await;
return Err(error);
}
JsFuture::from(stream.close()).await?;
Ok(())
}
async fn delete_file(directory: &FileSystemDirectoryHandle, hash: &ResourceHash) -> Result<(), JsValue> {
let name = file_name(hash);
match JsFuture::from(directory.remove_entry(&name)).await {
Ok(_) => Ok(()),
Err(error) if is_not_found(&error) => Ok(()),
Err(error) => Err(error),
}
}
async fn read_from_opfs(inner: Arc<Mutex<Inner>>, hash: ResourceHash) -> Option<Resource> {
let directory = {
let guard = inner.lock().unwrap();
if let Some(resource) = guard.cache.get(&hash) {
return Some(resource.clone());
}
if !guard.on_disk.contains(&hash) {
return None;
}
guard.directory.clone()
};
let name = file_name(&hash);
let handle: FileSystemFileHandle = match JsFuture::from(directory.get_file_handle(&name)).await {
Ok(value) => match value.dyn_into() {
Ok(handle) => handle,
Err(value) => {
log::error!("OPFS returned non-file handle for {hash}: {value:?}");
return None;
}
},
Err(error) if is_not_found(&error) => return None,
Err(error) => {
log::error!("OPFS getFileHandle for {hash} failed: {error:?}");
return None;
}
};
let file = match JsFuture::from(handle.get_file()).await {
Ok(value) => value,
Err(error) => {
log::error!("OPFS getFile for {hash} failed: {error:?}");
return None;
}
};
let blob: Blob = match file.dyn_into() {
Ok(blob) => blob,
Err(value) => {
log::error!("OPFS getFile returned non-Blob for {hash}: {value:?}");
return None;
}
};
let buffer = match JsFuture::from(blob.array_buffer()).await {
Ok(buffer) => buffer,
Err(error) => {
log::error!("OPFS arrayBuffer for {hash} failed: {error:?}");
return None;
}
};
let bytes: Arc<[u8]> = Uint8Array::new(&buffer).to_vec().into();
let actual = ResourceHash::from(bytes.as_ref());
if actual != hash {
log::error!("OPFS content-integrity failure: file {hash} hashes to {actual}");
return None;
}
let resource = Resource::new_unchecked(bytes, hash);
let mut guard = inner.lock().unwrap();
if let Some(resource) = guard.cache.get(&hash) {
return Some(resource.clone());
}
if !guard.on_disk.contains(&hash) {
return None;
}
guard.cache.insert(hash, resource.clone());
Some(resource)
}
fn file_name(hash: &ResourceHash) -> String {
String::from(hash)
}
fn is_not_found(error: &JsValue) -> bool {
error.dyn_ref::<DomException>().is_some_and(|error| error.name() == "NotFoundError")
}
fn oneshot() -> (OneshotSender, OneshotReceiver) {
let state = Arc::new(Mutex::new(OneshotState::default()));
(OneshotSender { state: state.clone() }, OneshotReceiver { state })
}
#[derive(Default)]
struct OneshotState {
value: Option<Option<Resource>>,
waker: Option<Waker>,
}
struct OneshotSender {
state: Arc<Mutex<OneshotState>>,
}
impl OneshotSender {
fn send(self, value: Option<Resource>) {
let mut guard = self.state.lock().unwrap();
guard.value = Some(value);
if let Some(waker) = guard.waker.take() {
waker.wake();
}
}
}
struct OneshotReceiver {
state: Arc<Mutex<OneshotState>>,
}
impl std::future::Future for OneshotReceiver {
type Output = Option<Resource>;
fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
let mut guard = self.state.lock().unwrap();
if let Some(value) = guard.value.take() {
return Poll::Ready(value);
}
guard.waker = Some(context.waker().clone());
Poll::Pending
}
}
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more