mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5faf5e67f2 | ||
|
|
1d3d32c169 |
No files matched your search
@@ -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' }}" --branch="master" --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' }}" --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
+9
-129
@@ -304,20 +304,6 @@ 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"
|
||||
@@ -826,12 +812,6 @@ 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"
|
||||
@@ -948,15 +928,6 @@ 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"
|
||||
@@ -1242,24 +1213,6 @@ 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"
|
||||
@@ -1521,7 +1474,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"libz-rs-sys",
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
@@ -1575,7 +1527,7 @@ checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
|
||||
dependencies = [
|
||||
"fontconfig-parser",
|
||||
"log",
|
||||
"memmap2 0.9.10",
|
||||
"memmap2",
|
||||
"slotmap",
|
||||
"tinyvec",
|
||||
"ttf-parser",
|
||||
@@ -1589,7 +1541,7 @@ checksum = "7c20b425addb8661e97fe1d51c4d8bcec3ec29ed6ad0db983976a7521276b8f7"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"linebender_resource_handle",
|
||||
"memmap2 0.9.10",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
@@ -1901,7 +1853,6 @@ dependencies = [
|
||||
"gungraun",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mmap-io",
|
||||
"pretty_assertions",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
@@ -1915,7 +1866,6 @@ dependencies = [
|
||||
"url",
|
||||
"vector-nodes",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"wgpu-executor",
|
||||
"winit",
|
||||
@@ -1925,11 +1875,9 @@ dependencies = [
|
||||
name = "graphene-application-io"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
@@ -2009,17 +1957,6 @@ 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"
|
||||
@@ -2171,6 +2108,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"dirs",
|
||||
"futures",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphite-editor",
|
||||
@@ -2210,7 +2148,6 @@ dependencies = [
|
||||
"num_enum",
|
||||
"once_cell",
|
||||
"preprocessor",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
@@ -2218,14 +2155,11 @@ dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"url",
|
||||
"usvg",
|
||||
"vello",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"wgpu-executor",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2259,6 +2193,7 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3024,15 +2959,6 @@ 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"
|
||||
@@ -3180,15 +3106,6 @@ 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"
|
||||
@@ -3225,21 +3142,6 @@ 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"
|
||||
@@ -4391,7 +4293,6 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"image",
|
||||
"kurbo",
|
||||
"ndarray",
|
||||
@@ -4952,7 +4853,7 @@ checksum = "1dd3accc0f3f4bbaf2c9e1957a030dc582028130c67660d44c0a0345a22ca69b"
|
||||
dependencies = [
|
||||
"ab_glyph",
|
||||
"log",
|
||||
"memmap2 0.9.10",
|
||||
"memmap2",
|
||||
"smithay-client-toolkit",
|
||||
"tiny-skia",
|
||||
]
|
||||
@@ -5134,7 +5035,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
@@ -5220,7 +5121,7 @@ dependencies = [
|
||||
"cursor-icon",
|
||||
"libc",
|
||||
"log",
|
||||
"memmap2 0.9.10",
|
||||
"memmap2",
|
||||
"rustix",
|
||||
"thiserror 2.0.18",
|
||||
"wayland-backend",
|
||||
@@ -5523,19 +5424,6 @@ 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"
|
||||
@@ -5566,7 +5454,6 @@ dependencies = [
|
||||
"fancy-regex",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"node-macro",
|
||||
"parley",
|
||||
@@ -7350,7 +7237,7 @@ name = "winit-common"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
dependencies = [
|
||||
"memmap2 0.9.10",
|
||||
"memmap2",
|
||||
"objc2 0.6.4",
|
||||
"objc2-core-foundation",
|
||||
"smol_str",
|
||||
@@ -7422,7 +7309,7 @@ dependencies = [
|
||||
"cursor-icon",
|
||||
"dpi",
|
||||
"libc",
|
||||
"memmap2 0.9.10",
|
||||
"memmap2",
|
||||
"raw-window-handle",
|
||||
"rustix",
|
||||
"sctk-adwaita",
|
||||
@@ -7726,18 +7613,11 @@ 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"
|
||||
|
||||
@@ -7,7 +7,6 @@ members = [
|
||||
"desktop/platform/linux",
|
||||
"desktop/platform/mac",
|
||||
"desktop/platform/win",
|
||||
"document/container",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -69,7 +68,6 @@ 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" }
|
||||
@@ -173,8 +171,6 @@ 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",
|
||||
|
||||
+10
-10
@@ -16,14 +16,13 @@ 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, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -92,14 +91,7 @@ impl App {
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random());
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
@@ -257,6 +249,12 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::WriteFile { path, content } => {
|
||||
if let Some(parent) = path.parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
&& let Err(e) = fs::create_dir_all(parent)
|
||||
{
|
||||
tracing::error!("Failed to create parent directory {}: {}", parent.display(), e);
|
||||
}
|
||||
if let Err(e) = fs::write(&path, content) {
|
||||
tracing::error!("Failed to write file {}: {}", path.display(), e);
|
||||
}
|
||||
@@ -534,6 +532,8 @@ impl ApplicationHandler for App {
|
||||
|
||||
self.resize();
|
||||
|
||||
self.desktop_wrapper.init(self.wgpu_context.clone());
|
||||
|
||||
self.startup_time = Some(Instant::now());
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ 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;
|
||||
|
||||
+1
-7
@@ -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, APP_RESOURCES_DIRECTORY_NAME};
|
||||
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
|
||||
|
||||
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
|
||||
if !path.exists() {
|
||||
@@ -51,12 +51,6 @@ 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,
|
||||
|
||||
@@ -20,6 +20,7 @@ wgpu-executor = { workspace = true }
|
||||
|
||||
wgpu = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
ron = { workspace = true}
|
||||
|
||||
@@ -9,9 +9,6 @@ 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));
|
||||
}
|
||||
@@ -34,6 +31,20 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
SaveFileDialogContext::File { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
SaveFileDialogContext::MultipleFiles { files, expected_extension } => {
|
||||
// Treat the chosen path as the folder name. Strip only the export's expected extension (e.g. ".png" for a
|
||||
// PNG animation export) so that arbitrary dotted folder names like `v1.0` are preserved as-is, while a user
|
||||
// who typed `MyAnim.png` still gets a `MyAnim/` folder rather than a `MyAnim.png/` folder.
|
||||
// The `WriteFile` handler creates parent directories if they don't exist, so the folder is materialized on first write.
|
||||
let folder = match path.extension().and_then(|e| e.to_str()) {
|
||||
Some(ext) if ext.eq_ignore_ascii_case(&expected_extension) => path.with_extension(""),
|
||||
_ => path,
|
||||
};
|
||||
for (filename, content) in files {
|
||||
let file_path = folder.join(&filename);
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: file_path, content });
|
||||
}
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::OpenFile { path, content } => {
|
||||
let message = PortfolioMessage::OpenFile { path, content };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use graphite_editor::messages::frontend::utility_types::ExportAnimationFrame;
|
||||
#[cfg(target_os = "macos")]
|
||||
use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
@@ -59,6 +60,61 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
context: SaveFileDialogContext::File { content },
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerExportAnimation {
|
||||
name,
|
||||
extension,
|
||||
mime,
|
||||
size,
|
||||
folder,
|
||||
frames,
|
||||
} => {
|
||||
// Materialize each frame to bytes; SVG strings are encoded as UTF-8.
|
||||
// Raster-needs-canvas-rasterize frames can't be encoded here without a Rust SVG rasterizer,
|
||||
// so fall through to the frontend zip path in that case.
|
||||
// TODO: This fallback is inconsistent with the desktop folder-save flow for the rest of the animation
|
||||
// export — desktop users will see a .zip download instead of a folder. Once SVG rasterization moves to
|
||||
// Rust (resvg), this fallback can be removed and all frame paths can save into the chosen folder.
|
||||
let mut needs_frontend_rasterization = false;
|
||||
let mut materialized = Vec::with_capacity(frames.len());
|
||||
// Dynamic zero-pad width so files keep sorting in playback order beyond 9,999 frames.
|
||||
let pad_width = frames.len().to_string().len().max(4);
|
||||
let safe_base = graphite_editor::messages::frontend::utility_types::sanitize_filename_component(&name);
|
||||
for (index, frame) in frames.iter().enumerate() {
|
||||
let filename = format!("{safe_base}_{:0pad$}.{extension}", index + 1, pad = pad_width);
|
||||
let bytes = match frame {
|
||||
ExportAnimationFrame::Svg(svg) if extension == "svg" => svg.as_bytes().to_vec(),
|
||||
ExportAnimationFrame::Bytes(bytes) => bytes.to_vec(),
|
||||
ExportAnimationFrame::Svg(_) => {
|
||||
needs_frontend_rasterization = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
materialized.push((filename, bytes));
|
||||
}
|
||||
|
||||
if needs_frontend_rasterization {
|
||||
return Some(FrontendMessage::TriggerExportAnimation {
|
||||
name,
|
||||
extension,
|
||||
mime,
|
||||
size,
|
||||
folder,
|
||||
frames,
|
||||
});
|
||||
}
|
||||
|
||||
// The dialog name is the folder the frames go into (analogous to the .zip on web).
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save Animation Frames Folder As".to_string(),
|
||||
default_filename: safe_base,
|
||||
default_folder: folder,
|
||||
filters: Vec::new(),
|
||||
context: SaveFileDialogContext::MultipleFiles {
|
||||
files: materialized,
|
||||
expected_extension: extension,
|
||||
},
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerVisitLink { url } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenUrl(url));
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
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, Wake};
|
||||
use graphite_editor::messages::prelude::{FrontendMessage, Message};
|
||||
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;
|
||||
@@ -25,7 +22,7 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
pub fn new(uuid_random_seed: u64) -> Self {
|
||||
#[cfg(target_os = "windows")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -33,13 +30,17 @@ 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, resource_storage, application_io, schedule_wake),
|
||||
editor: Editor::new(env, uuid_random_seed),
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -82,7 +82,6 @@ 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 },
|
||||
@@ -112,8 +111,21 @@ pub enum OpenFileDialogContext {
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
Document { document_id: DocumentId, content: Vec<u8> },
|
||||
File { content: Vec<u8> },
|
||||
Document {
|
||||
document_id: DocumentId,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
File {
|
||||
content: Vec<u8>,
|
||||
},
|
||||
/// Multiple files written into a folder whose path is the user-chosen path with the matching `expected_extension`
|
||||
/// stripped (e.g. for a PNG animation export, picking `MyAnim.png` yields a `MyAnim/` folder, while picking `v1.0`
|
||||
/// is preserved as `v1.0/` because `.0` isn't the expected extension). Each `(filename, content)` entry is written
|
||||
/// inside that folder, which is created if it doesn't exist.
|
||||
MultipleFiles {
|
||||
files: Vec<(String, Vec<u8>)>,
|
||||
expected_extension: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub enum MenuItem {
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
[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 }
|
||||
@@ -1,97 +0,0 @@
|
||||
//! 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())),
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
//! 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}"))
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
//! 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}")),
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
//! Container backend implementations.
|
||||
|
||||
pub mod memory;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub mod folder;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub mod opfs;
|
||||
@@ -1,191 +0,0 @@
|
||||
//! 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}"))),
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
//! 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(())
|
||||
}
|
||||
}
|
||||
@@ -1,475 +0,0 @@
|
||||
//! 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, ¤t_prefix, EntryKind::File).await? {
|
||||
paths.insert(file);
|
||||
}
|
||||
for dir in list_entries(root, ¤t_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)
|
||||
}
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
#![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);
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
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);
|
||||
}
|
||||
+1
-9
@@ -47,9 +47,6 @@ 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 }
|
||||
@@ -57,13 +54,8 @@ 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 }
|
||||
@@ -1,25 +1,18 @@
|
||||
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::{Arc, OnceLock};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub struct Editor {
|
||||
pub dispatcher: Dispatcher,
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
pub fn new(environment: Environment, uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, mut application_io: PlatformApplicationIo, wake: Wake) -> Self {
|
||||
pub fn new(environment: Environment, uuid_random_seed: u64) -> Self {
|
||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||
|
||||
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 }
|
||||
Self { dispatcher: Dispatcher::new() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -27,15 +20,11 @@ impl Editor {
|
||||
let _ = ENVIRONMENT.set(*Editor::environment());
|
||||
graphene_std::uuid::set_uuid_seed(0);
|
||||
|
||||
let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
|
||||
let (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)
|
||||
}
|
||||
|
||||
|
||||
+20
-41
@@ -6,8 +6,6 @@ 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 {
|
||||
@@ -21,7 +19,6 @@ 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,
|
||||
@@ -32,26 +29,17 @@ 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),
|
||||
..Self::default()
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +54,7 @@ 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,
|
||||
@@ -89,16 +78,15 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
|
||||
impl Dispatcher {
|
||||
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 new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
Self {
|
||||
message_handlers: DispatcherMessageHandlers::with_executor(executor),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
// If the deepest queues (higher index in queues list) are now empty (after being popped from) then remove them
|
||||
@@ -126,13 +114,6 @@ 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]);
|
||||
|
||||
@@ -182,9 +163,6 @@ 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, ()),
|
||||
@@ -205,7 +183,17 @@ impl Dispatcher {
|
||||
self.message_handlers.dialog_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
Message::Frontend(message) => {
|
||||
self.responses.push(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);
|
||||
}
|
||||
}
|
||||
Message::InputPreprocessor(message) => {
|
||||
self.message_handlers.input_preprocessor_message_handler.process_message(
|
||||
@@ -230,14 +218,6 @@ 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,
|
||||
@@ -250,7 +230,6 @@ 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,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -318,7 +297,7 @@ impl Dispatcher {
|
||||
document_id,
|
||||
document,
|
||||
input: &self.message_handlers.input_preprocessor_message_handler,
|
||||
fonts: &self.message_handlers.portfolio_message_handler.fonts,
|
||||
cached_data: &self.message_handlers.portfolio_message_handler.cached_data,
|
||||
node_graph: &self.message_handlers.portfolio_message_handler.executor,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
|
||||
@@ -7,6 +7,10 @@ pub enum ExportDialogMessage {
|
||||
FileType { file_type: FileType },
|
||||
ScaleFactor { factor: f64 },
|
||||
ExportBounds { bounds: ExportBounds },
|
||||
Animated { animated: bool },
|
||||
Fps { fps: f64 },
|
||||
StartSeconds { start: f64 },
|
||||
EndSeconds { end: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, ExportBounds, FileType};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -16,6 +16,10 @@ pub struct ExportDialogMessageHandler {
|
||||
pub bounds: ExportBounds,
|
||||
pub artboards: HashMap<LayerNodeIdentifier, String>,
|
||||
pub has_selection: bool,
|
||||
pub animated: bool,
|
||||
pub fps: f64,
|
||||
pub start_seconds: f64,
|
||||
pub end_seconds: f64,
|
||||
}
|
||||
|
||||
impl Default for ExportDialogMessageHandler {
|
||||
@@ -26,10 +30,32 @@ impl Default for ExportDialogMessageHandler {
|
||||
bounds: Default::default(),
|
||||
artboards: Default::default(),
|
||||
has_selection: false,
|
||||
animated: false,
|
||||
fps: 30.,
|
||||
start_seconds: 0.,
|
||||
end_seconds: 1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on how many frames a single animation export will queue. Each frame is rendered then held
|
||||
/// in memory until the whole batch ships to the frontend, so we cap to avoid pathological allocations from
|
||||
/// large time ranges. Tuned for typical animation lengths (10k frames is ~5.5 min at 30 fps, ~2.8 min at 60 fps).
|
||||
pub const ANIMATION_EXPORT_MAX_FRAMES: u32 = 10_000;
|
||||
|
||||
impl ExportDialogMessageHandler {
|
||||
fn total_frames(&self) -> u32 {
|
||||
// Sanitize against non-finite values that could otherwise propagate into `Duration::from_secs_f64` and panic.
|
||||
if !self.fps.is_finite() || self.fps <= 0. || !self.start_seconds.is_finite() || !self.end_seconds.is_finite() {
|
||||
return 1;
|
||||
}
|
||||
let duration = (self.end_seconds - self.start_seconds).max(0.);
|
||||
// `ceil` so a duration slightly longer than a frame multiple still gets the trailing frame.
|
||||
let raw = (duration * self.fps).ceil() as i64;
|
||||
raw.clamp(1, ANIMATION_EXPORT_MAX_FRAMES as i64) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for ExportDialogMessageHandler {
|
||||
fn process_message(&mut self, message: ExportDialogMessage, responses: &mut VecDeque<Message>, context: ExportDialogMessageContext) {
|
||||
@@ -39,6 +65,20 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
|
||||
ExportDialogMessage::Animated { animated } => self.animated = animated,
|
||||
ExportDialogMessage::Fps { fps } => {
|
||||
// Reject non-finite/non-positive values so we never feed NaN or infinity into duration math downstream.
|
||||
self.fps = if fps.is_finite() && fps > 0. { fps } else { 0.001 };
|
||||
}
|
||||
ExportDialogMessage::StartSeconds { start } => {
|
||||
self.start_seconds = if start.is_finite() { start.max(0.) } else { 0. };
|
||||
if self.end_seconds < self.start_seconds {
|
||||
self.end_seconds = self.start_seconds;
|
||||
}
|
||||
}
|
||||
ExportDialogMessage::EndSeconds { end } => {
|
||||
self.end_seconds = if end.is_finite() { end.max(self.start_seconds) } else { self.start_seconds };
|
||||
}
|
||||
|
||||
ExportDialogMessage::Submit => {
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
@@ -52,6 +92,13 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let animation = self.animated.then(|| AnimationExport {
|
||||
fps: self.fps,
|
||||
start_seconds: self.start_seconds,
|
||||
total_frames: self.total_frames(),
|
||||
});
|
||||
|
||||
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
||||
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
|
||||
file_type: self.file_type,
|
||||
@@ -59,6 +106,7 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count: self.artboards.len(),
|
||||
animation,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -163,6 +211,74 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
|
||||
let animation_checkbox_id = CheckboxId::new();
|
||||
let animation_toggle = vec![
|
||||
TextLabel::new("Animation").table_align(true).min_width(100).for_checkbox(animation_checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(self.animated)
|
||||
.on_update(|checkbox_input: &CheckboxInput| ExportDialogMessage::Animated { animated: checkbox_input.checked }.into())
|
||||
.for_label(animation_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let mut layout_groups = vec![
|
||||
LayoutGroup::row(export_type),
|
||||
LayoutGroup::row(resolution),
|
||||
LayoutGroup::row(export_area),
|
||||
LayoutGroup::row(animation_toggle),
|
||||
];
|
||||
|
||||
if self.animated {
|
||||
let fps_row = vec![
|
||||
TextLabel::new("FPS").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.fps))
|
||||
.unit(" fps")
|
||||
.min(0.001)
|
||||
.max(1000.)
|
||||
.increment_step(1.)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::Fps { fps: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let start_row = vec![
|
||||
TextLabel::new("Start").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.start_seconds))
|
||||
.unit(" sec")
|
||||
.min(0.)
|
||||
.increment_step(0.1)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::StartSeconds { start: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let end_row = vec![
|
||||
TextLabel::new("End").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.end_seconds))
|
||||
.unit(" sec")
|
||||
.min(self.start_seconds)
|
||||
.increment_step(0.1)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::EndSeconds { end: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let frame_count = self.total_frames();
|
||||
let frames_row = vec![
|
||||
TextLabel::new("Frames").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new(format!("{frame_count} frame{}", if frame_count == 1 { "" } else { "s" })).widget_instance(),
|
||||
];
|
||||
|
||||
layout_groups.push(LayoutGroup::row(fps_row));
|
||||
layout_groups.push(LayoutGroup::row(start_row));
|
||||
layout_groups.push(LayoutGroup::row(end_row));
|
||||
layout_groups.push(LayoutGroup::row(frames_row));
|
||||
}
|
||||
|
||||
Layout(layout_groups)
|
||||
}
|
||||
}
|
||||
@@ -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 graph_craft::application_io::EditorPreferences;
|
||||
use graphene_std::render_node::{EditorPreferences, wgpu_available};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct PreferencesDialogMessageContext<'a> {
|
||||
@@ -307,7 +307,7 @@ impl PreferencesDialogMessageHandler {
|
||||
// COMPATIBILITY
|
||||
// =============
|
||||
{
|
||||
let wgpu_available = graph_craft::application_io::wgpu_available().unwrap_or(false);
|
||||
let wgpu_available = 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()];
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
// 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()]),
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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,8 +4,6 @@ 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;
|
||||
|
||||
@@ -16,7 +14,5 @@ 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;
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, ExportAnimationFrame, EyedropperPreviewImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
@@ -15,6 +15,7 @@ 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;
|
||||
|
||||
@@ -106,10 +107,32 @@ pub enum FrontendMessage {
|
||||
mime: String,
|
||||
size: (f64, f64),
|
||||
},
|
||||
/// Export one or more animation frames as a bundle.
|
||||
/// On web, the frontend zips the frames into an uncompressed `.zip` and triggers a single download.
|
||||
/// On desktop, the wrapper intercepts this and writes each frame as a separate file to a user-chosen folder.
|
||||
TriggerExportAnimation {
|
||||
/// Base name without the index suffix or extension (e.g. "MyDocument" or "MyDocument - Artboard 1").
|
||||
name: String,
|
||||
/// File extension without leading dot ("png", "jpg", "svg").
|
||||
extension: String,
|
||||
/// MIME type matching the extension (e.g. "image/png").
|
||||
mime: String,
|
||||
/// Pixel size of each rasterized frame, used when the frontend needs to canvas-rasterize from SVG.
|
||||
size: (f64, f64),
|
||||
/// Document folder, used as a default location for the desktop save dialog.
|
||||
folder: Option<PathBuf>,
|
||||
/// One entry per frame, in playback order. Each frame is either an SVG string or pre-encoded bytes.
|
||||
frames: Vec<ExportAnimationFrame>,
|
||||
},
|
||||
TriggerFetchAndOpenDocument {
|
||||
name: String,
|
||||
filename: String,
|
||||
},
|
||||
TriggerFontCatalogLoad,
|
||||
TriggerFontDataLoad {
|
||||
font: Font,
|
||||
url: String,
|
||||
},
|
||||
TriggerPersistenceReadState,
|
||||
TriggerPersistenceReadDocument {
|
||||
#[serde(rename = "documentId")]
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
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::*;
|
||||
@@ -12,9 +10,6 @@ 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,
|
||||
}
|
||||
@@ -64,6 +59,14 @@ impl FileType {
|
||||
FileType::Svg => "image/svg+xml",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_extension(self) -> &'static str {
|
||||
match self {
|
||||
FileType::Png => "png",
|
||||
FileType::Jpg => "jpg",
|
||||
FileType::Svg => "svg",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -75,6 +78,56 @@ pub enum ExportBounds {
|
||||
Artboard(LayerNodeIdentifier),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AnimationExport {
|
||||
pub fps: f64,
|
||||
pub start_seconds: f64,
|
||||
pub total_frames: u32,
|
||||
}
|
||||
|
||||
impl Default for AnimationExport {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fps: 30.,
|
||||
start_seconds: 0.,
|
||||
total_frames: 30,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationExport {
|
||||
pub fn frame_time_seconds(&self, frame_index: u32) -> f64 {
|
||||
self.start_seconds + frame_index as f64 / self.fps
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of a multi-frame animation export, in playback order.
|
||||
/// `Svg` is text that the frontend can save directly (for SVG export) or rasterize via canvas (for PNG/JPG export).
|
||||
/// `Bytes` is already-encoded image bytes from the GPU export path, ready to write directly.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ExportAnimationFrame {
|
||||
Svg(String),
|
||||
Bytes(serde_bytes::ByteBuf),
|
||||
}
|
||||
|
||||
/// Replace characters that have special meaning in filesystem paths (or are otherwise unsafe in filenames) with `_`.
|
||||
/// Used to neutralize user-controlled strings — document names, artboard names — before they become export filenames,
|
||||
/// so a name like `..\evil` or `foo/bar` can't escape the export folder or create nested zip entries.
|
||||
pub fn sanitize_filename_component(name: &str) -> String {
|
||||
let cleaned: String = name
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'/' | '\\' | ':' | '*' | '?' | '<' | '>' | '|' | '"' | '\0' => '_',
|
||||
c if c.is_control() => '_',
|
||||
c => c,
|
||||
})
|
||||
.collect();
|
||||
// Strip leading/trailing dots and whitespace; Windows treats trailing `.` / ` ` as hidden and `..` is the parent dir.
|
||||
let trimmed = cleaned.trim().trim_matches('.').trim();
|
||||
if trimmed.is_empty() { "Untitled".to_string() } else { trimmed.to_string() }
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EyedropperPreviewImage {
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
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};
|
||||
@@ -24,8 +24,6 @@ pub enum Message {
|
||||
#[child]
|
||||
Frontend(FrontendMessage),
|
||||
#[child]
|
||||
Future(FutureMessage),
|
||||
#[child]
|
||||
InputPreprocessor(InputPreprocessorMessage),
|
||||
#[child]
|
||||
KeyMapping(KeyMappingMessage),
|
||||
@@ -34,14 +32,10 @@ pub enum Message {
|
||||
#[child]
|
||||
MenuBar(MenuBarMessage),
|
||||
#[child]
|
||||
Network(NetworkMessage),
|
||||
#[child]
|
||||
Portfolio(PortfolioMessage),
|
||||
#[child]
|
||||
Preferences(PreferencesMessage),
|
||||
#[child]
|
||||
ResourceStorage(ResourceStorageMessage),
|
||||
#[child]
|
||||
Tool(ToolMessage),
|
||||
#[child]
|
||||
Viewport(ViewportMessage),
|
||||
|
||||
@@ -9,16 +9,13 @@ 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;
|
||||
@@ -1,10 +0,0 @@
|
||||
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;
|
||||
@@ -1,49 +0,0 @@
|
||||
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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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;
|
||||
);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
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,8 +37,6 @@ 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::PanelType;
|
||||
use crate::messages::portfolio::utility_types::{CachedData, 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,14 +29,13 @@ 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};
|
||||
@@ -52,6 +51,7 @@ 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,8 +59,6 @@ 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)]
|
||||
@@ -87,9 +85,6 @@ 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,
|
||||
@@ -165,7 +160,6 @@ 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(),
|
||||
@@ -198,6 +192,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let DocumentMessageContext {
|
||||
document_id,
|
||||
ipp,
|
||||
cached_data,
|
||||
executor,
|
||||
viewport,
|
||||
current_tool,
|
||||
@@ -205,8 +200,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
data_panel_open,
|
||||
layers_panel_open,
|
||||
properties_panel_open,
|
||||
resource_storage,
|
||||
fonts,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -233,12 +226,11 @@ 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(),
|
||||
fonts,
|
||||
executor,
|
||||
cached_data,
|
||||
properties_panel_open,
|
||||
};
|
||||
self.properties_panel_message_handler.process_message(message, responses, context);
|
||||
@@ -282,10 +274,6 @@ 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,
|
||||
@@ -924,29 +912,19 @@ 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());
|
||||
|
||||
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,
|
||||
})
|
||||
responses.add(FrontendMessage::TriggerSaveDocument {
|
||||
document_id,
|
||||
name: format!("{}.{}", self.name.clone(), FILE_EXTENSION),
|
||||
path,
|
||||
folder,
|
||||
content: self.serialize_document().into_bytes().into(),
|
||||
});
|
||||
}
|
||||
DocumentMessage::SavedDocument { path } => {
|
||||
@@ -1328,10 +1306,11 @@ 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(|&(node_id, _)| self.network_interface.is_layer(&node_id, &[]))
|
||||
.map(|(node_id, frame)| {
|
||||
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
|
||||
(layer, frame)
|
||||
.filter_map(|(node_id, frame)| {
|
||||
self.network_interface.is_layer(&node_id, &[]).then(|| {
|
||||
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
|
||||
(layer, frame)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.network_interface.update_text_frames(layer_text_frames);
|
||||
@@ -2567,7 +2546,6 @@ 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,
|
||||
@@ -2657,6 +2635,23 @@ 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();
|
||||
@@ -3449,21 +3444,6 @@ 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
|
||||
|
||||
+1
-1
@@ -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 GraphOperationMessageContext { network_interface, .. } = context;
|
||||
let network_interface = context.network_interface;
|
||||
|
||||
match message {
|
||||
GraphOperationMessage::FillSet { layer, fill } => {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
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, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, 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};
|
||||
@@ -250,13 +248,12 @@ 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::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::scope("editor-api")),
|
||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::Font(font), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
|
||||
@@ -266,7 +263,6 @@ 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")
|
||||
@@ -279,8 +275,6 @@ 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);
|
||||
@@ -304,20 +298,13 @@ 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::Resource(resource_id), false))]);
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::ImageData(image), false))]);
|
||||
|
||||
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 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 transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
@@ -340,37 +327,6 @@ 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)
|
||||
@@ -526,14 +482,12 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
|
||||
/// Set the GradientStops list on the 'Gradient Value' node, creating it if necessary.
|
||||
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
|
||||
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 {
|
||||
let Some(gradient_node_id) = self.existing_proto_node_id(graphene_std::math_nodes::gradient_value::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
|
||||
let input_connector = InputConnector::node(gradient_node_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
|
||||
}
|
||||
|
||||
@@ -543,21 +497,13 @@ 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![walk_from], &[], FlowType::HorizontalFlow)
|
||||
.skip_while(|node_id| self.network_interface.is_layer(node_id, &[]))
|
||||
.upstream_flow_back_from_nodes(vec![output_layer.to_node()], &[], network_interface::FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|node_id| !self.network_interface.is_layer(node_id, &[]))
|
||||
.filter(|id| self.network_interface.reference(id, &[]).as_ref() == Some(&transform_reference))
|
||||
.filter(|node_id| self.network_interface.reference(node_id, &[]).as_ref() == Some(&transform_reference))
|
||||
.collect();
|
||||
|
||||
// Upstream walk yields downstream-to-upstream order, so the first hit is the chain's last `Transform`
|
||||
@@ -582,10 +528,15 @@ 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_composed = build_transform_with_y_preservation(composed_old, new_start, new_end);
|
||||
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 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 {
|
||||
@@ -593,7 +544,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_at(&target_input, graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
|
||||
let Some(id) = self.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
id
|
||||
@@ -607,13 +558,9 @@ 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_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
let Some(node_id) = self.existing_proto_node_id(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);
|
||||
@@ -622,13 +569,9 @@ 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_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
let Some(node_id) = self.existing_proto_node_id(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);
|
||||
@@ -823,14 +766,3 @@ 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,7 +7,6 @@ pub mod navigation;
|
||||
pub mod node_graph;
|
||||
pub mod overlays;
|
||||
pub mod properties_panel;
|
||||
pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
DocumentNodeMetadata, DocumentNodePersistentMetadata, InputMetadata, NodeNetworkInterface, NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodeTemplate, NodeTypePersistentMetadata,
|
||||
Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::prelude::{FontsMessageHandler, Message, ResourceMessageHandler};
|
||||
use crate::messages::portfolio::utility_types::CachedData;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
@@ -27,11 +28,10 @@ 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,7 +876,6 @@ 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,
|
||||
});
|
||||
|
||||
@@ -1316,7 +1315,6 @@ 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 },
|
||||
});
|
||||
|
||||
@@ -1559,7 +1557,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().is_none_or(|node_id| !all_selected_nodes.contains(&node_id)))
|
||||
.is_some_and(|connector| connector.node_id().map_or(true, |node_id| !all_selected_nodes.contains(&node_id)))
|
||||
{
|
||||
responses.add(NodeGraphMessage::DisconnectInput { input_connector });
|
||||
}
|
||||
|
||||
@@ -6,13 +6,12 @@ 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::fonts::utility_types::FontCatalogStyle;
|
||||
use crate::messages::portfolio::utility_types::{CachedData, 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};
|
||||
@@ -823,27 +822,11 @@ 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;
|
||||
|
||||
@@ -856,32 +839,66 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
return (vec![], None);
|
||||
};
|
||||
|
||||
if let Some(TaggedValue::Resource(resource_id)) = input.as_non_exposed_value() {
|
||||
let font = fonts.id_font(resources, *resource_id).unwrap_or_default();
|
||||
if let Some(TaggedValue::Font(font)) = &input.as_non_exposed_value() {
|
||||
first_widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(vec![
|
||||
fonts
|
||||
cached_data
|
||||
.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(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(&())],
|
||||
.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()
|
||||
}
|
||||
.into()
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
])
|
||||
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
|
||||
.selected_index(cached_data.font_catalog.0.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
|
||||
.virtual_scrolling(true)
|
||||
.widget_instance(),
|
||||
]);
|
||||
@@ -891,18 +908,32 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
second_row.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new({
|
||||
fonts
|
||||
cached_data
|
||||
.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)
|
||||
.on_update(move |_| assign_font_message(node_id, new_font.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)(&()),
|
||||
]),
|
||||
}
|
||||
}
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
};
|
||||
|
||||
@@ -915,8 +946,9 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.selected_index(
|
||||
fonts
|
||||
cached_data
|
||||
.font_catalog
|
||||
.0
|
||||
.iter()
|
||||
.find(|family| family.name == font.font_family)
|
||||
.and_then(|family| {
|
||||
@@ -2781,8 +2813,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,
|
||||
@@ -2792,7 +2824,6 @@ pub struct ParameterWidgetsInfo<'a> {
|
||||
input_type: FrontendGraphDataType,
|
||||
blank_assist: bool,
|
||||
exposable: bool,
|
||||
fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
impl<'a> ParameterWidgetsInfo<'a> {
|
||||
@@ -2805,10 +2836,9 @@ 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,12 +162,9 @@ pub enum ContextMenuData {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ContextMenuInformation {
|
||||
// The menu's display position in graph coordinates, which may be shifted from the click point to keep the menu on-screen
|
||||
// Stores whether the context menu is open and its position in graph coordinates
|
||||
#[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,
|
||||
}
|
||||
|
||||
File renamed without changes.
@@ -2,12 +2,11 @@ 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::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::text::{Font, FontCache, TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
use std::collections::HashMap;
|
||||
@@ -222,6 +221,16 @@ 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 {
|
||||
@@ -235,8 +244,12 @@ 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, &FALLBACK_FONT_RESOURCE, typesetting, false);
|
||||
let bounds = text_context.bounding_box(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
|
||||
bounds.x
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,8 @@ 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_TEXT_CONTEXT, hex_to_rgba_u8};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_FONT_CACHE, 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;
|
||||
@@ -15,7 +14,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::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::text::{Font, TextAlign, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
@@ -1116,16 +1115,21 @@ 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, &FALLBACK_FONT_RESOURCE, typesetting, false);
|
||||
let text_size = text_context.bounding_box(text, &font, &GLOBAL_FONT_CACHE, 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, &FALLBACK_FONT_RESOURCE, typesetting, false);
|
||||
let text_list = text_context.to_path(text, &font, &GLOBAL_FONT_CACHE, typesetting, false);
|
||||
|
||||
// Calculate position based on pivot
|
||||
let mut position = DVec2::ZERO;
|
||||
|
||||
+7
-9
@@ -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 fonts: &'a FontsMessageHandler,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub cached_data: &'a CachedData,
|
||||
pub properties_panel_open: bool,
|
||||
}
|
||||
|
||||
@@ -24,12 +24,11 @@ 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,
|
||||
fonts,
|
||||
executor,
|
||||
cached_data,
|
||||
properties_panel_open,
|
||||
} = context;
|
||||
|
||||
@@ -47,13 +46,12 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
}
|
||||
|
||||
let mut node_properties_context = NodePropertiesContext {
|
||||
cached_data,
|
||||
responses,
|
||||
executor,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
document_name,
|
||||
fonts,
|
||||
executor,
|
||||
};
|
||||
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
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};
|
||||
@@ -1,15 +0,0 @@
|
||||
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 },
|
||||
}
|
||||
@@ -1,299 +0,0 @@
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
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,7 +16,13 @@ pub enum EditorError {
|
||||
#[error("The operation caused a document error:\n{0:?}")]
|
||||
Document(String),
|
||||
|
||||
#[error("Failed to deserialize document: {0}")]
|
||||
#[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."
|
||||
)]
|
||||
DocumentDeserialization(String),
|
||||
|
||||
#[error("{0}")]
|
||||
|
||||
@@ -20,7 +20,6 @@ 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;
|
||||
@@ -511,10 +510,6 @@ 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)) => {
|
||||
@@ -5911,46 +5906,6 @@ 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) {
|
||||
@@ -6814,21 +6769,6 @@ 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,7 +6,6 @@ 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};
|
||||
@@ -17,7 +16,6 @@ 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"),
|
||||
@@ -1036,77 +1034,6 @@ 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();
|
||||
|
||||
@@ -1661,51 +1588,12 @@ 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);
|
||||
}
|
||||
|
||||
// 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,
|
||||
});
|
||||
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);
|
||||
|
||||
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);
|
||||
}
|
||||
// Insert a new empty input for the image
|
||||
document.network_interface.add_import(TaggedValue::None, false, 0, "Empty", "", &[*node_id]);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
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));
|
||||
@@ -1,26 +0,0 @@
|
||||
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,
|
||||
},
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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};
|
||||
@@ -1,164 +0,0 @@
|
||||
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,12 +3,9 @@ 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,9 +52,3 @@ impl MessageHandler<PersistentStateMessage, PersistentStateMessageContext> for P
|
||||
|
||||
advertise_actions!(PersistentStateMessageDiscriminant;);
|
||||
}
|
||||
|
||||
impl PersistentStateMessageHandler {
|
||||
pub fn loaded(&self) -> bool {
|
||||
self.loaded
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, 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)]
|
||||
@@ -15,8 +17,6 @@ pub enum PortfolioMessage {
|
||||
#[child]
|
||||
Document(DocumentMessage),
|
||||
#[child]
|
||||
Fonts(FontsMessage),
|
||||
#[child]
|
||||
PersistentState(PersistentStateMessage),
|
||||
|
||||
// Messages
|
||||
@@ -50,11 +50,20 @@ pub enum PortfolioMessage {
|
||||
},
|
||||
DestroyAllDocuments,
|
||||
EditorPreferences,
|
||||
GarbageCollectResources,
|
||||
ResolveDocumentResources {
|
||||
FontCatalogLoaded {
|
||||
catalog: FontCatalog,
|
||||
},
|
||||
LoadFontData {
|
||||
font: Font,
|
||||
},
|
||||
FontLoaded {
|
||||
font_family: String,
|
||||
font_style: String,
|
||||
data: Vec<u8>,
|
||||
},
|
||||
LoadDocumentResources {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
ResolveResources,
|
||||
LoadPersistedState {
|
||||
state: PersistedState,
|
||||
},
|
||||
@@ -62,12 +71,6 @@ 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,
|
||||
@@ -175,6 +178,7 @@ pub enum PortfolioMessage {
|
||||
bounds: ExportBounds,
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
animation: Option<AnimationExport>,
|
||||
},
|
||||
SubmitActiveGraphRender,
|
||||
SubmitGraphRender {
|
||||
|
||||
@@ -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::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
|
||||
use super::utility_types::{CachedData, 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,16 +26,15 @@ 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)]
|
||||
@@ -47,27 +46,16 @@ 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 fonts: FontsMessageHandler,
|
||||
pub cached_data: CachedData,
|
||||
copy_buffer: [Vec<CopyBufferEntry>; INTERNAL_CLIPBOARD_COUNT as usize],
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
@@ -86,7 +74,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
reset_node_definitions_on_open,
|
||||
timing_information,
|
||||
viewport,
|
||||
resource_storage,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -98,12 +85,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
let document_inputs = DocumentMessageContext {
|
||||
document_id,
|
||||
ipp,
|
||||
fonts: &self.fonts,
|
||||
cached_data: &self.cached_data,
|
||||
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,
|
||||
@@ -117,10 +103,6 @@ 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 => {
|
||||
@@ -172,12 +154,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
let document_inputs = DocumentMessageContext {
|
||||
document_id,
|
||||
ipp,
|
||||
fonts: &self.fonts,
|
||||
cached_data: &self.cached_data,
|
||||
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,
|
||||
@@ -202,8 +183,6 @@ 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 };
|
||||
@@ -211,7 +190,6 @@ 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 {
|
||||
@@ -390,41 +368,86 @@ 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::GarbageCollectResources => {
|
||||
if !self.persistent_state.loaded() {
|
||||
// We don't know what can be safely garbage collected
|
||||
PortfolioMessage::LoadDocumentResources { document_id } => {
|
||||
let catalog = &self.cached_data.font_catalog;
|
||||
|
||||
if catalog.0.is_empty() {
|
||||
responses.add_front(FrontendMessage::TriggerFontCatalogLoad);
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
if let Some(document) = self.documents.get_mut(&document_id) {
|
||||
document.load_layer_resources(responses);
|
||||
}
|
||||
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 {
|
||||
@@ -445,17 +468,11 @@ 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) && !self.unloaded_documents.contains_key(&info.id) {
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
newly_unloaded_ids.push(info.id);
|
||||
|
||||
if !self.documents.contains_key(&info.id) {
|
||||
self.unloaded_documents.insert(info.id, info);
|
||||
}
|
||||
}
|
||||
@@ -463,27 +480,9 @@ 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,
|
||||
@@ -502,85 +501,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_is_saved: info.is_saved,
|
||||
document_serialized_content,
|
||||
});
|
||||
|
||||
// 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}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::NewDocumentWithName { name } => {
|
||||
let mut new_document = DocumentMessageHandler::default();
|
||||
@@ -815,8 +736,6 @@ 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);
|
||||
@@ -825,37 +744,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
let mut document = match document {
|
||||
Ok(document) => document,
|
||||
Err(e) => {
|
||||
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);
|
||||
if !document_is_auto_saved {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Failed to open document".to_string(),
|
||||
description: e.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -865,25 +758,6 @@ 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);
|
||||
@@ -947,11 +821,6 @@ 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}".
|
||||
@@ -1075,6 +944,7 @@ 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());
|
||||
@@ -1559,7 +1429,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
};
|
||||
if !document.is_loaded {
|
||||
document.is_loaded = true;
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
responses.add(PortfolioMessage::LoadDocumentResources { document_id });
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
responses.add(PropertiesPanelMessage::Clear);
|
||||
}
|
||||
@@ -1571,6 +1441,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
animation,
|
||||
} => {
|
||||
let document_id = self.active_document_id.expect("Tried to render non-existent document");
|
||||
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
|
||||
@@ -1581,6 +1452,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
animation,
|
||||
..Default::default()
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
@@ -1605,13 +1477,6 @@ 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);
|
||||
@@ -1867,13 +1732,7 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
|
||||
pub fn persisted_state_snapshot(&self) -> PersistedState {
|
||||
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());
|
||||
}
|
||||
let documents = self.document_ids.iter().filter_map(|id| self.document_details(*id)).collect::<Vec<_>>();
|
||||
|
||||
PersistedState {
|
||||
documents,
|
||||
@@ -1917,18 +1776,6 @@ 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() {
|
||||
@@ -2024,7 +1871,6 @@ 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()
|
||||
@@ -2138,76 +1984,3 @@ 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,11 +1,95 @@
|
||||
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: cfg!(target_os = "linux"), // TODO: Set this back to false once we have ui acceleration working more reliably on linux
|
||||
disable_ui_acceleration: false,
|
||||
#[cfg(target_os = "macos")]
|
||||
vsync: false,
|
||||
}
|
||||
|
||||
@@ -16,26 +16,21 @@ 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};
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
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};
|
||||
@@ -1,10 +0,0 @@
|
||||
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]> },
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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,35 +271,6 @@ 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;
|
||||
@@ -313,8 +284,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 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 {
|
||||
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 {
|
||||
return None;
|
||||
};
|
||||
Some(stops.clone())
|
||||
@@ -460,21 +431,15 @@ 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. 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)> {
|
||||
/// Gets properties from the Text node
|
||||
pub fn get_text(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<(&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 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::Font(font)) = &inputs[graphene_std::text::text::FontInput::INDEX].as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(font_size)) = inputs[graphene_std::text::text::SizeInput::INDEX].as_value() else {
|
||||
return None;
|
||||
|
||||
@@ -16,6 +16,7 @@ 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};
|
||||
@@ -62,18 +63,17 @@ 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, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) -> Quad {
|
||||
pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, font_cache: &FontCache) -> 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, fonts, &document.resources) else {
|
||||
let Some((text, font, typesetting, _)) = get_text(layer, &document.network_interface) else {
|
||||
return Quad::from_box([DVec2::ZERO, DVec2::ZERO]);
|
||||
};
|
||||
let font = fonts.get_resource_or_queue_load(&font, responses);
|
||||
let far = graphene_std::text::bounding_box(text, &font, typesetting, false);
|
||||
let far = graphene_std::text::bounding_box(text, font, font_cache, typesetting, false);
|
||||
Quad::from_box([DVec2::ZERO, far])
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ 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};
|
||||
@@ -18,7 +19,7 @@ pub struct ToolMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
pub document: &'a mut DocumentMessageHandler,
|
||||
pub input: &'a InputPreprocessorMessageHandler,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub cached_data: &'a CachedData,
|
||||
pub node_graph: &'a NodeGraphExecutor,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
@@ -39,7 +40,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
document_id,
|
||||
document,
|
||||
input,
|
||||
fonts,
|
||||
cached_data,
|
||||
node_graph,
|
||||
preferences,
|
||||
viewport,
|
||||
@@ -126,7 +127,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
node_graph,
|
||||
preferences,
|
||||
viewport,
|
||||
fonts,
|
||||
cached_data,
|
||||
};
|
||||
|
||||
if let Some(tool_abort_message) = tool.event_to_message_map().tool_abort {
|
||||
@@ -217,7 +218,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);
|
||||
tool_data.tools.get(active_tool).unwrap().refresh_options(responses, cached_data);
|
||||
|
||||
// Notify the frontend about the initial active tool
|
||||
tool_data.send_layout(responses, LayoutTarget::ToolShelf, preferences.brush_tool);
|
||||
@@ -234,7 +235,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
node_graph,
|
||||
preferences,
|
||||
viewport,
|
||||
fonts,
|
||||
cached_data,
|
||||
};
|
||||
|
||||
// Set initial hints and cursor
|
||||
@@ -258,7 +259,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);
|
||||
tool_data.tools.get(&tool_data.active_tool_type).unwrap().refresh_options(responses, cached_data);
|
||||
}
|
||||
ToolMessage::RefreshToolShelf => {
|
||||
let tool_data = &mut self.tool_state.tool_data;
|
||||
@@ -346,7 +347,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
node_graph,
|
||||
preferences,
|
||||
viewport,
|
||||
fonts,
|
||||
cached_data,
|
||||
};
|
||||
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, gradient_chain_target_input};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer, get_gradient_stops};
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -347,19 +347,20 @@ 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) {
|
||||
// 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 {
|
||||
let GradientChainState {
|
||||
transform,
|
||||
gradient_type,
|
||||
spread_method,
|
||||
} = read_gradient_chain_state(layer, network_interface);
|
||||
return Some(Gradient {
|
||||
stops,
|
||||
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)
|
||||
gradient_type,
|
||||
spread_method,
|
||||
start: transform.transform_point2(DVec2::ZERO),
|
||||
end: transform.transform_point2(DVec2::X),
|
||||
});
|
||||
}
|
||||
graph_modification_utils::get_gradient(layer, network_interface)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -372,9 +373,6 @@ 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);
|
||||
@@ -384,8 +382,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![walk_from], &[], FlowType::HorizontalFlow)
|
||||
.skip_while(|node_id| network_interface.is_layer(node_id, &[]))
|
||||
.upstream_flow_back_from_nodes(vec![layer.to_node()], &[], FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|node_id| !network_interface.is_layer(node_id, &[]))
|
||||
{
|
||||
let Some(reference) = network_interface.reference(&node_id, &[]) else { continue };
|
||||
@@ -514,13 +512,14 @@ 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: get_gradient_stops(layer, &document.network_interface).is_some(),
|
||||
is_gradient_list,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2502,98 +2501,4 @@ 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,7 +720,13 @@ 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, fonts, .. } = tool_action_data;
|
||||
let ToolActionMessageContext {
|
||||
document,
|
||||
input,
|
||||
viewport,
|
||||
cached_data,
|
||||
..
|
||||
} = tool_action_data;
|
||||
|
||||
let ToolMessage::Select(event) = event else { return self };
|
||||
match (self, event) {
|
||||
@@ -745,7 +751,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, fonts, responses);
|
||||
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, &cached_data.font_cache);
|
||||
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::fonts::utility_types::{FontCatalog, FontCatalogStyle};
|
||||
use crate::messages::portfolio::utility_types::{CachedData, 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,13 +17,12 @@ 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, TextAlign, TypesettingConfig, lines_clipping};
|
||||
use graphene_std::text::{Font, FontCache, TextAlign, TypesettingConfig, lines_clipping};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI};
|
||||
use graphene_std::{Color, NodeInputDecleration};
|
||||
|
||||
@@ -106,28 +105,29 @@ 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 apply_font = move |font: Font| -> Message {
|
||||
let font_input_index = graphene_std::text::text::FontInput::INDEX;
|
||||
let apply_font = move |new_font: Font| -> Message {
|
||||
match text_node_id {
|
||||
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(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
None => TextToolMessage::UpdateOptions {
|
||||
options: TextOptionsUpdate::Font { font },
|
||||
Some(node_id) => NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: font_input_index,
|
||||
value: TaggedValue::Font(new_font),
|
||||
}
|
||||
.into(),
|
||||
None => TextToolMessage::UpdateOptions {
|
||||
options: TextOptionsUpdate::Font { font: new_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 {
|
||||
@@ -142,27 +142,35 @@ 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(¤t_font.font_style, "");
|
||||
let new_font = Font::new(family.name.clone(), family.closest_style(weight, italic).to_named_style());
|
||||
let commit_only_font = new_font.clone();
|
||||
let commit_only_font = Font::new(family.name.clone(), family.closest_style(weight, italic).to_named_style());
|
||||
|
||||
MenuListEntry::new(family.name.clone())
|
||||
.label(family.name.clone())
|
||||
.font(family.closest_style(400, false).preview_url(&family.name))
|
||||
.on_update(move |_| apply_font(new_font.clone()))
|
||||
.on_update(move |_| preview_font(new_font.clone()))
|
||||
.on_commit(move |_| commit_font(commit_only_font.clone()))
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
])
|
||||
.selected_index(font_catalog.iter().position(|family| family.name == tool.options.font.font_family).map(|i| i as u32))
|
||||
.selected_index(font_catalog.0.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| {
|
||||
@@ -174,7 +182,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
|
||||
|
||||
MenuListEntry::new(font_style.clone())
|
||||
.label(font_style)
|
||||
.on_update(move |_| apply_font(new_font.clone()))
|
||||
.on_update(move |_| preview_font(new_font.clone()))
|
||||
.on_commit(move |_| commit_font(new_font_for_commit.clone()))
|
||||
};
|
||||
|
||||
@@ -188,6 +196,7 @@ 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| {
|
||||
@@ -244,7 +253,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
|
||||
}
|
||||
|
||||
impl ToolRefreshOptions for TextTool {
|
||||
fn refresh_options(&self, responses: &mut VecDeque<Message>) {
|
||||
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData) {
|
||||
// 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);
|
||||
@@ -290,15 +299,11 @@ 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, context.fonts, &context.document.resources)
|
||||
&& let Some((_, font, typesetting, _)) = graph_modification_utils::get_text(layer, &context.document.network_interface)
|
||||
{
|
||||
self.options.align = typesetting.align;
|
||||
self.options.font_size = typesetting.font_size;
|
||||
@@ -306,7 +311,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;
|
||||
editing_text.font = font.clone();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,7 +326,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.fonts.font_catalog, context.document);
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog, context.document);
|
||||
return;
|
||||
}
|
||||
_ => {
|
||||
@@ -380,7 +385,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
}
|
||||
}
|
||||
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions, &context.fonts.font_catalog, context.document);
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog, context.document);
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
@@ -471,9 +476,9 @@ struct TextToolData {
|
||||
}
|
||||
|
||||
impl TextToolData {
|
||||
fn delete_empty_layer(&mut self, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) -> TextToolFsmState {
|
||||
fn delete_empty_layer(&mut self, font_cache: &FontCache, responses: &mut VecDeque<Message>) -> TextToolFsmState {
|
||||
// Remove the editable textbox UI first
|
||||
self.set_editing(false, fonts, responses);
|
||||
self.set_editing(false, font_cache, responses);
|
||||
|
||||
// Delete the empty text layer and update the graph
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
@@ -486,16 +491,15 @@ impl TextToolData {
|
||||
}
|
||||
|
||||
/// Set the editing state of the currently modifying layer
|
||||
fn set_editing(&self, editable: bool, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fn set_editing(&self, editable: bool, font_cache: &FontCache, 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_data: font_cache.get(&editing_text.font).map(|(data, _)| data.clone()).unwrap_or_default().into(),
|
||||
transform: editing_text.transform.to_cols_array(),
|
||||
max_width: editing_text.typesetting.max_width,
|
||||
max_height: editing_text.typesetting.max_height,
|
||||
@@ -513,13 +517,13 @@ impl TextToolData {
|
||||
}
|
||||
}
|
||||
|
||||
fn load_layer_text_node(&mut self, document: &DocumentMessageHandler, fonts: &FontsMessageHandler) -> Option<()> {
|
||||
fn load_layer_text_node(&mut self, document: &DocumentMessageHandler) -> 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, fonts, &document.resources)?;
|
||||
let (text, font, typesetting, _) = graph_modification_utils::get_text(self.layer, &document.network_interface)?;
|
||||
self.editing_text = Some(EditingText {
|
||||
text: text.clone(),
|
||||
font,
|
||||
font: font.clone(),
|
||||
typesetting,
|
||||
color: Some(color),
|
||||
transform,
|
||||
@@ -528,20 +532,20 @@ impl TextToolData {
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn start_editing_layer(&mut self, layer: LayerNodeIdentifier, tool_state: TextToolFsmState, document: &DocumentMessageHandler, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fn start_editing_layer(&mut self, layer: LayerNodeIdentifier, tool_state: TextToolFsmState, document: &DocumentMessageHandler, font_cache: &FontCache, 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, fonts, responses);
|
||||
self.set_editing(false, font_cache, responses);
|
||||
}
|
||||
|
||||
self.layer = layer;
|
||||
if self.load_layer_text_node(document, fonts).is_some() {
|
||||
if self.load_layer_text_node(document).is_some() {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
self.set_editing(true, fonts, responses);
|
||||
self.set_editing(true, font_cache, responses);
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![self.layer.to_node()] });
|
||||
// Make the rendered text invisible while editing
|
||||
@@ -553,16 +557,14 @@ impl TextToolData {
|
||||
};
|
||||
}
|
||||
|
||||
fn new_text(&mut self, document: &DocumentMessageHandler, editing_text: EditingText, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fn new_text(&mut self, document: &DocumentMessageHandler, editing_text: EditingText, font_cache: &FontCache, responses: &mut VecDeque<Message>) {
|
||||
// Create new text
|
||||
self.new_text = String::new();
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
self.layer = LayerNodeIdentifier::new_unchecked(NodeId::new());
|
||||
|
||||
responses.add(FontsMessage::Load {
|
||||
font: editing_text.font.clone(),
|
||||
response: Box::new(NodeGraphMessage::RunDocumentGraph.into()),
|
||||
});
|
||||
responses.add(PortfolioMessage::LoadFontData { font: editing_text.font.clone() });
|
||||
responses.add(GraphOperationMessage::NewTextLayer {
|
||||
id: self.layer.to_node(),
|
||||
text: String::new(),
|
||||
@@ -578,7 +580,7 @@ impl TextToolData {
|
||||
let transform = editing_text.transform;
|
||||
self.editing_text = Some(editing_text);
|
||||
|
||||
self.set_editing(true, fonts, responses);
|
||||
self.set_editing(true, font_cache, responses);
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![self.layer.to_node()] });
|
||||
|
||||
@@ -600,19 +602,20 @@ impl TextToolData {
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
fn check_click(document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, font_cache: &FontCache) -> Option<LayerNodeIdentifier> {
|
||||
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, fonts, responses);
|
||||
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);
|
||||
|
||||
transformed_quad.contains(mouse)
|
||||
})
|
||||
}
|
||||
|
||||
fn get_snap_candidates(&mut self, document: &DocumentMessageHandler, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fn get_snap_candidates(&mut self, document: &DocumentMessageHandler, font_cache: &FontCache) {
|
||||
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, fonts, responses);
|
||||
let quad = document.metadata().transform_to_document(id) * text_bounding_box(id, document, font_cache);
|
||||
snapping::get_bbox_points(quad, &mut self.snap_candidates, snapping::BBoxSnapValues::BOUNDING_BOX, document);
|
||||
}
|
||||
}
|
||||
@@ -648,7 +651,14 @@ impl Fsm for TextToolFsmState {
|
||||
tool_options: &Self::ToolOptions,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) -> Self {
|
||||
let ToolActionMessageContext { document, input, fonts, viewport, .. } = transition_data;
|
||||
let ToolActionMessageContext {
|
||||
document,
|
||||
input,
|
||||
cached_data,
|
||||
viewport,
|
||||
..
|
||||
} = transition_data;
|
||||
let font_cache = &cached_data.font_cache;
|
||||
let fill_color = COLOR_OVERLAY_BLUE_05;
|
||||
|
||||
let ToolMessage::Text(event) = event else { return self };
|
||||
@@ -657,8 +667,7 @@ 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 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);
|
||||
let far = graphene_std::text::bounding_box(&tool_data.new_text, &editing_text.font, font_cache, 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;
|
||||
@@ -685,7 +694,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, fonts, responses));
|
||||
let bounds = layer.map(|layer| text_bounding_box(layer, document, font_cache));
|
||||
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. {
|
||||
@@ -701,11 +710,10 @@ 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, 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.));
|
||||
}
|
||||
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.));
|
||||
}
|
||||
|
||||
bounding_box_manager.render_overlays(&mut overlay_context, false);
|
||||
@@ -720,7 +728,7 @@ impl Fsm for TextToolFsmState {
|
||||
}
|
||||
(state, TextToolMessage::EditSelected) => {
|
||||
if let Some(layer) = can_edit_selected(document) {
|
||||
tool_data.start_editing_layer(layer, state, document, fonts, responses);
|
||||
tool_data.start_editing_layer(layer, state, document, font_cache, responses);
|
||||
return TextToolFsmState::Editing;
|
||||
}
|
||||
|
||||
@@ -761,10 +769,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, fonts, responses);
|
||||
tool_data.get_snap_candidates(document, font_cache);
|
||||
|
||||
return TextToolFsmState::ResizingBounds;
|
||||
} else if let Some(clicked_layer) = TextToolData::check_click(document, input, fonts, responses) {
|
||||
} else if let Some(clicked_layer) = TextToolData::check_click(document, input, font_cache) {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
if selected != Some(clicked_layer) {
|
||||
@@ -776,7 +784,7 @@ impl Fsm for TextToolFsmState {
|
||||
id: clicked_layer,
|
||||
original_transform,
|
||||
});
|
||||
tool_data.get_snap_candidates(document, fonts, responses);
|
||||
tool_data.get_snap_candidates(document, font_cache);
|
||||
return TextToolFsmState::Dragging;
|
||||
}
|
||||
TextToolFsmState::Placing
|
||||
@@ -959,8 +967,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, fonts, responses) {
|
||||
tool_data.start_editing_layer(clicked_text_layer_path, self, document, fonts, responses);
|
||||
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);
|
||||
return TextToolFsmState::Editing;
|
||||
}
|
||||
|
||||
@@ -981,7 +989,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, fonts, responses);
|
||||
tool_data.new_text(document, editing_text, font_cache, responses);
|
||||
TextToolFsmState::Editing
|
||||
}
|
||||
(TextToolFsmState::Dragging, TextToolMessage::DragStop) => {
|
||||
@@ -996,7 +1004,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, fonts, responses);
|
||||
tool_data.start_editing_layer(layer_info.id, self, document, font_cache, responses);
|
||||
return TextToolFsmState::Editing;
|
||||
}
|
||||
tool_data.layer_dragging.take();
|
||||
@@ -1005,9 +1013,8 @@ 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_resource.as_ref().to_vec().into(),
|
||||
font_data: font_cache.get(&font).map(|(data, _)| data.clone()).unwrap_or_default().into(),
|
||||
});
|
||||
|
||||
TextToolFsmState::Editing
|
||||
@@ -1016,7 +1023,7 @@ impl Fsm for TextToolFsmState {
|
||||
tool_data.new_text = new_text;
|
||||
|
||||
if !is_left_or_right_click {
|
||||
tool_data.set_editing(false, fonts, responses);
|
||||
tool_data.set_editing(false, font_cache, responses);
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(graph_modification_utils::get_text_id(tool_data.layer, &document.network_interface).unwrap(), 1),
|
||||
@@ -1027,7 +1034,7 @@ impl Fsm for TextToolFsmState {
|
||||
TextToolFsmState::Ready
|
||||
} else {
|
||||
if tool_data.new_text.is_empty() {
|
||||
return tool_data.delete_empty_layer(fonts, responses);
|
||||
return tool_data.delete_empty_layer(font_cache, responses);
|
||||
}
|
||||
|
||||
responses.add(FrontendMessage::TriggerTextCommit);
|
||||
@@ -1048,7 +1055,7 @@ impl Fsm for TextToolFsmState {
|
||||
}
|
||||
(TextToolFsmState::Editing, TextToolMessage::Abort) => {
|
||||
if tool_data.new_text.is_empty() {
|
||||
return tool_data.delete_empty_layer(fonts, responses);
|
||||
return tool_data.delete_empty_layer(font_cache, responses);
|
||||
}
|
||||
|
||||
responses.add(FrontendMessage::TriggerTextCommit);
|
||||
|
||||
@@ -9,6 +9,7 @@ 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;
|
||||
@@ -24,7 +25,7 @@ pub struct ToolActionMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
pub global_tool_data: &'a DocumentToolData,
|
||||
pub input: &'a InputPreprocessorMessageHandler,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub cached_data: &'a CachedData,
|
||||
pub shape_editor: &'a mut ShapeState,
|
||||
pub node_graph: &'a NodeGraphExecutor,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
@@ -37,11 +38,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>);
|
||||
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData);
|
||||
}
|
||||
|
||||
impl<T: LayoutHolder> ToolRefreshOptions for T {
|
||||
fn refresh_options(&self, responses: &mut VecDeque<Message>) {
|
||||
fn refresh_options(&self, responses: &mut VecDeque<Message>, _cached_data: &CachedData) {
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{ExportAnimationFrame, ExportBounds, FileType};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::EditorPreferences;
|
||||
@@ -9,9 +9,12 @@ 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;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
mod runtime_io;
|
||||
pub use runtime_io::NodeRuntimeIO;
|
||||
@@ -58,6 +61,23 @@ pub struct NodeGraphExecutor {
|
||||
/// so the runtime can splice its monitor node alongside the target rather than only at the top level.
|
||||
/// Tracking the previously-sent value lets `update_node_graph` re-send the network when the inspection target changes.
|
||||
previous_node_to_inspect: Vec<NodeId>,
|
||||
/// Per-export accumulator for in-progress animation exports. Each frame execution pushes its rendered output here into the matching u64 export ID slot.
|
||||
/// Once `frames_received == total_frames`, the accumulator is drained into a single `TriggerExportAnimation` message.
|
||||
pending_animation_exports: HashMap<u64, AnimationExportAccumulator>,
|
||||
next_animation_export_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AnimationExportAccumulator {
|
||||
name: String,
|
||||
file_type: FileType,
|
||||
size: UVec2,
|
||||
folder: Option<PathBuf>,
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
frames: Vec<Option<ExportAnimationFrame>>,
|
||||
frames_received: u32,
|
||||
total_frames: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -80,6 +100,8 @@ impl NodeGraphExecutor {
|
||||
node_graph_hash: 0,
|
||||
current_execution_id: 0,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
pending_animation_exports: HashMap::new(),
|
||||
next_animation_export_id: 0,
|
||||
};
|
||||
(node_runtime, node_executor)
|
||||
}
|
||||
@@ -94,6 +116,10 @@ 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))
|
||||
@@ -108,14 +134,8 @@ 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,
|
||||
resources,
|
||||
node_to_inspect: Vec::new(),
|
||||
}))
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect: Vec::new() }))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
}
|
||||
@@ -129,10 +149,8 @@ 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, resources, node_to_inspect }))
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect }))
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
@@ -240,7 +258,6 @@ 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
|
||||
@@ -268,7 +285,7 @@ impl NodeGraphExecutor {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let render_config = RenderConfig {
|
||||
let base_render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: export_config.scale_factor,
|
||||
time: Default::default(),
|
||||
@@ -280,22 +297,78 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
export_config.size = resolution;
|
||||
|
||||
// Execute the node graph
|
||||
// Send the network update once; the runtime keeps it for all subsequent executions.
|
||||
self.runtime_io
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
node_to_inspect: Vec::new(),
|
||||
}))
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect: Vec::new() }))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
},
|
||||
));
|
||||
|
||||
if let Some(animation) = export_config.animation {
|
||||
// Defense-in-depth: the dialog already validates these, but reject non-finite/non-positive values here
|
||||
// too so a corrupt message can't reach `Duration::from_secs_f64` (which panics on NaN/negative/huge).
|
||||
if !animation.fps.is_finite() || animation.fps <= 0. || !animation.start_seconds.is_finite() {
|
||||
return Err("Animation export rejected: fps and start time must be finite, with fps > 0".to_string());
|
||||
}
|
||||
|
||||
// Allocate an export ID and accumulator, then queue one execution per frame.
|
||||
// TODO: All encoded frames are held in `pending_animation_exports` until the last frame arrives, so peak
|
||||
// memory grows with `total_frames * encoded_frame_size`. For long/high-resolution animations, this could
|
||||
// exhaust memory. A bounded cap is enforced upstream in the export dialog (ANIMATION_EXPORT_MAX_FRAMES),
|
||||
// but a true fix would stream frames out incrementally instead of accumulating.
|
||||
let export_id = self.next_animation_export_id;
|
||||
self.next_animation_export_id = self.next_animation_export_id.wrapping_add(1);
|
||||
|
||||
let folder = document.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
|
||||
self.pending_animation_exports.insert(
|
||||
export_id,
|
||||
AnimationExportAccumulator {
|
||||
name: export_config.name.clone(),
|
||||
file_type: export_config.file_type,
|
||||
size: resolution,
|
||||
folder,
|
||||
artboard_name: export_config.artboard_name.clone(),
|
||||
artboard_count: export_config.artboard_count,
|
||||
frames: (0..animation.total_frames).map(|_| None).collect(),
|
||||
frames_received: 0,
|
||||
total_frames: animation.total_frames,
|
||||
},
|
||||
);
|
||||
|
||||
for frame_index in 0..animation.total_frames {
|
||||
let frame_seconds = animation.frame_time_seconds(frame_index);
|
||||
// `Duration::from_secs_f64` panics on negative/NaN/huge values; clamp defensively (we've already
|
||||
// validated `fps`/`start_seconds` above, but a far-future `start_seconds` could still overflow).
|
||||
let safe_seconds = if frame_seconds.is_finite() { frame_seconds.clamp(0., 1e9) } else { 0. };
|
||||
let animation_time = Duration::from_secs_f64(safe_seconds);
|
||||
let timing = TimingInformation { time: frame_seconds, animation_time };
|
||||
|
||||
let frame_render_config = RenderConfig { time: timing, ..base_render_config };
|
||||
|
||||
let mut frame_export_config = export_config.clone();
|
||||
frame_export_config.animation_frame = Some(AnimationExportFrame {
|
||||
export_id,
|
||||
frame_index,
|
||||
total_frames: animation.total_frames,
|
||||
});
|
||||
|
||||
let execution_id = self.queue_execution(frame_render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(frame_export_config),
|
||||
document_id,
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let execution_id = self.queue_execution(base_render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -322,6 +395,24 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
|
||||
// If this failure belongs to an animation export, drop its accumulator so the partially
|
||||
// rendered frames don't stay pinned in memory. Subsequent failed frames for the same
|
||||
// export are then silently ignored by `process_animation_frame`.
|
||||
// TODO: An export can also leak if it's interrupted by something *outside* this error
|
||||
// path — e.g. the document is closed mid-export. A proper fix would route a
|
||||
// cancellation through `pending_animation_exports`. Tracked separately.
|
||||
let leaked_export_id = self
|
||||
.futures
|
||||
.iter()
|
||||
.find(|(fid, _)| *fid == execution_id)
|
||||
.and_then(|(_, ctx)| ctx.export_config.as_ref())
|
||||
.and_then(|cfg| cfg.animation_frame)
|
||||
.map(|af| af.export_id);
|
||||
if let Some(export_id) = leaked_export_id {
|
||||
self.pending_animation_exports.remove(&export_id);
|
||||
}
|
||||
|
||||
return Err(format!("Node graph evaluation failed:\n{e}"));
|
||||
}
|
||||
};
|
||||
@@ -467,7 +558,12 @@ impl NodeGraphExecutor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
fn process_export(&mut self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
// Route animation frames into the per-export accumulator. The final message is emitted when all frames arrive.
|
||||
if let Some(animation_frame) = export_config.animation_frame {
|
||||
return self.process_animation_frame(node_graph_output, &export_config, animation_frame, responses);
|
||||
}
|
||||
|
||||
let ExportConfig {
|
||||
file_type,
|
||||
name,
|
||||
@@ -511,43 +607,7 @@ impl NodeGraphExecutor {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => {
|
||||
use image::buffer::ConvertBuffer;
|
||||
use image::{ImageFormat, RgbImage, RgbaImage};
|
||||
|
||||
let Some(mut image) = RgbaImage::from_raw(width, height, data) else {
|
||||
return Err("Failed to create image buffer for export".to_string());
|
||||
};
|
||||
|
||||
let mut encoded = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(&mut encoded);
|
||||
|
||||
match file_type {
|
||||
FileType::Png => {
|
||||
let result = image.write_to(&mut cursor, ImageFormat::Png);
|
||||
if let Err(err) = result {
|
||||
return Err(format!("Failed to encode PNG: {err}"));
|
||||
}
|
||||
}
|
||||
FileType::Jpg => {
|
||||
// Composite onto a white background since JPG doesn't support transparency
|
||||
for pixel in image.pixels_mut() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
let alpha = a as f32 / 255.;
|
||||
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
|
||||
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
|
||||
}
|
||||
|
||||
let image: RgbImage = image.convert();
|
||||
let result = image.write_to(&mut cursor, ImageFormat::Jpeg);
|
||||
if let Err(err) = result {
|
||||
return Err(format!("Failed to encode JPG: {err}"));
|
||||
}
|
||||
}
|
||||
FileType::Svg => {
|
||||
return Err("SVG cannot be exported from an image buffer".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let encoded = encode_raster_buffer(file_type, data, width, height)?;
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name,
|
||||
folder,
|
||||
@@ -561,6 +621,115 @@ impl NodeGraphExecutor {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_animation_frame(
|
||||
&mut self,
|
||||
node_graph_output: TaggedValue,
|
||||
export_config: &ExportConfig,
|
||||
animation_frame: AnimationExportFrame,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) -> Result<(), String> {
|
||||
let file_type = export_config.file_type;
|
||||
|
||||
let frame_data = match node_graph_output {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => ExportAnimationFrame::Svg(svg),
|
||||
#[cfg(feature = "gpu")]
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => match encode_raster_buffer(file_type, data, width, height) {
|
||||
Ok(encoded) => ExportAnimationFrame::Bytes(serde_bytes::ByteBuf::from(encoded)),
|
||||
Err(err) => {
|
||||
// Drop the partial accumulator so its already-received frames don't leak.
|
||||
self.pending_animation_exports.remove(&animation_frame.export_id);
|
||||
return Err(err);
|
||||
}
|
||||
},
|
||||
other => {
|
||||
// Drop the partial accumulator so its already-received frames don't leak.
|
||||
self.pending_animation_exports.remove(&animation_frame.export_id);
|
||||
return Err(format!("Incorrect render type for animation frame ({file_type:?}, {other})"));
|
||||
}
|
||||
};
|
||||
|
||||
let Some(accumulator) = self.pending_animation_exports.get_mut(&animation_frame.export_id) else {
|
||||
// Export was cancelled or already finalized, drop it quietly
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let index = animation_frame.frame_index as usize;
|
||||
if let Some(slot) = accumulator.frames.get_mut(index)
|
||||
&& slot.is_none()
|
||||
{
|
||||
*slot = Some(frame_data);
|
||||
accumulator.frames_received += 1;
|
||||
}
|
||||
|
||||
if accumulator.frames_received < accumulator.total_frames {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// All frames received: drain the accumulator and emit a single message
|
||||
let accumulator = self.pending_animation_exports.remove(&animation_frame.export_id).expect("Accumulator was present");
|
||||
// Sanitize before the name reaches filesystem joins or zip entry names downstream.
|
||||
let safe_doc_name = crate::messages::frontend::utility_types::sanitize_filename_component(&accumulator.name);
|
||||
let base_name = match (accumulator.artboard_name.as_deref(), accumulator.artboard_count) {
|
||||
(Some(artboard_name), count) if count > 1 => format!("{safe_doc_name} - {}", crate::messages::frontend::utility_types::sanitize_filename_component(artboard_name)),
|
||||
_ => safe_doc_name,
|
||||
};
|
||||
let frames: Vec<_> = accumulator
|
||||
.frames
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| f.ok_or_else(|| format!("Missing animation frame {i}")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
responses.add(FrontendMessage::TriggerExportAnimation {
|
||||
name: base_name,
|
||||
extension: accumulator.file_type.to_extension().to_string(),
|
||||
mime: accumulator.file_type.to_mime().to_string(),
|
||||
size: accumulator.size.as_dvec2().into(),
|
||||
folder: accumulator.folder,
|
||||
frames,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "gpu")]
|
||||
fn encode_raster_buffer(file_type: FileType, data: Vec<u8>, width: u32, height: u32) -> Result<Vec<u8>, String> {
|
||||
use image::buffer::ConvertBuffer;
|
||||
use image::{ImageFormat, RgbImage, RgbaImage};
|
||||
|
||||
let Some(mut image) = RgbaImage::from_raw(width, height, data) else {
|
||||
return Err("Failed to create image buffer for export".to_string());
|
||||
};
|
||||
|
||||
let mut encoded = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(&mut encoded);
|
||||
|
||||
match file_type {
|
||||
FileType::Png => image.write_to(&mut cursor, ImageFormat::Png).map_err(|err| format!("Failed to encode PNG: {err}"))?,
|
||||
FileType::Jpg => {
|
||||
// Composite onto a white background since JPG doesn't support transparency
|
||||
for pixel in image.pixels_mut() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
let alpha = a as f32 / 255.;
|
||||
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
|
||||
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
|
||||
}
|
||||
|
||||
let image: RgbImage = image.convert();
|
||||
image.write_to(&mut cursor, ImageFormat::Jpeg).map_err(|err| format!("Failed to encode JPG: {err}"))?;
|
||||
}
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
}
|
||||
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, 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};
|
||||
@@ -17,6 +16,7 @@ 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,7 +42,6 @@ pub struct NodeRuntime {
|
||||
update_thumbnails: bool,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
node_graph_errors: GraphErrors,
|
||||
monitor_nodes: Vec<Vec<NodeId>>,
|
||||
|
||||
@@ -70,13 +69,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.
|
||||
@@ -92,13 +91,24 @@ pub struct ExportConfig {
|
||||
pub size: UVec2,
|
||||
pub artboard_name: Option<String>,
|
||||
pub artboard_count: usize,
|
||||
/// Set when this export is part of a multi-frame animation export. `None` means a normal single-frame export.
|
||||
pub animation: Option<AnimationExport>,
|
||||
/// Set on each per-frame `ExportConfig` to identify which animation export it belongs to and which frame index it represents.
|
||||
pub animation_frame: Option<AnimationExportFrame>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AnimationExportFrame {
|
||||
pub export_id: u64,
|
||||
pub frame_index: u32,
|
||||
pub total_frames: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct InternalNodeGraphUpdateSender(Sender<NodeGraphUpdate>);
|
||||
|
||||
impl InternalNodeGraphUpdateSender {
|
||||
fn send_compilation_response(&self, response: CompilationResponse) {
|
||||
fn send_generation_response(&self, response: CompilationResponse) {
|
||||
self.0.send(NodeGraphUpdate::CompilationResponse(response)).expect("Failed to send response")
|
||||
}
|
||||
|
||||
@@ -128,18 +138,14 @@ 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(),
|
||||
|
||||
@@ -159,6 +165,20 @@ 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;
|
||||
@@ -182,6 +202,7 @@ impl NodeRuntime {
|
||||
break;
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::FontCacheUpdate(_) => font = Some(request),
|
||||
GraphRuntimeRequest::EditorPreferencesUpdate(_) => preferences = Some(request),
|
||||
}
|
||||
}
|
||||
@@ -194,13 +215,27 @@ impl NodeRuntime {
|
||||
eyedropper.render_config.pointer = execution.render_config.pointer;
|
||||
}
|
||||
|
||||
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
|
||||
let requests = [font, 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),
|
||||
@@ -211,16 +246,11 @@ impl NodeRuntime {
|
||||
let _ = self.update_network(graph).await;
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
mut network,
|
||||
resources,
|
||||
node_to_inspect,
|
||||
}) => {
|
||||
GraphRuntimeRequest::GraphUpdate(GraphUpdate { mut network, 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;
|
||||
@@ -228,7 +258,7 @@ impl NodeRuntime {
|
||||
|
||||
self.update_thumbnails = true;
|
||||
|
||||
self.sender.send_compilation_response(CompilationResponse { result, node_graph_errors });
|
||||
self.sender.send_generation_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
|
||||
@@ -347,9 +377,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn update_network(&mut self, mut graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
if let Err(e) = preprocessor::expand_network(&mut graph, &self.substitutions, &self.resources) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
}
|
||||
preprocessor::expand_network(&mut graph, &self.substitutions);
|
||||
|
||||
let scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
|
||||
|
||||
@@ -554,23 +582,18 @@ pub async fn run_node_graph() -> (bool, Option<ImageTexture>) {
|
||||
(false, None)
|
||||
}
|
||||
|
||||
pub fn replace_node_runtime(runtime: NodeRuntime) -> Option<NodeRuntime> {
|
||||
pub async fn replace_node_runtime(runtime: NodeRuntime) -> Option<NodeRuntime> {
|
||||
let mut node_runtime = NODE_RUNTIME.lock();
|
||||
node_runtime.replace(runtime)
|
||||
}
|
||||
pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
|
||||
pub async fn replace_application_io(application_io: PlatformApplicationIo) {
|
||||
let mut node_runtime = NODE_RUNTIME.lock();
|
||||
if let Some(node_runtime) = &mut *node_runtime {
|
||||
node_runtime.replace_application_io(application_io);
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeRuntime {
|
||||
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
|
||||
self.editor_api = PlatformEditorApi {
|
||||
node_runtime.editor_api = PlatformEditorApi {
|
||||
font_cache: node_runtime.editor_api.font_cache.clone(),
|
||||
application_io: Some(application_io.into()),
|
||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||
editor_preferences: Box::new(self.editor_preferences.clone()),
|
||||
node_graph_message_sender: Box::new(node_runtime.sender.clone()),
|
||||
editor_preferences: Box::new(node_runtime.editor_preferences.clone()),
|
||||
}
|
||||
.into();
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
replace_node_runtime(NodeRuntime::new(request_receiver, response_sender));
|
||||
futures::executor::block_on(replace_node_runtime(NodeRuntime::new(request_receiver, response_sender)));
|
||||
|
||||
Self {
|
||||
sender: request_sender,
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
// Create the editor and subscriptions router
|
||||
const randomSeed = BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER));
|
||||
subscriptions = createSubscriptionsRouter();
|
||||
editor = await EditorWrapper.create(operatingSystem(), randomSeed, (messageType: MessageName, messageData: FrontendMessage) => {
|
||||
editor = EditorWrapper.create(operatingSystem(), randomSeed, (messageType: MessageName, messageData: FrontendMessage) => {
|
||||
subscriptions?.handleFrontendMessage(messageType, messageData);
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
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";
|
||||
@@ -42,6 +43,7 @@
|
||||
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.
|
||||
@@ -69,6 +71,7 @@
|
||||
destroyLocalizationManager();
|
||||
destroyPanicManager();
|
||||
destroyPersistenceManager();
|
||||
destroyFontsManager();
|
||||
destroyInputManager();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -97,7 +97,7 @@
|
||||
await tick();
|
||||
|
||||
const flattened = filteredEntries.flat();
|
||||
const highlightedFound = flattened.map((entry) => entry.value).includes(highlighted.value);
|
||||
const highlightedFound = highlighted?.label && flattened.map((entry) => entry.label).includes(highlighted.label);
|
||||
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 = flatEntries.map((entry) => entry.value).indexOf(highlighted.value);
|
||||
const index = highlighted ? flatEntries.map((entry) => entry.label).indexOf(highlighted.label) : 0;
|
||||
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.value === highlighted?.value, disabled: Boolean(entry.disabled) }}
|
||||
classes={{ open: openChildValue === entry.value, active: entry.label === highlighted?.label, disabled: Boolean(entry.disabled) }}
|
||||
styles={{ height: virtualScrollingEntryHeight || "20px" }}
|
||||
tooltipLabel={entry.tooltipLabel}
|
||||
tooltipDescription={entry.tooltipDescription}
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
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";
|
||||
@@ -17,7 +16,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, hasFirstArtworkBeenReceived, markFirstArtworkReceived } from "/src/utility-functions/viewports";
|
||||
import { setupViewportResizeObserver } from "/src/utility-functions/viewports";
|
||||
import type { EditorWrapper, MenuDirection, MouseCursorIcon, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
let rulerHorizontal: RulerInput | undefined;
|
||||
@@ -54,10 +53,6 @@
|
||||
// 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;
|
||||
@@ -475,11 +470,6 @@
|
||||
subscriptions.subscribeFrontendMessage("UpdateDocumentArtwork", async (data) => {
|
||||
await tick();
|
||||
|
||||
if (!firstArtworkReceived) {
|
||||
firstArtworkReceived = true;
|
||||
markFirstArtworkReceived();
|
||||
}
|
||||
|
||||
updateDocumentArtwork(data.svg);
|
||||
});
|
||||
subscriptions.subscribeFrontendMessage("UpdateEyedropperSamplingState", async (data) => {
|
||||
@@ -718,9 +708,6 @@
|
||||
>
|
||||
</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>
|
||||
@@ -957,31 +944,6 @@
|
||||
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;
|
||||
|
||||
@@ -33,17 +33,11 @@
|
||||
</LayoutCol>
|
||||
</LayoutCol>
|
||||
<LayoutCol class="bottom-message">
|
||||
{#if import.meta.env.MODE === "native"}
|
||||
<TextLabel italic={true} disabled={true}>
|
||||
<TextLabel italic={true} disabled={true}>
|
||||
{#if import.meta.env.MODE === "native"}
|
||||
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.
|
||||
</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}
|
||||
{/if}
|
||||
</TextLabel>
|
||||
</LayoutCol>
|
||||
</LayoutCol>
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@
|
||||
function createNode(identifier: string) {
|
||||
if ($nodeGraph.contextMenuInformation === undefined) return;
|
||||
|
||||
editor.createNode(identifier, $nodeGraph.contextMenuInformation.nodeCreationCoordinates[0], $nodeGraph.contextMenuInformation.nodeCreationCoordinates[1]);
|
||||
editor.createNode(identifier, $nodeGraph.contextMenuInformation.contextMenuCoordinates[0], $nodeGraph.contextMenuInformation.contextMenuCoordinates[1]);
|
||||
}
|
||||
|
||||
function nodeBorderMask(nodeWidth: number, primaryInputExists: boolean, exposedSecondaryInputs: number, primaryOutputExists: boolean, exposedSecondaryOutputs: number): string {
|
||||
|
||||
@@ -215,9 +215,9 @@
|
||||
return `${unitlessDisplayValue}${unPluralize(unit, displayValue)}`;
|
||||
}
|
||||
|
||||
// Removes the trailing "s" from a unit if the quantity is 1.
|
||||
// Removes the "s" suffix from a unit if the quantity is 1.
|
||||
function unPluralize(unit: string, quantity: number): string {
|
||||
if (quantity !== 1 || !unit.endsWith("s")) return unit;
|
||||
if (quantity !== 1 || !unit.endsWith("s") || unit.trim().length < 2) return unit;
|
||||
return unit.slice(0, -1);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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);
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { downloadFile, downloadFileBlob, upload } from "/src/utility-functions/files";
|
||||
import { rasterizeSVG } from "/src/utility-functions/rasterization";
|
||||
import { patchLayout } from "/src/utility-functions/widgets";
|
||||
import { createZipFromFiles } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { EditorWrapper, DocumentInfo, LayerPanelEntry, LayerStructureEntry, Layout, WorkspacePanelLayout } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type PortfolioStore = ReturnType<typeof createPortfolioStore>;
|
||||
@@ -129,6 +130,48 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: This handler orchestrates rasterization + zipping in JS because PNG/JPG frames arrive as SVG strings
|
||||
// TODO: that need the frontend's canvas-based `rasterizeSVG()` to encode. Once SVG rasterization moves to
|
||||
// TODO: always occur in Rust, the executor can build the .zip itself and emit a single `TriggerSaveFile`,
|
||||
// TODO: matching how PNG/JPG/SVG/.graphite single-file exports work today.
|
||||
subscriptions.subscribeFrontendMessage("TriggerExportAnimation", async (data) => {
|
||||
const { name, extension, mime, size, frames } = data;
|
||||
const isRaster = extension === "png" || extension === "jpg";
|
||||
const backgroundColor = mime.endsWith("jpeg") ? "white" : undefined;
|
||||
const padWidth = Math.max(4, String(frames.length).length);
|
||||
|
||||
// Materialize each frame to bytes, rasterizing SVG via canvas when the destination format is raster.
|
||||
// Any per-frame failure aborts the export rather than silently dropping frames, so the user never gets
|
||||
// a zip with mismatched indices vs. the requested playback range.
|
||||
const entries: [string, Uint8Array][] = [];
|
||||
try {
|
||||
for (let i = 0; i < frames.length; i++) {
|
||||
const frame = frames[i];
|
||||
const filename = `${name}_${String(i + 1).padStart(padWidth, "0")}.${extension}`;
|
||||
|
||||
let bytes: Uint8Array;
|
||||
if ("Bytes" in frame) {
|
||||
bytes = frame.Bytes;
|
||||
} else if (isRaster) {
|
||||
const blob = await rasterizeSVG(frame.Svg, size[0], size[1], mime, backgroundColor);
|
||||
bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
} else {
|
||||
bytes = new TextEncoder().encode(frame.Svg);
|
||||
}
|
||||
entries.push([filename, bytes]);
|
||||
}
|
||||
} catch (error) {
|
||||
editor.errorDialog("Animation export failed", error instanceof Error ? error.message : String(error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (entries.length === 0) return;
|
||||
|
||||
// Build the .zip in Rust (uncompressed store mode); web APIs can only deliver a single download, so the user gets one .zip
|
||||
const zipBytes = createZipFromFiles(entries);
|
||||
downloadFileBlob(`${name}.zip`, new Blob([new Uint8Array(zipBytes)], { type: "application/zip" }));
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateWorkspacePanelLayout", (data) => {
|
||||
update((state) => {
|
||||
state.panelLayout = data.panelLayout;
|
||||
@@ -196,6 +239,7 @@ export function destroyPortfolioStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSaveDocument");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSaveFile");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerExportImage");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerExportAnimation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateWorkspacePanelLayout");
|
||||
subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons");
|
||||
subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
|
||||
|
||||
@@ -17,18 +17,23 @@ export async function rasterizeSVGCanvas(svg: string, width: number, height: num
|
||||
const svgBlob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
|
||||
const url = URL.createObjectURL(svgBlob);
|
||||
|
||||
// Load the Image from the URL and wait until it's done
|
||||
// Load the Image from the URL and wait until it's done. Reject on error so callers don't hang forever
|
||||
// if the SVG fails to decode (malformed markup, zero-sized viewport with no width/height attrs, etc.).
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await new Promise<void>((resolve) => {
|
||||
image.onload = () => resolve();
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
image.onload = () => resolve();
|
||||
image.onerror = () => reject(new Error("Failed to decode SVG for rasterization"));
|
||||
});
|
||||
|
||||
// Draw our SVG to the canvas
|
||||
context?.drawImage(image, 0, 0, width, height);
|
||||
|
||||
// Clean up the SVG blob URL (once the URL is revoked, the SVG blob data itself is garbage collected after `svgBlob` goes out of scope)
|
||||
URL.revokeObjectURL(url);
|
||||
// Draw our SVG to the canvas
|
||||
context?.drawImage(image, 0, 0, width, height);
|
||||
} finally {
|
||||
// Always clean up the SVG blob URL (once the URL is revoked, the SVG blob data itself is garbage
|
||||
// collected after `svgBlob` goes out of scope), even if loading or drawing threw.
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
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 () => {};
|
||||
|
||||
@@ -39,6 +39,7 @@ web-sys = { workspace = true }
|
||||
ron = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
[package.metadata.wasm-pack.profile.dev]
|
||||
wasm-opt = false
|
||||
|
||||
@@ -9,9 +9,8 @@ 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, Error, FRONTEND_READY, MESSAGE_BUFFER};
|
||||
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER, Error, FRONTEND_READY, MESSAGE_BUFFER, PANIC_DIALOG_MESSAGE_CALLBACK};
|
||||
#[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;
|
||||
@@ -20,7 +19,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, PanelGroupId, PanelType};
|
||||
use editor::messages::portfolio::utility_types::{DockingSplitDirection, FontCatalog, FontCatalogFamily, PanelGroupId, PanelType};
|
||||
use editor::messages::prelude::*;
|
||||
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -53,10 +52,7 @@ 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() {
|
||||
@@ -73,31 +69,22 @@ impl EditorWrapper {
|
||||
// Editor wrapper machinery
|
||||
// ========================
|
||||
|
||||
#[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::*;
|
||||
#[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,
|
||||
);
|
||||
|
||||
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() {
|
||||
if EDITOR.with(|wrapper| wrapper.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() {
|
||||
log::error!("Attempted to initialize the editor more than once");
|
||||
}
|
||||
|
||||
@@ -647,6 +634,21 @@ 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) {
|
||||
@@ -972,6 +974,43 @@ impl EditorWrapper {
|
||||
// Static functions callable from JavaScript without an Editor instance
|
||||
// ====================================================================
|
||||
|
||||
/// Build an uncompressed (store-only) ZIP archive from a list of `[filename, bytes]` entries.
|
||||
///
|
||||
/// Used by the animation export flow on the web build: web APIs cannot offer a multi-file save,
|
||||
/// so the frontend packs all frames into a single `.zip` to download. On desktop, individual files
|
||||
/// are written to a user-chosen folder instead and this function is unused.
|
||||
#[wasm_bindgen(js_name = createZipFromFiles)]
|
||||
pub fn create_zip_from_files(entries: js_sys::Array) -> Result<Vec<u8>, JsValue> {
|
||||
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);
|
||||
|
||||
// Skip compression since raster/SVG payloads are already small or already compressed
|
||||
let options: SimpleFileOptions = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o644);
|
||||
|
||||
for entry in entries.iter() {
|
||||
let pair = entry
|
||||
.dyn_ref::<js_sys::Array>()
|
||||
.ok_or_else(|| JsValue::from_str("createZipFromFiles: each entry must be a [filename, bytes] array"))?;
|
||||
|
||||
let filename = pair.get(0).as_string().ok_or_else(|| JsValue::from_str("createZipFromFiles: filename must be a string"))?;
|
||||
// Defense in depth: callers should already sanitize, but if a stray path separator leaks through,
|
||||
// replace it here so the entry can't become a nested path inside the archive.
|
||||
let safe_filename: String = filename.chars().map(|c| if c == '/' || c == '\\' { '_' } else { c }).collect();
|
||||
let bytes = js_sys::Uint8Array::new(&pair.get(1)).to_vec();
|
||||
|
||||
writer
|
||||
.start_file(safe_filename, options)
|
||||
.map_err(|e| JsValue::from_str(&format!("createZipFromFiles: start_file failed: {e}")))?;
|
||||
writer.write_all(&bytes).map_err(|e| JsValue::from_str(&format!("createZipFromFiles: write_all failed: {e}")))?;
|
||||
}
|
||||
|
||||
writer.finish().map_err(|e| JsValue::from_str(&format!("createZipFromFiles: finish failed: {e}")))?;
|
||||
Ok(buffer.into_inner())
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = evaluateMathExpression)]
|
||||
pub fn evaluate_math_expression(expression: &str) -> Option<f64> {
|
||||
let value = math_parser::evaluate(expression)
|
||||
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user