Compare commits

...
Author SHA1 Message Date
Dennis Kobert 3902163e03 Resolve a batch of node positions in one downstream walk instead of one per node 2026-09-23 13:07:14 +00:00
Dennis Kobert 99824a70a9 Preview a node by redirecting the graph that is evaluated, not the document 2026-09-23 12:15:44 +00:00
Dennis Kobert c25410185c Answer the cycle question without writing the network 2026-09-23 11:31:05 +00:00
Dennis Kobert 93665c5e9d Give cache invalidation and per-peer view state their own accessors 2026-09-23 10:46:12 +00:00
Dennis Kobert ccb02ddf8d Make writing either parallel tree outside the store a compile error 2026-09-23 10:21:28 +00:00
Dennis Kobert 305cd02332 Stage what the store recorded instead of converting and diffing the whole document 2026-09-23 09:59:11 +00:00
Dennis Kobert 3394695fb9 Replay a recorded delta back into the interface without recording it again 2026-09-23 08:51:29 +00:00
Dennis Kobert 47f56b481c Store previewing and pinned order in the registry and stop rebuilding nodes to change their inputs 2026-09-23 08:13:16 +00:00
Dennis Kobert bdab64eb29 Record input arity and node entry writes, and route node type changes through the store 2026-09-23 07:29:09 +00:00
Dennis Kobert 0fe91cc0fd Record what each store write changed at the point of the write 2026-09-23 06:49:32 +00:00
Dennis Kobert 06672ddb39 Give each metadata field its own delta instead of diffing a wholesale copy 2026-09-23 06:27:06 +00:00
Dennis Kobert e060233d7c Record the interface restructure state and the open emission fork alongside the delta design 2026-09-22 21:00:23 +00:00
Dennis Kobert 70e0c51fae Index nodes by network and resource references once instead of rescanning the registry per removal 2026-09-22 20:52:57 +00:00
Dennis Kobert 3e46541ea0 Split shifting nodes into its selection, ordering, direction and settling phases 2026-09-22 20:48:21 +00:00
Dennis Kobert 526e760792 Name the phases of moving a layer into a stack and drop a measurement nothing read 2026-09-22 20:18:37 +00:00
Dennis Kobert 4749e2518f Name the policies set_input and the slot reorders were carrying inline 2026-09-22 19:39:54 +00:00
Dennis Kobert 07acbfad9f Carry a node's storage identity through the rebuild so it survives a document round trip 2026-09-22 18:58:09 +00:00
Dennis Kobert aca1805fcf Resolve node identities through one place, preferring a stored identity over a location hash
No node stores an identity yet, so every path still hashes and nothing changes. Minting needs
to land in one step across from_runtime, to_runtime, PathResolver and the rebuild, since a
node whose identity survives one path but not another silently changes id.
2026-09-22 15:50:21 +00:00
Dennis Kobert 35b9153f27 Name the invalidation rules and lift the frontend projections out of the query layer 2026-09-22 15:13:25 +00:00
Dennis Kobert 93ca25ebe5 Separate node graph geometry from the caches that store it 2026-09-22 14:58:54 +00:00
Dennis Kobert 6ef640c288 Turn each cache loader into a pure computation the slot stores itself 2026-09-22 14:49:01 +00:00
Dennis Kobert 0f21bbc337 Load transient caches through one load-on-miss helper instead of a per-slot ceremony 2026-09-22 14:24:03 +00:00
Dennis Kobert fee15b9048 Clear the workspace clippy warnings and shrink the message enum by boxing the mounted working copy 2026-09-22 14:12:17 +00:00
Dennis Kobert 6c52714194 Declare what a position change invalidates once instead of at each layout writer 2026-09-22 12:40:49 +00:00
Dennis Kobert f5f1b09eec Write node fields through a resolved cursor and close the raw tree accessors 2026-09-22 12:40:49 +00:00
Dennis Kobert 5528af9617 Write inputs and node entries through the store instead of the two trees directly 2026-09-22 12:40:49 +00:00
Dennis Kobert 1863e9ea67 Route import and export signature edits through paired store primitives 2026-09-22 12:40:48 +00:00
Dennis Kobert ea17f690a2 Derive node positions from layout metadata instead of click target geometry 2026-09-22 12:40:48 +00:00
Keavon Chambers 6d3951b26f Record the runtime delta design context and the storage-driven undo follow-up plan 2026-09-22 11:56:12 +00:00
Keavon Chambers 225c2cde98 Document the runtime delta modules where understanding needs it 2026-09-22 11:56:12 +00:00
Keavon Chambers 3799e55491 Adopt batch-scoped delta construction with shared removal and resource context, and carry visibility as a structural delta 2026-09-22 11:56:12 +00:00
Keavon Chambers 74a80b61bd Rework the runtime delta experiment to the agreed shape: graph-craft structural deltas, an editor metadata wrapper, and diff-derived metadata ops 2026-09-22 11:56:12 +00:00
Keavon Chambers 951005e5cf Expose scoped conversion, path ID derivation, and computed-op staging from the storage layer 2026-09-22 11:19:19 +00:00
57 changed files with 5297 additions and 2253 deletions

No files matched your search

