Compare commits

...
Author SHA1 Message Date
Dennis Kobert 9a08514812 Align the async execution RFC with the serve substrate 2026-09-06 16:59:10 +00:00
Dennis Kobert b58d2ab470 Record the settled level and generic-name decisions 2026-09-06 16:58:15 +00:00
Dennis Kobert 2e1d9c04f7 Update the soundness section to the landed enforcement 2026-09-06 16:57:31 +00:00
Dennis Kobert 5d967a6a17 Adopt the input and source vocabulary 2026-09-06 16:57:14 +00:00
Dennis Kobert c93395bb8f Add the arena, promotion, memo, and owned crossing reference 2026-09-06 16:56:20 +00:00
Dennis Kobert d0dae48575 Rewrite the runtime representation to the landed frame model 2026-09-06 16:55:50 +00:00
Dennis Kobert 658f37874c Align rfc with implementation 2026-08-29 23:00:50 +02:00
Dennis Kobert c01fb080bf Update rfc 2026-08-28 11:22:13 +02:00
Dennis Kobert d1779e8feb Update rfc with new tuple syntax for inputs 2026-08-06 16:58:04 +02:00
Dennis Kobert fa762379e3 Align RFC summary, soundness, and rationale with the stack model 2026-08-05 23:02:38 +02:00
Dennis Kobert 18225d0c12 Move evaluation to use a stack 2026-08-05 21:04:10 +02:00
Dennis Kobert f01429ff0b Fix the record buffer liveness rule and the index accessor 2026-08-04 23:56:16 +02:00
Dennis Kobert 32068fc8f5 Remove concept of sampled nodes 2026-08-04 23:39:14 +02:00
Dennis Kobert 00e40b4f53 Add RFC for the attribute system 2026-08-04 20:47:35 +02:00
Dennis Kobert 7623b68318 Add the core execution types needed for the async refactor (#4390)
* Add the core execution types, the borrowed context, and the seeded u64 fx hasher

* Fix frame table key aliasing and arena handle offset truncation

* Drop arena entries in reverse allocation order and require Send + Sync payloads

* Draw arena generations from a global counter so foreign handles never upgrade

* Forward serialize through node wrappers and free abandoned frame table reservations

* Make arena generation exhaustion fallible with an unsafe counter rewind

* Guard the shared generation counter in tests and reject oversized batch ranges

* Park the arena during drop glue, guard filled batches, and normalize deserialized sources

* Make the sources fields private and normalize them on every mutation

* Remove the unused CtxSnapshot scope reconstruction
2026-08-04 13:14:09 +02:00
Dennis Kobert 837a374554 Async execution RFC (#4385)
* Draft async execution rfc

* Add note on async runtime <-> editor interaction

* Align async RFC runtime details with the implemented source wiring
2026-08-04 13:12:48 +02:00
Timon eb50be844b Remove now obsolete disable-registration special case from node macro (#4375) 2026-07-25 13:54:46 +00:00
Dennis Kobert 0f0f62c2e9 Enforce unwind safety on all public executor entry points (#4356) 2026-07-24 09:34:40 +00:00
Timon f5b1fee85f Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-22 09:38:07 +00:00
Timon 6f8c4b2adb Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-07-18 10:33:38 +00:00
47 changed files with 5255 additions and 1022 deletions

No files matched your search

Generated
+5 -4
View File
@@ -2312,9 +2312,9 @@ dependencies = [
"graph-craft", "graph-craft",
"graphene-std", "graphene-std",
"graphite-editor", "graphite-editor",
"graphite-wasm-wrapper",
"image", "image",
"keyboard-types", "keyboard-types",
"ron",
"serde", "serde",
"serde_json", "serde_json",
"thiserror 2.0.18", "thiserror 2.0.18",
@@ -2374,6 +2374,7 @@ dependencies = [
name = "graphite-proc-macros" name = "graphite-proc-macros"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"convert_case",
"graphite-editor", "graphite-editor",
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -2385,17 +2386,17 @@ dependencies = [
name = "graphite-wasm-wrapper" name = "graphite-wasm-wrapper"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"bytemuck",
"graph-craft", "graph-craft",
"graphene-std", "graphene-std",
"graphite-editor", "graphite-editor",
"graphite-proc-macros",
"js-sys", "js-sys",
"log", "log",
"node-macro",
"ron",
"serde", "serde",
"serde-wasm-bindgen", "serde-wasm-bindgen",
"serde_bytes",
"serde_json", "serde_json",
"tsify",
"wasm-bindgen", "wasm-bindgen",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"web-sys", "web-sys",
+1 -2
View File
@@ -14,13 +14,12 @@ use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEv
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId; use winit::window::WindowId;
use graphite_desktop_ui::{UiCommand, UiInstance};
use crate::dirs; use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler}; use crate::event::{AppEvent, AppEventScheduler};
use crate::persist; use crate::persist;
use crate::preferences; use crate::preferences;
use crate::render::{RenderError, RenderState}; use crate::render::{RenderError, RenderState};
use crate::ui::{UiCommand, UiInstance};
use crate::window::Window; use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences}; use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages}; use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
+2 -1
View File
@@ -1,9 +1,10 @@
use crate::ui::Cursor;
use crate::wrapper::NodeGraphExecutionResult; use crate::wrapper::NodeGraphExecutionResult;
use crate::wrapper::messages::DesktopWrapperMessage; use crate::wrapper::messages::DesktopWrapperMessage;
pub(crate) enum AppEvent { pub(crate) enum AppEvent {
UiUpdate(wgpu::Texture), UiUpdate(wgpu::Texture),
CursorChange(graphite_desktop_ui::Cursor), CursorChange(Cursor),
WebCommunicationInitialized, WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage), DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult), NodeGraphExecutionResult(NodeGraphExecutionResult),
+3 -2
View File
@@ -3,12 +3,13 @@ use crate::cli::Cli;
use crate::consts::APP_LOCK_FILE_NAME; use crate::consts::APP_LOCK_FILE_NAME;
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt}; use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
use clap::Parser; use clap::Parser;
use graphite_desktop_ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use std::io::Write; use std::io::Write;
use std::process::ExitCode; use std::process::ExitCode;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
pub(crate) use graphite_desktop_ui as ui;
pub(crate) use graphite_desktop_wrapper as wrapper; pub(crate) use graphite_desktop_wrapper as wrapper;
mod app; mod app;
@@ -69,7 +70,7 @@ pub fn start() -> ExitCode {
} }
}; };
dirs::clear_dir(&graphite_desktop_ui::temp_dir_root()); dirs::clear_dir(&ui::temp_dir_root());
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory // TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory(); dirs::delete_old_cef_browser_directory();
+1 -1
View File
@@ -1,8 +1,8 @@
use crate::consts::APP_NAME; use crate::consts::APP_NAME;
use crate::event::AppEventScheduler; use crate::event::AppEventScheduler;
use crate::ui::Cursor;
use crate::wrapper::messages::MenuItem; use crate::wrapper::messages::MenuItem;
use crate::wrapper::{WgpuInstance, WgpuSurface}; use crate::wrapper::{WgpuInstance, WgpuSurface};
use graphite_desktop_ui::Cursor;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use winit::cursor::{CustomCursor, CustomCursorSource}; use winit::cursor::{CustomCursor, CustomCursorSource};
+1 -1
View File
@@ -14,6 +14,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
graphite-editor = { workspace = true } graphite-editor = { workspace = true }
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
graphene-std = { workspace = true } graphene-std = { workspace = true }
graph-craft = { workspace = true } graph-craft = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
@@ -22,7 +23,6 @@ wgpu = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
dirs = { workspace = true } dirs = { workspace = true }
ron = { workspace = true}
vello = { workspace = true } vello = { workspace = true }
image = { workspace = true } image = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
+5 -14
View File
@@ -1,7 +1,9 @@
use graph_craft::application_io::PlatformApplicationIo; use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage; use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform}; use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake}; use graphite_editor::messages::frontend::FrontendMessage;
use graphite_editor::messages::prelude::Wake;
use message_dispatcher::DesktopWrapperMessageDispatcher; use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage}; use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc; use std::sync::Arc;
@@ -65,21 +67,10 @@ pub enum NodeGraphExecutionResult {
} }
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> { pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
if let Ok(string) = std::str::from_utf8(data) { let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
if let Ok(message) = ron::de::from_str::<Message>(string) {
Some(DesktopWrapperMessage::FromWeb(message.into())) Some(DesktopWrapperMessage::FromWeb(message.into()))
} else {
None
}
} else {
None
}
} }
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> { pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
if let Ok(serialized) = ron::ser::to_string(&messages) { graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
Some(serialized.into_bytes())
} else {
None
}
} }
+1 -1
View File
@@ -45,7 +45,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
} }
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?; let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
sources.sort_by(|(a, _), (b, _)| a.cmp(b)); sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| { sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW. // `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
if later_key != kept_key { if later_key != kept_key {
@@ -1,7 +1,7 @@
use super::IconName; use super::IconName;
use super::utility_types::{MouseCursorIcon, PersistedState}; use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform; 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, EyedropperPreviewImage, RasterizedImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut; use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::node_graph::utility_types::{
@@ -14,7 +14,6 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary; use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use graphene_std::vector::style::FillChoiceUI; use graphene_std::vector::style::FillChoiceUI;
use std::path::PathBuf; use std::path::PathBuf;
@@ -235,7 +234,7 @@ pub enum FrontendMessage {
svg: String, svg: String,
}, },
UpdateImageData { UpdateImageData {
image_data: Vec<(u64, Image<SRGBA8>)>, image_data: Vec<RasterizedImage>,
}, },
UpdateDocumentLayerDetails { UpdateDocumentLayerDetails {
data: LayerPanelEntry, data: LayerPanelEntry,
@@ -82,3 +82,12 @@ pub struct EyedropperPreviewImage {
pub width: u32, pub width: u32,
pub height: u32, pub height: u32,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct RasterizedImage {
pub id: u64,
pub width: u32,
pub height: u32,
pub pixels: serde_bytes::ByteBuf,
}
@@ -1,5 +1,6 @@
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup; use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoiceUI; use graphene_std::vector::style::FillChoiceUI;
@@ -291,7 +292,11 @@ impl LayoutMessageHandler {
responses.add(callback_message); responses.add(callback_message);
} }
WidgetValueAction::Update => { WidgetValueAction::Update => {
let callback_message = (node_type_input.on_update.callback)(&value.into()); let Value::String(ref node_type) = value else {
error!("NodeCatalog update was not of type: String, found {value:?}");
return;
};
let callback_message = (node_type_input.on_update.callback)(&DefinitionIdentifier::from_serialized(node_type));
responses.add(callback_message); responses.add(callback_message);
} }
}, },
@@ -23,7 +23,6 @@ use graphene_std::raster_types::{CPU, Raster};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::*; use graphene_std::*;
use serde_json::Value;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> { pub struct NodePropertiesContext<'a> {
@@ -89,12 +88,8 @@ impl DefinitionIdentifier {
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data), DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
} }
} }
}
impl From<Value> for DefinitionIdentifier {
fn from(value: Value) -> Self {
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
pub fn from_serialized(s: &str) -> Self {
match s.split_once(':') { match s.split_once(':') {
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())), Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()), Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
@@ -323,6 +323,7 @@ pub(crate) fn property_from_type(
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(), Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context), Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context), Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Ref(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
}; };
extra_widgets.push(widgets); extra_widgets.push(widgets);
@@ -2406,7 +2406,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone() && let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
&& let Some(node_definition) = resolve_document_node_type(&reference) && let Some(node_definition) = resolve_document_node_type(&reference)
{ {
let context_features = node_definition.node_template.document_node.context_features; let context_features = node_definition.node_template.document_node.context_features.clone();
document.network_interface.set_context_features(node_id, network_path, context_features); document.network_interface.set_context_features(node_id, network_path, context_features);
} }
+5 -9
View File
@@ -1,4 +1,4 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType}; use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage};
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
@@ -660,19 +660,15 @@ impl NodeGraphExecutor {
match render_output.data { match render_output.data {
RenderOutputType::Svg { svg, image_data } => { RenderOutputType::Svg { svg, image_data } => {
// Convert each linear-light `Image<Color>` into the JS-boundary `Image<SRGBA8>` form (gamma byte channels) before dispatching. // Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
let image_data = image_data let image_data = image_data
.into_iter() .into_iter()
.map(|(id, image)| { .map(|(id, image)| RasterizedImage {
(
id, id,
graphene_std::raster::Image {
width: image.width, width: image.width,
height: image.height, height: image.height,
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(), pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
base64_string: image.base64_string,
},
)
}) })
.collect(); .collect();
responses.add(FrontendMessage::UpdateImageData { image_data }); responses.add(FrontendMessage::UpdateImageData { image_data });
+1
View File
@@ -1,4 +1,5 @@
node_modules/ node_modules/
wrapper/pkg/ wrapper/pkg/
wrapper/pkg-native/
public/build/ public/build/
dist/ dist/
+1
View File
@@ -29,6 +29,7 @@ export default defineConfig([
"**/node_modules/", "**/node_modules/",
"**/dist/", "**/dist/",
"**/pkg/", "**/pkg/",
"**/pkg-native/",
"wasm/pkg/", "wasm/pkg/",
// Don't ignore JS and TS dotfiles in this folder // Don't ignore JS and TS dotfiles in this folder
"!**/.*.js", "!**/.*.js",
+4 -1
View File
@@ -23,7 +23,10 @@ export default defineConfig(({ mode }) => {
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active // Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
define: { __WASM_PART_COUNT__: "1" }, define: { __WASM_PART_COUNT__: "1" },
resolve: { resolve: {
alias: [{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") }], alias: [
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") },
],
}, },
server: { server: {
port: 8080, port: 8080,
+15 -11
View File
@@ -11,33 +11,37 @@ repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0" license = "Apache-2.0"
[features] [features]
default = ["gpu", "shader-nodes"] default = ["gpu", "shader-nodes", "web"]
gpu = ["editor/gpu"] web = ["editor", "editor?/wasm"]
shader-nodes = ["graphene-std/shader-nodes", "gpu"] editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:wgpu"]
native = ["node-macro/disable-registration"] gpu = ["editor?/gpu"]
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
native = []
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
editor = { path = "../../editor", package = "graphite-editor", features = ["gpu", "wasm"] } editor = { path = "../../editor", package = "graphite-editor", optional = true }
graphene-std = { workspace = true } graphite-proc-macros = { workspace = true }
graphene-std = { workspace = true, optional = true }
# Workspace dependencies # Workspace dependencies
bytemuck = { workspace = true } graph-craft = { workspace = true, optional = true }
graph-craft = { workspace = true }
log = { workspace = true } log = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
wasm-bindgen = { workspace = true } wasm-bindgen = { workspace = true }
serde-wasm-bindgen = { workspace = true } serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true } js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true } wasm-bindgen-futures = { workspace = true }
wgpu = { workspace = true } wgpu = { workspace = true, optional = true }
web-sys = { workspace = true } web-sys = { workspace = true }
ron = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
node-macro = { workspace = true } tsify = { workspace = true }
[dev-dependencies]
serde_bytes = { workspace = true }
[lints.rust] [lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = [ unexpected_cfgs = { level = "warn", check-cfg = [
+690
View File
@@ -0,0 +1,690 @@
//! Commands that JS can call on the editor. Each function maps its arguments to a `Message`. On web the generated
//! stub dispatches it directly, on native the arguments are sent as an `EditorCommand` and the same body runs in
//! the editor process.
#![allow(clippy::too_many_arguments)]
#[cfg(target_family = "wasm")]
use crate::editor_wrapper::EditorWrapper;
use graphite_proc_macros::editor_commands;
use serde::{Deserialize, Serialize};
use tsify::Tsify;
#[cfg(target_family = "wasm")]
use wasm_bindgen::prelude::*;
#[editor_commands]
mod editor_commands {
use crate::helpers::translate_key;
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
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::PanelGroupId;
use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
use graph_craft::document::NodeId;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::FillChoice;
use std::path::PathBuf;
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
fn resend_all_layouts() -> Message {
LayoutMessage::ResendAllLayouts.into()
}
/// First message of a session, sent once the frontend is ready
fn init_portfolio() -> Message {
PortfolioMessage::Init.into()
}
/// Per-frame tick: advances the animation clock and broadcasts the animation frame event
fn animation_frame(timestamp: u64) -> Message {
Message::Batched {
messages: Box::new([
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
AnimationMessage::IncrementFrameCounter.into(),
// Used by auto-panning, but this could possibly be refactored in the future, see:
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
]),
}
}
fn auto_save_all_documents() -> Message {
PortfolioMessage::AutoSaveAllDocuments.into()
}
fn add_primary_import() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryImport.into()]),
}
}
fn add_secondary_import() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryImport.into()]),
}
}
fn add_primary_export() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryExport.into()]),
}
}
fn add_secondary_export() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryExport.into()]),
}
}
/// Start Pointer Lock
fn app_window_pointer_lock() -> Message {
AppWindowMessage::PointerLock.into()
}
/// Minimizes the application window to the taskbar or dock
fn app_window_minimize() -> Message {
AppWindowMessage::Minimize.into()
}
/// Toggles minimizing or restoring down the application window
fn app_window_maximize() -> Message {
AppWindowMessage::Maximize.into()
}
fn app_window_fullscreen() -> Message {
AppWindowMessage::Fullscreen.into()
}
/// Closes the application window
fn app_window_close() -> Message {
AppWindowMessage::Close.into()
}
/// Drag the application window
fn app_window_drag() -> Message {
AppWindowMessage::Drag.into()
}
/// Displays a dialog with an error message
fn error_dialog(title: String, description: String) -> Message {
DialogMessage::DisplayDialogError { title, description }.into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let update = LayoutMessage::WidgetValueUpdate {
layout_target,
widget_id,
value: value.cast(),
};
if resend_widget {
Message::Batched {
messages: Box::new([update.into(), LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into()]),
}
} else {
update.into()
}
}
/// Commit the value of a given UI widget to the history
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id: WidgetId(widget_id),
value: value.cast(),
}
.into()
}
/// Update the value of a given UI widget, and commit it to the history
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let mut messages: Vec<Message> = vec![
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id,
value: value.cast(),
}
.into(),
LayoutMessage::WidgetValueUpdate {
layout_target,
widget_id,
value: value.cast(),
}
.into(),
];
if resend_widget {
messages.push(LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into());
}
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
messages.push(DocumentMessage::EndTransaction.into());
Message::Batched { messages: messages.into() }
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
let widget_id = WidgetId(widget_id);
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
}
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
fn end_transaction() -> Message {
DocumentMessage::EndTransaction.into()
}
fn load_preferences(preferences: Option<String>) -> Message {
let Some(preferences) = preferences else { return Message::NoOp };
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return Message::NoOp;
};
PreferencesMessage::Load { preferences }.into()
}
fn load_document_content(document_id: u64, document: String) -> Message {
PersistentStateMessage::LoadDocument {
document_id: DocumentId(document_id),
document,
}
.into()
}
fn select_document(document_id: u64) -> Message {
PortfolioMessage::SelectDocument { document_id: DocumentId(document_id) }.into()
}
/// Rename the currently active document.
fn rename_document(new_name: String) -> Message {
PortfolioMessage::RenameDocument { new_name }.into()
}
fn new_document_dialog() -> Message {
DialogMessage::RequestNewDocumentDialog.into()
}
fn open_file(path: String, content: Vec<u8>) -> Message {
PortfolioMessage::OpenFile { path: PathBuf::from(path), content }.into()
}
fn import_file(path: String, content: Vec<u8>) -> Message {
PortfolioMessage::ImportFile { path: PathBuf::from(path), content }.into()
}
fn trigger_auto_save(document_id: u64) -> Message {
PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into()
}
fn reorder_document(document_id: u64, new_index: usize) -> Message {
PortfolioMessage::ReorderDocument {
document_id: DocumentId(document_id),
new_index,
}
.into()
}
fn reorder_panel_group_tab(group: u64, old_index: usize, new_index: usize) -> Message {
PortfolioMessage::ReorderPanelGroupTab {
group: PanelGroupId(group),
old_index,
new_index,
}
.into()
}
fn move_all_panel_tabs(source_group: u64, target_group: u64, insert_index: usize) -> Message {
PortfolioMessage::MoveAllPanelTabs {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
}
.into()
}
fn move_panel_tab(source_group: u64, target_group: u64, insert_index: usize) -> Message {
PortfolioMessage::MovePanelTab {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
}
.into()
}
fn set_panel_group_active_tab(group: u64, tab_index: usize) -> Message {
PortfolioMessage::SetPanelGroupActiveTab {
group: PanelGroupId(group),
tab_index,
}
.into()
}
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
PortfolioMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
tabs,
active_tab_index,
}
.into()
}
fn set_panel_group_sizes(split_path: Vec<u32>, sizes: Vec<f64>) -> Message {
let split_path = split_path.into_iter().map(|i| i as usize).collect();
PortfolioMessage::SetPanelGroupSizes { split_path, sizes }.into()
}
fn close_document_with_confirmation(document_id: u64) -> Message {
PortfolioMessage::CloseDocumentWithConfirmation { document_id: DocumentId(document_id) }.into()
}
fn request_about_graphite_dialog_with_localized_commit_date(localized_commit_date: String, localized_commit_year: String) -> Message {
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
}
.into()
}
fn request_licenses_third_party_dialog_with_license_text(license_text: String) -> Message {
DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text }.into()
}
/// Send new viewport info to the backend
fn update_viewport(x: f64, y: f64, width: f64, height: f64, scale: f64) -> Message {
ViewportMessage::Update { x, y, width, height, scale }.into()
}
/// Mouse movement within the screenspace bounds of the viewport
fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }.into()
}
/// Mouse scrolling within the screenspace bounds of the viewport
fn on_wheel_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) -> Message {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button depressed within screenspace the bounds of the viewport
fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button released
fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }.into()
}
/// Mouse shaken
fn on_mouse_shake(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys }.into()
}
/// Mouse double clicked
fn on_double_click(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
}
/// A keyboard button depressed within screenspace the bounds of the viewport
fn on_key_down(name: String, modifiers: u8, key_repeat: bool) -> Message {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys }.into()
}
/// A keyboard button released
fn on_key_up(name: String, modifiers: u8, key_repeat: bool) -> Message {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys }.into()
}
/// A text box was committed
fn on_change_text(new_text: String, is_left_or_right_click: bool) -> Message {
TextToolMessage::TextChange { new_text, is_left_or_right_click }.into()
}
/// Dialog got dismissed
fn on_dialog_dismiss() -> Message {
DialogMessage::Dismiss.into()
}
/// A text box was changed
fn update_bounds(new_text: String) -> Message {
TextToolMessage::UpdateBounds { new_text }.into()
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
fn update_primary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
}
.into()
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
fn update_secondary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
}
.into()
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
fn open_color_picker(initial_value: FillChoiceUI, allow_none: bool, disabled: bool) -> Message {
ColorPickerMessage::Open {
initial_value: FillChoice::from(&initial_value),
allow_none,
disabled,
}
.into()
}
/// Tell the Rust color picker handler that the popover is closing.
fn close_color_picker() -> Message {
ColorPickerMessage::Close.into()
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
fn update_gradient_stop_color(color: SRGBA8) -> Message {
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
}
/// Start a new undo transaction for gradient stop color editing
fn start_gradient_stop_color_transaction() -> Message {
GradientToolMessage::StartTransactionForColorStop.into()
}
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
fn commit_gradient_stop_color_transaction() -> Message {
GradientToolMessage::CommitTransactionForColorStop.into()
}
/// Close the gradient stop color picker and commit any pending transaction
fn close_gradient_stop_color_picker() -> Message {
GradientToolMessage::CloseStopColorPicker.into()
}
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
fn clip_layer(id: u64) -> Message {
DocumentMessage::ClipLayer { id: NodeId(id) }.into()
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
fn select_layer(id: u64, ctrl: bool, shift: bool) -> Message {
DocumentMessage::SelectLayer { id: NodeId(id), ctrl, shift }.into()
}
/// Deselect all layers
fn deselect_all_layers() -> Message {
DocumentMessage::DeselectAllLayers.into()
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
fn move_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
}
.into()
}
/// Reorder a draggable Properties panel section to the given index among its peers.
fn reorder_properties_section(node_id: u64, insert_index: usize) -> Message {
DocumentMessage::ReorderPropertiesSection {
node_id: NodeId(node_id),
insert_index,
}
.into()
}
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
/// If the folder is `None`, they are inserted into the document root.
/// If the insert index is `None`, they are inserted at the start of the folder.
fn duplicate_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
DocumentMessage::DuplicateSelectedLayersTo {
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
insert_index: insert_index.unwrap_or_default(),
}
.into()
}
/// Set the name for the layer
fn set_layer_name(id: u64, name: String) -> Message {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
}
.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
}
fn pan_canvas_abort(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbort { x_not_y_axis }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas(delta_x: f64, delta_y: f64) -> Message {
NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_by_fraction(delta_x: f64, delta_y: f64) -> Message {
NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() }.into()
}
/// Merge the selected nodes into a subnetwork
fn merge_selected_nodes() -> Message {
NodeGraphMessage::MergeSelectedNodes.into()
}
/// Toggle lock state of all selected layers
fn toggle_selected_locked() -> Message {
NodeGraphMessage::ToggleSelectedLocked.into()
}
/// Creates a new document node in the node graph
fn create_node(node_type: String, x: i32, y: i32) -> Message {
let id = NodeId::new();
NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: DefinitionIdentifier::from_serialized(&node_type),
xy: Some((x / 24, y / 24)),
add_transaction: true,
}
.into()
}
/// Respond to selection read
fn read_selection(content: Option<String>, cut: bool) -> Message {
ClipboardMessage::ReadSelection { content, cut }.into()
}
/// Paste from a serialized JSON representation
fn paste_text(data: String) -> Message {
ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
}
.into()
}
/// Pastes an image
fn paste_image(
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) -> Message {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
PortfolioMessage::InsertImage {
name,
image,
mouse,
parent_and_insert_index,
}
.into()
}
/// Pastes an SVG given its string representation
fn paste_svg(name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
PortfolioMessage::InsertSvg {
name,
svg,
mouse,
parent_and_insert_index,
}
.into()
}
/// Toggle visibility of a layer or node given its node ID
fn toggle_node_visibility_layer_panel(id: u64) -> Message {
NodeGraphMessage::ToggleVisibility {
node_id: NodeId(id),
network_path: Vec::new(),
}
.into()
}
/// Pin or unpin a node given its node ID
fn set_node_pinned(id: u64, pinned: bool) -> Message {
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
}
/// Collapse or expand a node's section in the Properties panel
fn toggle_node_properties_section_expanded(id: u64) -> Message {
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) }.into()
}
/// Delete a layer or node given its node ID
fn delete_node(id: u64) -> Message {
DocumentMessage::DeleteNode { node_id: NodeId(id) }.into()
}
/// Toggle lock state of a layer from the layer list
fn toggle_layer_lock(node_id: u64) -> Message {
NodeGraphMessage::ToggleLocked {
node_id: NodeId(node_id),
network_path: Vec::new(),
}
.into()
}
/// Toggle expansions state of a layer from the layer list
fn toggle_layer_expansion(tree_path: Vec<u64>, recursive: bool) -> Message {
let tree_path = tree_path.into_iter().map(NodeId).collect();
DocumentMessage::ToggleLayerExpansion { tree_path, recursive }.into()
}
/// Set the active panel to the most recently clicked panel
fn set_active_panel(panel: String) -> Message {
DocumentMessage::SetActivePanel { active_panel: panel.into() }.into()
}
/// Toggle display type for a layer
fn set_to_node_or_layer(id: u64, is_layer: bool) -> Message {
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
}
/// Set the name of an import or export
fn set_import_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
}
.into()
}
/// Set the name of an export
fn set_export_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
}
.into()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct Any(#[tsify(type = "any")] serde_json::Value);
impl Any {
#[cfg(feature = "editor")]
pub(crate) fn cast<T: for<'de> Deserialize<'de>>(&self) -> T {
serde_json::from_value(self.0.clone()).unwrap()
}
}
macro_rules! editor_proxy_types {
($($name:ident = $real:ty;)*) => {
$(
#[cfg(feature = "editor")]
pub type $name = $real;
#[cfg(not(feature = "editor"))]
pub type $name = Any;
)*
};
}
editor_proxy_types! {
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
SRGBA8 = graphene_std::color::SRGBA8;
FillChoiceUI = graphene_std::vector::style::FillChoiceUI;
}
+67 -808
View File
@@ -1,44 +1,33 @@
#![allow(clippy::too_many_arguments)] //! JS-facing editor handle. Owns the callback that delivers `FrontendMessage`s to JS; on web `dispatch` runs
// //! messages through the in-process editor, on native `send` forwards them as `EditorCommand`s.
// This file is where functions are defined to be called directly from JS.
// It serves as a thin wrapper over the editor backend API that relies
// on the dispatcher messaging system and more complex Rust data types.
//
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::EDITOR; use crate::EDITOR;
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation; use crate::MESSAGE_BUFFER;
use crate::helpers::{auto_save_all_documents, calculate_hash, render_image_data_to_canvases, request_animation_frame, set_timeout, translate_key, wrapper}; #[cfg(all(feature = "native", target_family = "wasm"))]
use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER}; use crate::editor_commands::EditorCommand;
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation;
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use crate::helpers::{calculate_hash, render_image_data_to_canvases};
use crate::helpers::{request_animation_frame, set_timeout};
use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY};
#[cfg(all(not(feature = "native"), target_family = "wasm"))] #[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::application::{Editor, Environment, Host, Platform}; use editor::application::{Editor, Environment, Host, Platform};
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION}; #[cfg(feature = "editor")]
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
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::prelude::*; use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId; #[cfg(feature = "editor")]
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::graphene_hash::CacheHashWrapper;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
use serde::Serialize; use serde::Serialize;
use serde_wasm_bindgen::{self, from_value};
use std::cell::RefCell; use std::cell::RefCell;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration; use std::time::Duration;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0); pub(crate) static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
/// This struct is, via wasm-bindgen, used by JS to interact with the editor backend. It does this by calling functions, which are `impl`ed
#[wasm_bindgen] #[wasm_bindgen]
#[derive(Clone)] #[derive(Clone)]
pub struct EditorWrapper { pub struct EditorWrapper {
@@ -46,13 +35,7 @@ pub struct EditorWrapper {
frontend_message_handler_callback: js_sys::Function, frontend_message_handler_callback: js_sys::Function,
} }
// Defined separately from the `impl` block below since this `impl` block lacks the `#[wasm_bindgen]` attribute.
// Quirks in wasm-bindgen prevent functions in `#[wasm_bindgen]` `impl` blocks from being made publicly accessible from Rust.
impl EditorWrapper { impl EditorWrapper {
pub fn send_frontend_message_to_js_rust_proxy(&self, message: FrontendMessage) {
self.send_frontend_message_to_js(message);
}
#[cfg(any(feature = "native", target_family = "wasm"))] #[cfg(any(feature = "native", target_family = "wasm"))]
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper { fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK}; use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
@@ -69,10 +52,6 @@ impl EditorWrapper {
#[wasm_bindgen] #[wasm_bindgen]
impl EditorWrapper { impl EditorWrapper {
// ========================
// Editor wrapper machinery
// ========================
#[cfg(all(not(feature = "native"), target_family = "wasm"))] #[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 { 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::PlatformApplicationIo;
@@ -115,7 +94,6 @@ impl EditorWrapper {
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) { pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
// Process no further messages after a crash to avoid spamming the console // Process no further messages after a crash to avoid spamming the console
use crate::MESSAGE_BUFFER;
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) { if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return; return;
} }
@@ -137,24 +115,15 @@ impl EditorWrapper {
self.send_frontend_message_to_js(message); self.send_frontend_message_to_js(message);
} }
} }
#[cfg(feature = "native")]
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
let message: Message = message.into();
let Ok(serialized_message) = ron::to_string(&message) else {
log::error!("Failed to serialize message");
return;
};
crate::native_communication::send_message_to_cef(serialized_message)
}
// Sends a FrontendMessage to JavaScript #[cfg(feature = "editor")]
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) { pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
if let FrontendMessage::UpdateImageData { ref image_data } = message { if let FrontendMessage::UpdateImageData { ref image_data } = message {
let new_hash = calculate_hash(&CacheHashWrapper(image_data)); let new_hash = calculate_hash(image_data);
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed); let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
if new_hash != prev_hash { if new_hash != prev_hash {
render_image_data_to_canvases(image_data.as_slice()); render_image_data_to_canvases(image_data.iter());
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed); IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
} }
return; return;
@@ -172,16 +141,31 @@ impl EditorWrapper {
} }
} }
// ================================================ pub(crate) fn forward_serialized_frontend_message_to_js(&self, name: &str, data: crate::wasm_value::WasmValue) {
// Functions for calling the editor in Rust from JS let js_return_value = self.frontend_message_handler_callback.call2(&JsValue::null(), &JsValue::from(name), &data.into());
// ================================================
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state. if let Err(error) = js_return_value {
#[wasm_bindgen(js_name = resendAllLayouts)] error!("While handling FrontendMessage {name:?}, JavaScript threw an error:\n{error:?}")
pub fn resend_all_layouts(&self) { }
self.dispatch(LayoutMessage::ResendAllLayouts);
} }
#[cfg(all(feature = "native", target_family = "wasm"))]
pub(crate) fn send(&self, command: EditorCommand) {
// Process no further commands after a crash to avoid spamming the console
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
let Ok(serialized) = serde_json::to_string(&command) else {
log::error!("Failed to serialize editor command");
return;
};
crate::native_communication::send_message_to_cef(serialized)
}
}
#[wasm_bindgen]
impl EditorWrapper {
#[wasm_bindgen(js_name = initAfterFrontendReady)] #[wasm_bindgen(js_name = initAfterFrontendReady)]
pub fn init_after_frontend_ready(&self) { pub fn init_after_frontend_ready(&self) {
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice // Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice
@@ -192,7 +176,8 @@ impl EditorWrapper {
#[cfg(feature = "native")] #[cfg(feature = "native")]
crate::native_communication::initialize_native_communication(); crate::native_communication::initialize_native_communication();
self.dispatch(PortfolioMessage::Init); #[cfg(target_family = "wasm")]
self.init_portfolio();
// Poll node graph evaluation on `requestAnimationFrame` // Poll node graph evaluation on `requestAnimationFrame`
{ {
@@ -203,25 +188,19 @@ impl EditorWrapper {
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation()); wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
if !EDITOR_HAS_CRASHED.load(Ordering::SeqCst) { #[cfg(any(not(feature = "native"), target_family = "wasm"))]
wrapper(|wrapper| { wrapper(|wrapper| {
// Process all messages that have been queued up // On web, flush the messages that queued up while the editor was locked before this frame's tick
let mut messages = MESSAGE_BUFFER.take(); #[cfg(not(feature = "native"))]
messages.push( {
InputPreprocessorMessage::CurrentTime { let messages = MESSAGE_BUFFER.take();
timestamp: js_sys::Date::now() as u64, if !messages.is_empty() {
}
.into(),
);
messages.push(AnimationMessage::IncrementFrameCounter.into());
// Used by auto-panning, but this could possibly be refactored in the future, see:
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
messages.push(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into());
wrapper.dispatch(Message::Batched { messages: messages.into() }); wrapper.dispatch(Message::Batched { messages: messages.into() });
});
} }
}
#[cfg(target_family = "wasm")]
wrapper.animation_frame(js_sys::Date::now() as u64);
});
// Schedule ourself for another requestAnimationFrame callback // Schedule ourself for another requestAnimationFrame callback
request_animation_frame(f.borrow().as_ref().unwrap()); request_animation_frame(f.borrow().as_ref().unwrap());
@@ -230,94 +209,25 @@ impl EditorWrapper {
request_animation_frame(g.borrow().as_ref().unwrap()); request_animation_frame(g.borrow().as_ref().unwrap());
} }
const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
// Auto save all documents on `setTimeout` // Auto save all documents on `setTimeout`
{ {
let f = std::rc::Rc::new(RefCell::new(None)); let f = std::rc::Rc::new(RefCell::new(None));
let g = f.clone(); let g = f.clone();
*g.borrow_mut() = Some(Closure::new(move || { *g.borrow_mut() = Some(Closure::new(move || {
auto_save_all_documents(); #[cfg(target_family = "wasm")]
wrapper(|wrapper| wrapper.auto_save_all_documents());
// Schedule ourself for another setTimeout callback // Schedule ourself for another setTimeout callback
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS)); set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
})); }));
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS)); set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
} }
} }
#[wasm_bindgen(js_name = addPrimaryImport)]
pub fn add_primary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryImport);
}
#[wasm_bindgen(js_name = addSecondaryImport)]
pub fn add_secondary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryImport);
}
#[wasm_bindgen(js_name = addPrimaryExport)]
pub fn add_primary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryExport);
}
#[wasm_bindgen(js_name = addSecondaryExport)]
pub fn add_secondary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryExport);
}
/// Start Pointer Lock
#[wasm_bindgen(js_name = appWindowPointerLock)]
pub fn app_window_pointer_lock(&self) {
let message = AppWindowMessage::PointerLock;
self.dispatch(message);
}
/// Minimizes the application window to the taskbar or dock
#[wasm_bindgen(js_name = appWindowMinimize)]
pub fn app_window_minimize(&self) {
let message = AppWindowMessage::Minimize;
self.dispatch(message);
}
/// Toggles minimizing or restoring down the application window
#[wasm_bindgen(js_name = appWindowMaximize)]
pub fn app_window_maximize(&self) {
let message = AppWindowMessage::Maximize;
self.dispatch(message);
}
#[wasm_bindgen(js_name = appWindowFullscreen)]
pub fn app_window_fullscreen(&self) {
let message = AppWindowMessage::Fullscreen;
self.dispatch(message);
}
/// Closes the application window
#[wasm_bindgen(js_name = appWindowClose)]
pub fn app_window_close(&self) {
let message = AppWindowMessage::Close;
self.dispatch(message);
}
/// Drag the application window
#[wasm_bindgen(js_name = appWindowDrag)]
pub fn app_window_start_drag(&self) {
let message = AppWindowMessage::Drag;
self.dispatch(message);
}
/// Displays a dialog with an error message
#[wasm_bindgen(js_name = errorDialog)]
pub fn error_dialog(&self, title: String, description: String) {
let message = DialogMessage::DisplayDialogError { title, description };
self.dispatch(message);
}
/// Answer whether or not the editor has crashed /// Answer whether or not the editor has crashed
#[wasm_bindgen(js_name = hasCrashed)] #[wasm_bindgen(js_name = hasCrashed)]
pub fn has_crashed(&self) -> bool { pub fn has_crashed(&self) -> bool {
@@ -330,676 +240,25 @@ impl EditorWrapper {
cfg!(debug_assertions) cfg!(debug_assertions)
} }
/// Get the constant `FILE_EXTENSION`
#[wasm_bindgen(js_name = fileExtension)] #[wasm_bindgen(js_name = fileExtension)]
pub fn file_extension(&self) -> String { pub fn file_extension(&self) -> String {
FILE_EXTENSION.into() "graphite".into()
} }
/// Get the constant `GDD_FILE_EXTENSION`
#[wasm_bindgen(js_name = gddFileExtension)] #[wasm_bindgen(js_name = gddFileExtension)]
pub fn gdd_file_extension(&self) -> String { pub fn gdd_file_extension(&self) -> String {
GDD_FILE_EXTENSION.into() "gdd".into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
#[wasm_bindgen(js_name = widgetValueUpdate)]
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
}
/// Commit the value of a given UI widget to the history
#[wasm_bindgen(js_name = widgetValueCommit)]
pub fn widget_value_commit(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value)
}
/// Update the value of a given UI widget, and commit it to the history
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
pub fn widget_value_commit_and_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value.clone())?;
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
self.dispatch(DocumentMessage::EndTransaction);
Ok(())
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
#[wasm_bindgen(js_name = widgetValueDragDrop)]
pub fn widget_value_drag_drop(&self, layout_target: LayoutTarget, widget_id: u64) {
let widget_id = WidgetId(widget_id);
self.dispatch(LayoutMessage::WidgetValueDragDrop { layout_target, widget_id });
}
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
#[wasm_bindgen(js_name = endTransaction)]
pub fn end_transaction(&self) {
self.dispatch(DocumentMessage::EndTransaction);
}
pub fn widget_value_update_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not update UI: {e}")))?;
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
self.dispatch(message);
if resend_widget {
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
self.dispatch(resend_message);
}
Ok(())
}
pub fn widget_value_commit_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not commit UI: {e}")))?;
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
self.dispatch(message);
Ok(())
}
#[wasm_bindgen(js_name = loadPreferences)]
pub fn load_preferences(&self, preferences: Option<String>) {
if let Some(preferences) = preferences {
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return;
};
let message = PreferencesMessage::Load { preferences };
self.dispatch(message);
}
} }
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
#[cfg(all(feature = "web", not(feature = "native")))]
#[wasm_bindgen(js_name = loadPersistedState)] #[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) { pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
self.dispatch(PersistentStateMessage::LoadState { state }); self.dispatch(PersistentStateMessage::LoadState { state });
} }
#[cfg(feature = "native")]
#[wasm_bindgen(js_name = loadDocumentContent)] #[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_document_content(&self, document_id: u64, document: String) { pub fn load_persisted_state(&self, _state: JsValue) {
let message = PersistentStateMessage::LoadDocument { log::error!("loadPersistedState is unavailable on desktop; persistence is handled natively");
document_id: DocumentId(document_id),
document,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = selectDocument)]
pub fn select_document(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::SelectDocument { document_id };
self.dispatch(message);
}
/// Rename the currently active document.
#[wasm_bindgen(js_name = renameDocument)]
pub fn rename_document(&self, new_name: String) {
let message = PortfolioMessage::RenameDocument { new_name };
self.dispatch(message);
}
#[wasm_bindgen(js_name = newDocumentDialog)]
pub fn new_document_dialog(&self) {
let message = DialogMessage::RequestNewDocumentDialog;
self.dispatch(message);
}
#[wasm_bindgen(js_name = openFile)]
pub fn open_file(&self, path: String, content: Vec<u8>) {
let message = PortfolioMessage::OpenFile { path: PathBuf::from(path), content };
self.dispatch(message);
}
#[wasm_bindgen(js_name = importFile)]
pub fn import_file(&self, path: String, content: Vec<u8>) {
let message = PortfolioMessage::ImportFile { path: PathBuf::from(path), content };
self.dispatch(message);
}
#[wasm_bindgen(js_name = triggerAutoSave)]
pub fn trigger_auto_save(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::AutoSaveDocument { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = reorderDocument)]
pub fn reorder_document(&self, document_id: u64, new_index: usize) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::ReorderDocument { document_id, new_index };
self.dispatch(message);
}
#[wasm_bindgen(js_name = reorderPanelGroupTab)]
pub fn reorder_panel_group_tab(&self, group: u64, old_index: usize, new_index: usize) {
let message = PortfolioMessage::ReorderPanelGroupTab {
group: PanelGroupId(group),
old_index,
new_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = moveAllPanelTabs)]
pub fn move_all_panel_tabs(&self, source_group: u64, target_group: u64, insert_index: usize) {
let message = PortfolioMessage::MoveAllPanelTabs {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = movePanelTab)]
pub fn move_panel_tab(&self, source_group: u64, target_group: u64, insert_index: usize) {
let message = PortfolioMessage::MovePanelTab {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = setPanelGroupActiveTab)]
pub fn set_panel_group_active_tab(&self, group: u64, tab_index: usize) {
let message = PortfolioMessage::SetPanelGroupActiveTab {
group: PanelGroupId(group),
tab_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = splitPanelGroup)]
pub fn split_panel_group(&self, target_group: u64, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) {
let message = PortfolioMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
tabs,
active_tab_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = setPanelGroupSizes)]
pub fn set_panel_group_sizes(&self, split_path: Vec<u32>, sizes: Vec<f64>) {
let split_path = split_path.into_iter().map(|i| i as usize).collect();
let message = PortfolioMessage::SetPanelGroupSizes { split_path, sizes };
self.dispatch(message);
}
#[wasm_bindgen(js_name = closeDocumentWithConfirmation)]
pub fn close_document_with_confirmation(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::CloseDocumentWithConfirmation { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestAboutGraphiteDialogWithLocalizedCommitDate)]
pub fn request_about_graphite_dialog_with_localized_commit_date(&self, localized_commit_date: String, localized_commit_year: String) {
let message = DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestLicensesThirdPartyDialogWithLicenseText)]
pub fn request_licenses_third_party_dialog_with_license_text(&self, license_text: String) {
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text };
self.dispatch(message);
}
/// Send new viewport info to the backend
#[wasm_bindgen(js_name = updateViewport)]
pub fn update_viewport(&self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
let message = ViewportMessage::Update { x, y, width, height, scale };
self.dispatch(message);
}
/// Mouse movement within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onMouseMove)]
pub fn on_mouse_move(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse scrolling within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onWheelScroll)]
pub fn on_wheel_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onMouseDown)]
pub fn on_mouse_down(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button released
#[wasm_bindgen(js_name = onMouseUp)]
pub fn on_mouse_up(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse shaken
#[wasm_bindgen(js_name = onMouseShake)]
pub fn on_mouse_shake(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse double clicked
#[wasm_bindgen(js_name = onDoubleClick)]
pub fn on_double_click(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A keyboard button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onKeyDown)]
pub fn on_key_down(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A keyboard button released
#[wasm_bindgen(js_name = onKeyUp)]
pub fn on_key_up(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A text box was committed
#[wasm_bindgen(js_name = onChangeText)]
pub fn on_change_text(&self, new_text: String, is_left_or_right_click: bool) -> Result<(), JsValue> {
let message = TextToolMessage::TextChange { new_text, is_left_or_right_click };
self.dispatch(message);
Ok(())
}
/// Dialog got dismissed
#[wasm_bindgen(js_name = onDialogDismiss)]
pub fn on_dialog_dismiss(&self) {
let message = DialogMessage::Dismiss;
self.dispatch(message);
}
/// A text box was changed
#[wasm_bindgen(js_name = updateBounds)]
pub fn update_bounds(&self, new_text: String) -> Result<(), JsValue> {
let message = TextToolMessage::UpdateBounds { new_text };
self.dispatch(message);
Ok(())
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updatePrimaryColor)]
pub fn update_primary_color(&self, color: SRGBA8) {
self.dispatch(ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
});
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updateSecondaryColor)]
pub fn update_secondary_color(&self, color: SRGBA8) {
self.dispatch(ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
});
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
#[wasm_bindgen(js_name = openColorPicker)]
pub fn open_color_picker(&self, initial_value: FillChoiceUI, allow_none: bool, disabled: bool) {
let initial_value = FillChoice::from(&initial_value);
self.dispatch(ColorPickerMessage::Open { initial_value, allow_none, disabled });
}
/// Tell the Rust color picker handler that the popover is closing.
#[wasm_bindgen(js_name = closeColorPicker)]
pub fn close_color_picker(&self) {
self.dispatch(ColorPickerMessage::Close);
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updateGradientStopColor)]
pub fn update_gradient_stop_color(&self, color: SRGBA8) {
self.dispatch(GradientToolMessage::UpdateStopColor { color: Color::from(color) });
}
/// Start a new undo transaction for gradient stop color editing
#[wasm_bindgen(js_name = startGradientStopColorTransaction)]
pub fn start_gradient_stop_color_transaction(&self) {
self.dispatch(GradientToolMessage::StartTransactionForColorStop);
}
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
#[wasm_bindgen(js_name = commitGradientStopColorTransaction)]
pub fn commit_gradient_stop_color_transaction(&self) {
self.dispatch(GradientToolMessage::CommitTransactionForColorStop);
}
/// Close the gradient stop color picker and commit any pending transaction
#[wasm_bindgen(js_name = closeGradientStopColorPicker)]
pub fn close_gradient_stop_color_picker(&self) {
self.dispatch(GradientToolMessage::CloseStopColorPicker);
}
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
#[wasm_bindgen(js_name = clipLayer)]
pub fn clip_layer(&self, id: u64) {
let id = NodeId(id);
let message = DocumentMessage::ClipLayer { id };
self.dispatch(message);
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
#[wasm_bindgen(js_name = selectLayer)]
pub fn select_layer(&self, id: u64, ctrl: bool, shift: bool) {
let id = NodeId(id);
let message = DocumentMessage::SelectLayer { id, ctrl, shift };
self.dispatch(message);
}
/// Deselect all layers
#[wasm_bindgen(js_name = deselectAllLayers)]
pub fn deselect_all_layers(&self) {
let message = DocumentMessage::DeselectAllLayers;
self.dispatch(message);
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
#[wasm_bindgen(js_name = moveLayerInTree)]
pub fn move_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
let message = DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Reorder a draggable Properties panel section to the given index among its peers.
#[wasm_bindgen(js_name = reorderPropertiesSection)]
pub fn reorder_properties_section(&self, node_id: u64, insert_index: usize) {
self.dispatch(DocumentMessage::ReorderPropertiesSection {
node_id: NodeId(node_id),
insert_index,
});
}
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
/// If the folder is `None`, they are inserted into the document root.
/// If the insert index is `None`, they are inserted at the start of the folder.
#[wasm_bindgen(js_name = duplicateLayerInTree)]
pub fn duplicate_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let message = DocumentMessage::DuplicateSelectedLayersTo {
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Set the name for the layer
#[wasm_bindgen(js_name = setLayerName)]
pub fn set_layer_name(&self, id: u64, name: String) {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
let message = NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
};
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasAbortPrepare)]
pub fn pan_canvas_abort_prepare(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis };
self.dispatch(message);
}
#[wasm_bindgen(js_name = panCanvasAbort)]
pub fn pan_canvas_abort(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbort { x_not_y_axis };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvas)]
pub fn pan_canvas(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasByFraction)]
pub fn pan_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Merge the selected nodes into a subnetwork
#[wasm_bindgen(js_name = mergeSelectedNodes)]
pub fn merge_nodes(&self) {
let message = NodeGraphMessage::MergeSelectedNodes;
self.dispatch(message);
}
/// Toggle lock state of all selected layers
#[wasm_bindgen(js_name = toggleSelectedLocked)]
pub fn toggle_selected_locked(&self) {
let message = NodeGraphMessage::ToggleSelectedLocked;
self.dispatch(message);
}
/// Creates a new document node in the node graph
#[wasm_bindgen(js_name = createNode)]
pub fn create_node(&self, node_type: JsValue, x: i32, y: i32) {
let value: serde_json::Value = serde_wasm_bindgen::from_value(node_type).unwrap();
let id = NodeId::new();
let message = NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: value.into(),
xy: Some((x / 24, y / 24)),
add_transaction: true,
};
self.dispatch(message);
}
/// Respond to selection read
#[wasm_bindgen(js_name = readSelection)]
pub fn read_selection(&self, content: Option<String>, cut: bool) {
let message = ClipboardMessage::ReadSelection { content, cut };
self.dispatch(message);
}
/// Paste from a serialized JSON representation
#[wasm_bindgen(js_name = pasteText)]
pub fn paste_text(&self, data: String) {
let message = ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
};
self.dispatch(message);
}
/// Pastes an image
#[wasm_bindgen(js_name = pasteImage)]
pub fn paste_image(
&self,
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::InsertImage {
name,
image,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Pastes an SVG given its string representation
#[wasm_bindgen(js_name = pasteSvg)]
pub fn paste_svg(&self, name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::InsertSvg {
name,
svg,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Toggle visibility of a layer or node given its node ID
#[wasm_bindgen(js_name = toggleNodeVisibilityLayerPanel)]
pub fn toggle_node_visibility_layer(&self, id: u64) {
let node_id = NodeId(id);
let message = NodeGraphMessage::ToggleVisibility { node_id, network_path: Vec::new() };
self.dispatch(message);
}
/// Pin or unpin a node given its node ID
#[wasm_bindgen(js_name = setNodePinned)]
pub fn set_node_pinned(&self, id: u64, pinned: bool) {
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
}
/// Collapse or expand a node's section in the Properties panel
#[wasm_bindgen(js_name = toggleNodePropertiesSectionExpanded)]
pub fn toggle_node_properties_section_expanded(&self, id: u64) {
self.dispatch(DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) });
}
/// Delete a layer or node given its node ID
#[wasm_bindgen(js_name = deleteNode)]
pub fn delete_node(&self, id: u64) {
self.dispatch(DocumentMessage::DeleteNode { node_id: NodeId(id) });
}
/// Toggle lock state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerLock)]
pub fn toggle_layer_lock(&self, node_id: u64) {
let message = NodeGraphMessage::ToggleLocked {
node_id: NodeId(node_id),
network_path: Vec::new(),
};
self.dispatch(message);
}
/// Toggle expansions state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerExpansion)]
pub fn toggle_layer_expansion(&self, tree_path: &[u64], recursive: bool) {
let tree_path = tree_path.iter().map(|&id| NodeId(id)).collect();
let message = DocumentMessage::ToggleLayerExpansion { tree_path, recursive };
self.dispatch(message);
}
/// Set the active panel to the most recently clicked panel
#[wasm_bindgen(js_name = setActivePanel)]
pub fn set_active_panel(&self, panel: String) {
let message = DocumentMessage::SetActivePanel { active_panel: panel.into() };
self.dispatch(message);
}
/// Toggle display type for a layer
#[wasm_bindgen(js_name = setToNodeOrLayer)]
pub fn set_to_node_or_layer(&self, id: u64, is_layer: bool) {
self.dispatch(DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer });
}
/// Set the name of an import or export
#[wasm_bindgen(js_name = setImportName)]
pub fn set_import_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
};
self.dispatch(message);
}
/// Set the name of an export
#[wasm_bindgen(js_name = setExportName)]
pub fn set_export_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
};
self.dispatch(message);
} }
} }
+18 -23
View File
@@ -1,14 +1,18 @@
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::EDITOR; use crate::EDITOR;
#[cfg(not(feature = "native"))]
use crate::EDITOR_HAS_CRASHED;
use crate::EDITOR_WRAPPER;
use crate::editor_wrapper::EditorWrapper; use crate::editor_wrapper::EditorWrapper;
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER}; use crate::native_communication::RasterizedImage;
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use editor::application::Editor; use editor::application::Editor;
#[cfg(feature = "editor")]
use editor::messages::input_mapper::utility_types::input_keyboard::Key; use editor::messages::input_mapper::utility_types::input_keyboard::Key;
#[cfg(not(feature = "native"))]
use editor::messages::prelude::*; use editor::messages::prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use js_sys::{Object, Reflect}; use js_sys::{Object, Reflect};
#[cfg(not(feature = "native"))]
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::time::Duration; use std::time::Duration;
use wasm_bindgen::JsCast; use wasm_bindgen::JsCast;
@@ -119,18 +123,8 @@ pub(crate) fn async_wake_callback() -> Wake {
}) })
} }
pub(crate) fn auto_save_all_documents() { /// Blits each rasterized image to a canvas registered on `window.imageCanvases`
// Process no further messages after a crash to avoid spamming the console pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<Item = &'a RasterizedImage>) {
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
wrapper(|wrapper| {
wrapper.dispatch(PortfolioMessage::AutoSaveAllDocuments);
});
}
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)]) {
let window = match window() { let window = match window() {
Some(window) => window, Some(window) => window,
None => { None => {
@@ -155,11 +149,13 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
}; };
let canvases_obj = Object::from(canvases_obj); let canvases_obj = Object::from(canvases_obj);
for (placeholder_id, image) in image_data.iter() { for image in image_data {
let (placeholder_id, width, height) = (image.id, image.width, image.height);
let pixels = image.pixels.as_slice();
let canvas_name = placeholder_id.to_string(); let canvas_name = placeholder_id.to_string();
let js_key = JsValue::from_str(&canvas_name); let js_key = JsValue::from_str(&canvas_name);
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || image.width == 0 || image.height == 0 { if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || width == 0 || height == 0 {
continue; continue;
} }
@@ -169,8 +165,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
.dyn_into::<HtmlCanvasElement>() .dyn_into::<HtmlCanvasElement>()
.expect("Failed to cast element to HtmlCanvasElement"); .expect("Failed to cast element to HtmlCanvasElement");
canvas.set_width(image.width); canvas.set_width(width);
canvas.set_height(image.height); canvas.set_height(height);
let context: CanvasRenderingContext2d = canvas let context: CanvasRenderingContext2d = canvas
.get_context("2d") .get_context("2d")
@@ -178,10 +174,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
.expect("2d context was not found") .expect("2d context was not found")
.dyn_into::<CanvasRenderingContext2d>() .dyn_into::<CanvasRenderingContext2d>()
.expect("Failed to cast context to CanvasRenderingContext2d"); .expect("Failed to cast context to CanvasRenderingContext2d");
// `SRGBA8` is `#[repr(C)]` of four `u8`s, so the data buffer is already the byte format the canvas expects let clamped_pixels = wasm_bindgen::Clamped(pixels);
let u8_data: &[u8] = bytemuck::cast_slice(&image.data); match ImageData::new_with_u8_clamped_array_and_sh(clamped_pixels, width, height) {
let clamped_u8_data = wasm_bindgen::Clamped(u8_data);
match ImageData::new_with_u8_clamped_array_and_sh(clamped_u8_data, image.width, image.height) {
Ok(image_data_obj) => { Ok(image_data_obj) => {
if context.put_image_data(&image_data_obj, 0, 0).is_err() { if context.put_image_data(&image_data_obj, 0, 0).is_err() {
error!("Failed to put image data on canvas for id: {placeholder_id}"); error!("Failed to put image data on canvas for id: {placeholder_id}");
@@ -209,6 +203,7 @@ pub(crate) fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
} }
/// Translate a keyboard key from its JS name to its Rust `Key` enum /// Translate a keyboard key from its JS name to its Rust `Key` enum
#[cfg(feature = "editor")]
pub(crate) fn translate_key(name: &str) -> Key { pub(crate) fn translate_key(name: &str) -> Key {
use Key::*; use Key::*;
+46 -16
View File
@@ -4,11 +4,18 @@
#[macro_use] #[macro_use]
extern crate log; extern crate log;
pub mod editor_commands;
pub mod editor_wrapper; pub mod editor_wrapper;
pub mod helpers; pub mod helpers;
pub mod native_communication; pub mod native_communication;
mod wasm_value;
#[cfg(any(feature = "native", not(target_family = "wasm")))]
pub use editor_commands::EditorCommand;
#[cfg(feature = "editor")]
use crate::helpers::wrapper; use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use editor::messages::prelude::*; use editor::messages::prelude::*;
use std::panic; use std::panic;
use std::sync::Mutex; use std::sync::Mutex;
@@ -24,6 +31,7 @@ pub static LOGGER: WasmLog = WasmLog;
thread_local! { thread_local! {
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) }; pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
#[cfg(not(feature = "native"))]
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) }; pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) }; pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) };
pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) }; pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) };
@@ -43,6 +51,10 @@ pub fn init_graphite() {
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies /// When a panic occurs, notify the user and log the error to the JS console before the backend dies
pub fn panic_hook(info: &panic::PanicHookInfo) { pub fn panic_hook(info: &panic::PanicHookInfo) {
let info = info.to_string(); let info = info.to_string();
// Node graph panics can only originate here when the node graph runs inside this wasm module
#[cfg(feature = "editor")]
{
let backtrace = Error::new("stack").stack().to_string(); let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") { if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}"); log::error!("Node graph evaluation panicked {info}");
@@ -64,14 +76,15 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
/text>"# /text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed. // It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string(); .to_string();
wrapper.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error }); wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error });
}); });
} }
return; return;
} else {
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
} }
}
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
log::error!("{info}"); log::error!("{info}");
@@ -82,30 +95,20 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
} }
fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> { fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> {
let message = FrontendMessage::DisplayDialogPanic { panic_info }; let message = PanicDialogMessage::DisplayDialogPanic { panic_info: panic_info.clone() };
let message_type = message.to_discriminant().local_name();
let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else { let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else {
log::error!("Failed to serialize crash dialog panic message"); log::error!("Failed to serialize crash dialog panic message");
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info); return Err(panic_info);
}; };
PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| { PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| {
let callback_ref = callback.borrow(); let callback_ref = callback.borrow();
let Some(callback) = callback_ref.as_ref() else { let Some(callback) = callback_ref.as_ref() else {
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info); return Err(panic_info);
}; };
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from(message_type), &message_data) { if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from("DisplayDialogPanic"), &message_data) {
log::error!("Failed to send crash dialog panic message to JS: {:?}", error); log::error!("Failed to send crash dialog panic message to JS: {error:?}");
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info); return Err(panic_info);
} }
@@ -201,3 +204,30 @@ impl log::Log for WasmLog {
fn flush(&self) {} fn flush(&self) {}
} }
#[cfg(feature = "editor")]
use editor::messages::prelude::FrontendMessage as PanicDialogMessage;
#[cfg(not(feature = "editor"))]
use PanicDialogMessageCopy as PanicDialogMessage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Serialize)]
enum PanicDialogMessageCopy {
DisplayDialogPanic {
#[serde(rename = "panicInfo")]
panic_info: String,
},
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
#[test]
fn panic_dialog_copy_matches_editor_shape() {
let copy = serde_json::to_value(PanicDialogMessageCopy::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
let real = serde_json::to_value(FrontendMessage::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
assert_eq!(copy, real);
}
}
+96 -9
View File
@@ -1,25 +1,77 @@
use crate::editor_wrapper::EditorWrapper; //! Messaging with the native process. Serialized `FrontendMessage`s come in and are forwarded to JS,
use crate::helpers::wrapper; //! `EditorCommand`s go back out. Encoding and decoding both live here so the wire format stays in one place.
use editor::messages::prelude::FrontendMessage;
use crate::editor_wrapper::{EditorWrapper, IMAGE_DATA_HASH};
use crate::helpers::{calculate_hash, render_image_data_to_canvases, wrapper};
use crate::wasm_value::WasmValue;
use js_sys::{ArrayBuffer, Uint8Array}; use js_sys::{ArrayBuffer, Uint8Array};
use std::sync::atomic::Ordering;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
#[wasm_bindgen(js_name = "receiveNativeMessage")] #[wasm_bindgen(js_name = "receiveNativeMessage")]
pub fn receive_native_message(buffer: ArrayBuffer) { pub fn receive_native_message(buffer: ArrayBuffer) {
let buffer = Uint8Array::new(buffer.as_ref()).to_vec(); let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
match ron::from_str::<Vec<FrontendMessage>>(str::from_utf8(buffer.as_slice()).unwrap()) { match serde_json::from_slice::<Vec<(String, String)>>(&buffer) {
Ok(messages) => { Ok(messages) => {
let callback = move |wrapper: &mut EditorWrapper| { wrapper(move |wrapper: &mut EditorWrapper| {
for message in messages { for (name, data) in messages {
wrapper.send_frontend_message_to_js_rust_proxy(message); match name.as_str() {
"UpdateImageData" => {
let new_hash = calculate_hash(&data);
if IMAGE_DATA_HASH.swap(new_hash, Ordering::Relaxed) == new_hash {
continue;
} }
};
wrapper(callback); match serde_json::from_str::<Vec<RasterizedImage>>(&data) {
Ok(image_data) => render_image_data_to_canvases(image_data.iter()),
Err(e) => error!("Failed to deserialize image data: {e:?}"),
}
}
_ => match serde_json::from_str::<WasmValue>(&data) {
Ok(value) => wrapper.forward_serialized_frontend_message_to_js(&name, value),
Err(e) => log::error!("Failed to deserialize frontend message {name}: {e:?}"),
},
}
}
});
} }
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"), Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
} }
} }
#[cfg(feature = "editor")]
pub fn encode_frontend_messages(messages: Vec<editor::messages::prelude::FrontendMessage>) -> Option<Vec<u8>> {
use editor::messages::prelude::FrontendMessage;
use editor::utility_traits::{AsMessage, ToDiscriminant};
let messages: Vec<(String, String)> = messages
.into_iter()
.map(|message| {
let name = message.to_discriminant().local_name();
let data = match message {
FrontendMessage::UpdateImageData { image_data } => serde_json::to_string(&image_data).inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}")).ok()?,
message => crate::wasm_value::encode(&message)
.inspect_err(|e| log::error!("Failed to serialize FrontendMessage {name}: {e}"))
.ok()?,
};
Some((name, data))
})
.collect::<Option<_>>()?;
serde_json::to_vec(&messages).ok()
}
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
pub fn decode_editor_command(data: &[u8]) -> Option<editor::messages::prelude::Message> {
match serde_json::from_slice::<crate::EditorCommand>(data) {
Ok(command) => Some(command.into()),
Err(e) => {
log::error!("Failed to deserialize editor command: {e}");
None
}
}
}
pub fn initialize_native_communication() { pub fn initialize_native_communication() {
let global = js_sys::global(); let global = js_sys::global();
@@ -44,3 +96,38 @@ pub fn send_message_to_cef(message: String) {
// Call it with argument // Call it with argument
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed"); func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
} }
#[cfg(feature = "editor")]
pub(crate) use editor::messages::frontend::utility_types::RasterizedImage;
#[cfg(not(feature = "editor"))]
pub(crate) use RasterizedImageCopy as RasterizedImage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Deserialize)]
pub(crate) struct RasterizedImageCopy {
pub(crate) id: u64,
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) pixels: Vec<u8>,
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
#[test]
fn rasterized_image_copy_matches_editor_shape() {
let editor_image = RasterizedImage {
id: 7,
width: 2,
height: 1,
pixels: serde_bytes::ByteBuf::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
};
let json = serde_json::to_string(&vec![editor_image]).unwrap();
let decoded: Vec<RasterizedImageCopy> = serde_json::from_str(&json).unwrap();
assert_eq!(decoded[0].id, 7);
assert_eq!((decoded[0].width, decoded[0].height), (2, 1));
assert_eq!(decoded[0].pixels, [1, 2, 3, 4, 5, 6, 7, 8]);
}
}
+448
View File
@@ -0,0 +1,448 @@
//! Serializable stand-in for `JsValue`, used to send `FrontendMessage`s from the native editor process to JS.
//! Keeps the types JSON can't represent (`BigInt`, `Uint8Array`, `Map`, `undefined`, `NaN`) so the wasm side
//! can reconstruct the same `JsValue`s that `serde_wasm_bindgen` produces on web.
use serde::{Deserialize, Serialize};
#[cfg(feature = "editor")]
use serde_json::Error;
use wasm_bindgen::JsValue;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) enum WasmValue {
Undefined,
Bool(bool),
Number(f64),
NonFinite(NonFinite),
Int(i64),
UInt(u64),
String(String),
Bytes(Vec<u8>),
Seq(Vec<WasmValue>),
Object(Vec<(String, WasmValue)>),
Map(Vec<(WasmValue, WasmValue)>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum NonFinite {
Nan,
PositiveInfinity,
NegativeInfinity,
}
impl From<NonFinite> for f64 {
fn from(value: NonFinite) -> Self {
match value {
NonFinite::Nan => f64::NAN,
NonFinite::PositiveInfinity => f64::INFINITY,
NonFinite::NegativeInfinity => f64::NEG_INFINITY,
}
}
}
impl From<WasmValue> for JsValue {
fn from(value: WasmValue) -> Self {
match value {
WasmValue::Undefined => JsValue::UNDEFINED,
WasmValue::Bool(value) => JsValue::from_bool(value),
WasmValue::Number(value) => JsValue::from_f64(value),
WasmValue::NonFinite(value) => JsValue::from_f64(value.into()),
WasmValue::Int(value) => JsValue::from(value),
WasmValue::UInt(value) => JsValue::from(value),
WasmValue::String(value) => JsValue::from_str(&value),
WasmValue::Bytes(bytes) => js_sys::Uint8Array::from(bytes.as_slice()).into(),
WasmValue::Seq(values) => {
let array = js_sys::Array::new();
for value in values {
array.push(&value.into());
}
array.into()
}
WasmValue::Object(fields) => {
let object = js_sys::Object::new();
for (key, value) in fields {
let _ = js_sys::Reflect::set(&object, &JsValue::from_str(&key), &value.into());
}
object.into()
}
WasmValue::Map(entries) => {
let map = js_sys::Map::new();
for (key, value) in entries {
map.set(&key.into(), &value.into());
}
map.into()
}
}
}
}
#[cfg(feature = "editor")]
pub(crate) fn encode<T: Serialize + ?Sized>(value: &T) -> Result<String, serde_json::Error> {
serde_json::to_string(&ser::to_value(value)?)
}
#[cfg(feature = "editor")]
mod ser {
use super::*;
use serde::ser::{self, Error as _};
pub(super) fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<WasmValue, Error> {
value.serialize(ValueSerializer)
}
struct ValueSerializer;
impl ser::Serializer for ValueSerializer {
type Ok = WasmValue;
type Error = Error;
type SerializeSeq = SeqSerializer;
type SerializeTuple = SeqSerializer;
type SerializeTupleStruct = SeqSerializer;
type SerializeTupleVariant = VariantSeqSerializer;
type SerializeMap = MapSerializer;
type SerializeStruct = ObjectSerializer;
type SerializeStructVariant = VariantObjectSerializer;
fn serialize_bool(self, v: bool) -> Result<WasmValue, Error> {
Ok(WasmValue::Bool(v))
}
fn serialize_i8(self, v: i8) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i16(self, v: i16) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i32(self, v: i32) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i64(self, v: i64) -> Result<WasmValue, Error> {
Ok(WasmValue::Int(v))
}
fn serialize_i128(self, v: i128) -> Result<WasmValue, Error> {
if let Ok(v) = i64::try_from(v) {
Ok(WasmValue::Int(v))
} else {
u64::try_from(v)
.map(WasmValue::UInt)
.map_err(|_| Error::custom(format!("i128 value {v} exceeds the wire BigInt range")))
}
}
fn serialize_u8(self, v: u8) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u16(self, v: u16) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u32(self, v: u32) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u64(self, v: u64) -> Result<WasmValue, Error> {
Ok(WasmValue::UInt(v))
}
fn serialize_u128(self, v: u128) -> Result<WasmValue, Error> {
u64::try_from(v)
.map(WasmValue::UInt)
.map_err(|_| Error::custom(format!("u128 value {v} exceeds the wire BigInt range")))
}
fn serialize_f32(self, v: f32) -> Result<WasmValue, Error> {
self.serialize_f64(v as f64)
}
fn serialize_f64(self, v: f64) -> Result<WasmValue, Error> {
Ok(if v.is_finite() {
WasmValue::Number(v)
} else if v.is_nan() {
WasmValue::NonFinite(NonFinite::Nan)
} else if v > 0. {
WasmValue::NonFinite(NonFinite::PositiveInfinity)
} else {
WasmValue::NonFinite(NonFinite::NegativeInfinity)
})
}
fn serialize_char(self, v: char) -> Result<WasmValue, Error> {
Ok(WasmValue::String(v.to_string()))
}
fn serialize_str(self, v: &str) -> Result<WasmValue, Error> {
Ok(WasmValue::String(v.to_string()))
}
fn serialize_bytes(self, v: &[u8]) -> Result<WasmValue, Error> {
Ok(WasmValue::Bytes(v.to_vec()))
}
fn serialize_none(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<WasmValue, Error> {
value.serialize(self)
}
fn serialize_unit(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<WasmValue, Error> {
Ok(WasmValue::String(variant.to_string()))
}
fn serialize_newtype_struct<T: Serialize + ?Sized>(self, _name: &'static str, value: &T) -> Result<WasmValue, Error> {
value.serialize(self)
}
fn serialize_newtype_variant<T: Serialize + ?Sized>(self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(variant.to_string(), value.serialize(ValueSerializer)?)]))
}
fn serialize_seq(self, len: Option<usize>) -> Result<SeqSerializer, Error> {
Ok(SeqSerializer(Vec::with_capacity(len.unwrap_or_default())))
}
fn serialize_tuple(self, len: usize) -> Result<SeqSerializer, Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqSerializer, Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantSeqSerializer, Error> {
Ok(VariantSeqSerializer {
variant,
elements: Vec::with_capacity(len),
})
}
fn serialize_map(self, len: Option<usize>) -> Result<MapSerializer, Error> {
Ok(MapSerializer {
entries: Vec::with_capacity(len.unwrap_or_default()),
pending_key: None,
})
}
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<ObjectSerializer, Error> {
Ok(ObjectSerializer(Vec::with_capacity(len)))
}
fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantObjectSerializer, Error> {
Ok(VariantObjectSerializer {
variant,
fields: Vec::with_capacity(len),
})
}
}
struct SeqSerializer(Vec<WasmValue>);
impl ser::SerializeSeq for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
self.0.push(value.serialize(ValueSerializer)?);
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Seq(self.0))
}
}
impl ser::SerializeTuple for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<WasmValue, Error> {
ser::SerializeSeq::end(self)
}
}
impl ser::SerializeTupleStruct for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<WasmValue, Error> {
ser::SerializeSeq::end(self)
}
}
struct VariantSeqSerializer {
variant: &'static str,
elements: Vec<WasmValue>,
}
impl ser::SerializeTupleVariant for VariantSeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
self.elements.push(value.serialize(ValueSerializer)?);
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Seq(self.elements))]))
}
}
struct MapSerializer {
entries: Vec<(WasmValue, WasmValue)>,
pending_key: Option<WasmValue>,
}
impl ser::SerializeMap for MapSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {
self.pending_key = Some(key.serialize(ValueSerializer)?);
Ok(())
}
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
let key = self.pending_key.take().ok_or_else(|| Error::custom("Map value serialized without a key"))?;
self.entries.push((key, value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Map(self.entries))
}
}
struct ObjectSerializer(Vec<(String, WasmValue)>);
impl ser::SerializeStruct for ObjectSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
self.0.push((key.to_string(), value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(self.0))
}
}
struct VariantObjectSerializer {
variant: &'static str,
fields: Vec<(String, WasmValue)>,
}
impl ser::SerializeStructVariant for VariantObjectSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
self.fields.push((key.to_string(), value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Object(self.fields))]))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wasm_value::encode;
use serde::Serialize;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
enum TestMessage {
UnitVariant,
StructVariant {
#[serde(rename = "nodeId")]
node_id: u64,
width: u32,
scale: f64,
min: f64,
max: f64,
label: Option<String>,
widths: std::collections::BTreeMap<u64, u32>,
flags: Vec<bool>,
bytes: serde_bytes::ByteBuf,
},
}
#[test]
fn mirrors_serde_wasm_bindgen_representations() {
assert_eq!(to_value(&TestMessage::UnitVariant).unwrap(), WasmValue::String("unitVariant".into()));
let message = TestMessage::StructVariant {
node_id: u64::MAX,
width: 8,
scale: f64::NAN,
min: f64::NEG_INFINITY,
max: f64::INFINITY,
label: None,
widths: [(42, 7)].into(),
flags: vec![true, false],
bytes: serde_bytes::ByteBuf::from(vec![0, 255]),
};
let expected = WasmValue::Object(vec![(
"structVariant".into(),
WasmValue::Object(vec![
("nodeId".into(), WasmValue::UInt(u64::MAX)),
("width".into(), WasmValue::Number(8.)),
("scale".into(), WasmValue::NonFinite(NonFinite::Nan)),
("min".into(), WasmValue::NonFinite(NonFinite::NegativeInfinity)),
("max".into(), WasmValue::NonFinite(NonFinite::PositiveInfinity)),
("label".into(), WasmValue::Undefined),
("widths".into(), WasmValue::Map(vec![(WasmValue::UInt(42), WasmValue::Number(7.))])),
("flags".into(), WasmValue::Seq(vec![WasmValue::Bool(true), WasmValue::Bool(false)])),
("bytes".into(), WasmValue::Bytes(vec![0, 255])),
]),
)]);
assert_eq!(to_value(&message).unwrap(), expected);
}
#[test]
fn encode_decode_roundtrip() {
let message = TestMessage::StructVariant {
node_id: 1,
width: 2,
scale: f64::NAN,
min: f64::NEG_INFINITY,
max: 1.5,
label: Some("hi".into()),
widths: [(3, 4)].into(),
flags: vec![true],
bytes: serde_bytes::ByteBuf::from(vec![9]),
};
let json: &str = &encode(&message).unwrap();
let decoded: WasmValue = serde_json::from_str(json).unwrap();
assert_eq!(decoded, to_value(&message).unwrap());
}
}
}
@@ -309,6 +309,7 @@ macro_rules! tagged_value {
pub fn from_type(input: &Type) -> Option<Self> { pub fn from_type(input: &Type) -> Option<Self> {
match input { match input {
Type::Generic(_) => None, Type::Generic(_) => None,
Type::Ref(_) => None,
Type::Concrete(concrete_type) => { Type::Concrete(concrete_type) => {
let name = concrete_type.name.as_ref(); let name = concrete_type.name.as_ref();
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types // TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
@@ -569,6 +570,7 @@ impl TaggedValue {
match ty { match ty {
Type::Generic(_) => None, Type::Generic(_) => None,
Type::Ref(_) => None,
Type::Concrete(concrete_type) => { Type::Concrete(concrete_type) => {
let ty = concrete_type.id?; let ty = concrete_type.id?;
use std::any::TypeId; use std::any::TypeId;
+9 -6
View File
@@ -370,13 +370,16 @@ impl ProtoNetwork {
let mut combined_deps = ContextFeatures::default(); let mut combined_deps = ContextFeatures::default();
let node_index = id.0 as usize; let node_index = id.0 as usize;
let context_features = self.nodes[node_index].1.context_features; let (extract, inject) = {
let dependencies = &self.nodes[node_index].1.context_features;
(dependencies.extract, dependencies.inject)
};
let mut inputs = match &self.nodes[node_index].1.construction_args { let mut inputs = match &self.nodes[node_index].1.construction_args {
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached // We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)), ConstructionArgs::Value(_) => return (extract, Some(id)),
ConstructionArgs::Nodes(items) => items.clone(), ConstructionArgs::Nodes(items) => items.clone(),
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)), ConstructionArgs::Inline(_) => return (extract, Some(id)),
}; };
// Compute the dependencies for each branch and combine all of them // Compute the dependencies for each branch and combine all of them
@@ -389,9 +392,9 @@ impl ProtoNetwork {
let mut new_deps = combined_deps; let mut new_deps = combined_deps;
// Remove requirements which this node provides // Remove requirements which this node provides
new_deps &= !context_features.inject; new_deps &= !inject;
// Add requirements we have // Add requirements we have
new_deps |= context_features.extract; new_deps |= extract;
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency // If we either introduce new dependencies, we can cache all children which don't yet need that dependency
let we_introduce_new_deps = !combined_deps.contains(new_deps); let we_introduce_new_deps = !combined_deps.contains(new_deps);
@@ -407,7 +410,7 @@ impl ProtoNetwork {
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs); self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
// Which dependencies do we supply (and don't need ourselves)? // Which dependencies do we supply (and don't need ourselves)?
let net_injections = context_features.inject.difference(context_features.extract); let net_injections = inject.difference(extract);
// Which dependencies still need to be met after this node? // Which dependencies still need to be met after this node?
let remaining_deps_from_children = combined_deps.difference(net_injections); let remaining_deps_from_children = combined_deps.difference(net_injections);
@@ -262,7 +262,7 @@ impl BorrowTree {
/// This ensures that no borrowed data can escape the node graph. /// This ensures that no borrowed data can escape the node graph.
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String> pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
where where
I: StaticType + 'static + Send + Sync, I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
{ {
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?; let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
let output = node.eval(Box::new(input)); let output = node.eval(Box::new(input));
+9 -24
View File
@@ -30,20 +30,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)], inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::INDEX,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)], inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
@@ -54,20 +48,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(1), 0),
], ],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)], inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
@@ -77,21 +65,18 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(3), 0), NodeInput::node(NodeId(3), 0),
], ],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(graphene_std::application_io::RenderConfig), call_argument: concrete!(graphene_std::application_io::RenderConfig),
inputs: vec![NodeInput::node(NodeId(4), 0)], inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work // We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
extract: ContextFeatures::INDEX, context_features: graphene_std::ContextDependencies::new(
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::INDEX,
}, ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
),
..Default::default() ..Default::default()
}, },
] ]
@@ -0,0 +1,414 @@
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
/// addressable and generations run out after ~3 days of 60fps resets.
const OFFSET_BITS: u32 = 40;
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
/// Out of the encodable range, so no handle, including `NULL`, matches it.
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
pub struct Arena {
generation: AtomicU64,
offset: AtomicUsize,
buf: Box<[UnsafeCell<MaybeUninit<u8>>]>,
drops: Mutex<Vec<DropEntry>>,
}
impl std::fmt::Debug for Arena {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Arena").field("generation", &self.generation).field("size", &self.buf.len()).finish()
}
}
struct DropEntry {
offset: usize,
drop_fn: unsafe fn(*mut u8),
}
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
// only by its allocating caller before publication, and cross-thread hand-off is
// ordered by the Release/Acquire pair on the published handle word. Payloads are
// `Send + Sync` by the bound on every allocating method.
unsafe impl Sync for Arena {}
unsafe impl Send for Arena {}
impl std::panic::UnwindSafe for Arena {}
impl std::panic::RefUnwindSafe for Arena {}
/// Shared by all arenas, so a foreign handle misses like a stale one.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
fn next_generation() -> Option<u64> {
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
(generation <= GENERATION_MASK).then_some(generation)
}
/// Rewinds the shared generation counter so previously issued values are reused.
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
/// check, which is a debugging aid rather than a guarantee.
///
/// # Safety
///
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
/// every [`Arena`] is not sufficient, since nodes also hold handles in
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
/// concurrently either, since the live check and the rewind are separate steps.
pub unsafe fn reset_generation_counter() -> bool {
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
return false;
}
NEXT_GENERATION.store(1, Ordering::Release);
true
}
impl Arena {
pub fn new(capacity: usize) -> Option<Self> {
let generation = next_generation()?;
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Some(Self {
generation: AtomicU64::new(generation),
offset: AtomicUsize::new(0),
buf,
drops: Mutex::new(Vec::new()),
})
}
pub fn generation(&self) -> u64 {
self.generation.load(Ordering::Acquire)
}
fn base(&self) -> *mut u8 {
self.buf.as_ptr() as *mut u8
}
fn reserve(&self, size: usize, align: usize) -> Option<usize> {
debug_assert!(align.is_power_of_two());
let base = self.base() as usize;
let mut start = 0;
self.offset
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
// Alignment is computed on the absolute address; the backbone
// allocation itself has no alignment guarantee.
let addr = (base.checked_add(current)?.checked_add(align - 1)?) & !(align - 1);
start = addr - base;
let end = start.checked_add(size)?;
(end <= self.buf.len()).then_some(end)
})
.ok()?;
Some(start)
}
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
let weak = ArenaWeak::new(self.generation(), offset)?;
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
unsafe { ptr.write(value) };
if std::mem::needs_drop::<T>() {
unsafe fn glue<T>(p: *mut u8) {
unsafe { p.cast::<T>().drop_in_place() }
}
self.drops.lock().unwrap().push(DropEntry { offset, drop_fn: glue::<T> });
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
Some((unsafe { &*ptr }, weak))
}
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
let buf = self.alloc_scratch::<T>(src.len())?;
for (slot, &value) in buf.iter_mut().zip(src) {
slot.write(value);
}
// SAFETY: every lane written above from `src`.
Some(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<T>(), src.len()) })
}
// Not drop-tracked: callers must either consume every written lane or
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
#[allow(clippy::mut_from_ref)]
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
// `&mut self`, so the slice cannot outlive the generation.
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
}
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
/// where every handle misses and further allocation is refused.
pub fn reset(&mut self) -> bool {
let base = self.base();
let entries = std::mem::take(self.drops.get_mut().unwrap());
self.generation.store(PARKED_GENERATION, Ordering::Release);
for entry in entries.into_iter().rev() {
// SAFETY: registered at alloc time; insert-only means the region was
// never overwritten within this generation.
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
}
*self.offset.get_mut() = 0;
let Some(generation) = next_generation() else { return false };
self.generation.store(generation, Ordering::Release);
true
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.reset();
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
}
}
pub struct ArenaWeak<T> {
word: u64,
_marker: PhantomData<*const T>,
}
impl<T> Clone for ArenaWeak<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for ArenaWeak<T> {}
impl<T> ArenaWeak<T> {
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
/// `None` once either field leaves its encodable range, so an oversized or parked
/// arena refuses to hand out a handle rather than truncating it to a live address.
fn new(generation: u64, offset: usize) -> Option<Self> {
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
(generation <= GENERATION_MASK).then_some(Self {
word: (generation << OFFSET_BITS) | offset,
_marker: PhantomData,
})
}
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
let generation = self.word >> OFFSET_BITS;
if generation != arena.generation() {
return None;
}
let offset = (self.word & OFFSET_MASK) as usize;
// SAFETY: same generation means the entry was fully written before its
// word was published (Release) and cannot move or be overwritten within
// a generation (insert-only); the Acquire load that produced this word
// ordered the payload writes.
Some(unsafe { &*arena.base().add(offset).cast::<T>() })
}
}
pub struct ArenaCell<T> {
word: AtomicU64,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for ArenaCell<T> {
fn clone(&self) -> Self {
Self {
word: AtomicU64::new(self.word.load(Ordering::Acquire)),
_marker: PhantomData,
}
}
}
impl<T> std::fmt::Debug for ArenaCell<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArenaCell").field("word", &self.word.load(Ordering::Relaxed)).finish()
}
}
impl<T> Default for ArenaCell<T> {
fn default() -> Self {
Self {
word: AtomicU64::new(0),
_marker: PhantomData,
}
}
}
impl<T> ArenaCell<T> {
pub fn new() -> Self {
Self::default()
}
pub fn load<'e>(&self, arena: &'e Arena) -> Option<&'e T> {
let weak = ArenaWeak::<T> {
word: self.word.load(Ordering::Acquire),
_marker: PhantomData,
};
weak.upgrade(arena)
}
pub fn store(&self, weak: ArenaWeak<T>) {
self.word.store(weak.word, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::PoisonError;
use std::sync::atomic::AtomicU32;
#[test]
fn alloc_upgrade_reset_miss() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (value, weak) = arena.alloc(41u32).unwrap();
assert_eq!(*value, 41);
cell.store(weak);
assert_eq!(cell.load(&arena), Some(&41));
arena.reset();
assert_eq!(cell.load(&arena), None, "stale handle must miss");
}
#[test]
fn capacity_survives_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
for _ in 0..10 {
for _ in 0..16 {
assert!(arena.alloc(0u32).is_some());
}
assert!(arena.alloc(0u32).is_none(), "exhausted within generation");
arena.reset();
}
}
#[test]
fn panics_leave_the_arena_coherent() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
assert_ref_unwind_safe::<Arena>();
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let result = std::panic::catch_unwind(|| {
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
cell.store(weak);
panic!("mid-eval");
});
assert!(result.is_err());
assert!(cell.load(&arena).is_some(), "the generation is still live after the caught panic");
arena.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "reset reclaims pre-panic allocations");
assert!(cell.load(&arena).is_none(), "the bump kills stale handles");
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
}
#[test]
fn a_panicking_destructor_leaves_no_resolvable_handle() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (_, weak) = arena.alloc(Bomb).unwrap();
cell.store(weak);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
}
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
/// is never observed by a concurrently constructing test.
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
#[test]
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let (_, weak) = arena.alloc(41u32).unwrap();
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
assert!(!arena.reset(), "an exhausted counter must report failure");
NEXT_GENERATION.store(restore, Ordering::Relaxed);
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
}
#[test]
fn the_generation_counter_rewinds_only_without_live_arenas() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(64).unwrap();
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
drop(arena);
}
#[test]
fn handles_do_not_upgrade_against_a_foreign_arena() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (_, weak) = first.alloc(41u32).unwrap();
assert_eq!(weak.upgrade(&first), Some(&41));
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
}
#[test]
fn reset_drops_dependents_before_their_dependencies() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
struct Probe(u32);
impl Drop for Probe {
fn drop(&mut self) {
ORDER.lock().unwrap().push(self.0);
}
}
let mut arena = Arena::new(1024).unwrap();
for id in 0..3 {
arena.alloc(Probe(id)).unwrap();
}
arena.reset();
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
}
#[test]
fn drop_glue_runs_on_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
arena.alloc(Probe("owns heap".into())).unwrap();
arena.alloc(Probe("me too".into())).unwrap();
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
arena.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,191 @@
use crate::gpoll::Finality;
use std::cell::UnsafeCell;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
const SLOT_EMPTY: u8 = 0;
const SLOT_FINAL: u8 = 1;
const SLOT_PARTIAL: u8 = 2;
pub struct FrameTable<T, const CAP: usize> {
slots: [FrameSlot<T>; CAP],
}
struct FrameSlot<T> {
key: AtomicU64,
state: AtomicU8,
value: UnsafeCell<MaybeUninit<T>>,
}
pub enum Lookup<'t, T> {
Hit(Finality, &'t T),
Vacant(VacantSlot<'t, T>),
Full,
}
pub struct VacantSlot<'t, T> {
slot: &'t FrameSlot<T>,
}
impl<T, const CAP: usize> Default for FrameTable<T, CAP> {
fn default() -> Self {
Self::new()
}
}
impl<T, const CAP: usize> FrameTable<T, CAP> {
pub fn new() -> Self {
Self {
slots: std::array::from_fn(|_| FrameSlot {
key: AtomicU64::new(0),
state: AtomicU8::new(SLOT_EMPTY),
value: UnsafeCell::new(MaybeUninit::uninit()),
}),
}
}
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
let key = if hash == 0 { 1 } else { hash };
for probe in 0..CAP {
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
let stored = slot.key.load(Ordering::Acquire);
if stored == key {
return match slot.state.load(Ordering::Acquire) {
// SAFETY: a published state was stored with Release after the
// value write; the Acquire load above ordered that write.
SLOT_FINAL => Lookup::Hit(Finality::AllFinal, unsafe { (*slot.value.get()).assume_init_ref() }),
SLOT_PARTIAL => Lookup::Hit(Finality::Partial, unsafe { (*slot.value.get()).assume_init_ref() }),
_ => Lookup::Full,
};
}
if stored == 0 && slot.key.compare_exchange(0, key, Ordering::AcqRel, Ordering::Acquire).is_ok() {
return Lookup::Vacant(VacantSlot { slot });
}
}
Lookup::Full
}
}
impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
fn drop(&mut self) {
for slot in &self.slots {
if slot.state.load(Ordering::Acquire) != SLOT_EMPTY {
// SAFETY: a non-empty state is only ever stored after the value
// write in `publish`.
unsafe { (*slot.value.get()).assume_init_drop() }
}
}
}
}
impl<'t, T> VacantSlot<'t, T> {
pub fn publish(self, value: T, finality: Finality) -> &'t T {
let slot = ManuallyDrop::new(self).slot;
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
// its state is still SLOT_EMPTY, so nobody reads the value yet.
let lent = unsafe { &*(*slot.value.get()).write(value) };
let state = match finality {
Finality::AllFinal => SLOT_FINAL,
Finality::Partial => SLOT_PARTIAL,
};
slot.state.store(state, Ordering::Release);
lent
}
pub fn release(self) {
drop(self);
}
}
/// Frees the reservation, so an early return or panic between `lookup` and
/// `publish` cannot retire the slot for the rest of the table's life.
impl<T> Drop for VacantSlot<'_, T> {
fn drop(&mut self) {
self.slot.key.store(0, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicU32;
#[test]
fn publish_then_hit_with_finality() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else {
panic!("fresh table must be vacant");
};
assert_eq!(*slot.publish(41, Finality::Partial), 41);
let Lookup::Hit(finality, value) = table.lookup(7) else {
panic!("published key must hit");
};
assert_eq!((finality, *value), (Finality::Partial, 41));
}
#[test]
fn released_slot_is_vacant_again() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
slot.release();
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
}
#[test]
fn a_dropped_reservation_frees_the_slot() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
drop(slot);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
}
#[test]
fn neighboring_hashes_do_not_share_an_entry() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
slot.publish(600, Finality::AllFinal);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
}
#[test]
fn the_zero_hash_round_trips() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
slot.publish(11, Finality::AllFinal);
let Lookup::Hit(_, value) = table.lookup(0) else {
panic!("the remapped sentinel hash must still hit");
};
assert_eq!(*value, 11);
}
#[test]
fn distinct_keys_probe_past_collisions_until_full() {
let table = FrameTable::<u32, 4>::new();
for hash in [2, 4, 6, 8] {
let Lookup::Vacant(slot) = table.lookup(hash) else {
panic!("hash {hash} should find a vacant slot");
};
slot.publish(hash as u32, Finality::AllFinal);
}
assert!(matches!(table.lookup(100), Lookup::Full));
}
#[test]
fn drop_runs_glue_for_published_values_only() {
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let table = FrameTable::<Probe, 8>::new();
let Lookup::Vacant(slot) = table.lookup(1) else { unreachable!() };
slot.publish(Probe, Finality::AllFinal);
let Lookup::Vacant(reserved_but_unpublished) = table.lookup(2) else { unreachable!() };
reserved_but_unpublished.release();
drop(table);
assert_eq!(DROPS.load(Ordering::Relaxed), 1);
}
}
@@ -0,0 +1,235 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Node(&'static str),
ArenaExhausted,
Panic,
}
impl PartialEq<&str> for ErrorKind {
fn eq(&self, other: &&str) -> bool {
matches!(self, ErrorKind::Node(kind) if kind == other)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphError {
pub kind: ErrorKind,
pub trace: Vec<usize>,
}
impl GraphError {
pub fn new(kind: &'static str) -> Self {
Self {
kind: ErrorKind::Node(kind),
trace: Vec::new(),
}
}
pub fn traced(mut self, input_index: usize) -> Self {
self.trace.push(input_index);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum GPoll<T> {
Pending,
Final(T),
Partial(T),
Fallback(Box<(T, GraphError)>),
Error(Box<GraphError>),
}
impl<T> GPoll<T> {
#[inline(always)]
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> GPoll<U> {
match self {
GPoll::Pending => GPoll::Pending,
GPoll::Final(value) => GPoll::Final(f(value)),
GPoll::Partial(value) => GPoll::Partial(f(value)),
GPoll::Fallback(boxed) => {
let (value, e) = *boxed;
GPoll::Fallback(Box::new((f(value), e)))
}
GPoll::Error(e) => GPoll::Error(e),
}
}
#[inline(always)]
pub fn and_then<U>(self, f: impl FnOnce(T) -> GPoll<U>) -> GPoll<U> {
match self {
GPoll::Pending => GPoll::Pending,
GPoll::Final(value) => f(value),
GPoll::Partial(value) => match f(value) {
GPoll::Final(result) => GPoll::Partial(result),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, e) = *boxed;
match f(value) {
GPoll::Pending => GPoll::Pending,
GPoll::Final(result) | GPoll::Partial(result) => GPoll::Fallback(Box::new((result, e))),
GPoll::Fallback(inner) => {
let (result, _) = *inner;
GPoll::Fallback(Box::new((result, e)))
}
GPoll::Error(inner) => GPoll::Error(inner),
}
}
GPoll::Error(e) => GPoll::Error(e),
}
}
#[inline(always)]
pub fn zip<U>(self, other: GPoll<U>) -> GPoll<(T, U)> {
match (self, other) {
(GPoll::Error(e), _) | (_, GPoll::Error(e)) => GPoll::Error(e),
(GPoll::Pending, _) | (_, GPoll::Pending) => GPoll::Pending,
(GPoll::Final(a), GPoll::Final(b)) => GPoll::Final((a, b)),
(GPoll::Fallback(boxed), GPoll::Final(b) | GPoll::Partial(b)) => {
let (a, e) = *boxed;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Final(a) | GPoll::Partial(a), GPoll::Fallback(boxed)) => {
let (b, e) = *boxed;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Fallback(first), GPoll::Fallback(second)) => {
let (a, e) = *first;
let (b, _) = *second;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Partial(a), GPoll::Final(b) | GPoll::Partial(b)) | (GPoll::Final(a), GPoll::Partial(b)) => GPoll::Partial((a, b)),
}
}
#[inline(always)]
pub fn trace(self, input: usize) -> Self {
match self {
GPoll::Fallback(mut boxed) => {
boxed.1.trace.push(input);
GPoll::Fallback(boxed)
}
GPoll::Error(mut e) => {
e.trace.push(input);
GPoll::Error(e)
}
other => other,
}
}
pub fn fallback(value: T, kind: &'static str) -> Self {
GPoll::Fallback(Box::new((value, GraphError::new(kind))))
}
pub fn error(kind: &'static str) -> Self {
GPoll::Error(Box::new(GraphError::new(kind)))
}
pub fn arena_exhausted() -> Self {
GPoll::Error(Box::new(GraphError {
kind: ErrorKind::ArenaExhausted,
trace: Vec::new(),
}))
}
pub fn panicked() -> Self {
GPoll::Error(Box::new(GraphError {
kind: ErrorKind::Panic,
trace: Vec::new(),
}))
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Interrupt {
Pending,
Error(Box<GraphError>),
}
impl From<GraphError> for Interrupt {
fn from(error: GraphError) -> Self {
Interrupt::Error(Box::new(error))
}
}
impl<T> From<Interrupt> for GPoll<T> {
fn from(interrupt: Interrupt) -> Self {
match interrupt {
Interrupt::Pending => GPoll::Pending,
Interrupt::Error(e) => GPoll::Error(e),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Extent {
Free,
Exactly(usize),
}
impl Extent {
pub fn meet(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
a.zip(b).and_then(|(a, b)| match (a, b) {
(Extent::Free, other) | (other, Extent::Free) => GPoll::Final(other),
(Extent::Exactly(n), Extent::Exactly(m)) if n == m => GPoll::Final(Extent::Exactly(n)),
(Extent::Exactly(n), Extent::Exactly(m)) => GPoll::fallback(Extent::Exactly(n.min(m)), "extent mismatch"),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Finality {
AllFinal,
Partial,
}
impl Finality {
pub fn meet(self, other: Finality) -> Finality {
match (self, other) {
(Finality::AllFinal, Finality::AllFinal) => Finality::AllFinal,
_ => Finality::Partial,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn free_is_the_meet_identity() {
let meet = Extent::meet(GPoll::Final(Extent::Free), GPoll::Final(Extent::Exactly(4)));
assert_eq!(meet, GPoll::Final(Extent::Exactly(4)));
}
#[test]
fn extent_mismatch_truncates_and_reports() {
let meet = Extent::meet(GPoll::Final(Extent::Exactly(3)), GPoll::Final(Extent::Exactly(5)));
let GPoll::Fallback(boxed) = meet else {
panic!("expected fallback, got {meet:?}");
};
assert_eq!(boxed.0, Extent::Exactly(3));
assert!(boxed.1.kind == "extent mismatch");
}
#[test]
fn error_dominates_pending_in_zip() {
let zipped = GPoll::<u32>::error("boom").zip(GPoll::<u32>::Pending);
assert!(matches!(zipped, GPoll::Error(_)));
}
#[test]
fn trace_builds_root_to_source_path() {
let poll = GPoll::<u32>::error("boom").trace(2).trace(0);
let GPoll::Error(e) = poll else { unreachable!() };
assert_eq!(e.trace, vec![2, 0]);
}
#[test]
fn interrupt_round_trips_to_gpoll() {
assert_eq!(GPoll::<u32>::from(Interrupt::Pending), GPoll::Pending);
let interrupt = Interrupt::from(GraphError::new("boom"));
assert!(matches!(GPoll::<u32>::from(interrupt), GPoll::Error(e) if e.kind == "boom"));
}
}
@@ -1,16 +1,21 @@
extern crate log; extern crate log;
pub mod arena;
pub mod bounds; pub mod bounds;
pub mod consts; pub mod consts;
pub mod context; pub mod context;
pub mod frame_table;
pub mod generic; pub mod generic;
pub mod gpoll;
pub mod list; pub mod list;
pub mod math; pub mod math;
pub mod memo; pub mod memo;
pub mod misc; pub mod misc;
pub mod node;
pub mod ops; pub mod ops;
pub mod registry; pub mod registry;
pub mod render_complexity; pub mod render_complexity;
pub mod runtime;
pub mod transform; pub mod transform;
pub mod uuid; pub mod uuid;
pub mod value; pub mod value;
+424
View File
@@ -0,0 +1,424 @@
use crate::context::InjectIndex;
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt};
use std::cell::Cell;
use std::mem::MaybeUninit;
use std::ops::Range;
#[derive(Debug)]
pub enum BatchStatus<'a, T> {
Lent(&'a [T], Finality),
Filled(FilledBatch<'a, T>, Finality),
Pending,
Error(GraphError),
NeedBuffer,
InvalidRange,
}
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
#[derive(Debug)]
pub struct FilledBatch<'a, T> {
values: &'a mut [T],
}
impl<'a, T> FilledBatch<'a, T> {
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
Self {
values: unsafe { assume_init_prefix_mut(scratch, len) },
}
}
pub fn values(&self) -> &[T] {
self.values
}
pub fn into_values(self) -> &'a mut [T] {
let mut guard = std::mem::ManuallyDrop::new(self);
std::mem::take(&mut guard.values)
}
}
impl<T> Drop for FilledBatch<'_, T> {
fn drop(&mut self) {
// SAFETY: every lane was initialized when the guard was built and none has
// been moved out, since `into_values` consumes the guard instead.
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
}
}
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
pub unsafe fn assume_init_prefix_mut<T>(scratch: &mut [MaybeUninit<T>], len: usize) -> &mut [T] {
debug_assert!(len <= scratch.len());
unsafe { std::slice::from_raw_parts_mut(scratch.as_mut_ptr().cast::<T>(), len) }
}
pub trait Node<Input> {
type Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
fn extent(&self, _input: &Input) -> GPoll<Extent> {
GPoll::Final(Extent::Free)
}
/// Introspection access to node-resident records; `None` for ordinary nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
None
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
if scratch.len() < len {
return BatchStatus::InvalidRange;
}
let mut local = *input;
let mut finality = Finality::AllFinal;
for offset in 0..len {
local.set_index(range.start + offset as u64);
let abort = match self.eval(&local) {
GPoll::Final(value) => {
scratch[offset].write(value);
None
}
GPoll::Partial(value) => {
scratch[offset].write(value);
finality = Finality::Partial;
None
}
GPoll::Pending => Some(BatchStatus::Pending),
GPoll::Fallback(boxed) => Some(BatchStatus::Error(boxed.1)),
GPoll::Error(e) => Some(BatchStatus::Error(*e)),
};
if let Some(status) = abort {
for written in scratch[..offset].iter_mut() {
// SAFETY: every lane before `offset` was written by this loop.
unsafe { written.assume_init_drop() };
}
return status;
}
}
// SAFETY: all `len` lanes were written by the loop above.
BatchStatus::Filled(unsafe { FilledBatch::new(scratch, len) }, finality)
}
}
impl<Input, N> Node<Input> for &N
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
(**self).eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
(**self).eval_batch(input, range, scratch)
}
}
impl<Input, N> Node<Input> for Box<N>
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
(**self).eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
(**self).eval_batch(input, range, scratch)
}
}
impl<Input, N> Node<Input> for std::sync::Arc<N>
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
(**self).eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
(**self).eval_batch(input, range, scratch)
}
}
pub struct StatusCell {
finality: Cell<Finality>,
error: Cell<Option<GraphError>>,
no_partial: bool,
}
impl Default for StatusCell {
fn default() -> Self {
Self::new()
}
}
impl StatusCell {
pub fn new() -> Self {
Self {
finality: Cell::new(Finality::AllFinal),
error: Cell::new(None),
no_partial: false,
}
}
pub fn no_partial() -> Self {
Self { no_partial: true, ..Self::new() }
}
pub fn eval_input<Input, N: Node<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
match node.eval(input) {
GPoll::Final(value) => Ok(value),
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
GPoll::Partial(value) => {
self.finality.set(Finality::Partial);
Ok(value)
}
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take();
self.error.set(first.or(Some(error.traced(input_index))));
Ok(value)
}
GPoll::Pending => Err(Interrupt::Pending),
GPoll::Error(mut error) => {
error.trace.push(input_index);
Err(Interrupt::Error(error))
}
}
}
pub fn finish<T>(self, value: T) -> GPoll<T> {
match (self.error.take(), self.finality.get()) {
(Some(error), _) => GPoll::Fallback(Box::new((value, error))),
(None, Finality::AllFinal) => GPoll::Final(value),
(None, Finality::Partial) => GPoll::Partial(value),
}
}
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
match poll {
GPoll::Final(value) => self.finish(value),
GPoll::Partial(_) if self.no_partial => GPoll::Pending,
GPoll::Partial(value) => match self.finish(value) {
GPoll::Final(value) => GPoll::Partial(value),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take().unwrap_or(error);
GPoll::Fallback(Box::new((value, first)))
}
interrupted => interrupted,
}
}
}
#[derive(Clone, Copy)]
pub struct LazyInput<'a, N> {
node: &'a N,
cell: &'a StatusCell,
input_index: usize,
}
impl<'a, N> LazyInput<'a, N> {
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize) -> Self {
Self { node, cell, input_index }
}
pub fn eval<Input>(&self, ctx: &Input) -> Result<N::Output, Interrupt>
where
N: Node<Input>,
{
self.cell.eval_input(self.input_index, self.node, ctx)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
#[derive(Clone, Copy)]
struct TestInput {
index: u64,
}
impl InjectIndex for TestInput {
fn set_index(&mut self, index: u64) {
self.index = index;
}
}
struct Double;
impl Node<TestInput> for Double {
type Output = u64;
fn eval(&self, input: &TestInput) -> GPoll<u64> {
GPoll::Final(input.index * 2)
}
}
#[test]
fn spec_loop_fills_scratch_per_lane() {
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = Double.eval_batch(&input, 2..6, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes.values(), &[4, 6, 8, 10]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn a_dropped_filled_batch_reclaims_every_lane() {
static DROPS: AtomicU32 = AtomicU32::new(0);
#[derive(Clone)]
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
struct Probes;
impl Node<TestInput> for Probes {
type Output = Probe;
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
GPoll::Final(Probe)
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 3];
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Filled(..)));
drop(status);
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
}
#[test]
fn probe_without_scratch_requests_a_buffer() {
let input = TestInput { index: 0 };
assert!(matches!(Double.eval_batch(&input, 0..4, None), BatchStatus::NeedBuffer));
}
#[test]
fn undersized_scratch_is_an_invalid_range() {
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 2];
assert!(matches!(Double.eval_batch(&input, 0..4, Some(&mut scratch)), BatchStatus::InvalidRange));
}
#[test]
fn partial_lane_downgrades_batch_finality() {
struct PartialAtThree;
impl Node<TestInput> for PartialAtThree {
type Output = u64;
fn eval(&self, input: &TestInput) -> GPoll<u64> {
match input.index {
3 => GPoll::Partial(input.index),
index => GPoll::Final(index),
}
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = PartialAtThree.eval_batch(&input, 0..4, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes.values(), &[0, 1, 2, 3]);
assert_eq!(finality, Finality::Partial);
}
#[test]
fn abort_drops_already_written_lanes() {
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
struct PendingAtTwo;
impl Node<TestInput> for PendingAtTwo {
type Output = Probe;
fn eval(&self, input: &TestInput) -> GPoll<Probe> {
match input.index {
2 => GPoll::Pending,
_ => GPoll::Final(Probe),
}
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = PendingAtTwo.eval_batch(&input, 0..4, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Pending));
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
#[test]
fn trait_is_object_safe_across_erased_edges() {
let erased: Box<dyn Node<TestInput, Output = u64>> = Box::new(Double);
let input = TestInput { index: 21 };
assert_eq!(erased.eval(&input), GPoll::Final(42));
let mut scratch = [const { MaybeUninit::uninit() }; 2];
let status = erased.eval_batch(&input, 0..2, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Filled(_, Finality::AllFinal)));
}
}
@@ -0,0 +1,148 @@
use crate::SourceId;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
#[cfg(not(target_family = "wasm"))]
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
#[cfg(target_family = "wasm")]
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + 'static>>;
#[cfg(not(target_family = "wasm"))]
pub type DynRuntime = dyn Runtime + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynRuntime = dyn Runtime;
pub trait Runtime {
fn spawn(&self, source: SourceId, future: SourceFuture);
}
#[derive(Clone)]
pub struct RuntimeHandle(pub Arc<DynRuntime>);
// SAFETY: wasm is single threaded, so the handle never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl Send for RuntimeHandle {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl Sync for RuntimeHandle {}
impl std::fmt::Debug for RuntimeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
}
}
impl graphene_hash::CacheHash for RuntimeHandle {
fn cache_hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
pub trait Spawner {
fn spawn(&self, task: SourceFuture);
}
#[cfg(not(target_family = "wasm"))]
pub type DynSpawner = dyn Spawner + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynSpawner = dyn Spawner;
#[cfg(not(target_family = "wasm"))]
pub type DynNotifier = dyn Fn() + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynNotifier = dyn Fn();
impl<S: Spawner + ?Sized> Spawner for Box<S> {
fn spawn(&self, task: SourceFuture) {
(**self).spawn(task)
}
}
/// Dropped tasks never complete.
pub struct NoopSpawner;
impl Spawner for NoopSpawner {
fn spawn(&self, _task: SourceFuture) {
log::warn!("async source spawned before a host spawner is wired; the task is dropped");
}
}
pub type DynGraphRuntime = GraphRuntime<Box<DynSpawner>>;
impl Default for RuntimeHandle {
fn default() -> Self {
Self(Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>)))
}
}
pub struct GraphRuntime<S> {
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
dirty: Arc<AtomicBool>,
notifier: Arc<Mutex<Arc<DynNotifier>>>,
spawner: S,
}
// SAFETY: wasm is single threaded, so the runtime never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl<S> Send for GraphRuntime<S> {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl<S> Sync for GraphRuntime<S> {}
impl<S> GraphRuntime<S> {
pub fn new(spawner: S) -> Self {
Self {
generations: Arc::default(),
dirty: Arc::default(),
notifier: Arc::new(Mutex::new(Arc::new(|| {}))),
spawner,
}
}
pub fn set_notifier(&self, notifier: Arc<DynNotifier>) {
*self.notifier.lock().unwrap_or_else(PoisonError::into_inner) = notifier;
}
pub fn retain_sources(&self, live: &[SourceId]) {
let mut generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
generations.retain(|source, _| live.contains(source));
for source in live {
generations.entry(*source).or_insert(0);
}
}
pub fn snapshot(&self) -> Vec<(SourceId, u64)> {
let generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
snapshot.sort_unstable();
snapshot
}
pub fn take_dirty(&self) -> bool {
self.dirty.swap(false, Ordering::Acquire)
}
pub fn spawner(&self) -> &S {
&self.spawner
}
}
impl<S: Spawner> Runtime for GraphRuntime<S> {
fn spawn(&self, source: SourceId, future: SourceFuture) {
let generations = Arc::clone(&self.generations);
let dirty = Arc::clone(&self.dirty);
let notifier = Arc::clone(&self.notifier);
self.spawner.spawn(Box::pin(async move {
future.await;
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
}));
}
}
@@ -235,6 +235,7 @@ pub enum Type {
Fn(Box<Type>, Box<Type>), Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type. /// Represents a future which promises to return the inner type.
Future(Box<Type>), Future(Box<Type>),
Ref(Box<Type>),
} }
impl Default for Type { impl Default for Type {
@@ -308,6 +309,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.size), Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None, Self::Fn(_, _) => None,
Self::Future(_) => None, Self::Future(_) => None,
Self::Ref(_) => None,
} }
} }
@@ -317,6 +319,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.align), Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None, Self::Fn(_, _) => None,
Self::Future(_) => None, Self::Future(_) => None,
Self::Ref(_) => None,
} }
} }
@@ -326,6 +329,7 @@ impl Type {
Self::Concrete(_) => self, Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(), Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(), Self::Future(output) => output.nested_type(),
Self::Ref(inner) => inner.nested_type(),
} }
} }
@@ -338,6 +342,7 @@ impl Type {
Self::Concrete(_) => None, Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f), Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f), Self::Future(output) => output.replace_nested(f),
Self::Ref(inner) => inner.replace_nested(f),
} }
} }
@@ -347,6 +352,7 @@ impl Type {
Type::Concrete(ty) => simplify_identifier_name(&ty.name), Type::Concrete(ty) => simplify_identifier_name(&ty.name),
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()), Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
Type::Future(ty) => ty.identifier_name(), Type::Future(ty) => ty.identifier_name(),
Type::Ref(ty) => ty.identifier_name(),
} }
} }
} }
@@ -441,6 +447,7 @@ impl std::fmt::Display for Type {
Type::Concrete(ty) => write!(f, "{ty}"), Type::Concrete(ty) => write!(f, "{ty}"),
Type::Fn(_, return_value) => write!(f, "{return_value}"), Type::Fn(_, return_value) => write!(f, "{return_value}"),
Type::Future(ty) => write!(f, "{ty}"), Type::Future(ty) => write!(f, "{ty}"),
Type::Ref(ty) => write!(f, "{ty}"),
} }
} }
} }
@@ -68,6 +68,7 @@ impl_via_hash! {
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl_via_hash! { impl_via_hash! {
String, String,
core::time::Duration,
} }
impl<'a> CacheHash for std::borrow::Cow<'a, str> { impl<'a> CacheHash for std::borrow::Cow<'a, str> {
@@ -235,3 +236,142 @@ impl_tuple!(A, B, C);
impl_tuple!(A, B, C, D); impl_tuple!(A, B, C, D);
impl_tuple!(A, B, C, D, E); impl_tuple!(A, B, C, D, E);
impl_tuple!(A, B, C, D, E, F); impl_tuple!(A, B, C, D, E, F);
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
/// a real wrong-value memo hit in the prototype.
#[derive(Clone)]
pub struct FxHasher64 {
hash: u64,
}
const K: u64 = 0xf1357aea2e62a9c5;
const SEED: u64 = 0x517cc1b727220a95;
const SEED1: u64 = 0x243f6a8885a308d3;
const SEED2: u64 = 0x13198a2e03707344;
const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0;
impl Default for FxHasher64 {
fn default() -> Self {
Self::new()
}
}
impl FxHasher64 {
pub const fn new() -> Self {
Self { hash: SEED }
}
#[inline]
fn add_to_hash(&mut self, i: u64) {
self.hash = self.hash.wrapping_add(i).wrapping_mul(K);
}
}
impl core::hash::Hasher for FxHasher64 {
#[inline]
fn write(&mut self, bytes: &[u8]) {
self.add_to_hash(hash_bytes(bytes));
}
#[inline]
fn write_u8(&mut self, i: u8) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u16(&mut self, i: u16) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u32(&mut self, i: u32) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u64(&mut self, i: u64) {
self.add_to_hash(i);
}
#[inline]
fn write_u128(&mut self, i: u128) {
self.add_to_hash(i as u64);
self.add_to_hash((i >> 64) as u64);
}
#[inline]
fn write_usize(&mut self, i: usize) {
self.add_to_hash(i as u64);
}
#[inline]
fn finish(&self) -> u64 {
self.hash.rotate_left(26)
}
}
#[inline]
fn multiply_mix(x: u64, y: u64) -> u64 {
let full = (x as u128) * (y as u128);
(full as u64) ^ ((full >> 64) as u64)
}
#[inline]
fn hash_bytes(bytes: &[u8]) -> u64 {
let len = bytes.len();
let mut s0 = SEED1;
let mut s1 = SEED2;
if len <= 16 {
if len >= 8 {
s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap());
s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
} else if len >= 4 {
s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64;
s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
} else if len > 0 {
let lo = bytes[0];
let mid = bytes[len / 2];
let hi = bytes[len - 1];
s0 ^= lo as u64;
s1 ^= ((hi as u64) << 8) | mid as u64;
}
} else {
let mut off = 0;
while off < len - 16 {
let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap());
let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap());
let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y);
s0 = s1;
s1 = t;
off += 16;
}
let suffix = &bytes[len - 16..];
s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap());
s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap());
}
multiply_mix(s0, s1) ^ (len as u64)
}
#[cfg(test)]
mod tests {
use super::FxHasher64;
use core::hash::Hasher;
#[test]
fn leading_zero_words_are_not_absorbed() {
let hash_words = |words: &[u64]| {
let mut hasher = FxHasher64::new();
for &word in words {
hasher.write_u64(word);
}
hasher.finish()
};
assert_ne!(hash_words(&[]), hash_words(&[0]), "a zero word must change the hash of the empty input");
assert_ne!(hash_words(&[0]), hash_words(&[0, 0]), "zero words must accumulate distinct states");
assert_ne!(hash_words(&[0, 7]), hash_words(&[7]), "a leading zero word must not be absorbed");
}
}
-3
View File
@@ -13,9 +13,6 @@ license = "Apache-2.0"
[lib] [lib]
proc-macro = true proc-macro = true
[features]
disable-registration = []
[dependencies] [dependencies]
# Workspace dependencies # Workspace dependencies
syn = { workspace = true } syn = { workspace = true }
+1 -7
View File
@@ -720,7 +720,7 @@ fn generate_register_node_impl(parsed: &ParsedNodeFn, field_names: &[&Ident], st
) )
)); ));
} }
let native = quote! { Ok(quote! {
#[cfg_attr(not(target_family = "wasm"), ctor)] #[cfg_attr(not(target_family = "wasm"), ctor)]
fn register_node() { fn register_node() {
let mut registry = NODE_REGISTRY.lock().unwrap(); let mut registry = NODE_REGISTRY.lock().unwrap();
@@ -731,13 +731,7 @@ fn generate_register_node_impl(parsed: &ParsedNodeFn, field_names: &[&Ident], st
] ]
); );
} }
};
if cfg!(feature = "disable-registration") {
return Ok(native);
}
Ok(quote! {
#native
#wasm_shim #wasm_shim
}) })
} }
+221
View File
@@ -0,0 +1,221 @@
# Summary
Replace the boxed-future execution model with synchronous, poll-based evaluation. Nodes return a `GPoll<T>` state instead of futures. Async work runs to completion on an executor outside the graph; completion bumps a per-source generation counter which is injected into the context and hashed by memo nodes, so cache invalidation along the downstream cone is an ordinary cache miss. Asynchrony is modeled as a context feature, reusing the fine-grained context nullification pass to scope invalidation. All mechanisms described here have been validated in a standalone prototype; figures quoted below are measurements from it.
# Motivation
In the current model every node's `eval` returns a `DynFuture` (`Pin<Box<dyn Future>>`), even for trivial arithmetic, and the whole graph evaluation is one large future driven per render request. Costs:
- **Allocation per edge**: every eval boxes a future; pure nodes pay async machinery they never use.
- **No progressive rendering**: one slow async operation stalls the entire evaluation; there is no placeholder or partial result.
- **Wasted evaluations**: driving async work through graph re-evaluation costs a full traversal per poll.
- **Poor error semantics**: errors propagate as panics caught with `catch_unwind` at the root.
- **Blocks the precompiled future**: emitting the graph as Rust source running against a minimal runtime cannot be built on a box per edge.
# Guide-level explanation
## Evaluation states
Node evaluation is synchronous and always returns immediately:
```rs
enum GPoll<T> {
/// Waiting on at least one future, with no placeholder to compute with.
Pending,
Final(T),
/// Computed from provisional data; recomputed once the source generation bumps.
Partial(T),
/// An error occurred; the boxed value is a stand-in, downstream keeps computing.
Fallback(Box<(T, GraphError)>),
/// An error occurred and no stand-in exists; the cone cannot compute this frame.
Error(Box<GraphError>),
}
```
The variants split into "has a value" (`Final`, `Partial`, `Fallback`) and "has no value" (`Pending`, `Error`). Value-carrying statuses flow through computation: a node receiving `Partial` computes normally and downgrades its own output; a node receiving `Fallback` computes on the stand-in and forwards the error. Valueless statuses stop the cone for this frame. Statuses combine with a meet (`Final ∧ Final = Final`, anything else drags the result down; `Error` dominates `Pending`).
`meet(Partial, Fallback)` collapses to `Fallback`, which alone would make an error from a still-incomplete source indistinguishable from a final document error. Finality therefore rides a separate `Finality` (`AllFinal ∧ Partial`) tracked beside the status rather than a sixth variant, so the executor can withhold provisional errors from the document without widening `GPoll`.
Layout: one tag plus one payload word for pointer-sized values (`GPoll<Arc<T>>` is 16 bytes); the stand-in and its error share a box, and `Error` boxes the error alone, so it crosses node boundaries without reallocating. Progress percentages are deliberately not part of the value: they change at high frequency and must not invalidate the dataflow, so they ride the monitor side channel.
`GraphError` records the path from the error source upward as a list of input indices (names are ambiguous; a node can have two inputs of the same type). Its kind is structured: `ErrorKind::Node(&'static str)` for node-declared failures versus operational failures such as `ErrorKind::ArenaExhausted`, which the executor answers by resetting or growing the arena and re-rendering, never by reporting a document error.
## Writing nodes
Node authors write plain Rust functions; the macro generates the node struct, the trait impl, and all status plumbing. The function must compile standalone; the generated eval calls it. Four return tiers:
- `-> T`: pure kernel over evaluated inputs. The macro meets input statuses; the author never sees them.
- `-> Result<T, Interrupt>`: for kernels that evaluate lazy inputs themselves or fail. `Interrupt = Pending | Error(Box<GraphError>)`, with `From<GraphError>`, so semantic errors and input bail-outs share the `?` operator.
- `-> Result<T, (T, GraphError)>`: an error with an explicit stand-in value.
- `-> GPoll<T>`: full manual control (memo-class nodes).
Lazy inputs (`content: impl Node<Output = T>`) expose `eval(ctx) -> Result<T, Interrupt>`. The status mapping is the meet in imperative form: `Final(v)` is `Ok(v)`; `Partial(v)` and `Fallback(v, e)` are also `Ok(v)`, recording partiality or the first error in a status cell owned by the generated eval (a stack-local threaded by reference into the input handles); `Pending` and `Error` are `Err(Interrupt::...)`, and the kernel bails with `?`, the only thing it could do without a value. After the kernel returns, the generated eval folds the cell into the result, and converts `Err(Interrupt)` back into `GPoll::Pending`/`Error`. Trace indices are pushed by the handles, which know their input position, never by author code.
Because only actually-evaluated inputs touch the cell, an untaken `switch` branch does not drag the status down. `#[node(no_partial)]`, for nodes where placeholder data is semantically nonsense, is a one-line change in the handle mapping: `Partial` maps to `Interrupt::Pending`. Errors produced while any input was non-`Final` are provisional and must not be reported as document errors.
A migrated node body changes mechanically: delete `async`, replace `.eval(ctx).await` with `.eval(ctx)?`, return `Result<T, Interrupt>`.
## Async nodes
An `async fn` node is an external source. It extracts and clones everything it needs, spawns a `'static` future onto the runtime, and immediately returns a placeholder:
```rs
#[node(placeholder = get_placeholder)]
async fn get(url: String) -> String { ... }
fn get_placeholder(url: &str) -> String {
format!("Waiting for response on GET {url}")
}
```
The generated struct holds a slot map keyed by the context hash. On eval: completed slot, return `Final`; in-flight slot, return `Partial(placeholder)`; no slot, insert a marker, spawn, return the placeholder. The graph never suspends; every evaluation runs to completion and produces a frame. Async bodies cannot touch the context (the future must be `'static`); the generated code checks input statuses before spawning, so no request is issued from provisional data.
## Invalidation by generation
Each async node is a source identified by its stable node id (injected like monitor paths, so identity survives recompiles and deduplicated nodes share a source). The runtime maps source id to a shared generation counter; the spawn wrapper captures its own counter:
```rs
future.await; // write result into the node's slot
*generations.lock() // bump under the table lock; absent means the
.get_mut(&source)? += 1; // source was dropped, so the epilogue is inert
dirty.store(true, Release); // request a re-render (coalesced)
```
The slot map is `Arc<Mutex<HashMap<ContextHash, Option<GPoll<T>>>>>`, cloned into the spawned future rather than borrowed from the node, so a task still in flight when `BorrowTree` rebuilds the node writes into live storage. `Option` carries the in-flight marker: absent is "never spawned", `None` is "spawned, not landed", `Some` is the landed value. The same mutex that guards the map publishes the write to the next `eval`, so neither the slot nor the generation needs a separate release/acquire protocol.
At the start of each evaluation the runtime injects a snapshot of `(SourceId, generation)` pairs into the root context, sorted by id so hashing is deterministic. Memos hash the context as usual, generations included, so after a bump exactly the memos downstream of that source miss, and every other branch hits. No cache-tracking logic, no runtime graph walking, identical behavior in the interpreter and a precompiled DAG.
The re-render typically runs with the same context except the bumped generation, so the async node finds its completed slot: a source's own generation must not be part of its slot key, which the compiler pass below guarantees.
## Asynchrony as a context feature
Which generations a subgraph observes is determined at compile time by the same branch analysis as context nullification; the feature domain is the set of upstream `SourceId`s instead of a fixed bitflag. Requirements propagate rootward (a node's set is the union of its children's, minus what it injects). At branch convergence a dependency mismatch inserts a context modification node whose payload carries a generation retain set alongside the feature bitflags: no new node kind, no separate pass. The edge into an async node retains only sources strictly upstream of it, which excludes its own generation from its slot key by construction.
## Caching
Memo nodes hash the (retain-filtered) context, generations included. `Final` and `Partial` are both cached; partials are safe because the finalizing bump changes the key. `Pending` and `Error` are never cached. Two memo nodes exist with different contracts. The frame memo is the cheap one the compiler inserts at nullification boundaries: it publishes a promoted span into the persistent arena region keyed on the lane-normalized context, hits serve straight out of the region until the region's epoch flush, and a flush makes an entry unreachable, never wrong, so compiler-inserted caching costs a re-publish rather than a deep copy. The explicit memoize node is two-tier: the same span fast path over deep copies that survive flushes, for content whose recomputation is what the author is paying to avoid. The arena split, promotion, and the laws they rest on are covered in the attribute RFC's arena section.
## Runtime
Two layers, so the runtime stays minimal and the executor swappable:
```rs
/// Node-facing scope input.
trait Runtime { fn spawn(&self, source: SourceId, future: BoxFuture); }
/// Host-provided task executor with no graph knowledge.
trait Spawner { fn spawn(&self, task: BoxFuture); }
struct GraphRuntime<S: Spawner> {
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
dirty: Arc<AtomicBool>,
spawner: S,
}
```
`GraphRuntime` wraps each task with the completion epilogue. The `Spawner` is tokio or a thread pool on desktop, `spawn_local` on wasm, or the host polling a task list in the precompiled case. The runtime reaches async nodes as a scope input (construction-time, not part of the context); a graph with zero async sources compiles to no runtime at all.
The execution path itself is synchronous: executor construction, update, and `execute` are plain fns, and hosts compile and evaluate without an async runtime of their own. All asynchrony lives in source kernels behind the spawner; `execute` surfaces the poll state (`GPoll`) and each host maps it at its boundary. The one genuine await is the GPU readback, which wasm cannot block on; sync hosts block on that future, with a dedicated device-poll thread driving completion.
Wakers are deliberately not the graph-level notification mechanism: wakers resume suspended computations and this graph never suspends; a re-evaluation is a fresh call. Wake also does not mean completion, and wakers do not survive composition across host executors. The host avoids busy-waiting with one coarse notification (park/unpark or event-loop message) shared by task wakes and the dirty epilogue.
Scheduling semantics: generations are read once per evaluation (completions landing mid-frame affect the next one); the dirty flag is drained once per frame (N completions, one re-render); on recompile, `retain_sources` drops removed sources from the table, so their epilogue still runs but finds no entry and bumps nothing, neither invalidating nor waking the host. Tasks are not cancelled; they are made inert.
# Reference-level explanation
## Node trait
```rs
pub trait Node<Input> {
/// Serves the node's record through the caller's claim; the proof is
/// mintable only by the claim's closing methods.
fn serve<'e, 'l>(&self, input: &Input, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>;
/// Rank polymorphism extension point, scalar (`Free`) by default.
fn extent(&self, input: &Input, level: Level) -> GPoll<Extent> { ... }
/// Batched evaluation; the default body is the per-lane spec loop.
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>,
scratch: Option<&'a mut [MaybeUninit<u64>]>,
frames: &Frames<'e>) -> BatchStatus<'a>
where Input: InjectIndex + Copy + ExtractArena<ArenaRef = &'e Arena> { ... }
}
```
With the record model there is no `Output` associated type: every node
serves a record whose layout is wiring state, the element at offset 0,
and `serve` is the one required method. The caller mints the claim out
of its own frame space at the node's declared layout, so a served
record is of that layout by construction, and kernels evaluate their
inputs through generated handles that own the claims (the `eval` name
survives on those handles and on the batch path).
Three load-bearing shape decisions:
- **Plain `&self` receiver.** An `&'i self` receiver forces the forwarding impl `impl Node for &'i N`, tying the node borrow to the eval lifetime, which makes shared references unable to satisfy higher-ranked bounds. With `&self`, sharing, erasure, and stack-scoped derived contexts compose. The price: nodes cannot lend their own storage; all lending rides the eval lifetime through the arena carried in the context (a node-resident value costs one clone into the arena per arena generation).
- **No lifetime parameter on the trait.** With `&self`, any lifetime in the output can only come from the input type, so lending impls quantify over it: `impl<'e> Node<Context<'e>> for Lend { type Output = &'e T; }`. `GPoll` is fixed in the signature the way `Poll` is fixed in `Future`.
- **Input by reference.** `Input` is the owned context type; calls pass `&Context`. A modifying node keeps one mutable local, mutates it between calls (per-lane index stepping is one u64 store), and lends `&local` down; sound because inputs are second-class (never stored). This halved erased-edge cost versus by-value contexts (48 bytes of ABI traffic became one pointer).
The batching law: `serve` is the sole semantic interface, and any `eval_batch` override must be indistinguishable from the default per-lane loop; overrides are optimization, never semantics. `extent` reports a node's domain (`Free` for index-invariant, `Exactly(n)` for bounded), with uncertainty riding the `GPoll` status axis like any other value.
## Context
Contexts are borrow-based `Copy` values. Eval is synchronous, so context lifetime is strictly stack-shaped, and every axis lives where its modification frequency is natural. The production shape (48 bytes, built 2026-07-25 in `core-types/src/context.rs`):
```rs
struct ContextImpl<'e> {
index: IndexLink<'e>, // per lane: inline head, mutable in place
position: Option<&'e PositionLink<'e>>, // per push: frame-resident cons cell
varargs: Option<&'e VarArgLink<'e>>, // per scope: chain of &[DynSlot] links
footprint: Option<&'e Footprint>, // per transform: borrowed from the modifier's frame
scope: &'e EvalScope<'e>, // per frame/scope: timing, generations, arena, cached hash
}
struct IndexLink<'e> { index: u64, outer: Option<&'e IndexLink<'e>> }
```
Leveled axes are cons cells: the field holds the innermost level, `outer` chains through the frames of the structure nodes that pushed the enclosing levels. Only the index keeps its head inline (and non-optional; an unindexed evaluation reads as canonical lane 0), because it is the one per-lane-mutable axis: `set_index` is a branchless u64 store, which is what lets the trait's generic default `eval_batch` run without per-lane context rebuilds. Measured against a by-ref head, where every lane must materialize a fresh context because an erased callee may legally retain the pointer: 1.5 vs 3.6 ns/lane on the erased per-lane path, and an identical 0.11 ns/lane once the batch body is visible to the compiler (`benches/context_shape.rs`).
Derivation has exactly two moves. Replace copies the context and overwrites a field; the original leaves the chain, so its contribution vanishes with the copy standing in (no masking machinery). Push spills the current head to the pusher's frame and chains a new head onto it. Mixing both stacks a shadowed copy and a push, two frame values.
`EvalScope` groups everything scope-constant (timing, pointer position, the generation table, the arena) behind one pointer, together with a hash computed at construction. Modifiers of scope axes spill a new scope to their frame with the hash recomputed; in particular the retain filter stores only the filtered-generations hash, so contexts carry no retain slice and memo visits stop walking the generation list. The general discipline: hash at write time, mix at read time. Replace-not-compose remains sound because the nullification pass computes each edge's set absolutely. Context hashing must use a seeded fast hasher (zero-initialized fx absorbs leading zero words, which produced a real wrong-value memo hit in the prototype; hash-only memo keys make collisions correctness bugs). Hash values owe no compatibility to the owned context; the invariants are pinned by the property suite in `context.rs` (axis sensitivity, level order, axis-boundary disambiguation, retain scoping).
Varargs are frame-lent references (`DynSlot = &dyn AnyHash`), never boxes: the injecting node owns the values and lends a slice from its frame, and nested scope injections chain, concatenating innermost-first.
The trait never names this type. Capabilities are extract-style bounds on the generic input (`Ctx`, `ExtractIndex`, `InjectIndex`, `ExtractArena`), matching production's context traits. Borrow-returning extracts carry the eval lifetime through an associated type (`ExtractArena<ArenaRef = &'e Arena>`, written `ExtractArena<'e>` in the macro's sugar): a lifetime in an associated-type equality is a constrained impl parameter, while a trait lifetime parameter in a plain predicate is rejected (E0207), so generated impls stay generic over the input type even for lending nodes. The authoring rule is one sentence: a named lifetime in a node fn is the eval lifetime; it enters through an extract bound and exits through `&'e` in the signature. Everything else, including "nodes cannot lend their own storage", is ordinary borrow checking of the author's standalone function.
## Compiler pass
Extends `find_context_dependencies`. Per node, alongside the `ContextFeatures` bitflags, track the set of upstream source ids. The existing convergence rule triggers insertion of a retain filter (a `context_modification` node with a generation-retain payload) exactly as nullification nodes are inserted today. Infrastructure (memo, lend, clone_out, monitor) is inserted as ordinary proto nodes, exactly as main inserts memo and nullification nodes; their registry rows are generated from a central type census (one macro invocation over the supported-type list, TaggedValue-derived plus a hand-maintained remainder) rather than written per type by hand. The wire itself carries no behavior: an edge handle is a typed erased node plus its `Type`, and every constructor is an ordinary registry row.
## Generated code and overhead
Codegen requirements: the stand-in and error share a box, the status axis is flattened into `GPoll` (together: `GPoll<u32>` is 16 bytes instead of 48), and the status plumbing is `#[inline(always)]` (a plain hint loses to the inliner cost model on the error drop-glue branches). With these, a fused pure region compiles to native arithmetic plus a final tag store; a nine-node add/mul graph evaluates behind `#[inline(never)]` as four adds and two stores, with all `Pending` checks and status meets const-folded away. A fixed-output type-erased edge (`dyn for<'a> Node<Context<'a>, Output = u32>`) is one indirect tail-call with values unboxed; lending edges erase the same way. Measured on the wired prototype: erased edges 1.8ns versus ~9ns for the per-eval box-and-downcast model; batch lend paths reach the memory bandwidth floor; steady-state interpreted frames are allocation-free (nodes in a graph arena, contexts on the stack, values and scratch in the eval arena, memo hits lending).
# Drawbacks
- **Double computation on the provisional path**: the cone downstream of an async node computes once on the placeholder and again on the real value. Inherent to progressive rendering; `#[node(no_partial)]` is the escape hatch.
- **`'static` futures cannot lazily evaluate their inputs**: everything a future needs is evaluated and cloned before spawning.
- **Migration is a cutover**: the macro, registry, and executor flip together (see the integration plan); node bodies migrate mechanically but the landing is one large reviewed unit.
- **Slot and cache memory**: slot maps and LRU caches hold completed values per context hash; eviction policy needs tuning.
# Rationale and alternatives
- **Inline pinned futures** (store each node's future unboxed, poll once per graph evaluation): rejected; `Pin`-through-`Mutex` soundness arguments, a trait bifurcation, conflicts with `BorrowTree` moving nodes, and graph evaluations as polling iterations.
- **Poll-once compatibility shims** for existing `async fn` bodies: rejected in favor of the mechanical `?` edit; genuine IO must move to the source tier anyway (a poll-once body would silently re-issue requests every frame), and the cosmetic sites are few.
- **Bail on `Partial`/`Fallback`** (all statuses through `Err`): rejected as the default; it kills progressive rendering and stand-in propagation, and a value-carrying error type does not typecheck across inputs. It survives as the `no_partial` mapping.
- **`Cow`-shaped wire values** (each edge carries owned-or-borrowed): rejected by measurement, 2.27 to 5.08 ns/edge on the cheapest chain, a graph-wide tax versus coercion adapters that cost only where inserted.
- **Waker as completion signal**: wake does not mean completion, wakers do not compose across host executors, and there is no suspended continuation to resume.
- **Manual downstream cache clearing on completion**: needs runtime topology introspection and cache-tracking logic; generation-in-hash gets the same effect through the compiler pass and works unchanged precompiled.
- **Per-evaluation scope mutation for memo GC**: scope inputs are construction-time and must not be per-frame channels; bounded LRU needs no external signal.
# Unresolved questions
- Partial epochs: futures that publish intermediate data (streams, progressive decode) want a weaker invalidation than completion.
- Arena sizing and growth on exhaustion (grow-and-retry across frames); ownership and the reset policy landed with the two-arena split, transient reset per evaluation and persistent epoch flush after a refused reservation.
- Exact policy for provisional errors.
- `Send`/wasm: spawned futures need `Send` on native only; the arena's concurrency claims need loom before any multi-threaded executor.
# Future possibilities
- **Rank polymorphism via extents**: lists as index-functions with the index carried in the context, domains reported by `extent`, batching as the interpreter's amortization; reserved here by the defaulted `extent` method. One `Add` implementation then covers scalar-scalar, scalar-list, and list-list with no monomorphization, and broadcasting is cheap because index-nullification lets the scalar branch memoize once per domain.
- **Precompiled DAG emission**: node structs in topological order as Rust source; the runtime shrinks to the generation table, a spawner hook, and a dirty flag.
- **JIT of graph regions**: the remaining gap between chunked interpretation and monomorphized code is unfused loop passes, the JIT's job, not the ABI's.
+882
View File
@@ -0,0 +1,882 @@
# Summary
Give every item flowing through the graph a set of named, typed attributes
next to its primary `element` value. Attributes are stored as a packed
record whose layout the compiler computes at graph compile time. Nodes
declare their attribute reads and writes in their signatures, and the
compiler resolves every access to a byte offset during wiring, so there is
no name lookup at runtime. Storage and batch results are per-attribute
columns. The contiguous record only exists as a per-lane view, assembled
into frames claimed from the evaluation's frame space. All of the machinery that could
corrupt a layout is generated code, so getting it wrong is a type error or
a graph compile error rather than undefined behavior.
# Motivation
Attributes currently exist as a string-keyed store of type-erased
columns beside the elements:
```rs
pub struct List<T> {
element: Vec<T>,
attributes: Attributes,
}
struct Attributes {
attributes: Vec<(String, Box<dyn AnyAttribute>)>,
len: usize,
}
```
So the storage is already columnar: one boxed column per name, each
holding `len` values. What it is not is resolved. Every access searches
the key list by string comparison and downcasts the column, and merging
eagerly pads missing attributes with materialized defaults. Scalar
access boxes per value at the item boundary, where the same store
appears as `ItemAttributeValues(Vec<(String, Box<dyn AnyAttributeValue>)>)`.
On a ten-node chain with eight attributes over 64k items this costs us
around 500ns per item. The design described here measures between 3.5
and 47ns on the same workload, depending on the execution mode, and the
cost is mostly independent of the attribute count.
There is also a cost at compile time and in the node catalog. Because
attributes ride inside `List<T>`, a node that touches a property carries
an implementations list enumerating every carrier type: the opacity and
blend-mode nodes each name seven. Each row monomorphizes, adding a new
carrier type means editing every one of these lists, and the duplicated
instantiations show up in the build size, measured at 6.16 MB and about
4% of frame rate when the rank work landed. An escape hatch exists for
the narrow case of reading an attribute without the element (`ListDyn`,
which erases the carrier), but it does not extend to nodes that write.
Separately, opacity on a group and opacity on each member composite
differently once members overlap, so the two are semantically distinct
and the representation has nowhere to record which one a node meant.
The requirements, briefly. Attributes are named with strings and work
for all types, and users can author read/write nodes with custom names.
A node placed before vs. after a structure node affects different
nesting levels. Items whose element types agree can merge regardless of
their attribute sets, with missing values filled from name-specific
defaults. Names resolve at graph compile time, with a dynamic escape
hatch for runtime-shaped data. A wire without attributes costs what a
plain wire costs, and an attribute that is constant across a domain
costs one slot rather than one per element. Batch access is the case to
optimize, and scalar access should not require a second representation
with conversions between the two.
# Guide-level explanation
## What an attribute is
An item is a primary value (the `element`, which determines the wire's
type and colour) plus a set of named attributes that flow along with it.
A node can read, add, or overwrite one attribute without touching the
element and without knowing which other attributes exist. Lists carry
attributes at every nesting level, so an attribute on a group is a
different thing from the same attribute on the group's members.
## Declaring an attribute
An attribute name is declared once, as a marker type:
```rs
attribute! {
/// How visible the content is.
pub Opacity("opacity"): f64 = 1.;
/// The item's label, parked in the arena by the writer.
pub Label("label"): &str;
}
```
Each entry expands to the marker struct, its `Attribute` impl, and the
census registration. This fixes the name, the value type, and the
name-specific default
(opacity should default to fully opaque, not to `f64::default()`). The
registry collects the declarations into a census, and a misspelled name
in a document can be diagnosed with a nearest-match suggestion. For
names declared in code, one name belongs to one marker, so a name can
never mean two different types. For user-supplied names, the marker
fixes the value type and the default in code, while the name itself
arrives as a constant text input on the document node. It joins the name
table at graph compile time, which is where every resolution happens
anyway, and two user-supplied names colliding at different value types
is a graph compile error naming both nodes.
A write can also be generic over the name. The shape is settled but not
yet built: the marker is `Generic<X, T>` with the value type declared
concretely in the signature, so `Attr<Generic<X, f64>>` and
`Attr<Generic<Y, f64>>` are two independently named f64 writes and no
runtime type dispatch exists. The name itself arrives as a constant
text input on the document node and joins the name table at graph
compile time, which is where every resolution happens anyway; two
user-supplied names colliding at different value types is a graph
compile error naming both nodes, the same one-name-one-type check that
covers declared markers. A generic read resolves only when the binding
is unique, and anything else is a validation error. The node is one
compiled instance per concrete value type; the name never enters
monomorphization. The build is sequenced after the current cleanup,
and its editor-facing access has to be design-checked against the
typed attribute key API (#4352) before it lands.
## Reading and writing attributes
A node declares its attribute io in its signature. A parameter that
reads attributes destructures its input into the wired value and the
reads taken from that input's wire. The opacity node becomes:
```rs
/// Modifies the opacity of the input by multiplying the existing value by this percentage.
#[node_macro::node(category("Blending"))]
fn opacity<T>(
_: impl Ctx,
(element, opacity): (T, Attr<Opacity>),
/// How visible the content should be, from 100% (fully opaque) to 0% (fully transparent).
#[default(100.)]
factor: Percentage,
) -> (T, Attr<Opacity>) {
(element, Attr(*opacity * factor / 100.))
}
```
An `Attr<A>` inside a parameter tuple is a read from that parameter's
wire (it yields the declared default if nothing upstream wrote the
attribute), an `Attr<A>` in the return tuple is a write, and the same
marker on both sides is a modify. A `RemoveAttr<A>` in the return
tuple is a delete: the name leaves the output layout, downstream reads
yield the default again, and the column leaves the Data panel. A read
binds to the input it is destructured from, so which wire an attribute
comes from is always explicit in the signature, and secondary inputs
declare reads the same way:
```rs
(factor, out_of_100): (Percentage, Attr<OutOf100>),
```
There is no implicit attribute flow between inputs. The primary
input's attributes pass through to the output, overwritten where the
node writes; a secondary input contributes exactly the reads its tuple
names. An input without reads stays a plain parameter. Parameter
attributes (`#[default]`, `#[implementations]`, doc comments) apply to
the value component; attribute markers are concrete types and never
enter monomorphization.
The first parameter after the context is the primary input, with or
without a read tuple, and an unbounded generic `element: T` in its
value position that is returned in the first tuple position means
"I pass the element through unchanged". The compiler lowers this to a
byte copy (often to nothing, see below), and a single compiled instance
covers every element type, with no trait bounds and no implementations
list. A node that actually computes on the element uses a concrete type
or a bound instead and monomorphizes per its implementations list.
`_: ()` means "no primary input".
## Levels: before vs. after a structure node
This part of the design is not settled, and the first implementation
resolves every attribute at a single level. It is written up here
because the requirement is real and the rest of the model has to leave
room for it; see the open question at the end.
Where a node sits in the chain should decide which nesting level it
affects. Applying the opacity node to a shape and then repeating it
would give every copy its own opacity. Repeating first and then applying
opacity would set one value on the whole group, which composites
differently where copies overlap. The node's code is identical in both
cases. Reads and writes bind to the top level of the wire at the node's
position in the chain, and Repeat pushed a level in one of the two
arrangements. Reaching an inner level from outside is an explicit
map/enter construct, so "set on the parent" and "map over the children"
are visibly different graphs.
## Structure nodes
A node that produces a list declares the new level's extent and writes
per-copy values. The body is one lane of that list. There are two
shapes, and which one applies is decided by whether the copies have to
re-evaluate the content.
The general shape takes the content lazily and evaluates it once per
copy, at that copy's index:
```rs
/// Instances the content a number of times, spaced by the direction vector.
#[node_macro::node(category("Repeat"), extent(repeat_extent))]
fn repeat<T>(
ctx: impl Ctx + DeriveCtx + ExtractIndex,
content: impl Node<Context<'_>, Output = (T, Attr<Transform>)>,
#[default(1)]
#[hard(1..)]
count: u32,
#[default(100., 100.)]
direction: DVec2,
) -> Result<IList<(T, Attr<Transform>)>, Interrupt> {
let inner = content.inner_extent(ctx)?;
let (copy, rest) = ctx.split_innermost(inner);
if copy >= count as u64 {
return Err(GraphError::past_end().into());
}
let offset = direction * copy as f64;
let mut frame = IndexLink { index: 0, outer: None };
let (element, transform) = content.eval(&ctx.push_level(&mut frame, copy, rest))?;
Ok((element, Attr(DAffine2::from_translation(offset) * *transform)))
}
```
The kernel splits the flat index into its own copy index and the index
below it, then evaluates the content at a context with the copy pushed
as a level. `DeriveCtx` is what admits the push, and only a lazy input
can receive a derived context, so this shape is exactly the one where
the copies are allowed to differ: anything upstream that reads the index
sees the copy it is being evaluated for.
Where the copies do not re-derive the content, the input stays an
ordinary carrier and the kernel only computes the copy's own attributes:
```rs
#[node_macro::node(category("Repeat"), extent(repeat_opacity_extent))]
fn repeat_opacity(ctx: impl Ctx + ExtractIndex, element: f64, count: u32) -> IList<(f64, Attr<Opacity>)> {
emit(element, Attr(ctx.index() as f64))
}
```
A carrier is evaluated once for the whole run rather than per lane, so
every copy sees the same element and the variation lives entirely in the
attributes. The `emit(...)` tail marks the one-lane form and doubles as
the tuple constructor, and it is optional.
## Merging
Merging concatenates. The merged attribute set is the union of the
inputs', and an attribute missing on one side is filled with its declared
default for that side's items, so the result is rectangular in every
attribute. A scalar input contributes one item. When lists are combined,
each input's own top-level attributes are pushed down onto that input's
items (composing by the attribute's declared rule where one exists;
otherwise the pushed value fills the items that never wrote the name
and the inner value wins where they did, resolved from the write sets
at graph compile time), and the merged list starts with an empty
top level. If the user wants to keep the groups as groups, they wrap
explicitly instead.
## Selecting
Switch takes two lazy inputs and returns one of them, for any carrier,
without an implementations list:
```rs
/// Evaluates either the "If True" or "If False" input branch based on the condition.
#[node_macro::node(category("Math: Logic"))]
fn switch<T>(
ctx: impl Ctx,
_: (),
condition: bool,
#[expose]
if_true: impl Node<Context<'_>, Output = T>,
#[expose]
if_false: impl Node<Context<'_>, Output = T>,
) -> T {
if condition { if_true.eval(ctx) } else { if_false.eval(ctx) }
}
```
An unbounded generic on a lazy input means the whole record flows
through. Evaluating a branch yields an opaque value carrying its record,
and whatever value the kernel returns is the output, element and
attributes together. Kernels can evaluate several inputs, hold the
results side by side, and pick among them with any logic, so fallback,
N-way multiplexers, and per-lane data-driven selection are the same
two-line pattern rather than new node kinds. The branches may carry
different attribute sets. The output carries their union, filled with
defaults per branch. A lazy input with a concrete output type is an
ordinary value input: its value flows, the attributes on its wire do
not. The tuple form composes with laziness: a lazy input declared
`Output = (T, Attr<A>)` yields the element and the declared reads at
each evaluation, so a kernel can branch on another input's attribute
without evaluating the branch it rejects. It is a read declaration
only: the lazy input's fields do not pass through to the output, since
the kernel controls whether and how often the input is evaluated;
forwarding a lazy input's attributes is routing.
The rest of the authoring surface composes. Categories, per-parameter
doc comments, `#[default]`, `#[hard]`, `#[expose]`, widget overrides, and
the kernel dialects (`Result<_, Interrupt>` with `?`, `GPoll` returns,
async sources) all compose with the forms above. An async source writes
its attributes through its claim like any other node; a reference-valued
attribute crosses the future boundary as an owned deep copy, covered in
the reference section.
# Reference-level explanation
## Records and layouts
A record is the element at offset 0 plus one field per written attribute,
aligned to the widest field. Since the element comes first, a pointer to
the record is also a valid pointer to the element. Element-only
consumers are wired without adaptation, the wire keeps the element's type
and colour, and the registry stays keyed on element types.
```
byte 0 4 8 12 16 20 24 28 31
┌───────────────┐
f64 │ element │
└───────────────┘
┌───────────────┬───────────────────────────────┬───────┬─┬───┐
+3 │ element │ Attr<&str> (ptr, len) │ u32 │b│pad│
└───────────────┴───────────────────────────────┴───────┴─┴───┘
Canonical order (descending alignment, then size) leaves no interior
padding here; 3 bytes of tail round the record up to align 8.
```
A wire's layout is the set of all attributes written in its upstream
cone and not removed since, in a canonical order (descending alignment,
then size, then name and level), computed at graph compile time. Some
consequences:
- Layout identity is captured by stable node ids, because the write set
is part of the hashed upstream cone. An instance that survives an
incremental recompile cannot meet a changed layout.
- Reads resolve to `Option<offset>` at wiring, each against the layout
of the input wire its tuple destructures. Present means a field
access, and absent means the macro emits the default constant. Writes
always resolve. The runtime does no name lookup, no hashing, and no
downcasting. A resolved read costs the same as a native struct field
access (0.43ns).
- Writes that are never read are diagnosed. Eliding them is a permitted
whole-graph optimization but not required. Keeping them in the layout
is what keeps the layout a pure function of the upstream cone.
- Layouts are derived data. The document stores only user-visible
structure, no attribute data is serialized, and representation changes
never require a document migration.
- Semantically a wire value has every attribute at all times: a read of
a name nobody wrote yields the declared default, so a written default
and an absent name are indistinguishable at runtime. Presence
(membership in the layout) is representation, consulted only by merge
push-down's fallback and the Data panel, which presents the layout:
column presence is a pure function of the graph, stable across frames
and across the branches a selector takes.
- Writes are unconditional: presence never depends on a value, so a
conditionally relevant attribute is written at its default, and a
runtime `Option` around a value buys nothing (`None` could only mean
the default). A name that wants a distinguished unset declares an
`Option` value type on its marker.
Fields are `Copy`, and larger payloads go behind a pointer-sized field.
Runtime-shaped data (CSV columns, arbitrary JSON) is a single dynamic
attribute holding a map in a fixed-size slot. It is the intended slow
path and puts no constraints on the fast one. Layouts are always static.
A name's type is unique by construction. For declared markers the census
admits one marker per name, checked when the registry is built. For
user-supplied names the binding forms at graph compile time, carrying the
marker's declared value type, and two names colliding at different types
is a graph compile error that names both nodes. Generic-named writes
join the same table, carrying the name and value type their bindings
resolve to, so the check runs over declared markers, user-supplied
names, and generic instantiations together. We do not attempt
coercion.
## Levels and residency
Layout keys carry a level, and levels are numbered from the innermost
out, which keeps them stable when a structure node pushes a level
(nothing renumbers) and matches how indices are already numbered. Only
level 0 is populated today: the packed-record tier is flat, so the
binding rules below and the residency analysis that follows them are the
intended design rather than the implemented one. The level in the key is
what leaves room for both. Keying is frozen at level 0 for the parity
landing: no re-leveling exists, a level other than 0 is unsupported,
and catalog nodes assume level 0.
The binding rules are:
- A read binds to the top level of the input wire it is destructured
from at the node's chain position; a write binds to the top level of
the output wire.
- A structure node pushes a level and then writes its per-copy
attributes into the former top row, and the new top row starts empty.
- A node that reads the element (concrete type or bound) is pinned to
level 0. An element-agnostic node binds to whatever the top currently
is, which is also what allows a pure attribute node to run at a level
where no element is materialized at all.
An attribute at level j ignores indices deeper than j by definition, so
the level a value's storage actually varies with (its residency) lies
somewhere between its binding level and the root. The compiler computes
residency with the same index-invariance analysis used for context
nullification. Constant-everywhere is residency at the root: one slot.
A per-item attribute that only varies per group is bound at level 0 but
resident at level 1, so it gets one slot per group rather than one per
item.
Storage is meant to be level-resident and columnar, with the contiguous
record as a view. Per-lane consumers get the view assembled across
levels and columns into their activation frames. Reads across a level
boundary use the same index decomposition the structure nodes already
perform, and in batches that decomposition is hoisted per run. Neither
the residency analysis nor the multi-level storage exists yet; a single
level with resolved offsets is the base case both are built on.
## Runtime representation
- Every node's per-lane output lands in a frame claimed from the
evaluation's frame space: a grow-only buffer the executor owns and
lends down, sized at wiring by folding each path's frame need, so
exhaustion is an accounting failure a debug assertion catches rather
than a hot-path branch, and frame bytes carry no drop glue. A node's
caller mints the node's frame claim out of its own free space; the
node writes through the claim and closes it through `serve`, the
`Node` trait's one required method, whose `Served` proof is mintable
only by the claim's closing methods, so a served record is of the
claimed layout by construction. The claim carries the free space
beyond the frame, the node's inputs claim past it one after another,
and a claim's space is free again when the claim dies, on value,
error, and pending exits alike, with no per-exit ritual. "Allocating"
a result is cursor arithmetic; a droppable payload parks in the arena
once and the record carries the reference.
- No global slot assignment exists: a node's wiring state is its own
frame size, so incremental recompiles and instance reuse cannot
invalidate storage. The frame space belongs to the evaluation rather
than to a thread, so worker counts never enter wiring. The reserve is
the peak of a per-path fold over the graph (a node's need is its own
frame plus its inputs' frames plus the deepest input's peak), computed
once at wiring; it exceeds the plain sum of node frames because
fan-out re-evaluation keeps several copies of a shared node's frame
live at once.
- Held record values are safe without a guard: a claim keeps its record
until it dies, so no input is released while a later sibling
evaluates. Shared subtrees additionally rely on single consumption.
The compiler's boundary frame memos provide it where the
nullification pass inserts them; automatic insertion at every fan-out
is designed but not built, and until it lands it gates the
stack-return optimization for shared un-memoized subtrees.
- Batch results are a run of lanes behind a resolved offset per field,
and the target form is per-field columns, each statically Varying (an
array) or Uniform (a single value) per the residency analysis. A node
that does not touch a column then forwards the pointer, so bypass
costs nothing, and uniform columns give constant attributes their
one-slot cost regardless of lane count. Both execution forms share one
layout descriptor, and crossing from a batched producer to a per-lane
consumer costs about 1.5ns per lane through a lane-view adapter. The
first implementation lays the run out as an array of records and
resolves each marker to an offset within a lane; moving that to
struct-of-arrays, and then to flat tables, happens behind the same
accessors. A batched producer serves lanes in place over the caller's
scratch through a claimed run of same-layout slots, so a lane serves
with no staging copy.
- A materialized level carries its lane count beside its layout and its
storage, which is either an arena-resident run or an owned copy.
Erased consumers (the Data panel, capture, deep copy) read the count
and the fields off that handle without reaching into the element type,
and Varying vs Uniform is meant to stay static in the layout, a
Uniform column addressing a single value. This is the same picture as
a batch result, so materializing a level and returning a batch are one
format. A record value is one pointer wide, and only a record whose
layout is empty rides inside the value itself; everything else spills
to claimed frame space.
- Alignment padding is what the column form buys. In a row, a `u8`
element costs the same as a `u64`, while packed columns keep the cost
proportional to the element size (2x cheaper than rows when
cache-resident, around 8x when memory-bound). Once columns are the
storage format, the proportional cost holds wherever data accumulates
and the padding survives only in transient view slots, whose number is
bounded by graph depth. Until then a run pays a row's padding on every
lane, which is the cost the struct-of-arrays step removes.
## Arenas, promotion, and memos
Droppable payloads and every borrow a record lends live in two arena
regions per executor. The transient arena is reset at the end of every
evaluation: allocation is a bump, a parked payload registers a drop
obligation, and the reset is a cursor rewind plus the registered drops.
The persistent region holds what must outlive an evaluation (published
memo spans, moved payloads) and flushes as a whole epoch, only between
evaluations and only after a refused reservation. Every crossing from
outside storage into a region is generation-checked, so a stale handle
is a cache miss, never a dangle.
Two rules the split rests on, both bought with measurements:
- The retention law: arena occupancy is not a proxy for retained heap.
A park costs one pointer in the region while owning arbitrary heap
outside it (a 52x gap was measured), so a single region cannot
decouple transient droppable heap from span lifetime; the one-arena
epoch design this replaced ran a real document to a 12.3 GiB OOM.
The split, plus a per-park retained-heap hint kept as a lower bound,
is the answer.
- The sharing law: sharing a payload between persistent entries is
sound because persistent invalidation is epochal, every entry dying
at one flush; per-entry eviction would need the refcounts this design
avoids. One level down, a reference-valued attribute field's header
is never provenance-shared: it clones, or moves where the payload
owns all of its content and the transient arena confirms the
reference is its own park keyed by the payload's static type. The
move is a header memcpy with the drop obligation and its heap hint
transferred, the source entry tombstoned in place, and a
per-generation forwarding map so a payload two records share moves
once.
Promotion into the persistent region is copy-on-write over provenance:
a reference already persistent or `'static` is shared pointer for
pointer, a transient leaf payload moves its header, and region bytes
memcpy. Types with arena-resident interiors register promote glue in
element- and field-keyed registries, so nested content takes the same
dispatch instead of a deep copy through an owned intermediate.
Two memo nodes ride this, with different contracts. The frame memo is
the cheap span-only memo the compiler inserts at nullification
boundaries: it publishes a promoted level into the persistent region
keyed on the lane-normalized context, a hit before the next flush
serves straight out of the region, and a flush makes an entry
unreachable, never wrong. The explicit memoize node is two-tier: the
same span fast path over deep copies that survive flushes, so
author-marked expensive content never pays recomputation for a flush.
An async source's future outlives the evaluation that spawns it and may
outlive a persistent epoch, so a reference-valued attribute cannot
cross into it as a region handle: a flush would invalidate the handle
mid-flight, and pinning the park would need the refcounts the sharing
law avoids. It crosses as an owned deep copy instead (`OwnedAttr`),
taken through the field glue before the first await while the spawning
evaluation's storage is live, and parked into the serving arena at
every lift, one copy per invocation.
## Kernel io lowering
| Signature form | Meaning | Lowering |
| --- | --- | --- |
| first non-context param | primary input | carrier record |
| `_: ()` | no primary input | no carrier input |
| `element: T` (unbounded, returned first) | explicit passthrough | erased byte carry, where `T` is instantiated with a zero-sized token, so the routing is checked by the type system and costs nothing |
| `element: Concrete` / bound | element read | field read at offset 0, monomorphized per implementations list, binds level 0 |
| `(x, a): (X, Attr<A>)` | input with attribute reads | the value as its ordinary lowering; each `Attr` an offset read into that input's record, or the default constant |
| `(_, a): ((), Attr<A>)` | attribute-only input | a wired record input with unit element; the attribute is the payload |
| `Attr<A>` in the return tuple | attribute write | offset write into the output record |
| `RemoveAttr<A>` in the return tuple | attribute delete | the name leaves the output layout; functionally a write of the default |
| `OwnedAttr<A>` in an async source's return tuple | owned attribute write | the value crosses the future boundary as a deep copy taken before the first await, and parks into the serving arena at every lift; exhaustion surfaces as a poll |
| `keys: IList<K>` | whole-extent input | a wired input, evaluated over its extent into a view |
| plain parameters | wired value inputs | ordinary wired value inputs; attributes on their wires do not flow |
| `impl Node<Context<'_>, Output = Concrete>` | lazy value input | the value flows, attributes do not |
| `impl Node<Context<'_>, Output = (T, Attr<A>, ..)>` | lazy input with attribute reads | each eval yields the element plus the declared reads, offsets resolved against that input's layout; a read declaration only, and no field pass-through |
| `impl Node<Context<'_>, Output = T>` (unbounded) | source of an opaque record family | routing, see below |
| `-> IList<W>` with a lazy subject and `DeriveCtx` | per-copy level production | the kernel splits the index and evaluates the subject at the pushed level |
| `-> IList<W>` with a carrier subject | per-lane level production | the carrier binds once for the run; the kernel computes each lane's own fields |
| `-> IList<W>` without `extent(fn)` | store form | whole-level body, node owns storage |
`extent(fn)` names a function over the node's inputs and the queried level
(author code never receives the node struct); `extent_raw(fn)` is the
escape hatch for anything that vocabulary cannot say. The declaration
answers what the level's counts are; the kernel performs the matching
index decomposition itself. The two are written separately and have to
agree, which is why the split and push go through shared helpers rather
than open-coded arithmetic. `emit(...)` is an optional tail marker for
the carrier form whose parentheses double as the tuple's, so multi-write
lanes pay no extra nesting.
The rule behind all the lazy forms: kernels control whether, when, and
at which index their inputs are evaluated, but never how the records
move. Attributes travel inside record values or
through generated machinery, so kernel-controlled evaluation cannot
misalign them, and domain declarations stay with the extent system.
## Structure shapes
A structure node pairs an extent composition with an index
decomposition. The extent composition is an ordinary extent override:
the node macro's `extent(fn)` attribute names a function over the node's
inputs and the queried level to `GPoll<Extent>`, with `extent_raw(fn)` as
the escape hatch keeping the raw node, context, and level form, so
multiplicative, additive, and data-dependent extents are one mechanism
rather than a macro taxonomy, and the default stays the meet over the
value inputs.
- Multiplicative (Repeat, map/enter): the extent override answers the
pushed level with the copy count and forwards inner levels to the
content. The kernel splits the flat index into the copy index and the
index below it through the shared split helper, and pushes the copy as
a level on a derived context before evaluating the content there. The
extent declaration and the split are written separately and have to
agree; the helpers are shared so that they can. Batches split into
maximal per-copy runs.
- Additive (Merge): an ordinary routing kernel whose selector condition
is the index. The kernel range-splits the flat index into a segment
and a local index through the shared split helper and evaluates that
input at the shifted index via the derived-context lowering; the
extent override sums the inputs' extents through `Extent::sum`. An
input with unbounded (Free) extent counts as exactly one item in the
sum, so merge is an extent-forcing boundary, which is the scalar base
case. Item rows union with per-segment default fill. Each input's top
row is pushed down one level onto that input's items via entries in
the translation plan (a level remap computed at wiring; no values are
needed at compile time), composing by the declared combine rule; the
fallback is inner wins iff the inner level wrote the name, resolved
from the write sets at wiring. The merged top row starts empty. An
explicit Wrap node is how the user nests instead; a marker on the
merge node enables the push-down plan variant. Batched merge forwards
per-segment sub-ranges derived from the same split helper, so column
uniformity survives concatenation per segment, default
materialization is only paid on the per-lane and store paths, and
per-lane vs batched agreement is law-bound.
## Opaque record values
An unbounded generic names a family of opaque record values. Its
sources are the lazy inputs whose `Output` is the generic; the element
passthrough is the same mechanism with the carrier as the family's only
source. Wiring computes the union of the sources' layouts and a
translation plan per source (field moves plus default fills). The
kernel-facing handles wrap the inputs the same way the error dialect
wraps status plumbing: evaluating a source evaluates its input at the
unchanged context and yields a value carrying the resulting record,
either through the plan into a claim of that source's own, or, when the
source's layout already equals the union, by forwarding the record
pointer untouched. The forwarding case compiles to a conditional move
plus a tail call; the +4.7ns per lane of a two-branch switch is the
condition and ordinary branch misprediction, and a translating source
costs +6.5ns per lane at eight attributes.
The kernel routes these values as ordinary Rust values. It can evaluate
any source any number of times, hold several results at once (per-source
claims keep them valid side by side), pass them through helper
functions, and return any of them. The returned value's record is the
node's output, so provenance is carried by the value itself: element and
attributes travel together, and returning a result obtained before some
later evaluation is well-defined. A value is live until its own source
is evaluated again, which reclaims that source's claim; a kernel that
needs two results of one input side by side declares the input twice.
The values are opaque and unforgeable, and inspecting one requires
bounds on the generic, which is element access and monomorphization as
usual.
This is the general form of selection: switch, fallback, N-way
multiplexers, and per-lane data-driven choice among inputs are all plain
kernels over the same mechanism, and none of them needs anything from
the macro beyond the family lowering. Whole-list switching vs. per-item
zip is just the residency of the condition: an invariant condition
collapses through nullification, a varying one selects per lane.
The one-source shape also covers the registry's infrastructure rows.
Monitor, context modification, memoize, and the lend and clone adapters
are all `T -> T` passthroughs with a side effect. Over the record family
each is a single generic node: the record forwards, and the side effect
is orthogonal to the type (a reflective snapshot through the layout
descriptor, a derived context, or a persistence copy sized by the
layout). Persisting a non-Copy element needs a clone and drop function
per element type, registered once beside the type itself rather than
once per infrastructure node, so the per-type surface is types plus
nodes rather than types times nodes, and compiler-inserted
infrastructure splices one generic proto node without naming value
types. The genuine conversion rows (the Into and Convert matrix)
remain, because those do real per-type work.
A kernel that modifies the index on the context evaluates an input at a
lane other than its own, which makes index-computable reorders plain
kernels:
```rs
/// Reverses the order of the input list.
#[node_macro::node(category("General"))]
fn reverse<T>(
ctx: impl Ctx + ModifyIndex + Copy,
_: (),
content: impl Node<Context<'_>, Output = T>,
) -> Result<T, Interrupt> {
let total = match content.extent(ctx, Level::Total) {
GPoll::Final(Extent::Exactly(count)) => count as u64,
GPoll::Pending => return Err(Interrupt::Pending),
_ => return Err(GraphError::new("reverse over a non-exact extent").into()),
};
let mut shifted = *ctx;
shifted.set_index(total - 1 - ctx.innermost_index());
content.eval(&shifted)
}
```
Shift, slice, and read-item-at-index are the same shape. Sort and
shuffle still compute a whole-extent permutation once per sweep, which a
pure per-lane kernel cannot hold, so they keep the remap-returning
kernel. Applying a remap has a spec: per lane, evaluate the input at the
permuted index. The generated batch kernel is the law-bound override of
that spec, materializing the input's columns once
and gathering each index-varying column through the wiring-resolved
table with index-invariant columns skipped (about 1.4ns per varying
column per lane; the comparison work of the sort itself does not depend
on the representation). For a bijective permutation the per-lane spec
already costs the same number of upstream evaluations as direct
consumption, so the batch form buys cache locality and run coherence
rather than correctness.
## Compiler passes
Everything happens at graph compile time. The census is assembled from
the marker declarations (names, types, defaults, combine rules). Each
wire's layout is constructed from its upstream write set, and residency
comes from the index-invariance analysis. Offsets are resolved into node
state, the stack bound is folded from the layouts, and union and
translation plans are built at selectors and merges. A per-name
dependency analysis feeds the cache keys. The diagnostics produced along
the way are unknown or misspelled names (checked against the census,
with nearest-match suggestions), custom-name collisions, reads that some
evaluation path cannot satisfy, and layout conflicts. The runtime does
no name lookup. Layout construction and the safe record builders check
field type identity and panic on a mismatch, which is what guards the
generated code against itself at wiring boundaries.
## Soundness
Attributes only move through generated machinery. Kernels receive
dereferenced values and opaque handles, and the translation and carry
plans behind them are emitted from wiring-resolved layouts. Layout
identity is captured by stable node ids, so an instance that survives a
recompile can never meet a changed layout. Because layouts are functions
of wires rather than of anything a kernel controls, safe kernel code can
make semantic mistakes (evaluating an input it did not need to) but
cannot misalign an offset. Kernels see contexts only as an opaque
`impl Ctx + ...` they cannot construct, and lifetimes keep them from
stashing handles in node state.
That is the property the design is for, and the enforcement now rests
on construction at the seams that used to be open. Type identity is
stamped on every layout field and on the element write, and both
participate in layout equality, so the union's shared-element assertion
and the identity-forwarding decision distinguish same-shape
different-type layouts. Retiring the inline register-return path in
favor of always-spill removed the one producer that wrote without an
installed layout. Serving closes only through a frame claim's own
methods, whose proof cannot be minted elsewhere, and assertion reads go
through an owned capture at the node's declared layout rather than raw
frame reads. Serving lifetimes make an arena-resident value
inexpressible beyond its evaluation in safe code, and an arena move is
keyed by the park's static type, so a mistyped or unkeyed reference
declines into the clone path instead of moving foreign bytes. What
remains unsafe is the irreducible core, the erased glue and the
wiring-computed byte plans, plus a small tracked set of open seams of
which the hoist mask's positional contract is the last
soundness-relevant survivor; an adversarial audit round over every
safety contract is scheduled before this lands upstream.
# Drawbacks
- The node macro absorbs real complexity: io classification, layout
bookkeeping, the structural skeletons, and the record-family lowering are all
generated code. That is the point (authors stay simple, the privileged
surface stays auditable), but macro diagnostics will need work to stay
better than raw trait-solver errors.
- Changing a document's attribute set changes layouts, which recompiles
the affected cone and reconstructs its instances. This is the same
cost class as editing node parameters today, but a runtime-map design
would absorb attribute renames without recompiling.
- Until an elision pass exists, attributes that are written but never
read occupy slots and copies.
- Per-lane views pad small elements up to the record alignment, and so
does a run of records until the columnar storage arrives; only the
column form is footprint-proportional.
- Two execution forms (per-lane views and batches) are more
machinery than one representation. They share a single layout
descriptor, and the measured seam between them is about 1.5ns per
lane, but the machinery still has to exist.
# Rationale and alternatives
- Keep runtime maps (the current implementation): roughly 500ns per item
on the reference chain and ~57ns marginal per attribute, an allocation
per column, and no compile-time name checking. Interning the keys
improves the constant (about 1.9ns per access vs. 0.43 for a resolved
offset) but keeps a per-access search and rules out the structural
optimizations that need static layouts: bypass, uniform columns, and
packing a level's fields to their resolved offsets.
- Attributes as separate graph edges, one channel per attribute: bypass
and per-channel caching become graph structure. We prototyped and
measured this. Without caching at fan-outs, every channel re-evaluates
the shared upstream work (2-4x slower on realistic chains), and the
cache that fixes it stores a multi-channel result, which is a record,
so the fixed version converges on this design while keeping the extra
edges, dispatch, and graph inflation. The two structural insights of
the channel model survive here as the column structure of batch
results.
- Typed attribute tuples in the wire type: layouts become
document-dependent types, which the registry's precompiled constructor
rows cannot cover, and row polymorphism leaks into type resolution.
Keeping layouts as side metadata means attribute sets never gate
convergence (merge unions them, defaults answer switch mismatches) and
the resolver is untouched.
- The numbers cited throughout come from a reference prototype with
type-erased node inputs (the indirect calls were verified in the
disassembly), thin LTO, 64k-lane workloads, and best-of-nine timing.
Chain results use ten nodes and eight f64 attributes.
# Prior art
Attributes were specified in issue #3779 and first implemented by the
Item and List wire types work, which remains the behavioral reference
for this design: name-specific defaults, merge with default fill, and
the Data panel's presentation of items all carry over, and the wire
rank display and Data panel belong to the editor and are unaffected
here. One behavior is refined rather than kept: flat merge
has to drop one input's top-level attributes, which the push-down rule
is meant to preserve. The present representation (string-keyed storage inside
`List<T>`, with per-carrier implementations rows) is what the Motivation
section measures. This RFC keeps its observable behavior while replacing
the storage and registration strategy underneath.
Outside Graphite, the nearest prior art is row polymorphism in records
(Rémy; PureScript and Elm) for the layout unions, ECS archetype storage
for resolved column handles, and the uniform vs. varying distinction
from shading languages for residency.
# Unresolved questions
- Leveled attributes, the largest open area. Attributes at more than one
nesting level are designed but not built, and the keying is frozen at
level 0 for this landing, which parity does not need. Open within the
area are the binding rules as stated (does a read really bind to the
top level of the wire it is destructured from, and is pinning
element-reading nodes to level 0 the right rule), how a structure
node's per-copy write lands in the former top row, whether residency
is worth its analysis or whether the extent machinery already answers
it (an attribute whose index function ignores the index is `Free`),
and what the storage for a level above 0 looks like given that the
record tier is flat. The UX half of the same question is the
map/enter construct: how "set on the parent" and "map over the
children" read differently in the graph. Until this is settled, the
Repeat-around-Opacity requirement is unmet.
- Where and how the combine rule is declared on the attribute marker.
Merge push-down and flatten both consume it, and inner-wins is the
intended fallback.
- The spelling of the push-down marker on the merge node, the one part
of the additive shape the extent override cannot express.
- Naming: the authoring list type is spelled `IList` here, as in the
implementation, to keep it clear of the legacy wire type's `List`; a
rename to `List` is planned once that type retires.
- Generic-named writes: the shape is settled (`Generic<X, T>`, concrete
value type, name as a constant text input resolved at graph compile
time), and what remains open is where the default for a generically
written name comes from (a `Default` bound on the value vs. an input
on the name source) and the graph UX of the name source node, to be
design-checked against the typed attribute key API (#4352).
- Whether evaluating at a lane outside the input's extent is clamped,
wrapped, or a debug assertion.
- `IList<IList<W>>` outputs, i.e. one node pushing two levels.
- How chatty the editor boundary becomes per frame, given that tools
consume materialized views today.
# Future possibilities
- Scope variables: varargs with graph-compile-time-known names, the
context-side mirror of this design. The same census and marker
machinery, reads resolved to a hop count into a stack-allocated chain
(0.43ns through two hops in our measurements), pushes that are free of
allocation (0.56ns), and injection handles that make a missing or
doubled push unrepresentable. This shrinks the context to a hot core
and replaces coarse context features with per-name dependencies in
cache keys.
- Write elision for never-read attributes, once the whole-graph analysis
pass exists.
- Mask-run decomposition in the selector's batch kernel: dense
sub-ranges for uniform condition runs, and optionally
compute-both-and-select speculation, which purity makes legal.
- GPU consumption: uniform vs. varying columns map directly onto
constant buffers vs. vertex attributes.
- A user-routable remap value (shuffle, manual orderings, an apply-remap
node) built on the sort machinery.
+1
View File
@@ -23,6 +23,7 @@ serde-discriminant = []
proc-macro2 = { workspace = true } proc-macro2 = { workspace = true }
syn = { workspace = true } syn = { workspace = true }
quote = { workspace = true } quote = { workspace = true }
convert_case = { workspace = true }
[dev-dependencies] [dev-dependencies]
# Local dependencies # Local dependencies
+128
View File
@@ -0,0 +1,128 @@
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{Error, FnArg, Ident, Item, ItemFn, ItemMod, ItemUse, Pat, Visibility};
pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result<TokenStream> {
if !attr.is_empty() {
return Err(Error::new(attr.span(), "#[editor_commands] takes no arguments"));
}
for attr in &module.attrs {
if !attr.path().is_ident("doc") {
return Err(Error::new(attr.span(), "the #[editor_commands] module may not have other attributes"));
}
}
let Some((_, items)) = module.content else {
return Err(Error::new(module.mod_token.span, "#[editor_commands] requires a module with an inline body"));
};
let mut imports: Vec<ItemUse> = Vec::new();
let mut functions: Vec<ItemFn> = Vec::new();
for item in items {
match item {
Item::Use(import) => imports.push(import),
Item::Fn(function) => functions.push(function),
other => return Err(Error::new(other.span(), "only `use` imports and command functions may appear in an #[editor_commands] module")),
}
}
let mut variants = TokenStream::new();
let mut stubs = TokenStream::new();
let mut arms = TokenStream::new();
for function in &functions {
for attr in &function.attrs {
if !attr.path().is_ident("doc") {
return Err(Error::new(
attr.span(),
"command functions may not have attributes; anything that doesn't fit the `fn name(args…) -> Message` contract belongs in a plain impl block",
));
}
}
if !matches!(function.vis, Visibility::Inherited) {
return Err(Error::new(
function.span(),
"command functions have no visibility modifier; the macro generates the public JS-facing stub",
));
}
let signature = &function.sig;
if let Some(receiver) = signature.receiver() {
return Err(Error::new(receiver.span(), "command functions take no `self`; they are pure `args… -> Message` translations"));
}
if !signature.generics.params.is_empty() || signature.asyncness.is_some() || signature.unsafety.is_some() {
return Err(Error::new(signature.span(), "command functions must be plain non-generic, non-async, safe functions"));
}
let docs = &function.attrs;
let fn_name = &signature.ident;
let variant = Ident::new(&fn_name.to_string().to_case(Case::Pascal), fn_name.span());
let js_name = Ident::new(&fn_name.to_string().to_case(Case::Camel), fn_name.span());
let mut param_names = Vec::new();
let mut param_types = Vec::new();
for parameter in &signature.inputs {
let FnArg::Typed(pat_type) = parameter else { unreachable!("receiver is rejected above") };
let Pat::Ident(pat_ident) = &*pat_type.pat else {
return Err(Error::new(pat_type.span(), "command parameters must be plain identifiers"));
};
param_names.push(&pat_ident.ident);
param_types.push(&*pat_type.ty);
}
let return_type = &signature.output;
let body = &function.block;
let span = fn_name.span();
variants.extend(quote_spanned! {span=>
#(#docs)*
#variant { #(#param_names: #param_types,)* },
});
stubs.extend(quote_spanned! {span=>
#(#docs)*
#[cfg(not(feature = "native"))]
#[wasm_bindgen(js_name = #js_name)]
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
self.dispatch((move || #return_type #body)())
}
#(#docs)*
#[cfg(feature = "native")]
#[wasm_bindgen(js_name = #js_name)]
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
self.send(EditorCommand::#variant { #(#param_names,)* })
}
});
arms.extend(quote_spanned! {span=>
EditorCommand::#variant { #(#param_names,)* } => #body,
});
}
Ok(quote! {
#(
#[cfg(feature = "editor")]
#imports
)*
#[cfg(any(feature = "native", not(target_family = "wasm")))]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum EditorCommand {
#variants
}
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
impl From<EditorCommand> for Message {
fn from(command: EditorCommand) -> Self {
match command {
#arms
}
}
}
#[cfg(target_family = "wasm")]
#[wasm_bindgen]
impl EditorWrapper {
#stubs
}
})
}
+8
View File
@@ -3,6 +3,7 @@
mod as_message; mod as_message;
mod combined_message_attrs; mod combined_message_attrs;
mod discriminant; mod discriminant;
mod editor_commands;
mod extract_fields; mod extract_fields;
mod helper_structs; mod helper_structs;
mod helpers; mod helpers;
@@ -15,6 +16,7 @@ mod widget_builder;
use crate::as_message::derive_as_message_impl; use crate::as_message::derive_as_message_impl;
use crate::combined_message_attrs::combined_message_attrs_impl; use crate::combined_message_attrs::combined_message_attrs_impl;
use crate::discriminant::derive_discriminant_impl; use crate::discriminant::derive_discriminant_impl;
use crate::editor_commands::editor_commands_impl;
use crate::extract_fields::derive_extract_field_impl; use crate::extract_fields::derive_extract_field_impl;
use crate::helper_structs::AttrInnerSingleString; use crate::helper_structs::AttrInnerSingleString;
use crate::hierarchical_tree::generate_hierarchical_tree; use crate::hierarchical_tree::generate_hierarchical_tree;
@@ -302,6 +304,12 @@ pub fn message_handler_data(attr: TokenStream, input_item: TokenStream) -> Token
TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error())) TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
} }
#[proc_macro_attribute]
pub fn editor_commands(attr: TokenStream, input_item: TokenStream) -> TokenStream {
let module = syn::parse_macro_input!(input_item as syn::ItemMod);
TokenStream::from(editor_commands_impl(attr.into(), module).unwrap_or_else(|err| err.to_compile_error()))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+9 -1
View File
@@ -8,7 +8,15 @@ use std::path::Path;
use std::process::ExitCode; use std::process::ExitCode;
use std::time::Duration; use std::time::Duration;
const EXCLUDED_DIRECTORIES: &[&str] = &["target", ".git", "frontend/node_modules", "frontend/dist", "frontend/wrapper/pkg", "tools"]; const EXCLUDED_DIRECTORIES: &[&str] = &[
"target",
".git",
"frontend/node_modules",
"frontend/dist",
"frontend/wrapper/pkg",
"frontend/wrapper/pkg-native",
"tools",
];
const INCLUDED_EXTENSIONS: &[&str] = &["rs"]; const INCLUDED_EXTENSIONS: &[&str] = &["rs"];
const DEBOUNCE: Duration = Duration::from_millis(500); const DEBOUNCE: Duration = Duration::from_millis(500);
+11 -7
View File
@@ -10,8 +10,12 @@ pub fn frontend_dir() -> PathBuf {
workspace_dir().join("frontend") workspace_dir().join("frontend")
} }
fn wasm_glue_path() -> PathBuf { fn pkg_dir(native: bool) -> PathBuf {
frontend_dir().join("wrapper").join("pkg").join(format!("{OUT_NAME}.js")) frontend_dir().join("wrapper").join(if native { "pkg-native" } else { "pkg" })
}
fn wasm_glue_path(native: bool) -> PathBuf {
pkg_dir(native).join(format!("{OUT_NAME}.js"))
} }
pub fn setup() -> Result<(), Error> { pub fn setup() -> Result<(), Error> {
@@ -50,15 +54,15 @@ pub fn build_wasm(release: bool, native: bool) -> Result<(), Error> {
pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> { pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
let wasm_artifact = target_dir().join(WASM_TARGET).join(if release { "release" } else { "debug" }).join(format!("{OUT_NAME}.wasm")); let wasm_artifact = target_dir().join(WASM_TARGET).join(if release { "release" } else { "debug" }).join(format!("{OUT_NAME}.wasm"));
let pkg_dir = frontend_dir().join("wrapper").join("pkg"); let pkg_dir = pkg_dir(native);
let mut steps = vec![ let mut steps = vec![
cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET) cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET)
.arg_if(release, "--release") .arg_if(release, "--release")
.args_if(native, ["--no-default-features", "--features", "native"]) .args_if(native, ["--no-default-features", "--features", "native"])
.dir(workspace_dir()) .dir(workspace_dir())
.before_spawn(|_| { .before_spawn(move |_| {
if is_build_corrupted() { if is_build_corrupted(wasm_glue_path(native)) {
clean_wasm(); clean_wasm();
} }
Ok(()) Ok(())
@@ -90,8 +94,8 @@ pub fn clean_wasm() -> bool {
true true
} }
pub fn is_build_corrupted() -> bool { pub fn is_build_corrupted(path: PathBuf) -> bool {
let Ok(js) = std::fs::read_to_string(wasm_glue_path()) else { let Ok(js) = std::fs::read_to_string(&path) else {
return false; return false;
}; };
js.contains("from \"env\"") || js.contains("from 'env'") js.contains("from \"env\"") || js.contains("from 'env'")