+4 -4
View File
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
if let Err(e) = fs::remove_dir_all(&entry_path) { if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e); tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
} }
} else if entry_path.is_file() { } else if entry_path.is_file()
if let Err(e) = fs::remove_file(&entry_path) { && let Err(e) = fs::remove_file(&entry_path)
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e); {
} tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
} }
} }
} }
+5 -4
View File
@@ -71,10 +71,11 @@ fn garbage_collect_document_files(state: &PersistedState) {
for entry in entries.flatten() { for entry in entries.flatten() {
let path = entry.path(); let path = entry.path();
if path.is_file() && !valid_paths.contains(&path) { if path.is_file()
if let Err(e) = std::fs::remove_file(&path) { && !valid_paths.contains(&path)
tracing::error!("Failed to remove orphaned document file {path:?}: {e}"); && let Err(e) = std::fs::remove_file(&path)
} {
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
} }
} }
} }
+4 -4
View File
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
pub(super) fn poll_node_graph_evaluation(&mut self) { pub(super) fn poll_node_graph_evaluation(&mut self) {
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) { if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
if e != "No active document" { && e != "No active document"
tracing::error!("Error poling node graph: {}", e); {
} tracing::error!("Error poling node graph: {}", e);
} }
while let Some(message) = responses.pop_front() { while let Some(message) = responses.pop_front() {
self.queue_editor_message(message); self.queue_editor_message(message);
+23
View File
@@ -76,6 +76,29 @@ impl<L: Layout> Gdd<L> {
Ok(()) Ok(())
} }
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
/// the whole document and diffing it against the working registry.
///
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
/// hot frame, and the proto-node declaration bytes go to the byte store.
#[cfg(feature = "conversion")]
pub fn stage_constructed_ops(
&mut self,
ops: Vec<document_graph_storage::RegistryDelta>,
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
byte_store: &dyn ResourceStorage,
) -> Result<(), Error> {
let hot_ops = self.session.stage_computed_ops(ops)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
for bytes in declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(())
}
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last /// Retire every pending hot op into durable history as a single interaction (marking the batch's last
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit, /// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there /// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
@@ -31,8 +31,6 @@ pub mod node {
pub mod session { pub mod session {
pub mod network { pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes // TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz"; pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform"; pub const NAV_TRANSFORM: &str = "ui::nav::transform";
@@ -60,6 +58,11 @@ pub mod network {
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The /// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion. /// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
pub const SCOPE_INJECTIONS: &str = "scope_injections"; pub const SCOPE_INJECTIONS: &str = "scope_injections";
/// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs.
/// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with
/// per-peer ordering would diverge with no way to reconcile.
pub const PINNED_ORDER: &str = "ui::pinned_order";
} }
pub mod delta { pub mod delta {
+13 -3
View File
@@ -1,4 +1,4 @@
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev}; use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use graphene_resource::ResourceHash; use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -92,7 +92,7 @@ impl Delta {
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible /// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`. /// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistryDelta { pub enum RegistryDelta {
AddNode { AddNode {
id: NodeId, id: NodeId,
@@ -109,6 +109,16 @@ pub enum RegistryDelta {
index: u32, index: u32,
new_input: NodeInput, new_input: NodeInput,
}, },
/// A node's whole input list, for a change to the number or order of its slots that the
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
/// per-slot edits are lost, which is inherent to the indices themselves moving.
///
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
/// with attribute ops on the same node instead of reverting them.
SetNodeInputs {
id: NodeId,
inputs: Vec<InputSlot>,
},
ChangeNodeAttribute { ChangeNodeAttribute {
id: NodeId, id: NodeId,
delta: AttributeDelta, delta: AttributeDelta,
@@ -190,7 +200,7 @@ pub enum RegistryDelta {
} }
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`. /// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta { pub struct AttributeDelta {
pub key: String, pub key: String,
pub value: Option<serde_json::Value>, pub value: Option<serde_json::Value>,
+16
View File
@@ -194,6 +194,10 @@ impl Document {
RegistryDelta::RemoveNode { id, .. } => { RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id); registry.node_instances.remove(&id);
} }
RegistryDelta::SetNodeInputs { id, inputs } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
node.inputs = inputs;
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => { RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?; let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?; let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
@@ -305,6 +309,14 @@ impl Document {
} }
self.ensure_node_exists(target, *id)?; self.ensure_node_exists(target, *id)?;
} }
RegistryDelta::SetNodeInputs { id, inputs } => {
for slot in inputs {
if let NodeInput::Node { id: referenced, .. } = slot.input {
self.ensure_node_exists(target, referenced)?;
}
}
self.ensure_node_exists(target, *id)?;
}
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?, RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
RegistryDelta::SetNetworkExport { RegistryDelta::SetNetworkExport {
id: network, export: export_target, .. id: network, export: export_target, ..
@@ -342,6 +354,10 @@ impl Document {
Ok(match delta { Ok(match delta {
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() }, RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
&RegistryDelta::SetNodeInputs { id, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
}
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => { &RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?; let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?; let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
+331 -38
View File
@@ -60,6 +60,34 @@ impl NodePath {
} }
} }
/// Resolves a node's storage identity: the identity the metadata source holds for it where there is
/// one, and a hash of its location otherwise. Every place a node is named goes through here, so a
/// node's own registry key and every reference to it agree.
///
/// A held identity travels with the node, so moving it between networks keeps it. A hashed one is
/// derived from the node's place in the tree, so it changes when the node moves; it stands in for a
/// node no source names, such as one in a network that has never been stored.
pub(crate) struct NodeIds<'a, M: NodeMetadataSource + ?Sized> {
pub(crate) metadata: Option<&'a M>,
pub(crate) metadata_path: &'a [RuntimeNodeId],
pub(crate) peer: PeerId,
}
impl<M: NodeMetadataSource + ?Sized> Clone for NodeIds<'_, M> {
fn clone(&self) -> Self {
*self
}
}
impl<M: NodeMetadataSource + ?Sized> Copy for NodeIds<'_, M> {}
impl<M: NodeMetadataSource + ?Sized> NodeIds<'_, M> {
fn resolve(&self, path: &NodePath, local_id: RuntimeNodeId) -> NodeId {
self.metadata
.and_then(|metadata| metadata.storage_node_id(self.metadata_path, local_id))
.unwrap_or_else(|| path.to_global_id(self.peer))
}
}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum ConversionError { pub enum ConversionError {
#[error("Failed to serialize value: {0}")] #[error("Failed to serialize value: {0}")]
@@ -182,33 +210,40 @@ fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced
if !referenced.contains(&id) { if !referenced.contains(&id) {
continue; continue;
} }
let Some(info) = resources.info(&id) else { continue }; if let Some(entry) = convert_resource_entry(resources, id, peer)? {
registry.resources.insert(id, entry);
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
} }
registry.resources.insert(id, entry);
} }
Ok(()) Ok(())
} }
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
let Some(info) = resources.info(&id) else { return Ok(None) };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
Ok(Some(entry))
}
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network /// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
/// (recursively through nested networks). These are the resources the document actually uses; the /// (recursively through nested networks). These are the resources the document actually uses; the
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage. /// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
@@ -261,6 +296,20 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
peer: PeerId, peer: PeerId,
} }
impl<'m, M: NodeMetadataSource + ?Sized> ConversionContext<'m, M> {
/// The identity resolver for nodes addressed inside the network at `metadata_path`.
fn ids<'a>(&self, metadata_path: &'a [RuntimeNodeId]) -> NodeIds<'a, M>
where
'm: 'a,
{
NodeIds {
metadata: Some(self.metadata),
metadata_path,
peer: self.peer,
}
}
}
fn convert_network<M: NodeMetadataSource + ?Sized>( fn convert_network<M: NodeMetadataSource + ?Sized>(
node_network: &NodeNetwork, node_network: &NodeNetwork,
network_id: NetworkId, network_id: NetworkId,
@@ -271,7 +320,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> { ) -> Result<(), ConversionError> {
for (runtime_node_id, doc_node) in &node_network.nodes { for (runtime_node_id, doc_node) in &node_network.nodes {
let node_path = child_path(parent_path, network_id, *runtime_node_id); let node_path = child_path(parent_path, network_id, *runtime_node_id);
let global_id = node_path.to_global_id(ctx.peer); let global_id = ctx.ids(metadata_path).resolve(&node_path, *runtime_node_id);
let location = NodeLocation { let location = NodeLocation {
network_id, network_id,
@@ -279,7 +328,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
metadata_path, metadata_path,
runtime_node_id: *runtime_node_id, runtime_node_id: *runtime_node_id,
}; };
let mut node = convert_node(doc_node, location, registry, ctx)?; let mut node = convert_node(doc_node, location, registry, ctx, true)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN); node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node); registry.node_instances.insert(global_id, node);
} }
@@ -289,15 +338,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.iter() .iter()
.map(|export| { .map(|export| {
Ok(ExportSlot { Ok(ExportSlot {
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?), target: Some(convert_input(export, parent_path, network_id, ctx.ids(metadata_path))?),
timestamp: TimeStamp::ORIGIN, timestamp: TimeStamp::ORIGIN,
}) })
}) })
.collect::<Result<Vec<_>, ConversionError>>()?; .collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new(); let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?; write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?; write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes }); registry.networks.insert(network_id, Network { exports, attributes });
ctx.network_ids.insert(metadata_path.to_vec(), network_id); ctx.network_ids.insert(metadata_path.to_vec(), network_id);
@@ -308,12 +357,12 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping /// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
/// each runtime-local node reference to its stable storage global ID so the reference survives a /// each runtime-local node reference to its stable storage global ID so the reference survives a
/// round trip even if runtime IDs are later reshuffled. /// round trip even if runtime IDs are later reshuffled.
fn write_scope_injections( fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes, attributes: &mut crate::Attributes,
node_network: &NodeNetwork, node_network: &NodeNetwork,
parent_path: Option<&NodePath>, parent_path: Option<&NodePath>,
network_id: NetworkId, network_id: NetworkId,
peer: PeerId, ids: NodeIds<'_, M>,
timestamp: TimeStamp, timestamp: TimeStamp,
) -> Result<(), ConversionError> { ) -> Result<(), ConversionError> {
if node_network.scope_injections.is_empty() { if node_network.scope_injections.is_empty() {
@@ -324,7 +373,7 @@ fn write_scope_injections(
.scope_injections .scope_injections
.iter() .iter()
.map(|(key, (runtime_id, ty))| { .map(|(key, (runtime_id, ty))| {
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer); let storage_id = ids.resolve(&child_path(parent_path, network_id, *runtime_id), *runtime_id);
(key.clone(), (storage_id, ty.clone())) (key.clone(), (storage_id, ty.clone()))
}) })
.collect(); .collect();
@@ -351,7 +400,13 @@ struct NodeLocation<'a> {
runtime_node_id: RuntimeNodeId, runtime_node_id: RuntimeNodeId,
} }
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> { fn convert_node<M: NodeMetadataSource + ?Sized>(
doc_node: &DocumentNode,
location: NodeLocation<'_>,
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Node, ConversionError> {
let NodeLocation { let NodeLocation {
network_id, network_id,
parent_path, parent_path,
@@ -368,7 +423,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?; write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
inputs.push(InputSlot { inputs.push(InputSlot {
input: convert_input(input, parent_path, network_id, ctx.peer)?, input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp, timestamp,
attributes: input_attrs, attributes: input_attrs,
}); });
@@ -383,7 +438,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
} else { } else {
metadata_path metadata_path
}; };
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?; let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults. // Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new(); let mut attributes = crate::Attributes::new();
@@ -410,6 +465,50 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
}) })
} }
/// The `call_argument` attribute write for a node, cleared when the value is the default that
/// `to_runtime` rehydrates an absent key from. For staging paths that encode this field alone.
pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::AttributeDelta, ConversionError> {
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
}
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
}
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
}
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
input_index: usize,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
}
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>( fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes, attributes: &mut crate::Attributes,
metadata: &M, metadata: &M,
@@ -451,11 +550,31 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
Ok(()) Ok(())
} }
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> { /// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections`
/// does it: a runtime ID is not stable across a round trip.
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
network_path: &[RuntimeNodeId],
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
if let Some(reference) = metadata.reference(network_path) { if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp); attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
} }
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
let pinned_order = metadata.pinned_order(network_path);
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
.set_serialized(network::PINNED_ORDER, &stored, timestamp)
.map_err(map_serialization_error(network::PINNED_ORDER))?;
}
Ok(()) Ok(())
} }
@@ -486,10 +605,10 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
Ok(()) Ok(())
} }
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> { fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, ids: NodeIds<'_, M>) -> Result<NodeInput, ConversionError> {
Ok(match input { Ok(match input {
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node { GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
id: child_path(parent_path, network_id, *node_id).to_global_id(peer), id: ids.resolve(&child_path(parent_path, network_id, *node_id), *node_id),
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?, index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
}, },
GraphCraftNodeInput::Value { tagged_value, exposed } => { GraphCraftNodeInput::Value { tagged_value, exposed } => {
@@ -506,7 +625,9 @@ fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, ne
}) })
} }
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> { /// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new(); let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN; let timestamp = TimeStamp::ORIGIN;
@@ -533,6 +654,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
child_metadata_path: &[RuntimeNodeId], child_metadata_path: &[RuntimeNodeId],
registry: &mut Registry, registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>, ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Implementation, ConversionError> { ) -> Result<Implementation, ConversionError> {
Ok(match implementation { Ok(match implementation {
DocumentNodeImplementation::ProtoNode(identifier) => { DocumentNodeImplementation::ProtoNode(identifier) => {
@@ -564,10 +686,181 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the // `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
// same node-path hashes underneath it). // same node-path hashes underneath it).
let nested_network_id = current_node_path.owned_network_id(ctx.peer); let nested_network_id = current_node_path.owned_network_id(ctx.peer);
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?; if recurse {
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
}
Implementation::Network(nested_network_id) Implementation::Network(nested_network_id)
} }
// TODO: Support Extract in the Registry format. // TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation), DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
}) })
} }
/// Derives the storage IDs for entities addressed by runtime network paths, resolving each through
/// the same [`NodeIds`] a whole-document conversion uses so scoped and whole-document conversions agree.
pub struct PathResolver<'m> {
metadata: Option<&'m dyn NodeMetadataSource>,
peer: PeerId,
}
impl<'m> PathResolver<'m> {
/// Without a metadata source every node falls back to a hash of its location, which only matches a
/// whole-document conversion while no node has a stored identity.
pub fn new(metadata: Option<&'m dyn NodeMetadataSource>, peer: PeerId) -> Self {
Self { metadata, peer }
}
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
match self.owner_path(local_path) {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
}
}
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
let owner = self.owner_path(local_path);
self.ids(local_path).resolve(&child_path(owner.as_ref(), self.network_id(local_path), local_id), local_id)
}
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
/// node references to their storage IDs.
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
let owner = self.owner_path(local_path);
convert_input(input, owner.as_ref(), self.network_id(local_path), self.ids(local_path))
}
/// The identity resolver for nodes addressed inside the network at `local_path`.
fn ids<'a>(&self, local_path: &'a [RuntimeNodeId]) -> NodeIds<'a, dyn NodeMetadataSource + 'm>
where
'm: 'a,
{
NodeIds {
metadata: self.metadata,
metadata_path: local_path,
peer: self.peer,
}
}
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
let mut owner: Option<NodePath> = None;
for &local_id in local_path {
let network_id = match &owner {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
};
owner = Some(child_path(owner.as_ref(), network_id, local_id));
}
owner
}
}
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
pub struct ScopedConversion<'m> {
ctx: ConversionContext<'m, dyn NodeMetadataSource + 'm>,
resolver: PathResolver<'m>,
}
impl<'m> ScopedConversion<'m> {
pub fn new(metadata: &'m dyn NodeMetadataSource, peer: PeerId) -> Self {
Self {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
},
resolver: PathResolver::new(Some(metadata), peer),
}
}
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
/// without it only the node itself is converted, with its nested network referenced by ID.
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let location = NodeLocation {
network_id: self.resolver.network_id(local_path),
parent_path: owner_path.as_ref(),
metadata_path: local_path,
runtime_node_id: local_id,
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
/// Converts the entry of the network at `local_path` (its export slots and network-level
/// attributes, not its nodes) into `registry`.
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let network_id = self.resolver.network_id(local_path);
let exports = node_network
.exports
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.ids(local_path))?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(
&mut attributes,
self.ctx.metadata,
local_path,
owner_path.as_ref(),
network_id,
self.ctx.ids(local_path),
TimeStamp::ORIGIN,
)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
Ok(())
}
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
pub fn finish(self) -> DeclarationBytes {
self.ctx.declaration_bytes
}
}
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
///
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
/// this stays in lockstep with the real serialization.
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
}
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
#[cfg(test)]
mod resource_ref_shape {
use super::*;
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+4 -1
View File
@@ -29,7 +29,10 @@ pub use resources::*;
pub use session::*; pub use session::*;
#[cfg(any(feature = "conversion", test))] #[cfg(any(feature = "conversion", test))]
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration}; pub use from_runtime::{
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
node_value_resource_refs, value_resource_ref,
};
#[cfg(any(feature = "conversion", test))] #[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position}; pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))] #[cfg(any(feature = "conversion", test))]
+19 -27
View File
@@ -8,11 +8,15 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId; use core_types::uuid::NodeId as RuntimeNodeId;
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. /// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct NodeMetadataEntry { pub struct NodeMetadataEntry {
pub network_path: Vec<RuntimeNodeId>, pub network_path: Vec<RuntimeNodeId>,
pub local_id: RuntimeNodeId, pub local_id: RuntimeNodeId,
/// The node's storage identity. Restoring it pins the node to this identity, so a later conversion
/// keeps it instead of re-deriving one from the node's location.
pub storage_id: crate::NodeId,
pub position: Option<Position>, pub position: Option<Position>,
pub is_layer: bool, pub is_layer: bool,
pub display_name: Option<String>, pub display_name: Option<String>,
@@ -24,19 +28,7 @@ pub struct NodeMetadataEntry {
pub output_names: Vec<String>, pub output_names: Vec<String>,
} }
impl NodeMetadataEntry { /// Per-network metadata. Separate from `NodeMetadataEntry` since these are
pub fn is_empty(&self) -> bool {
self.position.is_none()
&& !self.is_layer
&& self.display_name.is_none()
&& !self.locked
&& !self.pinned
&& self.output_names.is_empty()
&& self.input_metadata.iter().all(InputMetadataEntry::is_empty)
}
}
/// Per-network metadata (navigation, previewing). Separate from `NodeMetadataEntry` since these are
/// properties of a network, not of any node. /// properties of a network, not of any node.
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
pub struct NetworkMetadataEntry { pub struct NetworkMetadataEntry {
@@ -44,16 +36,13 @@ pub struct NetworkMetadataEntry {
/// Empty = root network. /// Empty = root network.
pub network_path: Vec<RuntimeNodeId>, pub network_path: Vec<RuntimeNodeId>,
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state /// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
/// (node-graph nav + previewing, in `session.json`) with a network across reparenting. /// (the node-graph nav, in `session.json`) with a network across reparenting.
pub network_id: crate::NetworkId, pub network_id: crate::NetworkId,
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag. /// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
pub reference: Option<String>, pub reference: Option<String>,
} /// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
/// a shared set with per-peer ordering could never reconcile.
impl NetworkMetadataEntry { pub pinned_order: Vec<RuntimeNodeId>,
pub fn is_empty(&self) -> bool {
self.reference.is_none()
}
} }
/// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so /// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -67,12 +56,6 @@ pub struct InputMetadataEntry {
pub input_data: HashMap<String, serde_json::Value>, pub input_data: HashMap<String, serde_json::Value>,
} }
impl InputMetadataEntry {
pub fn is_empty(&self) -> bool {
self.input_name.is_none() && self.input_description.is_none() && self.widget_override.is_none() && self.input_data.is_empty()
}
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what /// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.). /// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource { pub trait NodeMetadataSource {
@@ -110,9 +93,18 @@ pub trait NodeMetadataSource {
HashMap::new() HashMap::new()
} }
/// The storage identity this node is pinned to, if it has one. A node the source does not name
/// falls back to a hash of its location.
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
None
}
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> { fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
None None
} }
/// The display order of the network's pinned nodes.
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
Vec::new()
}
} }
/// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools). /// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools).
+6
View File
@@ -129,6 +129,12 @@ impl Session {
Ok(revs) Ok(revs)
} }
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
/// same way `stage_from_runtime` stages a diff's ops.
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
self.stage_ops(ops)
}
/// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in /// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in
/// order. Each tick is strictly later than the last, so the final frame carries the latest /// order. Each tick is strictly later than the last, so the final frame carries the latest
/// timestamp, which is what the caller passes to `retire`. /// timestamp, which is what the caller passes to `retire`.
+28 -13
View File
@@ -168,7 +168,7 @@ fn convert_network(
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?; let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() { if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id)); collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
} }
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default(); let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
@@ -176,10 +176,8 @@ fn convert_network(
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0); let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id); let runtime_id = RuntimeNodeId(local_id);
if let Some(collector) = node_collector.as_mut() if let Some(collector) = node_collector.as_mut() {
&& let Some(entry) = extract_ui_metadata(node, metadata_path, runtime_id) collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
{
collector.push(entry);
} }
let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?; let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?;
@@ -239,10 +237,10 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
.collect() .collect()
} }
/// Returns `None` when the node has no `ui::*` attributes at all so callers don't end up with /// Emitted for every node, since `storage_id` is worth restoring even where no `ui::*` attribute is.
/// empty entries for unconverted-from-runtime nodes. `input_metadata` is always sized to match /// `input_metadata` is always sized to match `node.inputs.len()` for a strict slot-by-slot rebuild;
/// `node.inputs.len()` for a strict slot-by-slot rebuild; empty slots use `InputMetadataEntry::default()`. /// empty slots use `InputMetadataEntry::default()`.
fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> Option<NodeMetadataEntry> { fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeMetadataEntry {
let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION); let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION);
let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false); let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false);
let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME); let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME);
@@ -252,9 +250,10 @@ fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect(); let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
let entry = NodeMetadataEntry { NodeMetadataEntry {
network_path: network_path.to_vec(), network_path: network_path.to_vec(),
local_id, local_id,
storage_id,
position, position,
is_layer, is_layer,
display_name, display_name,
@@ -262,15 +261,31 @@ fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local
pinned, pinned,
input_metadata, input_metadata,
output_names, output_names,
}; }
(!entry.is_empty()).then_some(entry)
} }
fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry { /// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
/// rather than failing the conversion: the preview target or a pinned node can have been deleted.
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
};
let pinned_order = attributes
.get_typed::<Vec<NodeId>>(network::PINNED_ORDER)
.unwrap_or_default()
.into_iter()
.filter_map(to_runtime_id)
.collect();
NetworkMetadataEntry { NetworkMetadataEntry {
network_path: network_path.to_vec(), network_path: network_path.to_vec(),
network_id, network_id,
reference: attributes.get_typed(node::ui::REFERENCE), reference: attributes.get_typed(node::ui::REFERENCE),
pinned_order,
} }
} }
+4 -8
View File
@@ -496,15 +496,11 @@ mod test {
if let FrontendMessage::UpdateLayout { if let FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::DialogColumn1, layout_target: LayoutTarget::DialogColumn1,
diff, diff,
} = response } = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
{ {
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value { print_problem_to_terminal_on_failure(value);
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
}
} }
} }
} }
@@ -95,7 +95,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
.network_interface .network_interface
.node_metadata(&layer.to_node(), &[]) .node_metadata(&layer.to_node(), &[])
.map(|node| node.persistent_metadata.display_name.clone()) .map(|node| node.persistent_metadata.display_name.clone())
.and_then(|name| if name.is_empty() { None } else { Some(name) }) .filter(|name| !name.is_empty())
.unwrap_or_else(|| "Artboard".to_string()); .unwrap_or_else(|| "Artboard".to_string());
(layer, name) (layer, name)
}) })
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
]; ];
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings; let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones())); let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat` // Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] { for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
for sublist in list { for sublist in list {
@@ -5,6 +5,7 @@ use document_graph_storage::Registry;
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage}; use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface; use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings}; use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is /// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
@@ -101,6 +102,7 @@ impl DocumentHistory {
/// round-trip check, off by default for its perf cost. /// round-trip check, off by default for its perf cost.
pub fn stage_snapshot( pub fn stage_snapshot(
&mut self, &mut self,
deltas: &[EditorDelta],
interface: &NodeNetworkInterface, interface: &NodeNetworkInterface,
registry: &ResourceRegistry, registry: &ResourceRegistry,
view_settings: BTreeMap<String, serde_json::Value>, view_settings: BTreeMap<String, serde_json::Value>,
@@ -109,21 +111,68 @@ impl DocumentHistory {
) { ) {
let Some(storage) = self.storage.as_mut() else { return }; let Some(storage) = self.storage.as_mut() else { return };
let network = interface.document_network(); // A working copy that does not hold the document yet has no baseline for a batch of changes to
let metadata_view = StorageMetadataView::new(interface); // apply to, so the first commit writes the whole document and every later one stages only what
// the store recorded. Reading that from the working copy rather than from the caller means a path
let network_view_settings = storage // that mounts storage and then commits does not have to know which of the two it is.
.network_ids(network, &metadata_view) let staged = match storage.registry().node_instances.is_empty() {
.ok() true => Self::stage_whole_document(storage, interface, registry, byte_store),
.map(|network_ids| collect_network_view_settings(interface, &network_ids)); // An autosave with nothing edited since the last commit still persists the view state below.
false if deltas.is_empty() => Ok(()),
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo false => Self::stage_recorded(storage, deltas, interface, registry, byte_store),
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary. };
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) { if let Err(error) = staged {
log::error!("Storage snapshot staging failed: {error}"); log::error!("Storage snapshot staging failed: {error}");
return; return;
} }
self.persist_view_state(interface, view_settings, legacy_document);
}
/// Converts the whole document and stages the difference from what the working copy holds.
///
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
let metadata_view = StorageMetadataView::new(interface);
storage
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
.map_err(|error| error.to_string())
}
/// Stages what the store recorded since the last drain.
///
/// This and the whole-document conversion produce the same registry for the same edit, which
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
/// what they cost and in what they can miss: a conversion sees every change however it was made,
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
fn stage_recorded(
storage: &mut document_format::GddV1,
deltas: &[EditorDelta],
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<(), String> {
let peer = storage.session().peer();
let metadata_view = StorageMetadataView::new(interface);
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
storage
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
.map_err(|error| error.to_string())
}
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
/// dual-write soak validates the new format against. Both staging paths persist them; they differ
/// only in how the graph ops are derived.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
let Some(storage) = self.storage.as_mut() else { return };
let network_view_settings = storage
.network_ids(interface.document_network(), &StorageMetadataView::new(interface))
.ok()
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
if let Err(error) = storage.set_view_settings(view_settings) { if let Err(error) = storage.set_view_settings(view_settings) {
log::error!("Persisting view settings failed: {error}"); log::error!("Persisting view settings failed: {error}");
} }
@@ -134,8 +183,6 @@ impl DocumentHistory {
log::error!("Persisting per-network view settings failed: {error}"); log::error!("Persisting per-network view settings failed: {error}");
} }
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
// can be validated against (and recovered from) the old one on open.
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) { if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
log::error!("Embedding legacy document into working copy failed: {error}"); log::error!("Embedding legacy document into working copy failed: {error}");
} }
@@ -2026,14 +2026,30 @@ impl DocumentMessageHandler {
self.history.retire_storage_interaction(); self.history.retire_storage_interaction();
} }
/// Stages the runtime network into the `Gdd` working copy. /// Stages what the store recorded since the last commit into the `Gdd` working copy.
///
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
/// session that never mounts one.
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) { pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings; let deltas = self.network_interface.take_deltas();
if self.history.storage().is_none() { if self.history.storage().is_none() {
return; return;
} }
let (view_settings, legacy_document) = self.storage_side_channels();
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// The per-peer view settings and legacy bytes that ride along with either kind of staging.
fn storage_side_channels(&self) -> (std::collections::BTreeMap<String, serde_json::Value>, String) {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
let view_settings = DocumentSettings { let view_settings = DocumentSettings {
document_ptz: &self.document_ptz, document_ptz: &self.document_ptz,
render_mode: &self.render_mode, render_mode: &self.render_mode,
@@ -2044,14 +2060,7 @@ impl DocumentMessageHandler {
} }
.to_view_map(); .to_view_map();
let legacy_document = self.serialize_document(); (view_settings, self.serialize_document())
self.history
.stage_snapshot(&self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
} }
/// Restore `view_settings` map into the document. /// Restore `view_settings` map into the document.
@@ -4106,10 +4115,11 @@ mod document_message_handler_tests {
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> { async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
let document = editor.active_document(); let document = editor.active_document();
for layer in document.metadata().all_layers() { for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) { if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. { && (bbox[0].x - min_x).abs() < 1.
return Some(layer); && (bbox[0].y - min_y).abs() < 1.
} {
return Some(layer);
} }
} }
None None
@@ -4166,7 +4176,6 @@ mod document_message_handler_tests {
// The operation completed without crashing // The operation completed without crashing
// Verifying application still functions by performing another operation // Verifying application still functions by performing another operation
editor.handle_message(DocumentMessage::CreateEmptyFolder).await; editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
assert!(true, "Application didn't crash after folder move operation");
} }
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports. // Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
@@ -60,7 +60,6 @@ pub enum NodeGraphMessage {
DisconnectInput { DisconnectInput {
input_connector: InputConnector, input_connector: InputConnector,
}, },
DisconnectRootNode,
EnterNestedNetwork, EnterNestedNetwork,
DuplicateSelectedNodes, DuplicateSelectedNodes,
ExposeInput { ExposeInput {
@@ -406,9 +406,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::DisconnectInput { input_connector } => { NodeGraphMessage::DisconnectInput { input_connector } => {
network_interface.disconnect_input(&input_connector, selection_network_path); network_interface.disconnect_input(&input_connector, selection_network_path);
} }
NodeGraphMessage::DisconnectRootNode => {
network_interface.start_previewing_without_restore(selection_network_path);
}
NodeGraphMessage::DuplicateSelectedNodes => { NodeGraphMessage::DuplicateSelectedNodes => {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path); let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
@@ -1099,18 +1096,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.wire_in_progress_to_connector = Some(point); self.wire_in_progress_to_connector = Some(point);
// Disconnect if the wire was previously connected to an input // Disconnect if the wire was previously connected to an input
if let Some(disconnecting) = &self.disconnecting { if let Some(disconnecting) = &self.disconnecting {
let mut disconnect_root_node = false; // Previewing leaves the export alone, so dragging its wire off is an ordinary disconnect
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path) responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
&& root_node_to_restore.is_some()
&& *disconnecting == InputConnector::Export(0)
{
disconnect_root_node = true;
}
if disconnect_root_node {
responses.add(NodeGraphMessage::DisconnectRootNode);
} else {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
}
// Update the frontend that the node is disconnected // Update the frontend that the node is disconnected
responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::SendGraph);
@@ -2691,8 +2678,8 @@ impl NodeGraphMessageHandler {
wire_path_update: None, wire_path_update: None,
})); }));
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) { if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_root); added_wires.push(wire_to_preview);
} else { } else {
added_wires.push(WirePathUpdate { added_wires.push(WirePathUpdate {
id: NodeId(u64::MAX), id: NodeId(u64::MAX),
@@ -2704,7 +2691,7 @@ impl NodeGraphMessageHandler {
added_wires added_wires
} }
fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNode> { pub(crate) fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNode> {
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { let Some(network) = network_interface.nested_network(breadcrumb_network_path) else {
log::error!("Could not get nested network when collecting nodes"); log::error!("Could not get nested network when collecting nodes");
return Vec::new(); return Vec::new();
@@ -2739,16 +2726,12 @@ impl NodeGraphMessageHandler {
(false, false) (false, false)
}; };
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let Some(position) = network_interface.position(&node_id, breadcrumb_network_path) else { let Some(position) = network_interface.position(&node_id, breadcrumb_network_path) else {
log::error!("Could not get position for node: {node_id}"); log::error!("Could not get position for node: {node_id}");
continue; continue;
}; };
let previewed = is_export && !is_root_node; // Asked of the preview itself rather than inferred from the export, which previewing no longer rewires
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path); let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -4,7 +4,7 @@
//! metadata survives the conversion. The end-to-end save/reopen pipeline is covered separately in //! metadata survives the conversion. The end-to-end save/reopen pipeline is covered separately in
//! [`round_trip_tests`](super::round_trip_tests). //! [`round_trip_tests`](super::round_trip_tests).
use std::collections::HashMap; use std::collections::{BTreeSet, HashMap};
use document_graph_storage::{NodeMetadataSource, PeerId, Registry}; use document_graph_storage::{NodeMetadataSource, PeerId, Registry};
@@ -57,22 +57,6 @@ fn editor_metadata_round_trip_against_demo() {
|| !source.input_data(&network_path, local_id, i).is_empty() || !source.input_data(&network_path, local_id, i).is_empty()
}); });
let any_metadata = expected_position.is_some()
|| expected_is_layer
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|| expected_locked
|| expected_pinned
|| any_input_metadata_present
|| !expected_output_names.is_empty();
if !any_metadata {
assert!(
!entries_by_address.contains_key(&(network_path.clone(), local_id)),
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
);
continue;
}
let entry = entries_by_address let entry = entries_by_address
.get(&(network_path.clone(), local_id)) .get(&(network_path.clone(), local_id))
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}")); .unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
@@ -262,6 +246,79 @@ fn editor_interface_rebuild_round_trip() {
assert!(checked_any_reference, "demo artwork produced no reference metadata: fixture is wrong or extraction is broken"); assert!(checked_any_reference, "demo artwork produced no reference metadata: fixture is wrong or extraction is broken");
} }
/// The rebuild pins every node to the identity storage named it, rather than leaving it to be
/// re-derived. Re-converting under a different peer is the sharp test: a location hash mixes the peer
/// in, so it would produce an entirely different set of IDs.
#[test]
fn rebuilt_interface_keeps_storage_identities() {
let document = load_demo("changing-seasons.graphite");
let view = StorageMetadataView::new(&document.network_interface);
let network = document.network_interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let reconverted_network = rebuilt.document_network().clone();
let reconverted = Registry::convert_from_runtime(&reconverted_network, &StorageMetadataView::new(&rebuilt), &Default::default(), PeerId(9)).expect("re-convert from_runtime failed");
let stored_ids: BTreeSet<_> = registry.node_instances.keys().copied().collect();
let reconverted_ids: BTreeSet<_> = reconverted.registry.node_instances.keys().copied().collect();
assert!(!stored_ids.is_empty(), "demo artwork produced no nodes: fixture is wrong");
assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities");
}
/// Opening an old document runs its upgrades through the ordinary mutators, so the store records them.
/// Those recordings are the document arriving rather than edits to it, so the migration has to leave
/// the buffer empty instead of handing the first commit a pile of changes to the document's own
/// starting state.
#[test]
fn migrating_a_document_records_no_changes() {
let mut document = load_demo("painted-dreams.graphite");
document.network_interface.discard_deltas();
crate::messages::portfolio::document_migration::document_migration_upgrades(&mut document, false);
let recorded = document.network_interface.take_deltas();
assert!(recorded.is_empty(), "migration left {} recorded changes behind", recorded.len());
}
/// The pinned display order is document state, so it survives a registry round trip. It names nodes and
/// the stored form uses storage IDs, so this also checks the references resolve back to the right
/// runtime nodes.
#[test]
fn pinned_order_round_trips_through_the_registry() {
let mut document = load_demo("changing-seasons.graphite");
let pinned: Vec<_> = document.network_interface.document_network().nodes.keys().copied().take(3).collect();
assert_eq!(pinned.len(), 3, "demo artwork should have at least three nodes: fixture is wrong");
{
let interface = &mut document.network_interface;
let Some(mut network) = interface.network_mut(&[]) else {
panic!("the document network should resolve")
};
network.set_pinned_order(pinned.clone());
}
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_metadata = rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve");
assert_eq!(
rebuilt_metadata.persistent_metadata.pinned_node_order, pinned,
"the pinned display order did not survive the registry round trip"
);
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into /// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches. /// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test] #[test]
@@ -1,14 +1,22 @@
mod apply;
mod caches; mod caches;
#[cfg(test)] #[cfg(test)]
mod characterization_tests; mod characterization_tests;
mod deserialization; mod deserialization;
pub mod editor_delta;
#[cfg(test)]
mod editor_delta_tests;
mod frontend;
mod geometry;
mod hit_tests; mod hit_tests;
mod invalidation;
mod layout; mod layout;
mod memo_network; mod memo_network;
mod mutations; mod mutations;
mod queries; mod queries;
mod resolved_types; mod resolved_types;
pub mod storage_metadata; pub mod storage_metadata;
mod store;
mod structure; mod structure;
mod template; mod template;
mod types; mod types;
@@ -16,6 +24,9 @@ mod types;
mod validation; mod validation;
mod view; mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
use store::Guarded;
pub use store::NodeLocator;
pub use template::*; pub use template::*;
pub use types::*; pub use types::*;
pub use view::{NetworkError, NetworkView}; pub use view::{NetworkError, NetworkView};
@@ -59,9 +70,9 @@ use std::sync::Arc;
pub struct NodeNetworkInterface { pub struct NodeNetworkInterface {
/// The node graph that generates this document's artwork. It recursively stores its sub-graphs, so this root graph is the whole snapshot of the document content. /// The node graph that generates this document's artwork. It recursively stores its sub-graphs, so this root graph is the whole snapshot of the document content.
/// A public mutable reference should never be created. It should only be mutated through custom setters which perform the necessary side effects to keep network_metadata in sync /// A public mutable reference should never be created. It should only be mutated through custom setters which perform the necessary side effects to keep network_metadata in sync
network: MemoNetwork, network: Guarded<MemoNetwork>,
/// Stores all editor information for a NodeNetwork. Should automatically kept in sync by the setter methods when changes to the document network are made. /// Stores all editor information for a NodeNetwork. Should automatically kept in sync by the setter methods when changes to the document network are made.
network_metadata: NodeNetworkMetadata, network_metadata: Guarded<NodeNetworkMetadata>,
// TODO: Wrap in a TransientCache // TODO: Wrap in a TransientCache
/// Stores the document network's structural topology. Should automatically kept in sync by the setter methods when changes to the document network are made. /// Stores the document network's structural topology. Should automatically kept in sync by the setter methods when changes to the document network are made.
#[serde(skip)] #[serde(skip)]
@@ -71,6 +82,14 @@ pub struct NodeNetworkInterface {
pub resolved_types: ResolvedDocumentNodeTypes, pub resolved_types: ResolvedDocumentNodeTypes,
#[serde(skip)] #[serde(skip)]
transaction_status: TransactionStatus, transaction_status: TransactionStatus,
/// What the writes since the last drain changed, in write order, appended by `store.rs` alone.
///
/// Emitting here rather than in the mutators makes it impossible to write without saying what was
/// written, the same way writing through the store makes it impossible to update one tree without
/// the other. Transient: a snapshot clone starts empty, since the snapshot is a state rather than
/// a set of changes.
#[serde(skip)]
deltas: Vec<EditorDelta>,
} }
impl Clone for NodeNetworkInterface { impl Clone for NodeNetworkInterface {
@@ -81,6 +100,7 @@ impl Clone for NodeNetworkInterface {
document_metadata: Default::default(), document_metadata: Default::default(),
resolved_types: Default::default(), resolved_types: Default::default(),
transaction_status: TransactionStatus::Finished, transaction_status: TransactionStatus::Finished,
deltas: Vec::new(),
} }
} }
} }
@@ -92,9 +112,14 @@ impl PartialEq for NodeNetworkInterface {
} }
impl NodeNetworkInterface { impl NodeNetworkInterface {
/// Normalizes the stored types of every node at every nesting level, for an older document whose stored types predate the current form.
pub fn normalize_stored_types(&mut self) {
self.migrate_graph(NodeNetwork::normalize_stored_types);
}
/// Add DocumentNodePath input to the PathModifyNode protonode /// Add DocumentNodePath input to the PathModifyNode protonode
pub fn migrate_path_modify_node(&mut self) { pub fn migrate_path_modify_node(&mut self) {
fix_network(self.document_network_mut()); self.migrate_graph(fix_network);
fn fix_network(network: &mut NodeNetwork) { fn fix_network(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() { for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() { if let Some(network) = node.implementation.get_network_mut() {
@@ -136,11 +161,11 @@ mod network_interface_tests {
content: ClipboardContentRaw::Text(clipboard), content: ClipboardContentRaw::Text(clipboard),
}) })
.await; .await;
let nodes = &mut editor.active_document_mut().network_interface.network_mut(&[]).unwrap().nodes; let nodes = &editor.active_document().network_interface.document_network().nodes;
let orignal = nodes.remove(&rectangle).expect("original node should exist"); let original = nodes.get(&rectangle).expect("original node should exist");
assert!( assert!(
nodes.values().any(|other| *other == orignal), nodes.iter().any(|(node_id, other)| *node_id != rectangle && other == original),
"duplicated node should exist\nother nodes: {nodes:#?}\norignal {orignal:#?}" "duplicated node should exist\nother nodes: {nodes:#?}\noriginal {original:#?}"
); );
} }
} }
@@ -0,0 +1,130 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
// Replay: putting a delta back into the interface, the inverse of the store recording one.
//
// Mechanism only. A mutator decides policy, validates, and lays nodes out, then records what it
// settled on; replaying reproduces that outcome rather than deciding it again. A peer running
// different layout rules must still end up with the state the delta describes.
impl NodeNetworkInterface {
/// Mirrors a delta into the interface without recording it.
///
/// A delta reaching here came from somewhere else, so recording it would offer a change this peer
/// never made back to whoever sent it. Writing through the store and then dropping what the store
/// recorded keeps the two parallel trees written by one place, which is the property the store
/// exists for, without the echo.
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
let recorded = self.deltas.len();
self.mirror(delta);
self.deltas.truncate(recorded);
}
fn mirror(&mut self, delta: &EditorDelta) {
match delta {
// The metadata arrives separately, so a node lands with default metadata that the paired
// snapshot then fills in. Replacing an entry and adding one are the same write here; they
// differ only in what the storage side has to remove first.
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default());
self.insert_node_entry(NodeLocator::new(*node_id, network_path), template);
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
self.remove_node_entry(NodeLocator::new(*node_id, network_path));
}
EditorDelta::Graph(RuntimeDelta::SetInput {
network_path,
node_id,
input_index,
input,
}) => {
self.set_input_slot(&InputConnector::node_at_index(*node_id, *input_index), network_path, input.clone());
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
// The slots are what changed; their metadata follows in the paired delta. Resizing keeps the
// two arrays the same length in the meantime, which the rest of the interface assumes.
let mut input_metadata = node.input_metadata().to_vec();
input_metadata.resize(inputs.len(), InputMetadata::default());
node.replace_inputs(inputs.clone(), input_metadata);
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => match input {
None => {
self.remove_export_slot(network_path, *export_index);
}
// A peer can name a slot past the end of this network's exports, which is an insert here
// rather than a write to a slot that does not exist yet.
Some(input) if *export_index >= self.number_of_exports(network_path) => {
self.insert_export_slot(network_path, *export_index, input.clone(), String::new());
}
Some(input) => {
self.set_input_slot(&InputConnector::Export(*export_index), network_path, input.clone());
}
},
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_visible(*visible);
}
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_call_argument(call_argument.clone());
}
}
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path,
node_id,
context_features,
}) => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_context_features(*context_features);
}
}
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.replace_metadata((**metadata).clone());
}
}
EditorDelta::NodeInputMetadata {
network_path,
node_id,
input_metadata,
} => {
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_input_metadata(input_metadata.clone());
}
}
EditorDelta::NodeMetadata { network_path, node_id, change } => {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
match change {
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
NodeMetadataChange::OutputNames(output_names) => node.set_output_names(output_names.clone()),
NodeMetadataChange::InputName { index, name } => node.set_input_name(*index, name.clone()),
NodeMetadataChange::WidgetOverride { index, widget_override } => node.set_widget_override(*index, widget_override.clone()),
};
}
EditorDelta::NetworkMetadata { network_path, change } => {
let Some(mut network) = self.network_mut(network_path) else { return };
match change {
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
};
}
}
}
}
@@ -29,48 +29,48 @@ impl NodeNetworkInterface {
}; };
self.unload_stack_dependents(network_path); self.unload_stack_dependents(network_path);
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes"); log::error!("Could not get nested network_metadata in selected_nodes");
return None; return None;
}; };
// Initialize default value if selection_undo_history is empty // Initialize default value if selection_undo_history is empty
if network_metadata.persistent_metadata.selection_undo_history.is_empty() { if history.undo.is_empty() {
network_metadata.persistent_metadata.selection_undo_history.push_back(SelectedNodes::default()); history.undo.push_back(SelectedNodes::default());
} }
// Update history only if selection is non-empty/does not contain only artboards // Update history only if selection is non-empty/does not contain only artboards
if !is_selection_empty && prev_state.as_ref() != Some(&last_selection_state) { if !is_selection_empty && prev_state.as_ref() != Some(&last_selection_state) {
network_metadata.persistent_metadata.selection_undo_history.push_back(last_selection_state); history.undo.push_back(last_selection_state);
network_metadata.persistent_metadata.selection_redo_history.clear(); history.redo.clear();
if network_metadata.persistent_metadata.selection_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN { if history.undo.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
network_metadata.persistent_metadata.selection_undo_history.pop_front(); history.undo.pop_front();
} }
} }
network_metadata.persistent_metadata.selection_undo_history.back_mut() history.undo.back_mut()
} }
pub fn selection_step_back(&mut self, network_path: &[NodeId]) { pub fn selection_step_back(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selection_step_back"); log::error!("Could not get nested network_metadata in selection_step_back");
return; return;
}; };
if let Some(selection_state) = network_metadata.persistent_metadata.selection_undo_history.pop_back() { if let Some(selection_state) = history.undo.pop_back() {
network_metadata.persistent_metadata.selection_redo_history.push_front(selection_state); history.redo.push_front(selection_state);
} }
} }
pub fn selection_step_forward(&mut self, network_path: &[NodeId]) { pub fn selection_step_forward(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selection_step_forward"); log::error!("Could not get nested network_metadata in selection_step_forward");
return; return;
}; };
if let Some(selection_state) = network_metadata.persistent_metadata.selection_redo_history.pop_front() { if let Some(selection_state) = history.redo.pop_front() {
network_metadata.persistent_metadata.selection_undo_history.push_back(selection_state); history.undo.push_back(selection_state);
} }
} }
@@ -96,11 +96,11 @@ impl NodeNetworkInterface {
} }
pub(crate) fn try_get_stack_dependents(&mut self, network_path: &[NodeId]) -> Option<&HashMap<NodeId, LayerOwner>> { pub(crate) fn try_get_stack_dependents(&mut self, network_path: &[NodeId]) -> Option<&HashMap<NodeId, LayerOwner>> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in try_get_stack_dependents"); log::error!("Could not get nested network_metadata in try_get_stack_dependents");
return None; return None;
}; };
let Some(stack_dependents) = network_metadata.transient_metadata.stack_dependents.get_loaded_mut() else { let Some(stack_dependents) = transient.stack_dependents.get_loaded_mut() else {
log::error!("could not load stack_dependents"); log::error!("could not load stack_dependents");
return None; return None;
}; };
@@ -240,14 +240,14 @@ impl NodeNetworkInterface {
} }
pub fn unload_stack_dependents(&mut self, network_path: &[NodeId]) { pub fn unload_stack_dependents(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_stack_dependents"); log::error!("Could not get nested network_metadata in unload_stack_dependents");
return; return;
}; };
network_metadata.transient_metadata.stack_dependents.unload(); transient.stack_dependents.unload();
// Drag offsets are only meaningful relative to the stack dependents snapshot they were accumulated against, so they must not outlive it // Drag offsets are only meaningful relative to the stack dependents snapshot they were accumulated against, so they must not outlive it
network_metadata.transient_metadata.drag_offsets.borrow_mut().clear(); transient.drag_offsets.borrow_mut().clear();
} }
/// The vertical distance the node has been pushed from its resting position during the current drag. /// The vertical distance the node has been pushed from its resting position during the current drag.
@@ -274,13 +274,13 @@ impl NodeNetworkInterface {
} }
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> { pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
self.try_load_import_export_ports(network_path); self.load_import_export_ports(network_path);
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in export_ports"); log::error!("Could not get nested network_metadata in export_ports");
return None; return None;
}; };
let Some(ports) = network_metadata.transient_metadata.import_export_ports.get_loaded_mut() else { let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("could not load import ports"); log::error!("could not load import ports");
return None; return None;
}; };
@@ -289,54 +289,26 @@ impl NodeNetworkInterface {
/// Reads the import/export ports through &self, loading them first if needed. /// Reads the import/export ports through &self, loading them first if needed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> { pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
self.try_load_import_export_ports(network_path); self.network_metadata(network_path)?
self.network_metadata(network_path)?.transient_metadata.import_export_ports.with_loaded(read) .transient_metadata
.import_export_ports
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
} }
fn try_load_import_export_ports(&self, network_path: &[NodeId]) { pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else { let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in export_ports"); log::error!("Could not get nested network_metadata in export_ports");
return; return;
}; };
if !network_metadata.transient_metadata.import_export_ports.is_loaded() { network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
self.load_import_export_ports(network_path);
}
}
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(import_export_position) = self.import_export_position(network_path) else {
log::error!("Could not get import_export_position");
return;
};
let Some(network) = self.nested_network(network_path) else { return };
let mut import_export_ports = Ports::new();
if !network_path.is_empty() {
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
for import_index in import_start_index..self.number_of_imports(network_path) {
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_index as f64 * 24.));
}
}
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
for export_index in export_start_index..network.exports.len() {
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., export_index as f64 * 24.));
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.store(import_export_ports);
} }
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) { pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports"); log::error!("Could not get nested network_metadata in unload_export_ports");
return; return;
}; };
network_metadata.transient_metadata.import_export_ports.unload(); transient.import_export_ports.unload();
// Always unload all wires connected to them as well // Always unload all wires connected to them as well
let number_of_imports = self.number_of_imports(network_path); let number_of_imports = self.number_of_imports(network_path);
@@ -364,18 +336,13 @@ impl NodeNetworkInterface {
} }
pub fn modify_import_export(&mut self, network_path: &[NodeId]) -> Option<&ModifyImportExportClickTarget> { pub fn modify_import_export(&mut self, network_path: &[NodeId]) -> Option<&ModifyImportExportClickTarget> {
let Some(network_metadata) = self.network_metadata(network_path) else { self.load_modify_import_export(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export"); log::error!("Could not get nested network_metadata in modify_import_export");
return None; return None;
}; };
if !network_metadata.transient_metadata.modify_import_export.is_loaded() { let Some(click_targets) = transient.modify_import_export.get_loaded_mut() else {
self.load_modify_import_export(network_path);
}
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
return None;
};
let Some(click_targets) = network_metadata.transient_metadata.modify_import_export.get_loaded_mut() else {
log::error!("could not load modify import export ports"); log::error!("could not load modify import export ports");
return None; return None;
}; };
@@ -383,74 +350,22 @@ impl NodeNetworkInterface {
} }
pub fn load_modify_import_export(&self, network_path: &[NodeId]) { pub fn load_modify_import_export(&self, network_path: &[NodeId]) {
let mut reorder_imports_exports = Ports::new();
let mut remove_imports_exports = Ports::new();
if !network_path.is_empty() {
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
for (import_index, import_click_target) in import_exports.output_ports() {
let Some(import_bounding_box) = import_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
continue;
};
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
if *import_index == 0 {
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
} else {
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
let reorder_import = ClickTarget::new_with_path(rectangle_path(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
}
}
for (export_index, export_click_target) in import_exports.input_ports() {
let Some(export_bounding_box) = export_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
continue;
};
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
if *export_index == 0 {
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
} else {
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
let reorder_export = ClickTarget::new_with_path(rectangle_path(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
}
}
});
if ports_built.is_none() {
log::error!("Could not get import_export_ports in load_modify_import_export");
return;
}
}
let Some(network_metadata) = self.network_metadata(network_path) else { let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_modify_import_export"); log::error!("Could not get nested network_metadata in modify_import_export");
return; return;
}; };
network_metadata
network_metadata.transient_metadata.modify_import_export.store(ModifyImportExportClickTarget { .transient_metadata
remove_imports_exports, .modify_import_export
reorder_imports_exports, .ensure_loaded(|| self.compute_modify_import_export(network_path));
});
} }
pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) { pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports"); log::error!("Could not get nested network_metadata in unload_export_ports");
return; return;
}; };
network_metadata.transient_metadata.modify_import_export.unload(); transient.modify_import_export.unload();
} }
/// Reads the owned nodes of a layer through &self if they are loaded. /// Reads the owned nodes of a layer through &self if they are loaded.
@@ -468,51 +383,47 @@ impl NodeNetworkInterface {
return None; return None;
}; };
if !network_metadata.transient_metadata.all_nodes_bounding_box.is_loaded() { let bounding_box = network_metadata
self.load_all_nodes_bounding_box(network_path); .transient_metadata
} .all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
let bounding_box = self.network_metadata(network_path)?.transient_metadata.all_nodes_bounding_box.with_loaded(|bounds| *bounds);
if bounding_box.is_none() { if bounding_box.is_none() {
log::error!("could not load all nodes bounding box"); log::error!("could not load all nodes bounding box");
} }
bounding_box bounding_box
} }
pub fn load_all_nodes_bounding_box(&self, network_path: &[NodeId]) { /// The combined bounds of every node in the network, in node graph space.
let Some(network_metadata) = self.network_metadata(network_path) else { fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
log::error!("Could not get nested network_metadata in load_all_nodes_bounding_box"); let network_metadata = self.network_metadata(network_path)?;
return;
};
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>(); let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
let all_nodes_bounding_box = nodes Some(
.iter() nodes
.filter_map(|node_id| self.node_bounding_box(node_id, network_path)) .iter()
.reduce(Quad::combine_bounds) .filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]); .reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
let Some(network_metadata) = self.network_metadata(network_path) else { return }; )
network_metadata.transient_metadata.all_nodes_bounding_box.store(all_nodes_bounding_box);
} }
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) { pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box"); log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
return; return;
}; };
network_metadata.transient_metadata.all_nodes_bounding_box.unload(); transient.all_nodes_bounding_box.unload();
self.unload_import_export_ports(network_path); self.unload_import_export_ports(network_path);
} }
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> { pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
self.try_load_outward_wires(network_path); self.load_outward_wires(network_path);
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in outward_wires"); log::error!("Could not get nested network_metadata in outward_wires");
return None; return None;
}; };
let Some(outward_wires) = network_metadata.transient_metadata.outward_wires.get_loaded_mut() else { let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
log::error!("could not load outward wires"); log::error!("could not load outward wires");
return None; return None;
}; };
@@ -522,28 +433,29 @@ impl NodeNetworkInterface {
/// Reads the outward wires through &self, loading them first if needed. /// Reads the outward wires through &self, loading them first if needed.
pub(crate) fn with_outward_wires<R>(&self, network_path: &[NodeId], read: impl FnOnce(&HashMap<OutputConnector, Vec<InputConnector>>) -> R) -> Option<R> { pub(crate) fn with_outward_wires<R>(&self, network_path: &[NodeId], read: impl FnOnce(&HashMap<OutputConnector, Vec<InputConnector>>) -> R) -> Option<R> {
self.try_load_outward_wires(network_path); self.network_metadata(network_path)?
self.network_metadata(network_path)?.transient_metadata.outward_wires.with_loaded(read) .transient_metadata
.outward_wires
.with_loaded_or(|| self.compute_outward_wires(network_path), read)
} }
fn try_load_outward_wires(&self, network_path: &[NodeId]) { fn load_outward_wires(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else { let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in outward_wires"); log::error!("Could not get nested network_metadata in outward_wires");
return; return;
}; };
if !network_metadata.transient_metadata.outward_wires.is_loaded() { network_metadata.transient_metadata.outward_wires.ensure_loaded(|| self.compute_outward_wires(network_path));
self.load_outward_wires(network_path);
}
} }
fn load_outward_wires(&self, network_path: &[NodeId]) { /// Every input fed by each node output and each import of the network.
fn compute_outward_wires(&self, network_path: &[NodeId]) -> Option<HashMap<OutputConnector, Vec<InputConnector>>> {
let mut outward_wires = HashMap::new(); let mut outward_wires = HashMap::new();
let Some(network) = self.nested_network(network_path) else { let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in load_outward_wires"); log::error!("Could not get nested network in compute_outward_wires");
return; return None;
}; };
// Initialize all output connectors for nodes // Initialize all output connectors for nodes
for (node_id, _) in network.nodes.iter() { for node_id in network.nodes.keys() {
let number_of_outputs = self.number_of_outputs(node_id, network_path); let number_of_outputs = self.number_of_outputs(node_id, network_path);
for output_index in 0..number_of_outputs { for output_index in 0..number_of_outputs {
outward_wires.insert(OutputConnector::node(*node_id, output_index), Vec::new()); outward_wires.insert(OutputConnector::node(*node_id, output_index), Vec::new());
@@ -583,9 +495,7 @@ impl NodeNetworkInterface {
} }
} }
let Some(network_metadata) = self.network_metadata(network_path) else { return }; Some(outward_wires)
network_metadata.transient_metadata.outward_wires.store(outward_wires);
} }
pub(crate) fn unload_outward_wires(&mut self, network_path: &[NodeId]) { pub(crate) fn unload_outward_wires(&mut self, network_path: &[NodeId]) {
@@ -600,10 +510,10 @@ impl NodeNetworkInterface {
/// avoiding a full rebuild. If the cache is not loaded, this is a no-op (it will be fully /// avoiding a full rebuild. If the cache is not loaded, this is a no-op (it will be fully
/// rebuilt on the next read via `outward_wires()`). /// rebuilt on the next read via `outward_wires()`).
pub(crate) fn update_outward_wires(&mut self, network_path: &[NodeId], input_connector: &InputConnector, old_input: &NodeInput, new_input: &NodeInput) { pub(crate) fn update_outward_wires(&mut self, network_path: &[NodeId], input_connector: &InputConnector, old_input: &NodeInput, new_input: &NodeInput) {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(transient) = self.network_transient_mut(network_path) else {
return; return;
}; };
let Some(outward_wires) = network_metadata.transient_metadata.outward_wires.get_loaded_mut() else { let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
return; return;
}; };
@@ -630,55 +540,23 @@ impl NodeNetworkInterface {
return None; return None;
} }
if !node_metadata.transient_metadata.layer_width.is_loaded() { node_metadata
self.load_layer_width(node_id, network_path); .transient_metadata
} .layer_width
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
let node_metadata = self.node_metadata(node_id, network_path)?;
node_metadata.transient_metadata.layer_width.with_loaded(|layer_width| *layer_width)
}
pub fn load_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
let thumbnail_width = 3. * GRID_SIZE as f64;
let layer_text = self.display_name(node_id, network_path);
let text_width = text_width(&layer_text, FONT_SIZE);
let grip_padding = 4.;
let grip_width = 8.;
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
let layer_width = ((layer_width_pixels / 24.).ceil() as u32).max(8);
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in load_layer_width");
return;
};
// Ensure layer width is not loaded for a non layer node
if node_metadata.persistent_metadata.is_layer() {
node_metadata.transient_metadata.layer_width.store(layer_width);
} else {
log::warn!("Tried loading layer width for non layer node");
}
} }
/// Unloads layer width if the node is a layer /// Unloads layer width if the node is a layer
pub fn try_unload_layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) { pub fn try_unload_layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let is_layer = self.is_layer(node_id, network_path); let is_layer = self.is_layer(node_id, network_path);
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else { let Some(transient) = self.node_transient_mut(node_id, network_path) else {
return; return;
}; };
// If the node is a layer, then the width and click targets need to be recalculated // If the node is a layer, then the width and click targets need to be recalculated
if is_layer { if is_layer {
node_metadata.transient_metadata.layer_width.unload(); transient.layer_width.unload();
} }
} }
@@ -810,26 +688,27 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.wires.borrow_mut().remove(input); network_metadata.transient_metadata.wires.borrow_mut().remove(input);
} }
/// When previewing, there may be a second path to the root node. /// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> { /// is really connected to.
///
/// Previewing does not rewire the export, so both are shown: the solid wire says what the document
/// renders, and this one says what this peer is looking at instead.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0); let input = InputConnector::Export(0);
let current_export = self.upstream_output_connector(&input, network_path)?;
let root_node = match self.previewing(network_path) { let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
Previewing::No => None,
}?;
if Some(root_node.node_id) == current_export.node_id() { // The export already reaches it, so a second wire would land on top of the solid one
if self.upstream_output_connector(&input, network_path).and_then(|export| export.node_id()) == Some(previewed.node_id) {
return None; return None;
} }
let Some(input_position) = self.get_input_center(&input, network_path) else { let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in root node: {input:?}"); log::error!("Could not get input position for wire end in preview: {input:?}");
return None; return None;
}; };
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index); let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else { let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in root node: {upstream_output:?}"); log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
return None; return None;
}; };
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0); let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -903,46 +782,38 @@ impl NodeNetworkInterface {
} }
pub fn node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeClickTargets> { pub fn node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNodeClickTargets> {
self.try_load_node_click_targets(node_id, network_path); self.load_node_click_targets(node_id, network_path);
let node_metadata = self.node_metadata_mut(node_id, network_path)?; let transient = self.node_transient_mut(node_id, network_path)?;
let Some(click_targets) = node_metadata.transient_metadata.click_targets.get_loaded_mut() else { let Some(click_targets) = transient.click_targets.get_loaded_mut() else {
log::error!("Could not load node type metadata when getting click targets"); log::error!("Could not load node type metadata when getting click targets");
return None; return None;
}; };
Some(click_targets) Some(click_targets)
} }
pub(crate) fn try_load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) { pub(crate) fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else { let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in node_click_targets"); log::error!("Could not get nested node_metadata in node_click_targets");
return; return;
}; };
if !node_metadata.transient_metadata.click_targets.is_loaded() { node_metadata.transient_metadata.click_targets.ensure_loaded(|| self.compute_node_click_targets(node_id, network_path));
self.load_node_click_targets(node_id, network_path)
};
} }
/// Loads the node click targets if needed, then reads them through &self. /// Loads the node click targets if needed, then reads them through &self.
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> { pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
self.try_load_node_click_targets(node_id, network_path); self.node_metadata(node_id, network_path)?
self.with_node_click_targets_if_loaded(node_id, network_path, read) .transient_metadata
.click_targets
.with_loaded_or(|| self.compute_node_click_targets(node_id, network_path), read)
} }
/// Reads the modify import/export click targets through &self, loading them first if needed. /// Reads the modify import/export click targets through &self, loading them first if needed.
pub(crate) fn with_modify_import_export<R>(&self, network_path: &[NodeId], read: impl FnOnce(&ModifyImportExportClickTarget) -> R) -> Option<R> { pub(crate) fn with_modify_import_export<R>(&self, network_path: &[NodeId], read: impl FnOnce(&ModifyImportExportClickTarget) -> R) -> Option<R> {
self.try_load_modify_import_export(network_path); self.network_metadata(network_path)?
self.network_metadata(network_path)?.transient_metadata.modify_import_export.with_loaded(read) .transient_metadata
} .modify_import_export
.with_loaded_or(|| self.compute_modify_import_export(network_path), read)
fn try_load_modify_import_export(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
return;
};
if !network_metadata.transient_metadata.modify_import_export.is_loaded() {
self.load_modify_import_export(network_path);
}
} }
/// Reads the node click targets through &self if they are already loaded. /// Reads the node click targets through &self if they are already loaded.
@@ -955,179 +826,8 @@ impl NodeNetworkInterface {
result result
} }
pub fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_position) = self.position_from_downstream_node(node_id, network_path) else {
log::error!("Could not get node position in load_node_click_targets for node {node_id}");
return;
};
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
let Some(document_node) = self.document_node(node_id, network_path) else {
log::error!("Could not get document node in load_node_click_targets");
return;
};
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut port_click_targets = Ports::new();
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
// Create input/output click targets
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
port_click_targets.insert_node_input(input_index, input_row_count, node_top_left);
}
// Primary input row is always displayed, even if the input is not exposed
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let number_of_outputs = match &document_node.implementation {
DocumentNodeImplementation::Network(network) => network.exports.len(),
_ => 1,
};
// If the node has a hidden primary output, do not display the first output
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..number_of_outputs {
port_click_targets.insert_node_output(output_index, node_top_left);
}
let height = input_row_count.max(number_of_outputs).max(1) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
// Layer inputs
port_click_targets.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
port_click_targets.insert_layer_input(1, node_top_left);
}
port_click_targets.insert_layer_output(node_top_left);
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in load_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = 2 * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// Update grip button click target, which is positioned to the left of the leftmost icon.
// The grip is 8px wide but spans the full layer-vertical-center band.
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// Create layer click target, which is contains the layer and the chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
node_metadata.transient_metadata.click_targets.store(document_node_click_targets);
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> { pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.try_load_node_click_targets(node_id, network_path); self.load_node_click_targets(node_id, network_path);
self.try_get_node_bounding_box(node_id, network_path) self.try_get_node_bounding_box(node_id, network_path)
} }
@@ -1136,103 +836,22 @@ impl NodeNetworkInterface {
.flatten() .flatten()
} }
pub fn try_load_all_node_click_targets(&self, network_path: &[NodeId]) { pub fn load_all_node_click_targets(&self, network_path: &[NodeId]) {
let Some(network) = self.nested_network(network_path) else { let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get network in load_all_node_click_targets"); log::error!("Could not get network in load_all_node_click_targets");
return; return;
}; };
for node_id in network.nodes.keys().cloned().collect::<Vec<_>>() { for node_id in network.nodes.keys().cloned().collect::<Vec<_>>() {
self.try_load_node_click_targets(&node_id, network_path); self.load_node_click_targets(&node_id, network_path);
}
}
/// Get the top left position in node graph coordinates for a node by recursively iterating downstream through cached positions, which means the iteration can be broken once a known position is reached.
pub fn position_from_downstream_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in position_from_downstream_node");
return None;
};
match &node_metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => {
match layer_metadata.position {
LayerPosition::Absolute(position) => Some(position),
LayerPosition::Stack(y_offset) => {
let Some(downstream_node_connectors) = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id)).cloned())
.flatten()
else {
log::error!("Could not get downstream node in position_from_downstream_node");
return None;
};
let downstream_connector = downstream_node_connectors
.iter()
.find_map(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())));
let Some((downstream_node_id, _)) = downstream_connector else {
log::error!("Could not get downstream node input connector for node {node_id}");
return None;
};
// Get the height of the node to ensure nodes do not overlap
let Some(downstream_node_height) = self.height_from_click_target(&downstream_node_id, network_path) else {
log::error!("Could not get click target height in position_from_downstream_node");
return None;
};
self.position(&downstream_node_id, network_path)
.map(|position| position + IVec2::new(0, 1 + downstream_node_height as i32 + y_offset as i32))
}
}
}
NodeTypePersistentMetadata::Node(node_metadata) => {
match node_metadata.position {
NodePosition::Absolute(position) => Some(position),
NodePosition::Chain => {
// Iterate through primary flow to find the first Layer
let mut current_node_id = *node_id;
let mut node_distance_from_layer = 1;
loop {
// TODO: Use root node to restore if previewing
let Some(downstream_node_connectors) = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(current_node_id)).cloned())
.flatten()
else {
log::error!("Could not get downstream node for node {node_id} with Position::Chain");
return None;
};
let Some(downstream_node_id) = downstream_node_connectors.iter().find_map(|input_connector| {
if let InputConnector::Node { node_id, input_index } = input_connector {
let downstream_input_index = if self.is_layer(node_id, network_path) { 1 } else { 0 };
if *input_index == downstream_input_index { Some(node_id) } else { None }
} else {
None
}
}) else {
log::error!("Could not get downstream node input connector with input index 1 for node with Position::Chain");
return None;
};
let Some(downstream_node_metadata) = self.network_metadata(network_path)?.persistent_metadata.node_metadata.get(downstream_node_id) else {
log::error!("Downstream node metadata not found in node_metadata for node with Position::Chain");
return None;
};
if downstream_node_metadata.persistent_metadata.is_layer() {
// Get the position of the layer
let layer_position = self.position(downstream_node_id, network_path)?;
return Some(layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
}
node_distance_from_layer += 1;
current_node_id = *downstream_node_id;
}
}
}
}
} }
} }
pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) { pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata_mut(node_id, network_path) else { let Some(transient) = self.node_transient_mut(node_id, network_path) else {
log::error!("Could not get nested node_metadata in unload_node_click_target"); log::error!("Could not get nested node_metadata in unload_node_click_target");
return; return;
}; };
node_metadata.transient_metadata.click_targets.unload(); transient.click_targets.unload();
self.unload_wires_for_node(node_id, network_path); self.unload_wires_for_node(node_id, network_path);
} }
@@ -126,29 +126,50 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
assert_invariants(&editor, "after rejecting a cyclic connection"); assert_invariants(&editor, "after rejecting a cyclic connection");
} }
/// The check answers for the network with the proposed input substituted, so it has to see a loop that
/// closes through intermediate nodes rather than only one that connects two neighbours.
#[tokio::test] #[tokio::test]
async fn toggling_preview_on_a_disconnected_export() { async fn a_cycle_closing_through_a_chain_is_rejected() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let c = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_input(&InputConnector::node_at_index(a, 1), NodeInput::node(b, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(b, 1), NodeInput::node(c, 0), &[]);
// `a` already reaches `c` through `b`, so feeding `a` back into `c` closes a three-node loop
let input_before = network_interface.input_from_connector(&InputConnector::node_at_index(c, 1), &[]).cloned();
network_interface.set_input(&InputConnector::node_at_index(c, 1), NodeInput::node(a, 0), &[]);
let input_after = network_interface.input_from_connector(&InputConnector::node_at_index(c, 1), &[]).cloned();
assert_eq!(input_before, input_after, "A cycle closing through an intermediate node should be rejected");
assert_invariants(&editor, "after rejecting a chained cyclic connection");
}
/// An export is not something a node takes as input, so connecting one cannot close a loop and must
/// not be refused.
#[tokio::test]
async fn connecting_an_export_is_never_cyclic() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await; let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface; let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.disconnect_input(&InputConnector::Export(0), &[]); network_interface.set_input(&InputConnector::Export(0), NodeInput::node(node, 0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore assert_eq!(
network_interface.toggle_preview(node, &[]); network_interface.input_from_connector(&InputConnector::Export(0), &[]).cloned(),
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None }); Some(NodeInput::node(node, 0)),
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]); "Connecting a node to the export should be accepted"
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export"); );
// Ending the preview restores the disconnected export assert_invariants(&editor, "after connecting the export");
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
} }
#[tokio::test] #[tokio::test]
@@ -360,8 +381,10 @@ async fn signature_edits_keep_parallel_metadata_in_sync() {
assert_invariants(&editor, "after removing the added export"); assert_invariants(&editor, "after removing the added export");
} }
/// Previewing renders a different node without rewiring anything: the export keeps whatever it is
/// connected to, so ending a preview has nothing to restore and cannot disconnect anything.
#[tokio::test] #[tokio::test]
async fn toggle_preview_transitions_with_a_connected_export() { async fn previewing_leaves_the_export_alone() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
@@ -373,31 +396,125 @@ async fn toggle_preview_transitions_with_a_connected_export() {
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node()); let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard)); assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node remembers the artboard as the connection to restore // Previewing a node names it without touching the export
network_interface.toggle_preview(node, &[]); network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!( assert_eq!(
network_interface.previewing(&[]), network_interface.previewing(&[]),
Previewing::Yes { Previewing::Yes {
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 }) previewed: RootNode { node_id: node, output_index: 0 }
} }
); );
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
// Toggling the previewed node again restores the artboard connection // Previewing a different node moves the preview, still without touching the export
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
network_interface.toggle_preview(node, &[]);
network_interface.toggle_preview(artboard, &[]); network_interface.toggle_preview(artboard, &[]);
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: artboard, output_index: 0 }
}
);
assert_eq!(export_node(network_interface), Some(artboard)); assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
// Toggling it once more ends the preview by disconnecting the export entirely // Toggling the previewed node again ends the preview, leaving the export as it always was
network_interface.toggle_preview(artboard, &[]); network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), None);
assert_eq!(network_interface.previewing(&[]), Previewing::No); assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_eq!(export_node(network_interface), Some(artboard));
assert_invariants(&editor, "after cycling through the preview states"); assert_invariants(&editor, "after cycling through the preview states");
} }
/// The graph handed to the compiler renders the previewed node, which is the whole point of a preview
/// that does not rewire the document.
#[tokio::test]
async fn the_evaluated_network_renders_the_previewed_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let evaluated = network_interface.network_to_evaluate();
assert_eq!(
evaluated.exports.first().and_then(|export| export.as_node()),
Some(node),
"The network being evaluated should export the previewed node"
);
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The document itself should be unchanged"
);
}
/// The previewed node is marked for the frontend so it can be highlighted. Derived from the preview
/// itself: it used to be inferred from the export, which previewing no longer rewires, so inferring it
/// would silently mark nothing.
#[tokio::test]
async fn the_previewed_node_is_flagged_for_the_frontend() {
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let handler = NodeGraphMessageHandler::default();
let network_interface = &mut editor.active_document_mut().network_interface;
let flagged = |handler: &NodeGraphMessageHandler, network_interface: &mut super::NodeNetworkInterface| {
handler
.collect_nodes(network_interface, &[])
.into_iter()
.filter(|node| node.previewed)
.map(|node| node.id)
.collect::<Vec<_>>()
};
assert!(flagged(&handler, network_interface).is_empty(), "Nothing is previewed to begin with");
network_interface.toggle_preview(node, &[]);
assert_eq!(flagged(&handler, network_interface), vec![node], "The previewed node should be the one flagged");
network_interface.toggle_preview(node, &[]);
assert!(flagged(&handler, network_interface).is_empty(), "Ending the preview should unflag it");
}
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
/// node on its own. A stack is the case that matters: every layer walks through the ones below it, so
/// a shared memo is what keeps the batch from being quadratic.
#[tokio::test]
async fn batched_positions_agree_with_resolving_each_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
for offset in 0..4 {
editor.draw_rect(0., offset as f64 * 20., 100., offset as f64 * 20. + 10.).await;
}
let network_interface = &editor.active_document().network_interface;
let node_ids = network_interface.document_network().nodes.keys().copied().collect::<Vec<_>>();
assert!(node_ids.len() > 4, "the fixture should build a stack, found {} nodes", node_ids.len());
let batched = network_interface.positions(node_ids.iter().copied(), &[]);
let individually = node_ids
.iter()
.filter_map(|node_id| network_interface.position(node_id, &[]).map(|position| (*node_id, position)))
.collect::<Vec<_>>();
assert_eq!(batched.len(), individually.len(), "The batch should resolve exactly the nodes that resolve on their own");
for (node_id, position) in individually {
assert_eq!(
batched.iter().find(|(batched_id, _)| *batched_id == node_id).map(|(_, position)| *position),
Some(position),
"Batched position disagrees for node {node_id}"
);
}
}
@@ -141,6 +141,8 @@ impl From<DocumentNodePersistentMetadataStringReference> for DocumentNodePersist
metadata.persistent_metadata.reference = old.reference; metadata.persistent_metadata.reference = old.reference;
} }
DocumentNodePersistentMetadata { DocumentNodePersistentMetadata {
// Predates stored identities, so this node falls back to a hash of its location
storage_id: None,
display_name: old.display_name, display_name: old.display_name,
input_metadata: old.input_metadata, input_metadata: old.input_metadata,
output_names: old.output_names, output_names: old.output_names,
@@ -0,0 +1,770 @@
use super::storage_metadata::position_from_runtime;
use super::{DocumentNodeMetadata, DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata};
use super::{InputMetadata, InputPersistentMetadata};
use document_graph_storage::attr::network as network_attr;
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
use document_graph_storage::{convert_input_attributes, convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::document::NodeId;
use graph_craft::runtime_delta::RuntimeDelta;
use std::collections::{HashMap, HashSet};
/// A [`RuntimeDelta`] extended with the editor-only change kinds, which carry the `ui::*` metadata
/// the compiler has no use for. The compiler consumes only the `Graph` variant.
#[derive(Debug, Clone, PartialEq)]
pub enum EditorDelta {
Graph(RuntimeDelta),
/// Every `ui::*` attribute of a node that has just been added, including everything nested under
/// it, so one delta covers a group and its contents.
///
/// Asserting the whole set is sound here precisely because the node is new: every field was just
/// written, so there is no concurrent peer holding state for it to clobber. An edit to an existing
/// node must use [`EditorDelta::NodeMetadata`] instead.
NodeMetadataSnapshot {
network_path: Vec<NodeId>,
node_id: NodeId,
metadata: Box<DocumentNodePersistentMetadata>,
},
/// One field of an existing node's metadata.
NodeMetadata {
network_path: Vec<NodeId>,
node_id: NodeId,
change: NodeMetadataChange,
},
/// A node's whole input metadata array, paired with the `SetInputs` that changed the slots it
/// indexes. Whole-array for the same reason: an insert shifts every later entry.
NodeInputMetadata {
network_path: Vec<NodeId>,
node_id: NodeId,
input_metadata: Vec<InputMetadata>,
},
/// One field of an existing network's metadata.
NetworkMetadata {
network_path: Vec<NodeId>,
change: NetworkMetadataChange,
},
}
/// One field of a node's persistent metadata, named the way the store writes it so each write has
/// exactly one delta. Every variant carries the post-change value, never a difference.
#[derive(Debug, Clone, PartialEq)]
pub enum NodeMetadataChange {
/// Whether the node is displayed as a layer and where it sits, which are one choice: a layer and a
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
NodeType(NodeTypePersistentMetadata),
DisplayName(String),
Locked(bool),
Pinned(bool),
/// The whole vec, since the encoding is one array-valued attribute rather than a slot each.
OutputNames(Vec<String>),
InputName {
index: usize,
name: String,
},
WidgetOverride {
index: usize,
widget_override: Option<String>,
},
}
/// One field of a network's persistent metadata. The navigation transform and width are absent
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
#[derive(Debug, Clone, PartialEq)]
pub enum NetworkMetadataChange {
/// The definition the network was instantiated from, dropped once it is edited away from it.
Reference(Option<String>),
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
PinnedOrder(Vec<NodeId>),
}
pub struct ConstructedOps {
pub ops: Vec<RegistryDelta>,
pub declaration_bytes: DeclarationBytes,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
/// resource liveness are computed against the whole batch, since several removals in one gesture
/// can jointly orphan a resource that each alone would not. Op timestamps are placeholders,
/// re-stamped by the staging clock.
///
/// `metadata` addresses each delta's node by the identity the interface holds for it, so the ops
/// land on the same nodes a whole-document conversion of that interface would produce.
pub fn construct_batch(
deltas: &[EditorDelta],
working: &Registry,
resources: &ResourceRegistry,
metadata: &dyn NodeMetadataSource,
peer: document_graph_storage::PeerId,
) -> Result<ConstructedOps, ConversionError> {
let identities = IdentitiesOnly(metadata);
let resolver = PathResolver::new(Some(&identities), peer);
let mut batch = BatchRegistry::new(working);
let mut ops = Vec::new();
let mut declaration_bytes = DeclarationBytes::new();
let mut batch_removed_nodes = Vec::new();
// In delta order, so each delta reads what the ones before it did. Removals accumulate as they are
// met rather than being gathered up front, since a removal can name a node an earlier delta added.
for delta in deltas {
delta.construct(resources, peer, &identities, &resolver, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declaration_bytes)?;
}
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
Ok(ConstructedOps { ops, declaration_bytes })
}
impl EditorDelta {
#[allow(clippy::too_many_arguments)]
fn construct(
&self,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
identities: &dyn NodeMetadataSource,
resolver: &PathResolver,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
match self {
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
}
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
},
});
}
EditorDelta::Graph(RuntimeDelta::SetInput {
network_path,
node_id,
input_index,
input,
}) => {
ops.push(RegistryDelta::ChangeNodeInput {
id: resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input: resolver.convert_input_at(input, network_path)?,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
ops.push(RegistryDelta::SetNetworkExport {
id: resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export: input.as_ref().map(|input| resolver.convert_input_at(input, network_path)).transpose()?,
});
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_call_argument(call_argument)?,
});
}
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path,
node_id,
context_features,
}) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_context_features(context_features)?,
});
}
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
construct_metadata_snapshot(network_path, *node_id, metadata, batch, resolver, ops)?;
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
// Only the slots are written, so the node's attributes and everything nested under it are
// left as they are: an edit made earlier in this batch is not reverted by the rebuild.
// The slots' `ui::*` attributes arrive with the paired input metadata delta.
let inputs = inputs
.iter()
.map(|input| {
Ok(document_graph_storage::InputSlot {
input: resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
ops.push(RegistryDelta::SetNodeInputs {
id: resolver.node_id(network_path, *node_id),
inputs,
});
}
EditorDelta::NodeMetadata { network_path, node_id, change } => {
ops.extend(node_metadata_ops(resolver.node_id(network_path, *node_id), change)?);
}
EditorDelta::NodeInputMetadata {
network_path,
node_id,
input_metadata,
} => {
let global_id = resolver.node_id(network_path, *node_id);
let source = InputMetadataSource(input_metadata);
let working_node = batch.node(global_id);
// An insert shifts every later slot, so the array is asserted whole: a `ui::` key the slot
// no longer carries is cleared rather than left behind at its old index.
for input_index in 0..input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, network_path, *node_id, input_index, TimeStamp::ORIGIN)?;
let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes);
for delta in ui_attribute_writes(current, &encoded) {
ops.push(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?,
delta,
});
}
}
}
EditorDelta::NetworkMetadata { network_path, change } => {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(serde_json::Value::String),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| resolver.node_id(network_path, *node_id)).collect();
AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
}
}
};
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: resolver.network_id(network_path),
delta,
});
}
}
Ok(())
}
}
fn serialize_attribute<T: serde::Serialize>(key: &str, value: &T) -> Result<serde_json::Value, ConversionError> {
serde_json::to_value(value).map_err(|error| ConversionError::SerializationError(format!("{key}: {error:?}")))
}
/// The attribute writes one metadata field makes, as the whole-document encoder would write them.
///
/// A field set back to its unset value clears the attribute, since absence is how that encoder spells
/// unset. Clearing rather than writing a sentinel keeps the two paths producing the same registry.
fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMetadataChange) -> Result<Vec<RegistryDelta>, ConversionError> {
let node_attribute = |key: &str, value: Option<serde_json::Value>| RegistryDelta::ChangeNodeAttribute {
id: global_id,
delta: AttributeDelta { key: key.to_string(), value },
};
let input_attribute = |key: &str, index: usize, value: Option<serde_json::Value>| {
Ok::<_, ConversionError>(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: index.try_into().map_err(|_| ConversionError::IndexOverflow(index))?,
delta: AttributeDelta { key: key.to_string(), value },
})
};
// Absence is how the encoder spells an unset flag, and the empty string is the runtime's own
// sentinel for an unset name.
let flag = |value: bool| value.then_some(serde_json::Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| serde_json::Value::String(value.to_string()));
Ok(match change {
NodeMetadataChange::NodeType(node_type) => {
let position = position_from_runtime(node_type);
vec![
node_attribute(node_attr::ui::POSITION, Some(serialize_attribute(node_attr::ui::POSITION, &position)?)),
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
]
}
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
NodeMetadataChange::OutputNames(output_names) => {
let value = (!output_names.is_empty()).then(|| serialize_attribute(node_attr::ui::OUTPUT_NAMES, output_names)).transpose()?;
vec![node_attribute(node_attr::ui::OUTPUT_NAMES, value)]
}
NodeMetadataChange::InputName { index, name } => vec![input_attribute(node_attr::input::ui::NAME, *index, non_empty(name))?],
NodeMetadataChange::WidgetOverride { index, widget_override } => {
let value = widget_override.as_deref().and_then(non_empty);
vec![input_attribute(node_attr::input::ui::WIDGET_OVERRIDE, *index, value)?]
}
})
}
/// Converts through the same encoders as a whole-document conversion, with identities only as the
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
#[allow(clippy::too_many_arguments)]
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
batch: &mut BatchRegistry,
resources: &ResourceRegistry,
identities: &dyn NodeMetadataSource,
peer: document_graph_storage::PeerId,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(identities, peer);
let mut scratch = Registry::default();
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
declaration_bytes.extend(scoped.finish());
let mut networks: Vec<_> = scratch.networks.iter().collect();
networks.sort_by_key(|(id, _)| **id);
for (id, network) in networks {
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
}
// Recorded as well as emitted, so a later delta in this batch that reads one of these nodes back
// finds it rather than looking only at the registry the batch started from.
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
for (id, node) in added {
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
batch.record_addition(id, node);
}
let mut new_resources: Vec<_> = scratch
.resources
.iter()
.filter(|(id, _)| !batch.working.resources.contains_key(id))
.map(|(id, entry)| (*id, entry.clone()))
.collect();
new_resources.sort_by_key(|(id, _)| *id);
for (id, entry) in new_resources {
if batch.record_resource(id, entry.clone()) {
ops.push(RegistryDelta::AddResource { id, entry });
}
}
let mut tagged: Vec<ResourceId> = scratch.node_instances.values().flat_map(node_value_resource_refs).collect();
tagged.sort();
tagged.dedup();
for id in tagged {
if batch.resource(id).is_none()
&& !scratch.resources.contains_key(&id)
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
{
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
}
}
Ok(())
}
fn construct_metadata_snapshot(
network_path: &[NodeId],
node_id: NodeId,
metadata: &DocumentNodePersistentMetadata,
batch: &BatchRegistry,
resolver: &PathResolver,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let source = MetadataCopySource {
anchor_path: network_path,
anchor_id: node_id,
metadata,
};
let mut pending = vec![(network_path.to_vec(), node_id, metadata)];
while let Some((path, id, node_metadata)) = pending.pop() {
let global_id = resolver.node_id(&path, id);
let working_node = batch.node(global_id);
let mut encoded = Attributes::new();
encode_node_ui_attributes(&mut encoded, &source, &path, id, TimeStamp::ORIGIN)?;
for delta in ui_attribute_writes(working_node.map(|node| node.attributes()), &encoded) {
ops.push(RegistryDelta::ChangeNodeAttribute { id: global_id, delta });
}
for input_index in 0..node_metadata.input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, &path, id, input_index, TimeStamp::ORIGIN)?;
let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes);
for delta in ui_attribute_writes(current, &encoded) {
ops.push(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?,
delta,
});
}
}
if let Some(network_metadata) = &node_metadata.network_metadata {
let mut nested_path = path.clone();
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
let current = batch
.working
.networks
.get(&network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: target,
},
});
}
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
}
}
Ok(())
}
/// Every `ui::` attribute of `encoded`, plus a clear for each `ui::` key of `current` that `encoded`
/// does not carry. Values are compared only to decide what to clear, never to skip a write.
///
/// Restating a value that already matches looks redundant but is load-bearing: `current` is the
/// registry as it stood before the batch, and these writes follow an op in the same batch that
/// rebuilt what they describe. A value the pre-batch state agrees with may already have been cleared
/// by that op, so skipping it would leave the attribute missing.
fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
let owned = |key: &str| key.starts_with("ui::");
let mut deltas = Vec::new();
if let Some(current) = current {
for key in current.keys() {
if owned(key) && !encoded.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
}
for (key, value) in encoded {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(value.value.clone()),
});
}
deltas.sort_by(|a, b| a.key.cmp(&b.key));
deltas
}
/// Emits the removal of a node and everything nested under it, recording what was removed so the
/// batch's resource liveness accounts for all of it at the end.
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, ops: &mut Vec<RegistryDelta>) {
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
let Some(snapshot) = batch.node(*id) else { continue };
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
}
for id in &removed_networks {
let Some(snapshot) = batch.working.networks.get(id) else { continue };
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
}
batch_removed_nodes.extend(removed_nodes);
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.filter_map(|id| batch.node(*id))
.flat_map(|node| {
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
})
.collect();
candidates.sort();
candidates.dedup();
if candidates.is_empty() {
return;
}
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
if removed_node_set.contains(id) {
continue;
}
if let Implementation::ProtoNode(declaration) = node.implementation() {
still_referenced.insert(*declaration);
}
still_referenced.extend(node_value_resource_refs(node));
}
for network in batch.working.networks.values() {
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
}
for candidate in candidates {
if !still_referenced.contains(&candidate)
&& let Some(entry) = batch.resource(candidate)
{
ops.push(RegistryDelta::RemoveResource {
id: candidate,
snapshot: entry.clone(),
});
}
}
}
/// The registry a delta is constructed against: what the batch started from, plus the nodes deltas
/// earlier in the same batch have added.
///
/// A delta that reads a node back cannot read only the starting registry. A node added and removed
/// within one batch is not in it, and a later delta that rebuilds a node would rebuild the version
/// that predates the batch. Additions are tracked rather than the whole registry copied, so the cost
/// is the size of the batch rather than of the document.
///
/// Nodes are also indexed by network, so a removal closure walks only the subtree it removes instead
/// of rescanning every node for each nested network it meets.
struct BatchRegistry<'a> {
working: &'a Registry,
added: HashMap<document_graph_storage::NodeId, document_graph_storage::Node>,
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
}
impl<'a> BatchRegistry<'a> {
fn new(working: &'a Registry) -> Self {
let mut by_network: HashMap<_, Vec<_>> = HashMap::new();
for (id, node) in &working.node_instances {
by_network.entry(node.network()).or_default().push(*id);
}
Self {
working,
added: HashMap::new(),
added_resources: HashMap::new(),
by_network,
}
}
/// Records a node an earlier delta in this batch added, so a later one can read it back.
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
self.by_network.entry(node.network()).or_default().push(id);
self.added.insert(id, node);
}
/// Records a resource this batch added. Returns whether it is new to the batch, so the caller emits
/// one addition for a resource several nodes reference.
fn record_resource(&mut self, id: ResourceId, entry: document_graph_storage::ResourceEntry) -> bool {
self.added_resources.insert(id, entry).is_none()
}
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
}
fn resource(&self, id: ResourceId) -> Option<&document_graph_storage::ResourceEntry> {
self.added_resources.get(&id).or_else(|| self.working.resources.get(&id))
}
fn children(&self, network_id: document_graph_storage::NetworkId) -> &[document_graph_storage::NodeId] {
self.by_network.get(&network_id).map_or(&[], Vec::as_slice)
}
}
/// The node together with everything nested under it, and the networks that nesting owns.
fn removal_closure(node_id: document_graph_storage::NodeId, batch: &BatchRegistry) -> (Vec<document_graph_storage::NodeId>, Vec<document_graph_storage::NetworkId>) {
let mut nodes = Vec::new();
let mut networks = Vec::new();
collect_removal_closure(node_id, batch, &mut nodes, &mut networks);
(nodes, networks)
}
fn collect_removal_closure(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, nodes: &mut Vec<document_graph_storage::NodeId>, networks: &mut Vec<document_graph_storage::NetworkId>) {
let Some(node) = batch.node(node_id) else { return };
nodes.push(node_id);
if let &Implementation::Network(network_id) = node.implementation() {
networks.push(network_id);
for &child_id in batch.children(network_id) {
collect_removal_closure(child_id, batch, nodes, networks);
}
}
}
/// Narrows a metadata source to the node identities alone, so a scoped conversion addresses nodes the
/// way a whole-document conversion does without also re-encoding ui attributes the gesture's paired
/// `NodeMetadata` delta already carries.
struct IdentitiesOnly<'a>(&'a dyn NodeMetadataSource);
impl NodeMetadataSource for IdentitiesOnly<'_> {
fn storage_node_id(&self, network_path: &[NodeId], local_id: NodeId) -> Option<document_graph_storage::NodeId> {
self.0.storage_node_id(network_path, local_id)
}
}
/// Serves one node's input metadata for encoding a [`EditorDelta::NodeInputMetadata`] delta. Only the
/// per-input accessors answer, since the node-level ones are never reached: the delta encodes through
/// `encode_input_ui_attributes` alone.
struct InputMetadataSource<'a>(&'a [InputMetadata]);
impl InputMetadataSource<'_> {
fn persistent(&self, input_index: usize) -> Option<&InputPersistentMetadata> {
self.0.get(input_index).map(|metadata| &metadata.persistent_metadata)
}
}
impl NodeMetadataSource for InputMetadataSource<'_> {
fn input_name(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> Option<&str> {
Some(self.persistent(input_index)?.input_name.as_str())
}
fn input_description(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> Option<&str> {
Some(self.persistent(input_index)?.input_description.as_str())
}
fn widget_override(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> Option<&str> {
self.persistent(input_index)?.widget_override.as_deref()
}
fn input_data(&self, _network_path: &[NodeId], _local_id: NodeId, input_index: usize) -> HashMap<String, serde_json::Value> {
self.persistent(input_index).map(|metadata| metadata.input_data.clone()).unwrap_or_default()
}
}
/// Serves a metadata copy as the [`document_graph_storage::NodeMetadataSource`] for its own
/// encoding, resolving requested paths relative to the anchor node the copy was taken from.
struct MetadataCopySource<'a> {
anchor_path: &'a [NodeId],
anchor_id: NodeId,
metadata: &'a DocumentNodePersistentMetadata,
}
impl MetadataCopySource<'_> {
fn metadata_for(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
let relative = metadata_path.strip_prefix(self.anchor_path)?;
let (mut current, rest) = match relative.split_first() {
None => return (node_id == self.anchor_id).then_some(self.metadata),
Some((first, rest)) if *first == self.anchor_id => (self.metadata, rest),
Some(_) => return None,
};
for step in rest {
current = child_metadata(current, *step)?;
}
child_metadata(current, node_id)
}
}
fn child_metadata(metadata: &DocumentNodePersistentMetadata, child_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
metadata
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.node_metadata.get(&child_id))
.map(|child: &DocumentNodeMetadata| &child.persistent_metadata)
}
impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
fn position(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<Position> {
match &self.metadata_for(metadata_path, node_id)?.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
}),
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
NodePosition::Chain => Position::Chain,
}),
}
}
fn is_layer(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id)
.is_some_and(|metadata| matches!(metadata.node_type_metadata, NodeTypePersistentMetadata::Layer(_)))
}
fn display_name(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&str> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.display_name.as_str())
}
fn locked(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.locked)
}
fn pinned(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.pinned)
}
fn output_names(&self, metadata_path: &[NodeId], node_id: NodeId) -> Vec<String> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.output_names.clone()).unwrap_or_default()
}
fn input_name(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_name.as_str())
}
fn input_description(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_description.as_str())
}
fn widget_override(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.and_then(|input| input.persistent_metadata.widget_override.as_deref())
}
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.clone())
.unwrap_or_default()
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let (owner_path, owner_id) = network_path.split_last().map(|(last, rest)| (rest, *last))?;
self.metadata_for(owner_path, owner_id)?
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.reference.as_deref())
}
}
@@ -0,0 +1,554 @@
use super::DocumentNodePersistentMetadata;
use super::InputConnector;
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch};
use super::storage_metadata::StorageMetadataView;
use crate::test_utils::test_prelude::*;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graph_craft::runtime_delta::RuntimeDelta;
use graphene_std::uuid::NodeId;
const PEER: PeerId = PeerId(7);
fn rectangle_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
fn convert(editor: &EditorTestUtils) -> Registry {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion should succeed")
.registry
}
fn construct(editor: &EditorTestUtils, deltas: &[EditorDelta], working: &Registry) -> Vec<RegistryDelta> {
let document = editor.active_document();
construct_batch(deltas, working, &document.resources.registry, &StorageMetadataView::new(&document.network_interface), PEER)
.expect("construction should succeed")
.ops
}
fn node_metadata(editor: &EditorTestUtils, node_id: NodeId) -> DocumentNodePersistentMetadata {
editor
.active_document()
.network_interface
.node_metadata(&node_id, &[])
.expect("node metadata should exist")
.persistent_metadata
.clone()
}
fn metadata_change(node_id: NodeId, change: NodeMetadataChange) -> EditorDelta {
EditorDelta::NodeMetadata {
network_path: Vec::new(),
node_id,
change,
}
}
fn assert_same_stored_effect(working: &Registry, constructed: Vec<RegistryDelta>, diffed: Vec<RegistryDelta>, at: &str) {
let baseline = compute_deltas(&Registry::default(), working);
let mut from_construction = Session::with_peer(PEER);
from_construction.stage_computed_ops(baseline.clone()).expect("baseline should stage");
from_construction.stage_computed_ops(constructed).expect("constructed ops should stage");
let mut from_diff = Session::with_peer(PEER);
from_diff.stage_computed_ops(baseline).expect("baseline should stage");
from_diff.stage_computed_ops(diffed).expect("diffed ops should stage");
assert!(
from_construction.registry().value_equal(from_diff.registry()),
"Constructed ops must produce the same stored state as the whole-document diff: {at}\nresidual: {:#?}",
compute_deltas(from_construction.registry(), from_diff.registry())
);
}
#[tokio::test]
async fn set_input_value_constructs_the_exact_diff_op() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::F64(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: node,
input_index: 1,
input,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A value edit should construct exactly the diff's op");
}
#[tokio::test]
async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let wire = NodeInput::node(b, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(a, 1), wire.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: a,
input_index: 1,
input: wire,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A wiring edit should construct exactly the diff's op");
let working = convert(&editor);
let export = NodeInput::node(a, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::Export(0), export.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: 0,
input: Some(export),
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "An export edit should construct exactly the diff's op");
}
#[tokio::test]
async fn adding_a_node_as_structure_plus_metadata_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
let (document_node, metadata) = template.clone().into_parts();
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
let deltas = [
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: Vec::new(),
node_id,
node: Box::new(document_node),
}),
EditorDelta::NodeMetadataSnapshot {
network_path: Vec::new(),
node_id,
metadata: Box::new(metadata),
},
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "node addition");
}
#[tokio::test]
async fn per_field_metadata_edits_match_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_visibility(&node, &[], false);
network_interface.set_locked(&node, &[], true);
network_interface.set_pinned(&node, &[], true);
network_interface.shift_node(&node, glam::IVec2::new(3, 5), &[]);
}
let metadata = node_metadata(&editor, node);
let deltas = [
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: Vec::new(),
node_id: node,
visible: false,
}),
// Pinning a node also appends it to the network's display order, which is network state.
EditorDelta::NetworkMetadata {
network_path: Vec::new(),
change: NetworkMetadataChange::PinnedOrder(vec![node]),
},
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "per-field metadata edits");
}
/// The encoding spells "unset" as an absent attribute, so a field set back to its unset value has to
/// clear the key rather than write a sentinel. The wholesale copy got this by omitting the key; a
/// per-field delta has to say it, and saying it wrong leaves the old value stored.
#[tokio::test]
async fn clearing_a_metadata_field_removes_the_attribute() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_locked(&node, &[], true);
}
let working = convert(&editor);
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, String::new(), &[]);
network_interface.set_locked(&node, &[], false);
}
let metadata = node_metadata(&editor, node);
let deltas = [
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "cleared metadata fields");
}
/// The gate emission exists for: what the store says it wrote has to be what a whole-document
/// conversion of the result would show. Hand-written deltas cannot catch a setter that forgets to
/// emit, or emits the wrong field; taking them from the interface after a real edit can.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_locked(&node, &[], true);
network_interface.set_pinned(&node, &[], true);
network_interface.set_visibility(&node, &[], false);
network_interface.shift_node(&node, glam::IVec2::new(3, 5), &[]);
}
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "the edits should have emitted deltas");
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted deltas");
}
/// A write that changes nothing is not a write, so it must not emit. Otherwise a redundant setter call
/// would stamp a fresh timestamp and win against a concurrent peer that did change the field.
#[tokio::test]
async fn unchanged_writes_emit_nothing() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
editor.active_document_mut().network_interface.set_display_name(&node, "Named".to_string(), &[]);
editor.active_document_mut().network_interface.discard_deltas();
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Named".to_string(), &[]);
network_interface.set_locked(&node, &[], false);
network_interface.shift_node(&node, glam::IVec2::ZERO, &[]);
}
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
}
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
/// without the caller saying anything about it.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff_for_structural_edits() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted node insertion");
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.delete_nodes(vec![node_id], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted node deletion");
}
/// Adding an import shifts every later input slot, which no index-addressed op can express. The store
/// restates the whole list instead, so this checks that restatement lands the same as the diff.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "adding an import should have emitted deltas");
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "emitted import addition");
}
/// An arity change rebuilds the node's whole record, so anything written to that node earlier in the
/// same batch has to survive it. Renaming first and adding the import second is the order that catches
/// a rebuild sourced from the pre-batch registry rather than from what the batch has done so far.
#[tokio::test]
async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "rename then arity change");
}
/// The gate replay exists for: what the store recorded has to be enough to reproduce the write that
/// produced it. Clone the interface before an edit, apply what the edit recorded onto the clone, and
/// the two should agree. Something the store failed to record, or recorded wrongly, surfaces here
/// rather than as drift on another peer.
async fn assert_replay_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
editor.active_document_mut().network_interface.discard_deltas();
let before = editor.active_document().network_interface.clone();
edit(&mut editor);
let recorded = editor.active_document_mut().network_interface.take_deltas();
assert!(!recorded.is_empty(), "the edit should have recorded something to replay");
let mut replayed = before;
for delta in &recorded {
replayed.apply(delta);
}
assert_eq!(
replayed,
editor.active_document().network_interface,
"replaying {} recorded deltas did not reproduce the edited interface",
recorded.len()
);
}
fn only_group(editor: &EditorTestUtils) -> NodeId {
editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node")
}
#[tokio::test]
async fn replaying_metadata_edits_reproduces_the_interface() {
assert_replay_reproduces(|editor| {
let group = only_group(editor);
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
network_interface.set_locked(&group, &[], true);
network_interface.set_pinned(&group, &[], true);
network_interface.set_visibility(&group, &[], false);
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
})
.await;
}
#[tokio::test]
async fn replaying_an_arity_change_reproduces_the_interface() {
assert_replay_reproduces(|editor| {
let group = only_group(editor);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn replaying_a_node_insertion_reproduces_the_interface() {
assert_replay_reproduces(|editor| {
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]);
})
.await;
}
/// A node added and removed inside one batch is never in the registry the batch started from, so the
/// removal has nothing to look up there. The pair has to cancel out rather than leaving the addition
/// staged on its own.
#[tokio::test]
async fn a_node_added_and_removed_in_one_batch_leaves_nothing_behind() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
editor.active_document_mut().network_interface.delete_nodes(vec![node_id], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "add then remove in one batch");
}
#[tokio::test]
async fn removing_a_nested_network_node_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let before: Vec<NodeId> = editor.active_document().network_interface.document_network().nodes.keys().copied().collect();
let working = convert(&editor);
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let network = editor.active_document().network_interface.document_network().clone();
let mut deltas: Vec<EditorDelta> = before
.iter()
.filter(|id| !network.nodes.contains_key(id))
.map(|id| {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: Vec::new(),
node_id: *id,
})
})
.collect();
for (index, export) in network.exports.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: index,
input: Some(export.clone()),
}));
}
for (node_id, node) in &network.nodes {
for (index, input) in node.inputs.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: *node_id,
input_index: index,
input: input.clone(),
}));
}
}
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
}
@@ -0,0 +1,181 @@
//! The shapes the node graph frontend is sent: one entry per visible port, carrying its type, its
//! name and what it connects to. Read-only projections of the graph, never a source of truth.
use super::*;
impl NodeNetworkInterface {
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
return Vec::new();
};
let mut frontend_imports = (0..node.inputs.len())
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected_to = self
.upstream_output_connector(input_connector, network_path)
.map(|output_connector| match output_connector {
OutputConnector::Node { node_id, output_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to output #{output_index} of \"{name}\", ID: {node_id}.")
}
OutputConnector::Import(import_index) => format!("Connected to import #{import_index}."),
})
.unwrap_or("Connected to nothing.".to_string());
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => {
// Get export name from parent node metadata input, which must match the number of exports.
// Empty string means to use type, or "Export + index" if type is empty determined
let export_name = if network_path.is_empty() {
"Canvas".to_string()
} else {
self.encapsulating_node_metadata(network_path)
.and_then(|encapsulating_metadata| encapsulating_metadata.persistent_metadata.output_names.get(*export_index).cloned())
.unwrap_or_default()
};
let export_name = if !export_name.is_empty() {
export_name
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(ToString::to_string) {
export_type_name
} else {
format!("Export #{}", export_index)
};
(export_name, String::new())
}
};
let valid_types = self.potential_valid_input_types(input_connector, network_path).iter().map(ToString::to_string).collect::<Vec<_>>();
let valid_types = {
// Dedupe while preserving order
let mut found = HashSet::new();
valid_types.into_iter().filter(|s| found.insert(s.clone())).collect::<Vec<_>>()
};
Some(FrontendGraphInput {
data_type,
resolved_type,
name,
description,
valid_types,
connected_to,
})
}
/// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector {
OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
return None;
};
// Get the output name from the interior network export name
let node_metadata = self.node_metadata(node_id, network_path)?;
let output_name = node_metadata.persistent_metadata.output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
(output_name, String::new())
}
OutputConnector::Import(import_index) => {
// Get the import name from the encapsulating node input metadata
let Some((encapsulating_node_id, encapsulating_path)) = network_path.split_last() else {
// Return None if it is an import in the document network
return None;
};
// Return None if the primary input is hidden and this is the primary import
if *import_index == 0 && self.hidden_primary_import(network_path) {
return None;
};
let (import_name, description) = self.displayed_input_name_and_description(encapsulating_node_id, *import_index, encapsulating_path);
let import_name = if !import_name.is_empty() {
import_name
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(ToString::to_string) {
import_type_name
} else {
format!("Import #{}", import_index)
};
(import_name, description)
}
};
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let mut connected_to = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).cloned())
.flatten()
.unwrap_or_default()
.iter()
.map(|input| match input {
&InputConnector::Node { node_id, input_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to input #{input_index} of \"{name}\", ID: {node_id}.")
}
InputConnector::Export(export_index) => format!("Connected to export #{export_index}."),
})
.collect::<Vec<_>>();
if connected_to.is_empty() {
connected_to.push("Connected to nothing.".to_string());
}
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
connected_to,
})
}
/// Returns the input name to display in the properties panel. If the name is empty then the type is used.
pub fn displayed_input_name_and_description(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> (String, String) {
let Some(input_metadata) = self.persistent_input_metadata(node_id, input_index, network_path) else {
log::warn!("input metadata not found in displayed_input_name_and_description");
return (String::new(), String::new());
};
let description = input_metadata.input_description.to_string();
let name = if input_metadata.input_name.is_empty() {
self.input_type(&InputConnector::node_at_index(*node_id, input_index), network_path).resolved_type_node_string()
} else {
input_metadata.input_name.to_string()
};
(name, description)
}
}
@@ -0,0 +1,352 @@
//! Geometry of the node graph: where a node's body, ports and handles sit in node graph space.
//!
//! Derived from the grid model in `layout`, never the other way round. These are pure computations;
//! the caller decides whether to cache the result.
use super::*;
impl NodeNetworkInterface {
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
return None;
};
let node_metadata = self.node_metadata(node_id, network_path)?;
let Some(document_node) = self.document_node(node_id, network_path) else {
log::error!("Could not get document node in compute_node_click_targets");
return None;
};
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut port_click_targets = Ports::new();
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
// Create input/output click targets
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
port_click_targets.insert_node_input(input_index, input_row_count, node_top_left);
}
// Primary input row is always displayed, even if the input is not exposed
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let number_of_outputs = match &document_node.implementation {
DocumentNodeImplementation::Network(network) => network.exports.len(),
_ => 1,
};
// If the node has a hidden primary output, do not display the first output
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..number_of_outputs {
port_click_targets.insert_node_output(output_index, node_top_left);
}
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
// Layer inputs
port_click_targets.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
port_click_targets.insert_layer_input(1, node_top_left);
}
port_click_targets.insert_layer_output(node_top_left);
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in load_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// Update grip button click target, which is positioned to the left of the leftmost icon.
// The grip is 8px wide but spans the full layer-vertical-center band.
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// Create layer click target, which is contains the layer and the chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
Some(document_node_click_targets)
}
/// The add, remove and reorder handles that sit beside each import and export port.
pub(super) fn compute_modify_import_export(&self, network_path: &[NodeId]) -> Option<ModifyImportExportClickTarget> {
let mut reorder_imports_exports = Ports::new();
let mut remove_imports_exports = Ports::new();
if !network_path.is_empty() {
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
for (import_index, import_click_target) in import_exports.output_ports() {
let Some(import_bounding_box) = import_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
continue;
};
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
if *import_index == 0 {
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
} else {
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
let reorder_import = ClickTarget::new_with_path(rectangle_path(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
}
}
for (export_index, export_click_target) in import_exports.input_ports() {
let Some(export_bounding_box) = export_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
continue;
};
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
if *export_index == 0 {
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
} else {
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
let reorder_export = ClickTarget::new_with_path(rectangle_path(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
}
}
});
if ports_built.is_none() {
log::error!("Could not get import_export_ports in compute_modify_import_export");
return None;
}
}
Some(ModifyImportExportClickTarget {
remove_imports_exports,
reorder_imports_exports,
})
}
/// A port for each import and export of the network, placed down the left and right edges.
pub(super) fn compute_import_export_ports(&self, network_path: &[NodeId]) -> Option<Ports> {
let Some(import_export_position) = self.import_export_position(network_path) else {
log::error!("Could not get import_export_position");
return None;
};
let network = self.nested_network(network_path)?;
let mut import_export_ports = Ports::new();
if !network_path.is_empty() {
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
for import_index in import_start_index..self.number_of_imports(network_path) {
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_index as f64 * 24.));
}
}
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
for export_index in export_start_index..network.exports.len() {
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., export_index as f64 * 24.));
}
Some(import_export_ports)
}
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
/// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
let thumbnail_width = 3. * GRID_SIZE as f64;
let layer_text = self.display_name(node_id, network_path);
let text_width = text_width(&layer_text, FONT_SIZE);
let grip_padding = 4.;
let grip_width = 8.;
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
((layer_width_pixels / 24.).ceil() as u32).max(8)
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
log::error!("Could not get all nodes bounding box in load_export_ports");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in load_export_ports");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_export_ports");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
let target_viewport_top_left = DVec2::new(IMPORTS_TO_LEFT_EDGE_PIXEL_GAP as f64, IMPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
let node_graph_pixel_offset_top_left = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_left);
// A 5x5 grid offset from the top left corner
let node_graph_grid_space_offset_top_left = node_graph_to_viewport.inverse().transform_point2(DVec2::ZERO) + DVec2::new(5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the import is the highest/furthest left of the two offsets
let top_left_inner_bound = DVec2::new(
node_graph_pixel_offset_top_left.x.min(node_graph_grid_space_offset_top_left.x),
node_graph_pixel_offset_top_left.y.min(node_graph_grid_space_offset_top_left.y),
);
let offset_from_top_left = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(-4. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(-4. * GRID_SIZE as f64, 0.)
};
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
let import_top_left = DVec2::new(top_left_inner_bound.x.min(bounding_box_top_left.x), top_left_inner_bound.y.min(bounding_box_top_left.y));
let rounded_import_top_left = DVec2::new((import_top_left.x / 24.).round() * 24., (import_top_left.y / 24.).round() * 24.);
let viewport_width = network_metadata.persistent_metadata.navigation_metadata.node_graph_width;
let target_viewport_top_right = DVec2::new(viewport_width - EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP as f64, EXPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
// An offset from the right edge in viewport pixels
let node_graph_pixel_offset_top_right = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_right);
// A 5x5 grid offset from the right corner
let node_graph_grid_space_offset_top_right = node_graph_to_viewport.inverse().transform_point2(DVec2::new(viewport_width, 0.)) + DVec2::new(-5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the export is the highest/furthest right of the two offsets.
// When zoomed out this keeps it a constant grid space away from the edge, but when zoomed in it prevents the exports from getting too far in
let top_right_inner_bound = DVec2::new(
node_graph_pixel_offset_top_right.x.max(node_graph_grid_space_offset_top_right.x),
node_graph_pixel_offset_top_right.y.min(node_graph_grid_space_offset_top_right.y),
);
let offset_from_top_right = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(2. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(4. * GRID_SIZE as f64, 0.)
};
let mut bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.);
bounding_box_top_right += offset_from_top_right;
let export_top_right = DVec2::new(top_right_inner_bound.x.max(bounding_box_top_right.x), top_right_inner_bound.y.min(bounding_box_top_right.y));
let rounded_export_top_right = DVec2::new((export_top_right.x / 24.).round() * 24., (export_top_right.y / 24.).round() * 24.);
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
}
}
@@ -121,11 +121,11 @@ impl NodeNetworkInterface {
} }
pub fn node_graph_ptz_mut(&mut self, network_path: &[NodeId]) -> Option<&mut PTZ> { pub fn node_graph_ptz_mut(&mut self, network_path: &[NodeId]) -> Option<&mut PTZ> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else { let Some(navigation) = self.navigation_mut(network_path) else {
log::error!("Could not get nested network_metadata in node_graph_ptz_mut"); log::error!("Could not get nested network_metadata in node_graph_ptz_mut");
return None; return None;
}; };
Some(&mut network_metadata.persistent_metadata.navigation_metadata.node_graph_ptz) Some(&mut navigation.node_graph_ptz)
} }
// TODO: Optimize getting click target intersections from click by using a spacial data structure like a quadtree instead of linear search // TODO: Optimize getting click target intersections from click by using a spacial data structure like a quadtree instead of linear search
@@ -0,0 +1,40 @@
//! What a change feeds: each rule names a kind of edit and unloads everything derived from it.
//!
//! Declared here once rather than restated at each mutation site, so two edits of the same kind cannot
//! disagree about what they invalidate.
use super::*;
impl NodeNetworkInterface {
/// Unloads everything a node's position feeds: its own geometry, the geometry of every node placed
/// relative to it, and the network bounds. A chain node also sets the width of the layer encapsulating
/// its chain, so that layer reloads too.
///
/// Takes the changed nodes as a batch, so a run of moves walks the upstream cone once.
pub(crate) fn invalidate_positions(&mut self, node_ids: Vec<NodeId>, network_path: &[NodeId]) {
let encapsulating_layers = node_ids
.iter()
.filter(|node_id| self.is_chain(node_id, network_path))
.filter_map(|node_id| self.downstream_layer_for_chain_node(node_id, network_path))
.collect::<Vec<_>>();
for downstream_layer in encapsulating_layers {
self.unload_node_click_targets(&downstream_layer, network_path);
}
self.unload_upstream_node_click_targets(node_ids, network_path);
self.unload_all_nodes_bounding_box(network_path);
}
/// Unloads the network's import and export strip: the ports themselves and the handles beside them
/// for adding, removing and reordering.
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
self.unload_import_export_ports(network_path);
self.unload_modify_import_export(network_path);
}
/// Unloads what a node's name or lock state feeds: a layer's width, and the geometry sized from it.
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path);
self.unload_node_click_targets(node_id, network_path);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -22,10 +22,24 @@ impl NodeNetworkInterface {
pub fn document_network(&self) -> &NodeNetwork { pub fn document_network(&self) -> &NodeNetwork {
self.network.network() self.network.network()
} }
pub fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.network_mut()
}
/// The document network as it should be evaluated, which is the document itself with the previewed
/// node substituted for the export.
///
/// Previewing is this peer's alone, so it is applied to the copy being compiled rather than written
/// into the document. Every path that compiles the graph goes through here, so none of them can
/// render the export while the user is previewing something else.
pub fn network_to_evaluate(&self) -> NodeNetwork {
let mut network = self.document_network().clone();
if let Previewing::Yes { previewed } = self.previewing(&[])
&& let Some(export) = network.exports.first_mut()
{
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
network
}
/// Gets the nested network based on network_path /// Gets the nested network based on network_path
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> { pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
let Some(network) = self.document_network().nested_network(network_path) else { let Some(network) = self.document_network().nested_network(network_path) else {
@@ -172,6 +186,11 @@ impl NodeNetworkInterface {
self.query(network_path, "has_primary_input", |view| view.has_primary_input(node_id)).unwrap_or_default() self.query(network_path, "has_primary_input", |view| view.has_primary_input(node_id)).unwrap_or_default()
} }
/// Grid rows the node body spans, which is the greater of its input rows and its output count.
pub fn displayed_row_count(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
self.query(network_path, "displayed_row_count", |view| view.displayed_row_count(node_id)).unwrap_or(1)
}
pub fn number_of_outputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize { pub fn number_of_outputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
self.query(network_path, "number_of_outputs", |view| view.number_of_outputs(node_id)).unwrap_or_default() self.query(network_path, "number_of_outputs", |view| view.number_of_outputs(node_id)).unwrap_or_default()
} }
@@ -293,23 +312,6 @@ impl NodeNetworkInterface {
} }
} }
pub fn position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
self.try_load_node_click_targets(node_id, network_path);
let top_left_position = self.try_get_node_bounding_box(node_id, network_path).map(|mut bounding_box| {
if !self.is_layer(node_id, network_path) {
bounding_box[0] -= DVec2::new(0., 12.);
}
(bounding_box[0] / 24.).as_ivec2()
});
top_left_position.map(|position| {
if self.is_layer(node_id, network_path) {
position + IVec2::new(self.chain_width(node_id, network_path) as i32, 0)
} else {
position
}
})
}
pub fn collect_used_resources(&self, target: &mut HashSet<ResourceId>) { pub fn collect_used_resources(&self, target: &mut HashSet<ResourceId>) {
visit_network_resources(self.document_network(), &mut |id| { visit_network_resources(self.document_network(), &mut |id| {
target.insert(id); target.insert(id);
@@ -322,254 +324,6 @@ impl NodeNetworkInterface {
counts counts
} }
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
match network_path.split_last() {
Some((node_id, encapsulating_network_path)) => {
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
return Vec::new();
};
let mut frontend_imports = (0..node.inputs.len())
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
log::error!("Could not get all nodes bounding box in load_export_ports");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in load_export_ports");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_export_ports");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
let target_viewport_top_left = DVec2::new(IMPORTS_TO_LEFT_EDGE_PIXEL_GAP as f64, IMPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
let node_graph_pixel_offset_top_left = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_left);
// A 5x5 grid offset from the top left corner
let node_graph_grid_space_offset_top_left = node_graph_to_viewport.inverse().transform_point2(DVec2::ZERO) + DVec2::new(5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the import is the highest/furthest left of the two offsets
let top_left_inner_bound = DVec2::new(
node_graph_pixel_offset_top_left.x.min(node_graph_grid_space_offset_top_left.x),
node_graph_pixel_offset_top_left.y.min(node_graph_grid_space_offset_top_left.y),
);
let offset_from_top_left = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(-4. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(-4. * GRID_SIZE as f64, 0.)
};
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
let import_top_left = DVec2::new(top_left_inner_bound.x.min(bounding_box_top_left.x), top_left_inner_bound.y.min(bounding_box_top_left.y));
let rounded_import_top_left = DVec2::new((import_top_left.x / 24.).round() * 24., (import_top_left.y / 24.).round() * 24.);
let viewport_width = network_metadata.persistent_metadata.navigation_metadata.node_graph_width;
let target_viewport_top_right = DVec2::new(viewport_width - EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP as f64, EXPORTS_TO_TOP_EDGE_PIXEL_GAP as f64);
// An offset from the right edge in viewport pixels
let node_graph_pixel_offset_top_right = node_graph_to_viewport.inverse().transform_point2(target_viewport_top_right);
// A 5x5 grid offset from the right corner
let node_graph_grid_space_offset_top_right = node_graph_to_viewport.inverse().transform_point2(DVec2::new(viewport_width, 0.)) + DVec2::new(-5. * GRID_SIZE as f64, 4. * GRID_SIZE as f64);
// The inner bound of the export is the highest/furthest right of the two offsets.
// When zoomed out this keeps it a constant grid space away from the edge, but when zoomed in it prevents the exports from getting too far in
let top_right_inner_bound = DVec2::new(
node_graph_pixel_offset_top_right.x.max(node_graph_grid_space_offset_top_right.x),
node_graph_pixel_offset_top_right.y.min(node_graph_grid_space_offset_top_right.y),
);
let offset_from_top_right = if network
.exports
.first()
.is_some_and(|export| export.as_node().is_some_and(|export_node| self.is_layer(&export_node, network_path)))
{
DVec2::new(2. * GRID_SIZE as f64, -2. * GRID_SIZE as f64)
} else {
DVec2::new(4. * GRID_SIZE as f64, 0.)
};
let mut bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.);
bounding_box_top_right += offset_from_top_right;
let export_top_right = DVec2::new(top_right_inner_bound.x.max(bounding_box_top_right.x), top_right_inner_bound.y.min(bounding_box_top_right.y));
let rounded_export_top_right = DVec2::new((export_top_right.x / 24.).round() * 24., (export_top_right.y / 24.).round() * 24.);
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected_to = self
.upstream_output_connector(input_connector, network_path)
.map(|output_connector| match output_connector {
OutputConnector::Node { node_id, output_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to output #{output_index} of \"{name}\", ID: {node_id}.")
}
OutputConnector::Import(import_index) => format!("Connected to import #{import_index}."),
})
.unwrap_or("Connected to nothing.".to_string());
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => {
// Get export name from parent node metadata input, which must match the number of exports.
// Empty string means to use type, or "Export + index" if type is empty determined
let export_name = if network_path.is_empty() {
"Canvas".to_string()
} else {
self.encapsulating_node_metadata(network_path)
.and_then(|encapsulating_metadata| encapsulating_metadata.persistent_metadata.output_names.get(*export_index).cloned())
.unwrap_or_default()
};
let export_name = if !export_name.is_empty() {
export_name
} else if let Some(export_type_name) = input_type.compiled_nested_type().map(ToString::to_string) {
export_type_name
} else {
format!("Export #{}", export_index)
};
(export_name, String::new())
}
};
let valid_types = self.potential_valid_input_types(input_connector, network_path).iter().map(ToString::to_string).collect::<Vec<_>>();
let valid_types = {
// Dedupe while preserving order
let mut found = HashSet::new();
valid_types.into_iter().filter(|s| found.insert(s.clone())).collect::<Vec<_>>()
};
Some(FrontendGraphInput {
data_type,
resolved_type,
name,
description,
valid_types,
connected_to,
})
}
/// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector {
OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
return None;
};
// Get the output name from the interior network export name
let node_metadata = self.node_metadata(node_id, network_path)?;
let output_name = node_metadata.persistent_metadata.output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
(output_name, String::new())
}
OutputConnector::Import(import_index) => {
// Get the import name from the encapsulating node input metadata
let Some((encapsulating_node_id, encapsulating_path)) = network_path.split_last() else {
// Return None if it is an import in the document network
return None;
};
// Return None if the primary input is hidden and this is the primary import
if *import_index == 0 && self.hidden_primary_import(network_path) {
return None;
};
let (import_name, description) = self.displayed_input_name_and_description(encapsulating_node_id, *import_index, encapsulating_path);
let import_name = if !import_name.is_empty() {
import_name
} else if let Some(import_type_name) = output_type.compiled_nested_type().map(ToString::to_string) {
import_type_name
} else {
format!("Import #{}", import_index)
};
(import_name, description)
}
};
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let mut connected_to = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).cloned())
.flatten()
.unwrap_or_default()
.iter()
.map(|input| match input {
&InputConnector::Node { node_id, input_index } => {
let name = self.display_name(&node_id, network_path);
format!("Connected to input #{input_index} of \"{name}\", ID: {node_id}.")
}
InputConnector::Export(export_index) => format!("Connected to export #{export_index}."),
})
.collect::<Vec<_>>();
if connected_to.is_empty() {
connected_to.push("Connected to nothing.".to_string());
}
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
connected_to,
})
}
pub fn height_from_click_target(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.try_load_node_click_targets(node_id, network_path);
let mut node_height: Option<u32> = self
.try_get_node_bounding_box(node_id, network_path)
.map(|bounding_box| ((bounding_box[1].y - bounding_box[0].y) / 24.) as u32);
if !self.is_layer(node_id, network_path) {
node_height = node_height.map(|height| height + 1);
}
node_height
}
/// Returns whether every downstream path from the node's outputs stays within the dependent set defined by `classify`, meaning nothing else in the graph depends on this node. /// Returns whether every downstream path from the node's outputs stays within the dependent set defined by `classify`, meaning nothing else in the graph depends on this node.
/// Reaching an export or a dead end (a walked node with no outward wires) always escapes. O(nodes + wires) per call. /// Reaching an export or a dead end (a walked node with no outward wires) always escapes. O(nodes + wires) per call.
pub(crate) fn is_sole_dependent(&self, node_id: NodeId, network_path: &[NodeId], classify: impl Fn(NodeId, usize) -> SoleDependentStep) -> bool { pub(crate) fn is_sole_dependent(&self, node_id: NodeId, network_path: &[NodeId], classify: impl Fn(NodeId, usize) -> SoleDependentStep) -> bool {
@@ -795,29 +549,11 @@ impl NodeNetworkInterface {
} }
pub fn set_input_override(&mut self, node_id: &NodeId, index: usize, widget_override: Option<String>, network_path: &[NodeId]) { pub fn set_input_override(&mut self, node_id: &NodeId, index: usize, widget_override: Option<String>, network_path: &[NodeId]) {
let Some(metadata) = self let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
.node_metadata_mut(node_id, network_path) log::error!("Could not get node {node_id} in set_input_override");
.and_then(|node_metadata| node_metadata.persistent_metadata.input_metadata.get_mut(index))
else {
log::error!("Could not get input metadata for {node_id} index {index} in set_input_override");
return; return;
}; };
metadata.persistent_metadata.widget_override = widget_override; node.set_widget_override(index, widget_override);
}
/// Returns the input name to display in the properties panel. If the name is empty then the type is used.
pub fn displayed_input_name_and_description(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> (String, String) {
let Some(input_metadata) = self.persistent_input_metadata(node_id, input_index, network_path) else {
log::warn!("input metadata not found in displayed_input_name_and_description");
return (String::new(), String::new());
};
let description = input_metadata.input_description.to_string();
let name = if input_metadata.input_name.is_empty() {
self.input_type(&InputConnector::node_at_index(*node_id, input_index), network_path).resolved_type_node_string()
} else {
input_metadata.input_name.to_string()
};
(name, description)
} }
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type. /// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
@@ -1184,40 +920,14 @@ impl NodeNetworkInterface {
nested_network_metadata.persistent_metadata.node_metadata.insert(node_id, node_metadata); nested_network_metadata.persistent_metadata.node_metadata.insert(node_id, node_metadata);
} }
} }
Self { Self::from_trees(node_network, network_metadata)
network: MemoNetwork::new(node_network),
network_metadata,
document_metadata: DocumentMetadata::default(),
resolved_types: ResolvedDocumentNodeTypes::default(),
transaction_status: TransactionStatus::Finished,
}
} }
} }
// Private mutable getters for use within the network interface // Private mutable getters for use within the network interface
impl NodeNetworkInterface { impl NodeNetworkInterface {
pub(crate) fn network_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
self.document_network_mut().nested_network_mut(network_path)
}
pub(crate) fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
self.network_metadata.nested_metadata_mut(network_path)
}
pub(crate) fn node_metadata_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata");
return None;
};
let Some(node_metadata) = network_metadata.persistent_metadata.node_metadata.get_mut(node_id) else {
log::error!("Could not get nested node_metadata for node {node_id} in network {network_path:?}");
return None;
};
Some(node_metadata)
}
/// Mutably get the network which the encapsulating node of the currently viewed network is part of. Will always be None in the document network. /// Mutably get the network which the encapsulating node of the currently viewed network is part of. Will always be None in the document network.
pub(crate) fn encapsulating_network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> { pub(super) fn encapsulating_network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
let mut encapsulating_path = network_path.to_vec(); let mut encapsulating_path = network_path.to_vec();
encapsulating_path.pop()?; encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else { let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
@@ -1228,7 +938,7 @@ impl NodeNetworkInterface {
} }
/// Get the node metadata for the node which encapsulates the currently viewed network. Will always be None in the document network. /// Get the node metadata for the node which encapsulates the currently viewed network. Will always be None in the document network.
pub(crate) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> { pub(super) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let mut encapsulating_path = network_path.to_vec(); let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?; let encapsulating_node_id = encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else { let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
@@ -13,10 +13,9 @@ use glam::IVec2;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use graphene_std::vector::style::RenderMode; use graphene_std::vector::style::RenderMode;
use super::memo_network::MemoNetwork;
use super::{ use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata, DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ,
}; };
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings; use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
use crate::messages::portfolio::document::utility_types::misc::SnappingState; use crate::messages::portfolio::document::utility_types::misc::SnappingState;
@@ -65,16 +64,7 @@ impl StorageMetadataView<'_> {
impl NodeMetadataSource for StorageMetadataView<'_> { impl NodeMetadataSource for StorageMetadataView<'_> {
fn position(&self, network_path: &[NodeId], local_id: NodeId) -> Option<Position> { fn position(&self, network_path: &[NodeId], local_id: NodeId) -> Option<Position> {
match &self.persistent(network_path, local_id)?.node_type_metadata { Some(position_from_runtime(&self.persistent(network_path, local_id)?.node_type_metadata))
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
LayerPosition::Stack(offset) => Some(Position::Stack(offset)),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
NodePosition::Chain => Some(Position::Chain),
},
}
} }
fn is_layer(&self, network_path: &[NodeId], local_id: NodeId) -> bool { fn is_layer(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
@@ -114,10 +104,21 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
self.persistent(network_path, local_id).map(|p| p.output_names.clone()).unwrap_or_default() self.persistent(network_path, local_id).map(|p| p.output_names.clone()).unwrap_or_default()
} }
fn storage_node_id(&self, network_path: &[NodeId], local_id: NodeId) -> Option<document_graph_storage::NodeId> {
self.persistent(network_path, local_id)?.storage_id.map(document_graph_storage::NodeId)
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> { fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?; let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?;
network_metadata.persistent_metadata.reference.as_deref() network_metadata.persistent_metadata.reference.as_deref()
} }
fn pinned_order(&self, network_path: &[NodeId]) -> Vec<NodeId> {
self.interface
.network_metadata
.nested_metadata(network_path)
.map(|network_metadata| network_metadata.persistent_metadata.pinned_node_order.clone())
.unwrap_or_default()
}
} }
impl DocumentSettings<'_> { impl DocumentSettings<'_> {
@@ -148,6 +149,20 @@ impl DocumentSettings<'_> {
/// Inverse of the position extraction in `NodeMetadataSource::position`. /// Inverse of the position extraction in `NodeMetadataSource::position`.
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant. /// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
/// The stored position of a node, which pairs with `is_layer` to reconstruct the runtime node type.
pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position {
match node_type {
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Position::Absolute([v.x, v.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Position::Absolute([v.x, v.y]),
NodePosition::Chain => Position::Chain,
},
}
}
pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata { pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata {
match (position, is_layer) { match (position, is_layer) {
(Position::Absolute([x, y]), true) => NodeTypePersistentMetadata::layer(IVec2::new(x, y)), (Position::Absolute([x, y]), true) => NodeTypePersistentMetadata::layer(IVec2::new(x, y)),
@@ -173,12 +188,7 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
apply_entries_into_tree(&network, &mut network_metadata, node_entries)?; apply_entries_into_tree(&network, &mut network_metadata, node_entries)?;
apply_network_entries_into_tree(&mut network_metadata, network_entries); apply_network_entries_into_tree(&mut network_metadata, network_entries);
let interface = NodeNetworkInterface { Ok(NodeNetworkInterface::from_trees(network, network_metadata))
network: MemoNetwork::new(network),
network_metadata,
..Default::default()
};
Ok(interface)
} }
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that /// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
@@ -223,13 +233,6 @@ pub fn collect_network_view_settings(
settings.insert(session::network::NAV_WIDTH.to_string(), value); settings.insert(session::network::NAV_WIDTH.to_string(), value);
} }
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
&& let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing)
{
settings.insert(session::network::PREVIEWING.to_string(), value);
}
if !settings.is_empty() { if !settings.is_empty() {
out.insert(network_id, settings); out.insert(network_id, settings);
} }
@@ -249,30 +252,24 @@ pub fn apply_network_view_settings(
) { ) {
for (network_path, network_id) in network_ids { for (network_path, network_id) in network_ids {
let Some(settings) = network_view_settings.get(network_id) else { continue }; let Some(settings) = network_view_settings.get(network_id) else { continue };
let Some(network_metadata) = interface.network_metadata.nested_metadata_mut(network_path) else { let Some(navigation) = interface.navigation_mut(network_path) else {
continue; continue;
}; };
let persistent = &mut network_metadata.persistent_metadata;
if let Some(value) = settings.get(session::network::NAV_PTZ) if let Some(value) = settings.get(session::network::NAV_PTZ)
&& let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone()) && let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone())
{ {
persistent.navigation_metadata.node_graph_ptz = ptz; navigation.node_graph_ptz = ptz;
} }
if let Some(value) = settings.get(session::network::NAV_TRANSFORM) if let Some(value) = settings.get(session::network::NAV_TRANSFORM)
&& let Ok(transform) = serde_json::from_value(value.clone()) && let Ok(transform) = serde_json::from_value(value.clone())
{ {
persistent.navigation_metadata.node_graph_to_viewport = transform; navigation.node_graph_to_viewport = transform;
} }
if let Some(value) = settings.get(session::network::NAV_WIDTH) if let Some(value) = settings.get(session::network::NAV_WIDTH)
&& let Ok(width) = serde_json::from_value(value.clone()) && let Ok(width) = serde_json::from_value(value.clone())
{ {
persistent.navigation_metadata.node_graph_width = width; navigation.node_graph_width = width;
}
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
{
persistent.previewing = previewing;
} }
} }
} }
@@ -288,6 +285,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
if let Some(reference) = entry.reference { if let Some(reference) = entry.reference {
network_metadata.persistent_metadata.reference = Some(reference); network_metadata.persistent_metadata.reference = Some(reference);
} }
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
} }
} }
@@ -329,6 +327,10 @@ fn apply_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMeta
let persistent = &mut document_node_metadata.persistent_metadata; let persistent = &mut document_node_metadata.persistent_metadata;
// Pins the node to the identity storage holds for it, so the next conversion reuses it rather
// than re-deriving one from the node's location.
persistent.storage_id = Some(entry.storage_id.0);
if let Some(position) = entry.position { if let Some(position) = entry.position {
persistent.node_type_metadata = position_to_runtime(position, entry.is_layer); persistent.node_type_metadata = position_to_runtime(position, entry.is_layer);
} else if entry.is_layer { } else if entry.is_layer {
@@ -0,0 +1,936 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
/// Holds one of the two parallel trees so that only this module can write it.
///
/// `Deref` passes reads straight through, so a query reads the tree as though the interface held it
/// directly. There is deliberately no `DerefMut` and the field is private to this module, so the only
/// route to a `&mut` is the store API below, and a write that skips it does not compile rather than
/// silently going unrecorded.
///
/// Transparent to serde, so wrapping a field does not change the document format.
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Guarded<T>(T);
impl<T> std::ops::Deref for Guarded<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> Guarded<T> {
/// Both of these are private to the store, which is what makes the wrapper worth having: a sibling
/// module can neither write a tree in place nor swap a different one into its place.
fn new(value: T) -> Self {
Self(value)
}
fn get_mut(&mut self) -> &mut T {
&mut self.0
}
}
/// A network's selection undo and redo stacks, borrowed together since every operation on one is
/// paired with one on the other.
pub(crate) struct SelectionHistoryMut<'a> {
pub(crate) undo: &'a mut VecDeque<SelectedNodes>,
pub(crate) redo: &'a mut VecDeque<SelectedNodes>,
}
/// Addresses one node: the network it lives in, and its ID within that network.
///
/// The store is the only place node identity is used for addressing, so this is the one type that
/// changes when identity stops being derived from the node's location.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NodeLocator<'a> {
pub node_id: NodeId,
pub network_path: &'a [NodeId],
}
impl<'a> NodeLocator<'a> {
pub fn new(node_id: NodeId, network_path: &'a [NodeId]) -> Self {
Self { node_id, network_path }
}
/// The path of the network this node owns, if it implements one.
pub fn owned_network_path(&self) -> Vec<NodeId> {
[self.network_path, &[self.node_id]].concat()
}
}
/// The graph and metadata halves of one node, resolved together so the two parallel trees are never
/// reached separately and cannot drift apart.
///
/// Holds the halves directly rather than the interface, so a write cannot reach back out to query the
/// graph or unload a cache: what a write invalidates is declared, not performed here.
pub(crate) struct NodeMut<'a> {
node: &'a mut DocumentNode,
metadata: &'a mut DocumentNodePersistentMetadata,
deltas: NodeDeltas<'a>,
}
/// Where a node's writes record what they changed, carrying the node's address so each setter names
/// what it wrote without its caller repeating it.
struct NodeDeltas<'a> {
deltas: &'a mut Vec<EditorDelta>,
locator: NodeLocator<'a>,
}
impl NodeDeltas<'_> {
fn metadata(&mut self, change: NodeMetadataChange) {
self.deltas.push(EditorDelta::NodeMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
change,
});
}
/// The nested network a node owns is addressed by the node's own path extended with its ID, which
/// is the path a scoped conversion resolves that network's ID from.
fn owned_network(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.locator.owned_network_path(),
change,
});
}
fn graph(&mut self, delta: RuntimeDelta) {
self.deltas.push(EditorDelta::Graph(delta));
}
fn input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.deltas.push(EditorDelta::NodeInputMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
input_metadata,
});
}
fn snapshot(&mut self, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
metadata,
});
}
fn network_path(&self) -> Vec<NodeId> {
self.locator.network_path.to_vec()
}
fn node_id(&self) -> NodeId {
self.locator.node_id
}
}
impl NodeMut<'_> {
/// Places the node at an absolute grid position, keeping whether it is displayed as a layer or a node.
pub(crate) fn set_absolute_position(&mut self, position: IVec2) -> bool {
let node_type = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::layer(position),
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::node(position),
};
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
let shifted = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
}) => NodeTypePersistentMetadata::layer(position + shift),
NodeTypePersistentMetadata::Node(ref node) => match node.position {
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
NodePosition::Chain => return false,
},
NodeTypePersistentMetadata::Layer(_) => return false,
};
self.set_node_type(shifted)
}
/// Stacks a layer `y_offset` below the sibling it feeds. Nodes are never stacked.
pub(crate) fn set_stack_position(&mut self, y_offset: u32) -> bool {
if !self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(y_offset),
}))
}
/// Chains a node to the left of the layer it feeds. Layers are never chained.
pub(crate) fn set_chain_position(&mut self) -> bool {
if self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)))
}
/// Whether the node is displayed as a layer, which decides the kinds of position it can hold.
pub(crate) fn is_layer(&self) -> bool {
self.metadata.is_layer()
}
/// Whether the node is rendered, which the compiler reads to replace it with a passthrough.
pub(crate) fn set_visible(&mut self, visible: bool) -> bool {
let changed = self.node.visible != visible;
self.node.visible = visible;
if changed {
let delta = RuntimeDelta::SetVisibility {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
visible,
};
self.deltas.graph(delta);
}
changed
}
/// The type of argument the node can be evaluated with.
pub(crate) fn set_call_argument(&mut self, call_argument: Type) -> bool {
let changed = self.node.call_argument != call_argument;
self.node.call_argument = call_argument;
if changed {
let delta = RuntimeDelta::SetCallArgument {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
call_argument: self.node.call_argument.clone(),
};
self.deltas.graph(delta);
}
changed
}
/// The Extract and Inject annotations the node declares for the Context.
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
let changed = self.node.context_features != context_features;
self.node.context_features = context_features;
if changed {
let delta = RuntimeDelta::SetContextFeatures {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
context_features: self.node.context_features,
};
self.deltas.graph(delta);
}
changed
}
/// The user-chosen name for this instance, empty when it has none.
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
let changed = self.metadata.display_name != display_name;
self.metadata.display_name = display_name;
if changed {
let change = NodeMetadataChange::DisplayName(self.metadata.display_name.clone());
self.deltas.metadata(change);
}
changed
}
pub(crate) fn set_locked(&mut self, locked: bool) -> bool {
let changed = self.metadata.locked != locked;
self.metadata.locked = locked;
if changed {
self.deltas.metadata(NodeMetadataChange::Locked(locked));
}
changed
}
pub(crate) fn set_pinned(&mut self, pinned: bool) -> bool {
let changed = self.metadata.pinned != pinned;
self.metadata.pinned = pinned;
if changed {
self.deltas.metadata(NodeMetadataChange::Pinned(pinned));
}
changed
}
/// Whether the node is displayed as a layer or a node, together with its position, which are one
/// choice: a layer and a node do not have the same kinds of position.
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
let changed = self.metadata.node_type_metadata != node_type;
self.metadata.node_type_metadata = node_type;
if changed {
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
}
changed
}
/// The definition this node's nested network was instantiated from, dropped once the node is edited
/// away from it. Only network nodes carry one.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let Some(network_metadata) = self.metadata.network_metadata.as_mut() else { return false };
let changed = network_metadata.persistent_metadata.reference != reference;
network_metadata.persistent_metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(network_metadata.persistent_metadata.reference.clone());
self.deltas.owned_network(change);
}
changed
}
pub(crate) fn set_input_name(&mut self, input_index: usize, input_name: String) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
let changed = input_metadata.persistent_metadata.input_name != input_name;
input_metadata.persistent_metadata.input_name = input_name;
if changed {
let change = NodeMetadataChange::InputName {
index: input_index,
name: input_metadata.persistent_metadata.input_name.clone(),
};
self.deltas.metadata(change);
}
changed
}
/// The identifier of the widget override the properties panel uses for this input, or `None` for the
/// widget generated from its type.
pub(crate) fn set_widget_override(&mut self, input_index: usize, widget_override: Option<String>) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
input_metadata.persistent_metadata.widget_override = widget_override;
let change = NodeMetadataChange::WidgetOverride {
index: input_index,
widget_override: input_metadata.persistent_metadata.widget_override.clone(),
};
self.deltas.metadata(change);
true
}
pub(crate) fn set_output_name(&mut self, output_index: usize, output_name: String) -> bool {
let Some(existing) = self.metadata.output_names.get_mut(output_index) else { return false };
let changed = *existing != output_name;
*existing = output_name;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The metadata array the node's inputs index, one entry per input.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
/// Grows `output_names` to one entry per export, which an older document may be missing.
pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) {
if self.metadata.output_names.len() == number_of_exports {
return;
}
self.metadata.output_names.resize(number_of_exports, String::new());
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
/// entry for the added index. Restores the parallel-array invariant for an older document.
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
if self.metadata.input_metadata.len() >= number_of_inputs {
return;
}
for added_input_index in self.metadata.input_metadata.len()..number_of_inputs {
self.metadata.input_metadata.push(defaults(added_input_index).unwrap_or_default());
}
self.emit_input_metadata();
}
/// Swaps in a new implementation together with the nested network metadata that belongs to it.
///
/// Replaces the node and everything nested under it, since the nested network goes with the
/// implementation.
pub(crate) fn replace_implementation(&mut self, implementation: DocumentNodeImplementation, network_metadata: Option<NodeNetworkMetadata>) {
self.node.implementation = implementation;
self.metadata.network_metadata = network_metadata;
let delta = RuntimeDelta::ReplaceNode {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
node: Box::new(self.node.clone()),
};
self.deltas.graph(delta);
let metadata = Box::new(self.metadata.clone());
self.deltas.snapshot(metadata);
}
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
let snapshot = Box::new(self.metadata.clone());
self.deltas.snapshot(snapshot);
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
}
/// Swaps in new inputs together with their metadata, returning the inputs replaced.
pub(crate) fn replace_inputs(&mut self, inputs: Vec<NodeInput>, input_metadata: Vec<InputMetadata>) -> Vec<NodeInput> {
self.metadata.input_metadata = input_metadata;
let previous = std::mem::replace(&mut self.node.inputs, inputs);
self.emit_inputs();
previous
}
/// Records the node's input list and the metadata array indexed by it, which change together
/// whenever the number or order of slots does.
fn emit_inputs(&mut self) {
let delta = RuntimeDelta::SetInputs {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
inputs: self.node.inputs.clone(),
};
self.deltas.graph(delta);
self.emit_input_metadata();
}
fn emit_input_metadata(&mut self) {
let input_metadata = self.metadata.input_metadata.clone();
self.deltas.input_metadata(input_metadata);
}
}
/// The persistent metadata of one network, resolved once so a run of writes walks the tree a single time.
///
/// Metadata only: the graph half of a network is its export slots, which are addressed through
/// [`NodeNetworkInterface::set_input_slot`] like any other input.
pub(crate) struct NetworkMut<'a> {
metadata: &'a mut NodeNetworkPersistentMetadata,
deltas: &'a mut Vec<EditorDelta>,
network_path: &'a [NodeId],
}
impl NetworkMut<'_> {
/// Which node the network renders instead of its export.
///
/// Per-peer view state, so this is not recorded: the document is untouched, and the compile path
/// substitutes the previewed node into the graph it evaluates.
pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool {
let changed = self.metadata.previewing != previewing;
self.metadata.previewing = previewing;
changed
}
/// The definition this network was instantiated from, dropped once it is edited away from it.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let changed = self.metadata.reference != reference;
self.metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(self.metadata.reference.clone());
self.emit(change);
}
changed
}
/// The display order of pinned nodes in the Properties panel.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order;
self.metadata.pinned_node_order = pinned_node_order;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Appends a newly pinned node to the display order, or drops one that is no longer pinned.
pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool {
let order = &mut self.metadata.pinned_node_order;
let changed = match pinned {
true if !order.contains(&node_id) => {
order.push(node_id);
true
}
true => false,
false => {
let before = order.len();
order.retain(|id| *id != node_id);
order.len() != before
}
};
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Drops every node the order names that is no longer in the network.
pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool {
let before = self.metadata.pinned_node_order.len();
self.metadata.pinned_node_order.retain(&surviving);
let changed = self.metadata.pinned_node_order.len() != before;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
fn emit(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.network_path.to_vec(),
change,
});
}
/// The transform from node graph space to viewport space.
pub(crate) fn set_navigation_transform(&mut self, transform: DAffine2) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_to_viewport != transform;
self.metadata.navigation_metadata.node_graph_to_viewport = transform;
changed
}
/// The width of the node graph in viewport space.
pub(crate) fn set_navigation_width(&mut self, node_graph_width: f64) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_width != node_graph_width;
self.metadata.navigation_metadata.node_graph_width = node_graph_width;
changed
}
}
// The store: the only writer of the node graph and its parallel metadata tree. Every write keeps the
// two halves in step by construction, so the invariants checked by `validate_invariants` hold without
// each caller restating them.
impl NodeNetworkInterface {
/// Builds an interface around a freshly-assembled pair of trees, for a document arriving from
/// storage or from an older format rather than being edited into existence.
///
/// The only way to install them, since `Guarded` cannot be constructed outside this module either.
/// Nothing is recorded: the trees are the document, not a set of changes to it.
pub(super) fn from_trees(network: NodeNetwork, network_metadata: NodeNetworkMetadata) -> Self {
Self {
network: Guarded::new(MemoNetwork::new(network)),
network_metadata: Guarded::new(network_metadata),
..Default::default()
}
}
/// The transient caches of a network.
///
/// Deliberately separate from the document write API: unloading a cache is not a change to the
/// document, so there is nothing to record. Handing these out through their own accessor is what
/// lets the document-writing ones stay closed.
pub(super) fn network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.transient_metadata)
}
/// The transient caches of one node, for the same reason.
pub(super) fn node_transient_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeTransientMetadata> {
let network_metadata = self.network_metadata_mut(network_path)?;
Some(&mut network_metadata.persistent_metadata.node_metadata.get_mut(node_id)?.transient_metadata)
}
/// What the selection was, for the undo and redo of selection alone.
///
/// Stored in the persistent tree but not part of the document: which nodes a peer has selected is
/// that peer's, so these writes are not recorded and do not reach storage.
pub(super) fn selection_history_mut(&mut self, network_path: &[NodeId]) -> Option<SelectionHistoryMut<'_>> {
let persistent = &mut self.network_metadata_mut(network_path)?.persistent_metadata;
Some(SelectionHistoryMut {
undo: &mut persistent.selection_undo_history,
redo: &mut persistent.selection_redo_history,
})
}
/// The graph of the network at `network_path`. Private: every write to it is one of the primitives
/// below, which is what keeps a change from going unrecorded.
fn network_graph_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
self.document_network_mut().nested_network_mut(network_path)
}
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
///
/// Nothing is recorded: a migration produces the document the peer should have had rather than
/// changing the one they have. Not a route for editing, which goes through the writes below.
pub(super) fn migrate_graph(&mut self, migrate: impl FnOnce(&mut NodeNetwork)) {
migrate(self.document_network_mut());
}
/// Where the node graph is panned and zoomed to.
///
/// Per-peer view state like the selection: it rides in the persistent tree but is persisted to
/// `session.json` rather than the registry, so these writes are deliberately not recorded.
pub(super) fn navigation_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NavigationMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.persistent_metadata.navigation_metadata)
}
/// The root of the graph tree. The only `&mut` to it in the codebase, since `Guarded` withholds one
/// everywhere else.
fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.get_mut().network_mut()
}
/// The metadata tree at `network_path`. The only `&mut` to it, for the same reason.
pub(super) fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
self.network_metadata.get_mut().nested_metadata_mut(network_path)
}
/// The persistent metadata of a network, or `None` if the network is missing.
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
Some(NetworkMut {
metadata,
deltas: &mut self.deltas,
network_path,
})
}
/// Both halves of a node, or `None` if either is missing.
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.get_mut(&locator.node_id)?;
Some(NodeMut {
node,
metadata: &mut metadata.persistent_metadata,
deltas: NodeDeltas { deltas: &mut self.deltas, locator },
})
}
/// Inserts an input and its metadata at `index`, clamped to the end. Returns whether the node was found.
pub(crate) fn insert_input_slot(&mut self, locator: NodeLocator, index: usize, input: NodeInput, metadata: InputMetadata) -> bool {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in _input_slot", locator.node_id);
return false;
};
let index = index.min(node.node.inputs.len());
node.node.inputs.insert(index, input);
node.metadata.input_metadata.insert(index.min(node.metadata.input_metadata.len()), metadata);
node.emit_inputs();
true
}
/// Removes the input at `index` together with its metadata, returning both.
pub(crate) fn remove_input_slot(&mut self, locator: NodeLocator, index: usize) -> Option<(NodeInput, InputMetadata)> {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in _input_slot", locator.node_id);
return None;
};
if index >= node.node.inputs.len() {
log::error!("Input index {index} out of bounds in remove_input_slot for node {}", locator.node_id);
return None;
}
let input = node.node.inputs.remove(index);
let metadata = (index < node.metadata.input_metadata.len()).then(|| node.metadata.input_metadata.remove(index));
node.emit_inputs();
Some((input, metadata.unwrap_or_default()))
}
/// Moves the input at `from` to `to`, carrying its metadata with it.
///
/// Records the removal and the insertion separately, so the list is briefly one slot short. Both
/// land in the same batch, where the second supersedes the first.
pub(crate) fn move_input_slot(&mut self, locator: NodeLocator, from: usize, to: usize) -> bool {
let Some((input, metadata)) = self.remove_input_slot(locator, from) else { return false };
self.insert_input_slot(locator, to, input, metadata)
}
/// Inserts an export at `index`, clamped to the end, along with the name the encapsulating node shows
/// for it. The document network has no encapsulating node, so it carries no name.
pub(crate) fn insert_export_slot(&mut self, network_path: &[NodeId], index: usize, export: NodeInput, output_name: String) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in insert_export_slot");
return false;
};
let index = index.min(network.exports.len());
network.exports.insert(index, export);
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
output_names.insert(index.min(output_names.len()), output_name);
}
self.emit_exports_from(network_path, index, None);
true
}
/// Removes the export at `index` together with the encapsulating node's name for it.
pub(crate) fn remove_export_slot(&mut self, network_path: &[NodeId], index: usize) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in remove_export_slot");
return None;
};
if index >= network.exports.len() {
log::error!("Export index {index} out of bounds in remove_export_slot");
return None;
}
let export = network.exports.remove(index);
// The list shrank by one, so what was the last index now has no slot and has to be cleared.
let vacated = network.exports.len();
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
if index < output_names.len() {
output_names.remove(index);
}
}
self.emit_exports_from(network_path, index, Some(vacated));
Some(export)
}
/// Records every export slot from `index` on, plus a clear for `vacated` when the list shrank.
///
/// Export slots are addressed by index, so inserting or removing one changes the meaning of every
/// later slot and each has to be restated. The encapsulating node's names for them ride along as one
/// whole-array metadata write.
fn emit_exports_from(&mut self, network_path: &[NodeId], index: usize, vacated: Option<usize>) {
let Some(network) = self.network.network().nested_network(network_path) else { return };
let exports: Vec<_> = network.exports.iter().skip(index).cloned().collect();
for (offset, export) in exports.into_iter().enumerate() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: index + offset,
input: Some(export),
}));
}
if let Some(vacated) = vacated {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: vacated,
input: None,
}));
}
let Some((&node_id, parent_path)) = network_path.split_last() else { return };
let Some(metadata) = self.encapsulating_node_metadata(network_path) else { return };
let change = NodeMetadataChange::OutputNames(metadata.persistent_metadata.output_names.clone());
self.deltas.push(EditorDelta::NodeMetadata {
network_path: parent_path.to_vec(),
node_id,
change,
});
}
/// Moves the export at `from` to `to`, carrying the encapsulating node's name for it.
pub(crate) fn move_export_slot(&mut self, network_path: &[NodeId], from: usize, to: usize) -> bool {
let name = self
.encapsulating_node_metadata(network_path)
.and_then(|metadata| metadata.persistent_metadata.output_names.get(from).cloned())
.unwrap_or_default();
let Some(export) = self.remove_export_slot(network_path, from) else { return false };
self.insert_export_slot(network_path, to, export, name)
}
/// Writes the input at `connector`, returning the input it replaced.
pub(crate) fn set_input_slot(&mut self, connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in set_input_slot");
return None;
};
let slot = match connector {
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
};
let Some(slot) = slot else {
log::error!("Could not get input {connector:?} in set_input_slot");
return None;
};
if *slot == input {
return Some(input);
}
let previous = std::mem::replace(slot, input.clone());
self.deltas.push(EditorDelta::Graph(match connector {
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
network_path: network_path.to_vec(),
node_id: *node_id,
input_index: *input_index,
input,
},
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: *export_index,
input: Some(input),
},
}));
Some(previous)
}
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
///
/// For a change expressed as an operation on the existing value rather than as a replacement of it.
/// Reading the value out, editing it, and writing it back would copy it twice; the recorded delta
/// still carries the whole result, since the storage op is a whole-value write.
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in edit_input_value");
return false;
};
let slot = match connector {
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
};
let Some(slot) = slot else {
log::error!("Could not get input {connector:?} in edit_input_value");
return false;
};
let Some(mut value) = slot.as_value_mut() else {
log::error!("Input {connector:?} is not a value in edit_input_value");
return false;
};
edit(&mut value);
drop(value);
let input = slot.clone();
self.deltas.push(EditorDelta::Graph(match connector {
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
network_path: network_path.to_vec(),
node_id: *node_id,
input_index: *input_index,
input,
},
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: *export_index,
input: Some(input),
},
}));
true
}
/// Inserts a node and its metadata, returning the entry it replaced.
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in insert_node_entry", locator.network_path);
return None;
}
let (document_node, persistent_metadata) = template.into_parts();
let node = Box::new(document_node.clone());
let metadata = Box::new(persistent_metadata.clone());
let previous_node = self
.network
.get_mut()
.network_mut()
.nested_network_mut(locator.network_path)?
.nodes
.insert(locator.node_id, document_node);
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
locator.node_id,
DocumentNodeMetadata {
persistent_metadata,
transient_metadata: DocumentNodeTransientMetadata::default(),
},
);
// Overwriting an existing entry replaces the node and everything nested under it, which is what
// distinguishes the two from the storage side.
let network_path = locator.network_path.to_vec();
let node_id = locator.node_id;
self.deltas.push(EditorDelta::Graph(match previous_node.is_some() {
true => RuntimeDelta::ReplaceNode {
network_path: network_path.clone(),
node_id,
node,
},
false => RuntimeDelta::AddNode {
network_path: network_path.clone(),
node_id,
node,
},
}));
self.deltas.push(EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata });
previous_node
.zip(previous_metadata)
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Removes a node and its metadata, returning them joined as a template.
pub(crate) fn remove_node_entry(&mut self, locator: NodeLocator) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in remove_node_entry", locator.network_path);
return None;
}
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.remove(&locator.node_id);
if node.is_some() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: locator.network_path.to_vec(),
node_id: locator.node_id,
}));
}
node.zip(metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
/// halves out of step.
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
}
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
std::mem::take(&mut self.deltas)
}
/// Drops what the writes since the last drain changed, for writes that are not edits to the
/// document. Bringing an old document up to date produces the document rather than changing it, so
/// there is nothing to report.
pub(crate) fn discard_deltas(&mut self) {
self.deltas.clear();
}
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
/// once its signature is edited.
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
if let Some(mut network) = self.network_mut(network_path) {
network.set_reference(None);
}
}
}
@@ -103,6 +103,10 @@ pub struct NodeNetworkTemplate {
impl NodeTemplate { impl NodeTemplate {
/// Joins a [`DocumentNode`] and its persistent metadata into the unified template shape. Missing nested metadata is filled with defaults. /// Joins a [`DocumentNode`] and its persistent metadata into the unified template shape. Missing nested metadata is filled with defaults.
///
/// A template names no node, so the storage identity is dropped here and left unset by
/// [`Self::into_parts`]: a node inserted from a template is addressed by its location until storage
/// names it.
pub fn from_parts(document_node: DocumentNode, persistent_node_metadata: DocumentNodePersistentMetadata) -> Self { pub fn from_parts(document_node: DocumentNode, persistent_node_metadata: DocumentNodePersistentMetadata) -> Self {
let DocumentNode { let DocumentNode {
inputs, inputs,
@@ -114,6 +118,7 @@ impl NodeTemplate {
original_location: _, original_location: _,
} = document_node; } = document_node;
let DocumentNodePersistentMetadata { let DocumentNodePersistentMetadata {
storage_id: _,
display_name, display_name,
input_metadata, input_metadata,
output_names, output_names,
@@ -196,6 +201,7 @@ impl NodeTemplate {
original_location: Default::default(), original_location: Default::default(),
}; };
let persistent_node_metadata = DocumentNodePersistentMetadata { let persistent_node_metadata = DocumentNodePersistentMetadata {
storage_id: None,
display_name, display_name,
input_metadata, input_metadata,
output_names, output_names,
@@ -93,6 +93,9 @@ pub enum ImportOrExport {
pub const PRIMARY_INPUT_INDEX: usize = 0; pub const PRIMARY_INPUT_INDEX: usize = 0;
/// The secondary input (index 1) of a layer-shaped node: the horizontal wire from the left, carrying the node chain or child stack that the layer renders. /// The secondary input (index 1) of a layer-shaped node: the horizontal wire from the left, carrying the node chain or child stack that the layer renders.
pub const LAYER_SECONDARY_INPUT_INDEX: usize = 1; pub const LAYER_SECONDARY_INPUT_INDEX: usize = 1;
/// The height in grid cells of a node displayed as a layer, which is fixed regardless of its inputs.
pub const LAYER_GRID_HEIGHT: u32 = 2;
/// The primary output (index 0) of a node, which most nodes expose as their only output. /// The primary output (index 0) of a node, which most nodes expose as their only output.
pub const PRIMARY_OUTPUT_INDEX: usize = 0; pub const PRIMARY_OUTPUT_INDEX: usize = 0;
@@ -336,10 +339,15 @@ impl RootNode {
} }
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)] #[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
/// Which node the node graph renders instead of the network's export.
///
/// Per-peer view state, not part of the document: the export keeps whatever it is wired to, and the
/// compile path substitutes the previewed node into the graph it evaluates. So previewing a node
/// changes nothing another peer would see, and there is nothing to restore when it ends.
pub enum Previewing { pub enum Previewing {
/// If there is a node to restore the connection to the export for, then it is stored in the option. Yes {
/// Otherwise, nothing gets restored and the primary export is disconnected. previewed: RootNode,
Yes { root_node_to_restore: Option<RootNode> }, },
#[default] #[default]
No, No,
} }
@@ -442,6 +450,24 @@ impl<T> TransientCache<T> {
*self.0.borrow_mut() = None; *self.0.borrow_mut() = None;
} }
/// Computes and stores the value with `load` if it is not already loaded.
///
/// `load` runs with no borrow held, so it is free to read other cache slots.
pub(crate) fn ensure_loaded(&self, load: impl FnOnce() -> Option<T>) {
let already_loaded = self.0.borrow().is_some();
if already_loaded {
return;
}
let Some(value) = load() else { return };
self.store(value);
}
/// Runs `read` on the cached value, computing it with `load` first if it is not loaded.
pub(crate) fn with_loaded_or<R>(&self, load: impl FnOnce() -> Option<T>, read: impl FnOnce(&T) -> R) -> Option<R> {
self.ensure_loaded(load);
self.with_loaded(read)
}
/// Runs `read` on the cached value if it is loaded. /// Runs `read` on the cached value if it is loaded.
pub(crate) fn with_loaded<R>(&self, read: impl FnOnce(&T) -> R) -> Option<R> { pub(crate) fn with_loaded<R>(&self, read: impl FnOnce(&T) -> R) -> Option<R> {
self.0.borrow().as_ref().map(read) self.0.borrow().as_ref().map(read)
@@ -655,6 +681,11 @@ impl InputPersistentMetadata {
#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct DocumentNodePersistentMetadata { pub struct DocumentNodePersistentMetadata {
/// The identity storage holds for this node, pinned when the interface is built from a document so
/// a conversion back reuses it instead of re-deriving one. Absent for a node storage has not named,
/// which falls back to a hash of its location.
#[serde(default)]
pub storage_id: Option<u64>,
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed to the user in italics. /// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed to the user in italics.
#[serde(default)] #[serde(default)]
pub display_name: String, pub display_name: String,
@@ -225,6 +225,22 @@ impl<'a, 'p> NetworkView<'a, 'p> {
Ok(self.node(node_id)?.inputs.iter().filter(|input| input.is_exposed()).count()) Ok(self.node(node_id)?.inputs.iter().filter(|input| input.is_exposed()).count())
} }
/// Input rows the node displays: every exposed input, plus the primary input, whose row is shown even when it is not exposed.
pub fn input_row_count(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self
.node(node_id)?
.inputs
.iter()
.enumerate()
.filter(|(input_index, input)| *input_index == 0 || input.is_exposed())
.count())
}
/// Grid rows the node body spans, which is the greater of its input rows and its output count.
pub fn displayed_row_count(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self.input_row_count(node_id)?.max(self.number_of_outputs(node_id)?).max(1))
}
pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> { pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(match self.implementation(node_id)? { Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(), DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
@@ -266,19 +282,15 @@ impl<'a, 'p> NetworkView<'a, 'p> {
} }
/// The root node (the node that the solid line is connected to), or None if no nodes are connected to the output. /// The root node (the node that the solid line is connected to), or None if no nodes are connected to the output.
///
/// Simply what the export is wired to: previewing renders a different node but does not rewire it.
pub fn root_node(&self) -> Option<RootNode> { pub fn root_node(&self) -> Option<RootNode> {
match &self.metadata.persistent_metadata.previewing { match self.network.exports.first() {
Previewing::Yes { root_node_to_restore } => *root_node_to_restore, Some(NodeInput::Node { node_id, output_index, .. }) => Some(RootNode {
Previewing::No => self.network.exports.first().and_then(|export| { node_id: *node_id,
if let NodeInput::Node { node_id, output_index, .. } = export { output_index: *output_index,
Some(RootNode {
node_id: *node_id,
output_index: *output_index,
})
} else {
None
}
}), }),
_ => None,
} }
} }
@@ -1143,7 +1143,7 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) { pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node(); document.network_interface.migrate_path_modify_node();
document.network_interface.document_network_mut().normalize_stored_types(); document.network_interface.normalize_stored_types();
let network = document.network_interface.document_network().clone(); let network = document.network_interface.document_network().clone();
@@ -1216,7 +1216,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
let mut multiply_template = multiply_node.default_node_template(); let mut multiply_template = multiply_node.default_node_template();
multiply_template.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false); multiply_template.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false);
let multiply_node_id = NodeId::new(); let multiply_node_id = NodeId::new();
if let Some(transform_position) = document.network_interface.position_from_downstream_node(node_id, network_path) { if let Some(transform_position) = document.network_interface.position(node_id, network_path) {
let multiply_position = transform_position + IVec2::new(-7, 1); let multiply_position = transform_position + IVec2::new(-7, 1);
document.network_interface.insert_node(multiply_node_id, multiply_template, network_path); document.network_interface.insert_node(multiply_node_id, multiply_template, network_path);
document.network_interface.shift_absolute_node_position(&multiply_node_id, multiply_position, network_path); document.network_interface.shift_absolute_node_position(&multiply_node_id, multiply_position, network_path);
@@ -1370,6 +1370,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path); document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path);
} }
} }
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
document.network_interface.discard_deltas();
} }
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type. /// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
@@ -2527,7 +2532,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let merge_node_id = NodeId::new(); let merge_node_id = NodeId::new();
// Decide on the placement position of the new Merge node // Decide on the placement position of the new Merge node
let Some(morph_position) = document.network_interface.position_from_downstream_node(node_id, network_path) else { let Some(morph_position) = document.network_interface.position(node_id, network_path) else {
log::error!("Could not get position for morph node {node_id}"); log::error!("Could not get position for morph node {node_id}");
return None; return None;
}; };
@@ -2568,7 +2573,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// Reconnect content (input 0) and leave path (input 4) as default // Reconnect content (input 0) and leave path (input 4) as default
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
let Some(morph_position) = document.network_interface.position_from_downstream_node(node_id, network_path) else { let Some(morph_position) = document.network_interface.position(node_id, network_path) else {
log::error!("Could not get position for morph node {node_id}"); log::error!("Could not get position for morph node {node_id}");
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
return None; return None;
@@ -55,7 +55,7 @@ pub enum PortfolioMessage {
reopened: bool, reopened: bool,
#[serde(skip, default)] #[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))] #[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<document_format::GddV1>, gdd: Option<Box<document_format::GddV1>>,
}, },
DestroyAllDocuments, DestroyAllDocuments,
EditorPreferences, EditorPreferences,
@@ -314,7 +314,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Document was closed before its working copy finished mounting. // Document was closed before its working copy finished mounting.
return; return;
}; };
document.set_storage(gdd); document.set_storage(gdd.map(|gdd| *gdd));
if !reopened { if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip); document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction(); document.retire_storage_interaction();
@@ -1325,7 +1325,7 @@ impl PortfolioMessageHandler {
Message::Portfolio(PortfolioMessage::DocumentStorageMounted { Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id, document_id,
reopened, reopened,
gdd: Some(gdd), gdd: Some(Box::new(gdd)),
}) })
}; };
future.into() future.into()
@@ -68,6 +68,7 @@ impl SpiralTurns {
self.handle_state == SpiralTurnsState::Dragging self.handle_state == SpiralTurnsState::Dragging
} }
#[expect(clippy::too_many_arguments, reason = "the gizmo records one value per spiral parameter, so grouping them would only move the argument list")]
pub fn store_initial_parameters( pub fn store_initial_parameters(
&mut self, &mut self,
layer: LayerNodeIdentifier, layer: LayerNodeIdentifier,
@@ -865,7 +865,7 @@ impl ShapeState {
/// Deselects all the anchors across every selected layer. /// Deselects all the anchors across every selected layer.
pub fn deselect_all_anchors(&mut self) { pub fn deselect_all_anchors(&mut self) {
for (_, state) in self.selected_shape_state.iter_mut() { for state in self.selected_shape_state.values_mut() {
let selected_anchor_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_anchor().is_some()).cloned().collect(); let selected_anchor_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_anchor().is_some()).cloned().collect();
for point in selected_anchor_points { for point in selected_anchor_points {
@@ -876,7 +876,7 @@ impl ShapeState {
/// Deselects all the handles across every selected layer. /// Deselects all the handles across every selected layer.
pub fn deselect_all_handles(&mut self) { pub fn deselect_all_handles(&mut self) {
for (_, state) in self.selected_shape_state.iter_mut() { for state in self.selected_shape_state.values_mut() {
let selected_handle_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_handle().is_some()).cloned().collect(); let selected_handle_points: Vec<ManipulatorPointId> = state.selected_points.iter().filter(|selected_point| selected_point.as_handle().is_some()).cloned().collect();
for point in selected_handle_points { for point in selected_handle_points {
@@ -89,11 +89,8 @@ impl ShapeType {
} }
pub fn tooltip_description(&self) -> String { pub fn tooltip_description(&self) -> String {
(match self { // TODO: Add descriptions to all the shape tools
// TODO: Add descriptions to all the shape tools String::new()
_ => "",
})
.into()
} }
pub fn icon_name(&self) -> String { pub fn icon_name(&self) -> String {
@@ -677,7 +677,6 @@ mod tests {
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(), down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(), left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(), right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
..Default::default()
}; };
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.); let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
let snap_results = &mut SnapResults::default(); let snap_results = &mut SnapResults::default();
+5 -7
View File
@@ -138,7 +138,7 @@ impl NodeGraphExecutor {
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> { pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache. // We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid(); self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone(); let mut network = document.network_interface.network_to_evaluate();
let instrumented = Instrumented::new(&mut network); let instrumented = Instrumented::new(&mut network);
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
@@ -158,7 +158,7 @@ impl NodeGraphExecutor {
let network_hash = document.network_interface.network_hash(); let network_hash = document.network_interface.network_hash();
// Refresh the graph when it changes or the inspect node changes // Refresh the graph when it changes or the inspect node changes
if network_hash != self.node_graph_hash || self.previous_node_to_inspect != node_to_inspect || ignore_hash { if network_hash != self.node_graph_hash || self.previous_node_to_inspect != node_to_inspect || ignore_hash {
let network = document.network_interface.document_network().clone(); let network = document.network_interface.network_to_evaluate();
self.previous_node_to_inspect.clone_from(&node_to_inspect); self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.node_graph_hash = network_hash; self.node_graph_hash = network_hash;
@@ -286,7 +286,7 @@ impl NodeGraphExecutor {
/// Evaluates a node graph for export /// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, mut export_config: ExportConfig) -> Result<(), String> { pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, mut export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone(); let network = document.network_interface.network_to_evaluate();
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
let export_format = if export_config.file_type == FileType::Svg { let export_format = if export_config.file_type == FileType::Svg {
@@ -522,7 +522,7 @@ impl NodeGraphExecutor {
scale: f64, scale: f64,
responses: &mut VecDeque<Message>, responses: &mut VecDeque<Message>,
) { ) {
let mut network = document.network_interface.document_network().clone(); let mut network = document.network_interface.network_to_evaluate();
// On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough. // On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough.
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry. // But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
@@ -939,10 +939,8 @@ mod test {
Some(x.output.clone()) Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() { } else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
Some(x.output.clone()) Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
Some(x.output.clone())
} else { } else {
None dynamic.downcast_ref::<IORecord<Context, Output>>().map(|x| x.output.clone())
} }
} }
+15 -1
View File
@@ -659,13 +659,27 @@ impl NodeNetwork {
/// Check there are no cycles in the graph (this should never happen). /// Check there are no cycles in the graph (this should never happen).
pub fn is_acyclic(&self) -> bool { pub fn is_acyclic(&self) -> bool {
self.is_acyclic_with(None)
}
/// Whether the network is acyclic, optionally answering for one input replaced by a proposed value
/// rather than for the inputs as they stand, so a write can be tested without being performed.
///
/// `replaced` names the node, the input index, and what would be written there.
pub fn is_acyclic_with(&self, replaced: Option<(NodeId, usize, &NodeInput)>) -> bool {
let dependency = |input: &NodeInput| if let NodeInput::Node { node_id, .. } = input { Some(*node_id) } else { None };
let mut dependencies: HashMap<NodeId, Vec<NodeId>> = HashMap::new(); let mut dependencies: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
for (node_id, node) in &self.nodes { for (node_id, node) in &self.nodes {
dependencies.insert( dependencies.insert(
*node_id, *node_id,
node.inputs node.inputs
.iter() .iter()
.filter_map(|input| if let NodeInput::Node { node_id, .. } = input { Some(*node_id) } else { None }) .enumerate()
.filter_map(|(index, input)| match replaced {
Some((replaced_node, replaced_index, proposed)) if replaced_node == *node_id && replaced_index == index => dependency(proposed),
_ => dependency(input),
})
.collect(), .collect(),
); );
} }
+1
View File
@@ -7,6 +7,7 @@ pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descri
pub mod application_io; pub mod application_io;
pub mod document; pub mod document;
pub mod runtime_delta;
pub use document::{DocumentNode, NodeNetwork}; pub use document::{DocumentNode, NodeNetwork};
pub mod graphene_compiler; pub mod graphene_compiler;
pub mod proto; pub mod proto;
@@ -0,0 +1,69 @@
use crate::document::{DocumentNode, NodeId, NodeInput};
use core_types::{ContextDependencies, Type};
/// One mutation's worth of structural graph change, carrying its post-change data as plain runtime
/// types. Constructed by the mutation itself; a compound mutation emits several. Consumed typed and
/// unserialized by the compiler, and paired with `EditorDelta` metadata for storage staging.
///
/// Every variant names a write that a peer actually made, never a difference observed between two
/// states: a delta derived by comparison would assert values nobody wrote, and its timestamp would
/// win against a concurrent peer that did write them.
///
/// A node's inputs are addressed by index, which is stable only while its arity is. Changing arity
/// is therefore a `ReplaceNode`, not an edit to the input list.
#[derive(Debug, Clone, PartialEq)]
pub enum RuntimeDelta {
/// The node's nested network, if it implements one, rides inside the `DocumentNode`.
AddNode {
network_path: Vec<NodeId>,
node_id: NodeId,
node: Box<DocumentNode>,
},
ReplaceNode {
network_path: Vec<NodeId>,
node_id: NodeId,
node: Box<DocumentNode>,
},
/// Address-only: removal snapshots come from the storage layer's working registry.
RemoveNode {
network_path: Vec<NodeId>,
node_id: NodeId,
},
SetInput {
network_path: Vec<NodeId>,
node_id: NodeId,
input_index: usize,
input: NodeInput,
},
/// A node's whole input list, which is how a change to the number or order of its slots is
/// expressed, since `SetInput` addresses one index and cannot move the others. Everything nested
/// under the node is left alone, unlike `ReplaceNode`.
SetInputs {
network_path: Vec<NodeId>,
node_id: NodeId,
inputs: Vec<NodeInput>,
},
/// `None` removes the slot, matching the storage op this converts to.
SetExport {
network_path: Vec<NodeId>,
export_index: usize,
input: Option<NodeInput>,
},
SetVisibility {
network_path: Vec<NodeId>,
node_id: NodeId,
visible: bool,
},
/// The type of argument the node can be evaluated with.
SetCallArgument {
network_path: Vec<NodeId>,
node_id: NodeId,
call_argument: Type,
},
/// The Extract and Inject annotations the node declares for the Context.
SetContextFeatures {
network_path: Vec<NodeId>,
node_id: NodeId,
context_features: ContextDependencies,
},
}
-1
View File
@@ -7,7 +7,6 @@ use document_format::{GddV1, GddV1Layout};
use fern::colors::{Color, ColoredLevelConfig}; use fern::colors::{Color, ColoredLevelConfig};
use futures::executor::block_on; use futures::executor::block_on;
use graph_craft::application_io::EditorPreferences; use graph_craft::application_io::EditorPreferences;
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::*; use graph_craft::document::*;
use graph_craft::graphene_compiler::Compiler; use graph_craft::graphene_compiler::Compiler;
@@ -18,6 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
(executor, proto_network) (executor, proto_network)
} }
#[allow(dead_code, reason = "shared by the bench targets, only some of which call it, and each compiles this module separately")]
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F) pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
where where
F: Fn(&str, &mut BenchmarkGroup<M>), F: Fn(&str, &mut BenchmarkGroup<M>),
@@ -219,7 +219,7 @@ impl SvgRender {
let (size_x, size_y) = (bounds_max - bounds_min).into(); let (size_x, size_y) = (bounds_max - bounds_min).into();
let svg_header = format!( let svg_header = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art" viewBox="{x} {y} {size_x} {size_y}"><defs>{defs}</defs>"#, r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art" viewBox="{x} {y} {size_x} {size_y}"><defs>{defs}</defs>"#,
defs = &self.svg_defs defs = self.svg_defs
); );
self.svg_defs = String::new(); self.svg_defs = String::new();
self.svg.insert(0, svg_header.into()); self.svg.insert(0, svg_header.into());
@@ -237,7 +237,7 @@ impl SvgRender {
let svg_header = format!( let svg_header = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art" {view_box}><defs>{defs}</defs><g{transform}>"#, r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art" {view_box}><defs>{defs}</defs><g{transform}>"#,
defs = &self.svg_defs defs = self.svg_defs
); );
self.svg_defs = String::new(); self.svg_defs = String::new();
self.svg.insert(0, svg_header.into()); self.svg.insert(0, svg_header.into());
+3 -3
View File
@@ -3708,7 +3708,7 @@ mod test {
let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await; let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await;
let vector = result.element(); let vector = result.element();
assert!(vector.use_face_fill()); assert!(vector.use_face_fill());
assert!(vector.segment_domain.ids().len() > 0); assert!(!vector.segment_domain.ids().is_empty());
} }
#[tokio::test] #[tokio::test]
@@ -3739,8 +3739,8 @@ mod test {
assert_eq!(vector.point_domain.ids().len(), points.len()); assert_eq!(vector.point_domain.ids().len(), points.len());
assert_ne!(vector.point_domain.positions(), &points[..]); assert_ne!(vector.point_domain.positions(), &points[..]);
// The convex-hull corners are pinned. // The convex-hull corners are pinned.
for i in 0..4 { for (corner, (&position, &point)) in vector.point_domain.positions().iter().zip(&points).take(4).enumerate() {
assert_eq!(vector.point_domain.positions()[i], points[i], "hull corner {i} should be pinned"); assert_eq!(position, point, "hull corner {corner} should be pinned");
} }
for &point in vector.point_domain.positions() { for &point in vector.point_domain.positions() {
assert!(point.x >= -1e-6 && point.x <= 10. + 1e-6); assert!(point.x >= -1e-6 && point.x <= 10. + 1e-6);
+58 -58
View File
@@ -29,76 +29,76 @@ pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream
if segment.ident != "MessageHandler" { if segment.ident != "MessageHandler" {
return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait")); return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait"));
} }
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments { if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
if args.args.len() >= 2 { && args.args.len() >= 2
// Extract the message type (M) and context struct type (C) from the trait params {
let message_type = &args.args[0]; // Extract the message type (M) and context struct type (C) from the trait params
let data_type = &args.args[1]; let message_type = &args.args[0];
let data_type = &args.args[1];
let impl_item = match data_type { let impl_item = match data_type {
syn::GenericArgument::Type(t) => { syn::GenericArgument::Type(t) => {
match t { match t {
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => { syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
// Get just the base identifier (ToolMessageData) without generics // Get just the base identifier (ToolMessageData) without generics
let type_name = &type_path.path.segments.first().unwrap().ident; let type_name = &type_path.path.segments.first().unwrap().ident;
let handler_data_line_number = type_name.span().start().line; let handler_data_line_number = type_name.span().start().line;
quote! { quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
syn::Type::Tuple(_) => quote! {
#input_item #input_item
impl #message_type { impl #message_type {
pub fn message_handler_str() -> MessageData { pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number()) MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
}
} }
}, pub fn message_handler_str() -> MessageData {
syn::Type::Reference(type_reference) => { MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
let type_line_number = type_ident.span().start().line;
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
} }
} }
} }
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
} }
} syn::Type::Tuple(_) => quote! {
#input_item
impl #message_type {
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
},
syn::Type::Reference(type_reference) => {
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
_ => quote! { let type_line_number = type_ident.span().start().line;
#input_item
}, let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
}; quote! {
return Ok(impl_item); #input_item
} impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
}
}
_ => quote! {
#input_item
},
};
return Ok(impl_item);
} }
} }
Ok(input_item) Ok(input_item)
+268
View File
@@ -0,0 +1,268 @@
# Runtime deltas: design context and follow-up plan
Working notes for the in-vivo runtime delta effort on this branch, recording what exists, the
motivation behind each decision, and the context needed to complete the remaining phases. The
decisions here were settled in design discussion between Keavon and TrueDoctor during July 2026.
## What exists on this branch
- `graph_craft::runtime_delta::RuntimeDelta`: the structural delta enum. Payload-carrying,
constructed at mutation time, plain runtime types, no serialization. Variants: `AddNode`,
`ReplaceNode` (carrying `Box<DocumentNode>`), `RemoveNode` (address-only), `SetInput`,
`SetExport`, `SetVisibility`.
- `editor::...::network_interface::editor_delta`: the editor-side wrapper `EditorDelta
{ Graph(RuntimeDelta), NodeMetadata { .. } }` and `construct_batch`, which turns one gesture's
deltas into storage `RegistryDelta` ops.
- Parity tests (`editor_delta_tests`) proving the constructed ops equal the ops a whole-document
diff would stage: exactly (op-for-op) for slot, export, visibility, and metadata changes;
by stored-state equivalence for structural add/remove batches.
- Substrate reused from the earlier marker-based experiment: `ScopedConversion` (per-entity
conversion through the canonical `from_runtime` encoders), `PathResolver` (path-hash ID
derivation without conversion), `Session::stage_computed_ops`, `GddV1::stage_runtime_deltas`.
Not yet wired: mutation sites do not emit deltas, staging does not consume them, and the compiler
still receives whole-network clones.
## Decisions and their motivations
**In-vivo payload deltas, not dirty-set markers.** An earlier experiment (branches
`runtime-deltas-1-record` / `runtime-deltas-3-flip`, kept for reference) recorded scope markers and
re-derived deltas at staging by scoped reconversion. Rejected because the perf case did not hold
holistically: the editor stages after every mutation for the compiler anyway, so the data is in
hand at mutation time regardless, and payload capture costs nothing extra. Payloads also make the
delta a bidirectional currency (storage, compiler, and later undo/collab all speak it), which
markers structurally cannot.
**Graph-craft structural enum plus an editor wrapper.** The compiler must consume deltas without
editor dependencies, and a separate compiler-only delta type (a third set) was explicitly ruled
out. `SetInput`/`SetExport` are separate variants so the editor's `InputConnector` type does not
leak into graph-craft.
**Wholesale metadata copies, diffed by storage.** Rather than per-field metadata variants, one
`NodeMetadata` delta carries a copy of the node's persistent metadata (cheap to clone). Storage
diffs it against the working registry so minimal attribute ops fall out; the compiler throws it
away. This also absorbs ambiguity: the delta does not need to know which fields changed.
**`SetVisibility` is structural.** `visible` is a `DocumentNode` field the compiler consumes for
rendering. The rare other scalar setters (`call_argument`, `context_features`) go through
`ReplaceNode` instead of dedicated variants.
**Batch-scoped construction.** Removal closures and resource liveness are properties of the whole
gesture, not one delta: deleting a group with children removes several nodes whose shared
declaration only becomes unreferenced once all of them are gone. `construct_batch` is therefore
the construction unit, matching how mutations emit (compound operations produce several deltas)
and how staging consumes.
**Arc-backed input values (agreed, not yet implemented).** `NodeInput::Value`'s `TaggedValue`
storage should become `Arc`-backed (inside the existing `MemoHash`), mutating via `Arc::make_mut`.
Delta capture, compiler updates, and undo snapshots then share by pointer bump instead of cloning;
copy-on-write fires only when an old version is genuinely still held, which is exactly when a copy
is semantically required. This is a prerequisite for cheap drag/paint deltas and should land in
graph-craft before the mutation sites are wired.
**Accumulation and desync carry over from the earlier design.** A pending buffer on the interface
accumulates delta batches with same-target coalescing (a drag keeps first-to-last one `SetInput`).
Anything that cannot itemize its changes (document open, snapshot install, raw network access,
storage mount) desyncs the buffer, forcing one whole-document diff before delta staging resumes.
The `verify_journal_projection` soak pattern from the earlier branches (constructed ops compared
against the whole-document diff on every staging under the `validate_storage_round_trip`
preference) is the validation harness to reuse; it caught real bugs twice there.
## Remaining phases to land forward deltas
1. Arc-backed values in graph-craft.
2. The pending buffer on `NodeNetworkInterface` (accumulation, coalescing, desync states).
3. Site wiring: roughly thirty mutation sites emit their delta batches, capturing state after
mutating. The site catalog from the earlier experiment maps every `transaction_modified` call
site to what it touches. **Open fork, see "Emission" below; do not start without a decision.**
4. Staging: `construct_batch` into `Session::stage_computed_ops` via `GddV1::stage_runtime_deltas`,
with the whole-document diff as the desync fallback and the parity soak in validate mode.
5. Compiler consumption: replace the per-update whole-network clone in `GraphUpdate` with the
`RuntimeDelta` stream reconciling a mirror on the runtime thread, using apply-reported change
as the invalidation signal.
### Emission: the open fork on phase 3
Mutators do not yield deltas today; the delta is recovered by diffing the whole registry at commit
time (`Session::stage_from_runtime`). Three shapes, none chosen:
- **(a) Emit at the `store.rs` primitives.** Every write already funnels through them, so emission
cannot be forgotten. But they are finer-grained than `RuntimeDelta` (`insert_input_slot`, not
`SetInput`), so peers would receive a different, lower-level language than `EditorDelta` defines.
- **(b) Emit at the mutator level.** Matches `RuntimeDelta` granularity exactly, but must be
hand-added to roughly forty public mutators and can silently be forgotten in a new one.
- **(c) Keep diffing, but scope the diff to the batch's touched set** rather than the whole
document. Reuses `compute_deltas`, cannot drift, and `verify_round_trip` already proves the diff
faithful. Cost: no semantic delta, a move stays a remove-plus-add. Fine for peers, since
`RegistryDelta` is the wire format anyway; not what incremental compilation wants.
Rough read at the time of writing: (c) if peer sync is the driver, (b) if incremental compilation
is. (a) is the only structurally un-forgettable one but changes what a delta means.
Sequencing once that is decided: the **batch boundary** comes first (a scope a run of writes
happens inside, collecting emitted deltas and the dirty set, flushed once at the end), because both
emission and the deferred invalidation flush need it. Decide explicit `finish()` versus `Drop`;
`Drop` cannot report failure and interacts awkwardly with `transaction_modified`. Then `apply` as
mechanism only, which is the smaller half because `store.rs` is already total and already the
single writer. Gate for `apply`: `validate_invariants()` empty afterwards, and applying a
mutation's own delta to a clone of the interface reproduces that interface.
## Interface restructure state (branch `runtime-deltas-2`, 2026-09-22)
The restructure that prepares `NodeNetworkInterface` for the above. Twenty-two commits, rebased
onto `origin/master` at `d7ae6029e0`, nothing pushed.
### Module shape
`editor/src/messages/portfolio/document/utility_types/network_interface/`
| file | role | lines, start to now |
|---|---|---|
| `store.rs` | the only writer of both parallel trees | new, 428 |
| `mutations.rs` | policy: validation, layout decisions | 1629 to 1271 |
| `layout.rs` | positioning policy | 1295 |
| `caches.rs` | transient cache slots | 1258 to 876 |
| `queries.rs` | reads | 1229 to 966 |
| `geometry.rs` | click targets, ports, widths | new, 352 |
| `frontend.rs` | frontend projections | new, 181 |
| `invalidation.rs` | named invalidation rules | new, 40 |
`network: MemoNetwork` and `network_metadata: NodeNetworkMetadata` are parallel trees keyed by the
same `NodeId`s. `store.rs` is their single writer, so every write keeps them in step by
construction; `validate_invariants` (test-only, `validation.rs`) checks it.
The resolved cursors `NodeMut` / `NetworkMut` hold disjoint field borrows and therefore cannot call
back into the interface. That is deliberate: it forces what a write invalidates to be *declared* by
the caller rather than performed inside the write.
### Identity
Storage `NodeId` resolution goes through exactly one place, `NodeIds::resolve` in
`document/graph-storage/src/from_runtime.rs`: it prefers the identity the metadata source holds and
falls back to `blake3(peer, NodePath)`, a hash of the node's location. Every naming site routes
through it, including the node's own registry key, input references, scope injections,
`PathResolver` and `ScopedConversion`.
`NodeMetadataEntry` carries `storage_id` and is emitted for every node (`is_empty()` is gone).
`build_interface_from_storage` pins it onto `DocumentNodePersistentMetadata::storage_id`, so a
document that round-trips through storage keeps its identities.
`rebuilt_interface_keeps_storage_identities` (in `storage_tests/metadata_tests.rs`) asserts a
re-conversion under a *different peer* reproduces the same ids.
**Minting is deliberately not done** (Dennis chose this on 2026-09-22), because:
- `NodeTemplate` drops `storage_id` in both `from_parts` and `into_parts`, so a remove/insert
template round trip loses the pin. Making the template carry it collides with its other role as
the clipboard and definition type.
- Grouping, ungrouping and paste all go through `copy_nodes`, which assigns *new runtime* `NodeId`s
to everything, so a node entering a group is already a new node at the runtime level.
- Nothing else in a session changes a node's location while keeping its runtime id, so a mint is
currently unobservable.
Agreed sequencing: make grouping preserve runtime ids **first**, then mint. The north star stays
"the gdd native path is minting, the hash is only polyfill".
### Open items
1. **Deferred dirty-set flush** (step 4 tail). Blocked on the batch boundary above; do not invent
one just to have somewhere to flush into.
2. **Deleting the `queries.rs` wrappers** (step 5). Standing objection: roughly forty one-line
delegations against migrating hundreds of call sites. Not done; reopen only if Dennis disagrees.
3. **Move the module up beside `node_graph/`** (step 6). Pure file shuffle, do it whenever.
4. **Grouping preserving runtime ids**, the prerequisite for minting.
### Complexity
Fixed: `collect_removal_closure` was O(nested networks x all nodes), rescanning `node_instances`
per network; it now uses a `NodesByNetwork` index built once. `construct_resource_removals` was
O(candidates x (nodes + exports)); it now builds a `still_referenced` set in one pass. Dead
plumbing removed along the way (`batch_removed_networks` was computed and never read; `construct`
took `batch_removed_nodes` only to discard it).
Still open, design-level rather than local bugs:
- **`position()` is not memoized.** Each call walks downstream to the first stored absolute
position, so computing positions for many nodes is O(n x depth). A document that is one tall
stack makes `nodes_sorted_top_to_bottom`, and therefore every `shift_nodes`, quadratic. Fixing it
means caching resolved positions against an invalidation epoch.
- **`settle_drag_offsets` and `push_stack_down_to_fit` move one grid row per iteration**, calling
`check_collision_with_stack_dependents` / `vertical_shift_with_push` each time, so cost scales
with the distance moved times a stack walk rather than with node count. Inherent to the
incremental-push model.
### Latent bugs found and left alone
- `reposition_disconnected_upstream` (`layout.rs`): the nested `if` is load-bearing. A layer left
feeding the bottom of a *non-layer* currently does nothing, neither stacks nor goes absolute.
Flattening it changes behaviour, so it was moved verbatim. Looks like a bug, not a deliberate
case.
- `add_export` reaches into `encapsulating_network_metadata_mut(..).transient_metadata` directly to
unload two caches, bypassing `invalidation.rs`. It cannot simply call
`unload_all_nodes_bounding_box`, which *also* invalidates import/export ports, so substituting
would add an invalidation. Needs a decision.
- `add_export` / `add_import` invalidate almost exactly what `finish_signature_edit` does, but in a
different order, with different `load_structure` gates, and `add_export` must handle the root
network. Merging them would be behaviour-changing, not a refactor.
- The dead `lowest_upstream_node_height` loop removed from `move_layer_to_stack` had a `log::error!`
plus `return` that aborted the whole move as a side effect of computing a value nobody read.
Removing it narrows that abort; reinstate as an explicit check if it turns out to matter.
### Gates
- `cargo check -p graphite-editor --all-targets`
- `cargo clippy --workspace --all-targets`, must be **zero** warnings; pre-existing ones were fixed
too, on Dennis's instruction.
- `cargo fmt --all` after every change.
- `cargo test -p graphite-editor` (225 pass, 1 ignored);
`cargo test -p document-graph-storage` (57); `-p document-format -p document-container` (48).
- Wasm gate, needed only when touching `document-container`, `document-format`, `graph-storage` or
the editor `future` module: `nix develop --command cargo run build web debug`, about two minutes.
`wasm-pack` is not on the bare PATH; the flake provides it.
The sharp round-trip gate for identity work is `recommit_after_open_is_stable` in
`storage_tests/round_trip_tests.rs`, plus `verify_round_trip` in `document_history.rs`, which
panics under `#[cfg(test)]` on registry value drift after commit.
### Method note
Extracting named pieces from this code costs roughly as many lines as it saves once signatures, doc
comments and the `-> bool` plumbing that preserves abort-on-error behaviour are counted. Across
three refactors the net was about -38, +5 and +35 lines. Promise readability, not line reduction. A
pedantic clippy sweep on the editor is not worth running: roughly five hundred warnings
workspace-wide, dominated by house-style choices (`&NodeId` parameters, `use super::*`). Take idiom
fixes only in code you are already touching.
## Follow-up PR: storage-driven undo (decided: debug-compare rollout)
Direction: undo/redo stop installing interface snapshots and instead replay deltas returned by the
storage layer, whose retirement machinery already precomputes every delta's reverse and applies it
to the working registry on cursor moves.
Shape agreed in discussion:
1. `Session::undo`/`redo` return the `RegistryDelta` ops they applied (today they are applied and
discarded).
2. A backward projection turns those ops into `EditorDelta`s: slot and export ops via single-input
`to_runtime`; `AddNode`/`AddNetwork` ops materialize nodes from the op payloads (reverses carry
full snapshots, so nothing is missing); attribute ops collapse into one `NodeMetadata` delta
per touched node, read from the post-move registry through the existing `to_runtime` metadata
path; global-to-local IDs resolve via the stashed `original_node_id` attributes.
3. `NodeNetworkInterface::apply_deltas(&[EditorDelta])` maps each variant onto existing mutation
primitives plus a shared cache-invalidation epilogue. Applying must not re-record into the
pending buffer (the ops are already history), so apply runs with recording suppressed; that
suppression flag is the one new piece of interface state.
Rollout decision: **debug-compare**. Legacy snapshot undo remains authoritative while the
storage-driven path runs in parallel, applying to the same interface state and comparing against
the snapshot result; divergence logs in release and panics in tests, mirroring the existing
round-trip soak conventions. Snapshots are deleted only once the compare has been quiet across the
test suite and real use.
Known open points for that PR:
- Compare granularity: full interface equality per undo step is the strongest check and is likely
affordable at undo frequency; decide whether metadata-only divergence should fail equally hard.
- Selection and view state are not in the registry, so storage-driven undo must leave them to the
existing selection-history machinery rather than expecting them back from deltas.
- The same backward projection and apply pair is the future collab receive path; keep signatures
free of undo-specific assumptions.
+4 -1
View File
@@ -249,6 +249,9 @@ fn dot_to_svg(dot: &str) -> Result<String> {
String::from_utf8(output.stdout).with_context(|| "SVG output was not valid UTF-8") String::from_utf8(output.stdout).with_context(|| "SVG output was not valid UTF-8")
} }
/// A Graphviz subgraph cluster: its id, its label, its fill color, and which crates belong to it.
type Cluster = (&'static str, &'static str, &'static str, Box<dyn Fn(&CrateInfo) -> bool>);
fn generate_dot(crates: &[CrateInfo]) -> String { fn generate_dot(crates: &[CrateInfo]) -> String {
let mut out = String::new(); let mut out = String::new();
out.push_str("digraph CrateHierarchy {\n"); out.push_str("digraph CrateHierarchy {\n");
@@ -257,7 +260,7 @@ fn generate_dot(crates: &[CrateInfo]) -> String {
out.push_str(" edge [color=gray];\n\n"); out.push_str(" edge [color=gray];\n\n");
// Define subgraph clusters // Define subgraph clusters
let clusters: &[(&str, &str, &str, Box<dyn Fn(&CrateInfo) -> bool>)] = &[ let clusters: &[Cluster] = &[
( (
"cluster_core", "cluster_core",
"Core Components", "Core Components",