diff --git a/editor/src/messages/clipboard/clipboard_message_handler.rs b/editor/src/messages/clipboard/clipboard_message_handler.rs index 5f59efca86..eead094f35 100644 --- a/editor/src/messages/clipboard/clipboard_message_handler.rs +++ b/editor/src/messages/clipboard/clipboard_message_handler.rs @@ -182,27 +182,35 @@ impl MessageHandler> for Clipboard responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::SendGraph); } - ClipboardMessage::WriteItems { items } => { + ClipboardMessage::WriteItems { mut items } => { let has_content = items.iter().any(|item| match item { ClipboardItem::Layer(entry) => !entry.nodes.is_empty(), ClipboardItem::Nodes(nodes) => !nodes.is_empty(), ClipboardItem::ChainNodes(copies) => !copies.is_empty(), ClipboardItem::Vector(vector) => !vector.is_empty(), ClipboardItem::Resource(_) => true, + ClipboardItem::Definition(_) => false, }); if !has_content { return; } + // The table entries the copied nodes name travel with them, so a paste into another document can add them + let definitions = portfolio + .active_document() + .map(|document| document.network_interface.copied_definitions(items.iter().flat_map(item_templates))) + .unwrap_or_default(); + let mut resource_ids = HashSet::new(); - for item in &items { - match item { - ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)), - ClipboardItem::Nodes(nodes) => nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)), - ClipboardItem::ChainNodes(copies) => copies.iter().for_each(|copy| network_interface::collect_template_resources(©.template, &mut resource_ids)), - ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {} - } + for template in items.iter().flat_map(item_templates) { + network_interface::collect_template_resources(template, &mut resource_ids); } + for definition in &definitions { + network_interface::visit_network_resources(&definition.network, &mut |id| { + resource_ids.insert(id); + }); + } + items.extend(definitions.into_iter().map(|definition| ClipboardItem::Definition(Box::new(definition)))); // Snapshot each resource's registry entry; embedded ones also need their bytes let mut resources = Vec::new(); @@ -225,7 +233,6 @@ impl MessageHandler> for Clipboard } if bytes_to_load.is_empty() { - let mut items = items; items.extend(resources.into_iter().map(ClipboardItem::Resource)); if let Some(content) = serialize_clipboard(&items) { responses.add(ClipboardMessage::Write { content }); @@ -240,7 +247,6 @@ impl MessageHandler> for Clipboard resources[index].data = Some(ResourceData(resource.as_ref().to_vec())); } } - let mut items = items; items.extend(resources.into_iter().map(ClipboardItem::Resource)); match serialize_clipboard(&items) { Some(content) => ClipboardMessage::Write { content }.into(), @@ -263,6 +269,7 @@ impl MessageHandler> for Clipboard let mut chain_node_groups = Vec::new(); let mut vectors = Vec::new(); let mut resources = Vec::new(); + let mut definitions = Vec::new(); for item in items { // Pasted templates skip document migration, so stored types normalize here match item { @@ -286,6 +293,27 @@ impl MessageHandler> for Clipboard } ClipboardItem::Vector(vector) => vectors.push(vector), ClipboardItem::Resource(resource) => resources.push(resource), + ClipboardItem::Definition(definition) => definitions.push(*definition), + } + } + + // The carried table entries go in as the nodes naming them do, renamed where this document holds a different entry under the same ID + if !definitions.is_empty() + && let Some(document) = portfolio.active_document_mut() + { + let Some(renamed) = document.network_interface.carry_definitions(definitions) else { + log::error!("Discarding the paste: its subgraphs name one another in a cycle or name one it does not carry"); + return; + }; + if !renamed.is_empty() { + let templates = layers + .iter_mut() + .flat_map(|entry| entry.nodes.iter_mut().map(|(_, template)| template)) + .chain(node_groups.iter_mut().flatten().map(|(_, template)| template)) + .chain(chain_node_groups.iter_mut().flatten().map(|copy| &mut copy.template)); + for template in templates { + template.rename_definitions(&renamed); + } } } @@ -535,11 +563,23 @@ fn serialize_clipboard(items: &[ClipboardItem]) -> Option { } } +/// The node templates a clipboard item carries. +fn item_templates(item: &ClipboardItem) -> Vec<&network_interface::NodeTemplate> { + match item { + ClipboardItem::Layer(entry) => entry.nodes.iter().map(|(_, template)| template).collect(), + ClipboardItem::Nodes(nodes) => nodes.iter().map(|(_, template)| template).collect(), + ClipboardItem::ChainNodes(copies) => copies.iter().map(|copy| ©.template).collect(), + ClipboardItem::Vector(_) | ClipboardItem::Resource(_) | ClipboardItem::Definition(_) => Vec::new(), + } +} + #[cfg(test)] mod test { use crate::messages::clipboard::utility_types::{ClipboardItem, ClipboardResource, ResourceData}; + use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::test_utils::test_prelude::*; use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId}; + use graph_craft::document::NodeInput; /// Create an editor with three layers /// 1. A red rectangle @@ -702,4 +742,104 @@ mod test { assert!(registry.contains(&id), "the carried resource should be registered after paste"); assert_eq!(registry.hash(&id), Some(hash), "the carried resource should resolve to the carried bytes' hash"); } + + /// The table entry each layer in the active document's network names. + fn layer_entries(editor: &EditorTestUtils) -> Vec { + let mut entries: Vec<_> = editor + .active_document() + .network_interface + .document_network() + .nodes + .values() + .filter_map(|node| match node.implementation { + graph_craft::document::DocumentNodeImplementation::Definition(id) => Some(id), + _ => None, + }) + .collect(); + entries.sort(); + entries + } + + fn assert_consistent(editor: &EditorTestUtils) { + let violations = editor.active_document().network_interface.validate_invariants(); + assert!(violations.is_empty(), "{violations:#?}"); + } + + /// Pasting into the document a layer was copied from shares one network between the copy and the original. + #[tokio::test] + async fn a_pasted_copy_shares_its_network() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + + let clipboard = copy_layers_to_clipboard(&mut editor).await; + paste_from_clipboard(&mut editor, &clipboard).await; + + let entries = layer_entries(&editor); + assert_eq!(entries.len(), 2); + assert_eq!(entries[0], entries[1], "the copy should name the original's entry"); + assert_eq!(editor.active_document().network_interface.document_network().definitions.len(), 1); + assert_consistent(&editor); + } + + /// Pasting into another document adds the copied network under its own ID, and pasting the same content again reuses it. + #[tokio::test] + async fn pasting_into_another_document_carries_the_network() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + let copied = layer_entries(&editor); + let clipboard = copy_layers_to_clipboard(&mut editor).await; + + editor.new_document().await; + paste_from_clipboard(&mut editor, &clipboard).await; + assert_eq!(layer_entries(&editor), copied); + assert_consistent(&editor); + + paste_from_clipboard(&mut editor, &clipboard).await; + assert_eq!(layer_entries(&editor), [copied.clone(), copied].concat(), "identical content should be reused"); + assert_eq!(editor.active_document().network_interface.document_network().definitions.len(), 1); + assert_consistent(&editor); + } + + /// Pasting a network that differs from the one this document holds under the same ID adds it under a fresh ID instead. + #[tokio::test] + async fn pasting_a_diverged_network_gives_it_a_new_id() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + let clipboard = copy_layers_to_clipboard(&mut editor).await; + + editor.new_document().await; + paste_from_clipboard(&mut editor, &clipboard).await; + let [entry] = layer_entries(&editor)[..] else { panic!("the paste should add one layer") }; + + // Diverge the pasted entry from the copied one + let interface = &mut editor.active_document_mut().network_interface; + let layer = interface + .document_network() + .nodes + .iter() + .find_map(|(id, node)| (node.implementation == graph_craft::document::DocumentNodeImplementation::Definition(entry)).then_some(*id)) + .expect("the pasted layer"); + let (inner, input_index) = interface.document_network().definitions[&entry] + .nodes + .iter() + .find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index))) + .expect("the entry should have a value input"); + let before = interface.document_network().definitions[&entry].clone(); + let NodeInput::Value { tagged_value, exposed } = &before.nodes[&inner].inputs[input_index] else { + unreachable!("the input was found as a value") + }; + let flipped = NodeInput::value((**tagged_value).clone(), !exposed); + interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[layer]); + assert_ne!(interface.document_network().definitions[&entry], before, "the edit should change the pasted entry"); + + paste_from_clipboard(&mut editor, &clipboard).await; + let entries = layer_entries(&editor); + assert_eq!(entries.len(), 2); + assert!(entries.contains(&entry)); + assert_ne!(entries[0], entries[1], "the diverged entry should not be overwritten or reused"); + assert_consistent(&editor); + } } diff --git a/editor/src/messages/clipboard/utility_types.rs b/editor/src/messages/clipboard/utility_types.rs index fb8689d992..d79bf9015a 100644 --- a/editor/src/messages/clipboard/utility_types.rs +++ b/editor/src/messages/clipboard/utility_types.rs @@ -1,5 +1,5 @@ use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; -use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate}; +use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, CopiedDefinition, NodeTemplate}; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64; use glam::DAffine2; @@ -31,6 +31,8 @@ pub enum ClipboardItem { ChainNodes(Vec), Vector(Vec), Resource(ClipboardResource), + /// A definitions table entry the copied nodes name, listed after the entries it names. + Definition(Box), } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index c5660d5618..53d3843d4b 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -242,6 +242,9 @@ pub enum DocumentMessage { SetSnappingAngleStep { degrees: f64, }, + MakeNodeUnique { + node_id: NodeId, + }, SetToNodeOrLayer { node_id: NodeId, is_layer: bool, diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 45eaaf01f1..c530084d4b 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -1617,6 +1617,11 @@ impl MessageHandler> for DocumentMes } responses.add(PortfolioMessage::UpdateDocumentWidgets); } + DocumentMessage::MakeNodeUnique { node_id } => { + responses.add(DocumentMessage::StartTransaction); + responses.add(NodeGraphMessage::MakeUnique { node_id }); + responses.add(DocumentMessage::EndTransaction); + } DocumentMessage::SetToNodeOrLayer { node_id, is_layer } => { responses.add(DocumentMessage::StartTransaction); responses.add(NodeGraphMessage::SetToNodeOrLayer { node_id, is_layer }); diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs index 086efdfd64..792ba1ccf9 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs @@ -235,6 +235,10 @@ pub enum NodeGraphMessage { network_path: Vec, alias: String, }, + /// Gives the node its own copy of the network it shares with other nodes. + MakeUnique { + node_id: NodeId, + }, SetToNodeOrLayer { node_id: NodeId, is_layer: bool, diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index 2a5399bab2..8f82092bfe 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -1042,6 +1042,7 @@ impl<'a> MessageHandler> for NodeG node_id, has_selected_layers, all_selected_layers_locked, + is_shared: network_interface.is_shared(&node_id, selection_network_path), } } else { ContextMenuData::CreateNode { compatible_type: None } @@ -2204,6 +2205,18 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::SendWires); } + NodeGraphMessage::MakeUnique { node_id } => { + if !network_interface.make_unique(&node_id, selection_network_path) { + return; + } + + self.context_menu = None; + responses.add(FrontendMessage::UpdateContextMenuInformation { + context_menu_information: self.context_menu.clone(), + }); + responses.add(NodeGraphMessage::RunDocumentGraph); + responses.add(NodeGraphMessage::SendGraph); + } NodeGraphMessage::SetToNodeOrLayer { node_id, is_layer } => { if is_layer && !network_interface.is_eligible_to_be_layer(&node_id, selection_network_path) { return; diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index 2a11dd4a3d..1cfe807395 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -159,6 +159,9 @@ pub enum ContextMenuData { has_selected_layers: bool, #[serde(rename = "allSelectedLayersLocked")] all_selected_layers_locked: bool, + /// Whether the node names a table entry other nodes name too, which "Make Unique" gives it its own copy of. + #[serde(rename = "isShared")] + is_shared: bool, }, CreateNode { #[serde(rename = "compatibleType")] diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface.rs b/editor/src/messages/portfolio/document/utility_types/network_interface.rs index b788697f3b..e640a4ce98 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -103,6 +103,9 @@ pub struct NodeNetworkInterface { /// Only these are judged, so a Passthrough left without a wire by anything other than an edit (like one a migration made from a removed node) is left in place. #[serde(skip)] dots_that_lost_a_wire: HashMap, HashSet<(NodeId, DotSide)>>, + /// The table entries the last paste carried, under the IDs they take here, added once a node names one. + #[serde(skip)] + carried_definitions: HashMap, } impl Clone for NodeNetworkInterface { @@ -118,6 +121,7 @@ impl Clone for NodeNetworkInterface { transaction_edited_nodes_scanned: 0, transaction_edited_nodes_changed: false, dots_that_lost_a_wire: HashMap::new(), + carried_definitions: HashMap::new(), } } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs index a43d54b475..327ee5dcc5 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs @@ -892,17 +892,30 @@ async fn an_edit_inside_a_table_entry_constructs_the_diff() { assert_same_stored_effect(&working, constructed, diffed, "edit inside a table entry"); } -/// A template of a node that names a table entry carries a copy of the entry, so it also works where the entry does not exist. +/// A template of a node that names a table entry names it too, so a copy shares the entry. #[tokio::test] -async fn a_template_of_a_table_node_stands_alone() { +async fn a_template_of_a_table_node_names_its_entry() { let mut editor = EditorTestUtils::create(); editor.new_document().await; editor.draw_rect(0., 0., 100., 100.).await; - let (layer, _) = table_layer(&editor); + let (layer, definition) = table_layer(&editor); let template = editor.active_document().network_interface.create_node_template(&layer, &[]).expect("template"); let (node, _) = template.into_parts(); - assert!(matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_))); + assert_eq!(node.implementation, graph_craft::document::DocumentNodeImplementation::Definition(definition)); +} + +/// A template of `node_id` that carries its table entry inline, as one from before networks moved into the table does. +fn inline_copy(interface: &super::NodeNetworkInterface, node_id: NodeId) -> super::NodeTemplate { + let mut node = interface.document_network().nodes[&node_id].clone(); + let mut metadata = interface.network_metadata.persistent_metadata.node_metadata[&node_id].persistent_metadata.clone(); + let graph_craft::document::DocumentNodeImplementation::Definition(id) = node.implementation else { + panic!("the node should name a table entry") + }; + + node.implementation = graph_craft::document::DocumentNodeImplementation::Network(interface.document_network().definitions[&id].clone()); + metadata.network_metadata = Some(interface.network_metadata.persistent_metadata.definitions[&id].clone()); + super::NodeTemplate::from_parts(node, metadata) } /// A write inside an instance stays with the network it was made in, even when the instance changes implementation later in the same batch. @@ -918,7 +931,7 @@ async fn a_write_keeps_its_network_when_the_instance_changes_implementation() { interface.discard_deltas(); interface.set_input(&InputConnector::node_at_index(inner, input_index), NodeInput::value(TaggedValue::None, false), &[layer]); - let mut inline_copy = interface.create_node_template(&layer, &[]).expect("template"); + let mut inline_copy = inline_copy(interface, layer); interface.replace_implementation(&layer, &[], &mut inline_copy); let deltas = interface.take_deltas(); @@ -933,6 +946,7 @@ fn insert_shared_copy(editor: &mut EditorTestUtils, layer: NodeId) -> NodeId { let copy = NodeId::new(); interface.insert_node_entry(super::NodeLocator::new(copy, &[]), super::NodeTemplate::from_parts(node, metadata)); + interface.unload_outward_wires(&[]); interface.settle_definitions(); copy } @@ -962,7 +976,7 @@ async fn inserting_a_nested_network_stages_incrementally() { editor.draw_rect(0., 0., 100., 100.).await; let (layer, _) = table_layer(&editor); - let inline_copy = editor.active_document().network_interface.create_node_template(&layer, &[]).expect("template"); + let inline_copy = inline_copy(&editor.active_document().network_interface, layer); let emitted = assert_stages_incrementally(&mut editor, "insert a nested network", |editor| { let interface = &mut editor.active_document_mut().network_interface; interface.insert_node_entry(super::NodeLocator::new(NodeId::new(), &[]), inline_copy); @@ -1025,7 +1039,7 @@ async fn replaying_an_insertion_that_lifts_reproduces_the_interface() { assert_replay_reproduces(|editor| { let group = only_group(editor); let interface = &mut editor.active_document_mut().network_interface; - let inline_copy = interface.create_node_template(&group, &[]).expect("template"); + let inline_copy = inline_copy(interface, group); interface.insert_node_entry(super::NodeLocator::new(NodeId(0x11F7), &[]), inline_copy); }) .await; @@ -1057,7 +1071,7 @@ async fn a_resource_an_entry_exports_follows_the_entry() { registry.resolve(&resource, ResourceHash::from(&b"exported bytes"[..])); let (layer, _) = table_layer(&editor); - let template = editor.active_document().network_interface.create_node_template(&layer, &[]).expect("template"); + let template = inline_copy(&editor.active_document().network_interface, layer); let (mut node, metadata) = template.into_parts(); let graph_craft::document::DocumentNodeImplementation::Network(network) = &mut node.implementation else { panic!("the template should carry the layer's network inline") @@ -1099,3 +1113,84 @@ async fn a_resource_exported_and_removed_in_one_batch_leaves_nothing_behind() { interface.delete_nodes(vec![layer], true, &[]); }); } + +/// Making one of two instances unique gives it its own copy of the network, so an edit inside it no longer reaches the other. +#[tokio::test] +async fn making_an_instance_unique_forks_its_network() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + + let (layer, definition) = table_layer(&editor); + let copy = insert_shared_copy(&mut editor, layer); + assert!(editor.active_document().network_interface.is_shared(©, &[])); + + assert_stages_incrementally(&mut editor, "make an instance unique", |editor| { + assert!(editor.active_document_mut().network_interface.make_unique(©, &[])); + }); + + let interface = &editor.active_document().network_interface; + let graph_craft::document::DocumentNodeImplementation::Definition(forked) = interface.document_network().nodes[©].implementation else { + panic!("the copy should still name a table entry") + }; + assert_ne!(forked, definition); + assert!(!interface.is_shared(©, &[]) && !interface.is_shared(&layer, &[])); + + let (inner, input_index) = value_input_inside(&editor, forked); + let original = editor.active_document().network_interface.document_network().definitions[&definition].clone(); + let interface = &mut editor.active_document_mut().network_interface; + let NodeInput::Value { tagged_value, exposed } = &interface.document_network().definitions[&forked].nodes[&inner].inputs[input_index] else { + unreachable!("the input was found as a value") + }; + let flipped = NodeInput::value((**tagged_value).clone(), !exposed); + interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[copy]); + + assert_ne!(interface.document_network().definitions[&forked], original, "the edit should change the copy's network"); + assert_eq!(interface.document_network().definitions[&definition], original, "the original's network should be untouched"); +} + +/// Carried subgraphs that name one another in a cycle are refused, since inserting them would never finish. +#[tokio::test] +async fn a_cyclic_paste_is_refused() { + use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NodeNetwork}; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let (first, second) = (NetworkId::new(), NetworkId::new()); + let naming = |id| super::CopiedDefinition { + id: if id == first { second } else { first }, + network: NodeNetwork { + nodes: [( + NodeId(0), + DocumentNode { + implementation: DocumentNodeImplementation::Definition(id), + ..Default::default() + }, + )] + .into_iter() + .collect(), + ..Default::default() + }, + metadata: Default::default(), + }; + + let interface = &mut editor.active_document_mut().network_interface; + assert!(interface.carry_definitions(vec![naming(first), naming(second)]).is_none()); +} + +/// Making an instance unique marks the open transaction as modified, so the transaction commits rather than cancels. +#[tokio::test] +async fn making_an_instance_unique_modifies_the_transaction() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + + let (layer, _) = table_layer(&editor); + let copy = insert_shared_copy(&mut editor, layer); + + let interface = &mut editor.active_document_mut().network_interface; + interface.start_transaction(); + assert!(interface.make_unique(©, &[])); + assert_eq!(interface.transaction_status(), super::TransactionStatus::Modified); +} diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs index d3cc7c7d64..8afa13d2d0 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs @@ -394,6 +394,15 @@ impl NodeNetworkInterface { } } + /// Gives the node its own copy of the network it shares with other nodes, returning whether it had one to copy. + pub fn make_unique(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> bool { + let forked = self.fork_definition(NodeLocator::new(*node_id, network_path)); + if forked { + self.transaction_modified(); + } + forked + } + /// Replaces the implementation and corresponding metadata. pub fn replace_implementation(&mut self, node_id: &NodeId, network_path: &[NodeId], new_template: &mut NodeTemplate) { let (new_implementation, new_network_metadata) = std::mem::take(&mut new_template.implementation).into_parts(); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs index 398867fc3c..96264fb7e1 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs @@ -468,6 +468,69 @@ impl NodeNetworkInterface { new_nodes.into_iter().map(move |(new, node_id, node)| (new, self.map_ids(node, &node_id, new_ids, network_path))) } + /// The table entries `templates` name, directly or through other entries, each listed after the entries it names. + pub fn copied_definitions<'a>(&self, templates: impl IntoIterator) -> Vec { + let mut named = Vec::new(); + for template in templates { + template.named_definitions(&mut named); + } + + let mut ordered = Vec::new(); + let mut visited = HashSet::new(); + for id in named { + self.order_definitions_named_by(id, &mut visited, &mut ordered); + } + + ordered + .into_iter() + .filter_map(|id| { + Some(CopiedDefinition { + id, + network: self.document_network().definitions.get(&id)?.clone(), + metadata: self.network_metadata.persistent_metadata.definitions.get(&id)?.clone(), + }) + }) + .collect() + } + + /// Appends `id` to `ordered` after every entry it names, skipping entries already visited. + fn order_definitions_named_by(&self, id: NetworkId, visited: &mut HashSet, ordered: &mut Vec) { + if !visited.insert(id) { + return; + } + let Some(network) = self.document_network().definitions.get(&id) else { return }; + + let mut named: Vec = network + .nodes + .values() + .filter_map(|node| match node.implementation { + DocumentNodeImplementation::Definition(named) => Some(named), + _ => None, + }) + .collect(); + named.sort(); + for named in named { + self.order_definitions_named_by(named, visited, ordered); + } + ordered.push(id); + } + + /// Whether the node names a table entry that another node names too. + pub fn is_shared(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool { + let Some(location) = self.locate(network_path) else { return false }; + let network = self.document_network(); + let Some(DocumentNodeImplementation::Definition(id)) = network.located_network(location).and_then(|located| located.nodes.get(node_id)).map(|node| &node.implementation) else { + return false; + }; + + let naming = std::iter::once(network) + .chain(network.definitions.values()) + .flat_map(|network| network.nodes.values()) + .filter(|node| node.implementation == DocumentNodeImplementation::Definition(*id)) + .count(); + naming > 1 + } + /// Create a node template from an existing node. pub fn create_node_template(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option { self.query(network_path, "create_node_template", |view| view.create_node_template(node_id)) diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs index 95f7cd7633..dbf2086e79 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs @@ -340,6 +340,9 @@ impl NodeNetworkInterface { let (mut document_node, mut persistent_metadata) = template.into_parts(); self.lift_into_table(&mut document_node.implementation, &mut persistent_metadata.network_metadata); + if let DocumentNodeImplementation::Definition(id) = document_node.implementation { + self.insert_carried_definition(id); + } let node = Box::new(document_node.clone()); let metadata = Box::new(persistent_metadata.clone()); @@ -423,6 +426,9 @@ impl NodeNetworkInterface { self.lift_into_table(&mut implementation, &mut network_metadata); } + if let DocumentNodeImplementation::Definition(id) = implementation { + self.insert_carried_definition(id); + } let Some(mut node) = self.node_mut_at(location, locator.node_id) else { log::error!("Could not get node {} in replace_node_implementation", locator.node_id); @@ -454,6 +460,19 @@ impl NodeNetworkInterface { /// Adds the definitions table entry `id` with its metadata, recording the network and then the metadata of it and its nodes. pub(crate) fn insert_definition(&mut self, id: NetworkId, network: NodeNetwork, metadata: NodeNetworkMetadata) { + let mut named: Vec = network + .nodes + .values() + .filter_map(|node| match node.implementation { + DocumentNodeImplementation::Definition(named) => Some(named), + _ => None, + }) + .collect(); + named.sort(); + for named in named { + self.insert_carried_definition(named); + } + let location = OwnedNetworkLocation::definition(id); self.deltas.push(EditorDelta::Graph(RuntimeDelta::AddNetwork { id, @@ -491,6 +510,86 @@ impl NodeNetworkInterface { self.network_metadata.get_mut().persistent_metadata.definitions.insert(id, metadata); } + /// Takes the table entries a paste carries, each listed after the entries it names, and returns the new ID of every entry that has to be renamed. + /// + /// An entry the document already holds with the same content is reused. One it holds with different content goes in under a fresh ID. + /// Nothing is added yet: each entry goes in once a node names it, so it lands in the same transaction as that node. + /// + /// Returns `None` for a list that names an entry before listing it, which no copy produces and which a cycle always does. + pub(crate) fn carry_definitions(&mut self, definitions: Vec) -> Option> { + let mut listed = HashSet::new(); + for definition in &definitions { + let names_unlisted = definition.network.nodes.values().any(|node| match node.implementation { + DocumentNodeImplementation::Definition(named) => !listed.contains(&named) && !self.document_network().definitions.contains_key(&named), + _ => false, + }); + if names_unlisted { + return None; + } + listed.insert(definition.id); + } + + let mut renamed = HashMap::new(); + let mut carried = HashMap::new(); + for CopiedDefinition { id, mut network, metadata } in definitions { + for node in network.nodes.values_mut() { + if let DocumentNodeImplementation::Definition(named) = &mut node.implementation + && let Some(new_id) = renamed.get(named) + { + *named = *new_id; + } + } + + let held = self.document_network().definitions.get(&id).zip(self.network_metadata.persistent_metadata.definitions.get(&id)); + let id = match held { + Some((held_network, held_metadata)) if *held_network != network || !same_content(&held_metadata.persistent_metadata, &metadata.persistent_metadata) => { + let new_id = NetworkId::new(); + renamed.insert(id, new_id); + new_id + } + _ => id, + }; + carried.insert(id, CopiedDefinition { id, network, metadata }); + } + + self.carried_definitions = carried; + Some(renamed) + } + + /// Gives the node its own copy of the table entry it names, leaving the entries nested in it shared. + pub(crate) fn fork_definition(&mut self, locator: NodeLocator) -> bool { + let Some(location) = self.locate(locator.network_path) else { return false }; + let Some(DocumentNodeImplementation::Definition(id)) = self + .document_network() + .located_network(location) + .and_then(|network| network.nodes.get(&locator.node_id)) + .map(|node| node.implementation.clone()) + else { + return false; + }; + let Some(network) = self.document_network().definitions.get(&id).cloned() else { return false }; + let Some(metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else { + return false; + }; + + let unique = NetworkId::new(); + self.insert_definition(unique, network, metadata); + let Some(mut node) = self.node_mut_at(location, locator.node_id) else { return false }; + node.replace_implementation(DocumentNodeImplementation::Definition(unique)); + true + } + + /// Adds the carried table entry `id` if the document does not hold it. + fn insert_carried_definition(&mut self, id: NetworkId) { + if self.document_network().definitions.contains_key(&id) { + return; + } + let Some(CopiedDefinition { network, metadata, .. }) = self.carried_definitions.get(&id).cloned() else { + return; + }; + self.insert_definition(id, network, metadata); + } + /// Drops the definitions table entry `id` from both trees. pub(crate) fn remove_definition(&mut self, id: NetworkId) { let removed = self.network.get_mut().network_mut().definitions.remove(&id).is_some(); @@ -592,6 +691,18 @@ impl NodeNetworkInterface { } } +/// Whether two networks' metadata describe the same content, ignoring this peer's view of them. +fn same_content(first: &NodeNetworkPersistentMetadata, second: &NodeNetworkPersistentMetadata) -> bool { + let content = |metadata: &NodeNetworkPersistentMetadata| NodeNetworkPersistentMetadata { + previewing: Previewing::No, + navigation_metadata: NavigationMetadata::default(), + selection_undo_history: VecDeque::new(), + selection_redo_history: VecDeque::new(), + ..metadata.clone() + }; + content(first) == content(second) +} + /// Whether any of `descriptions` says anything, since storage keeps the whole list then, but not a list that's all empty. fn has_description(descriptions: &[String]) -> bool { descriptions.iter().any(|description| !description.is_empty()) diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs index 494d95ff3b..96212c1fd7 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs @@ -234,6 +234,28 @@ impl NodeTemplate { (document_node, persistent_node_metadata) } + /// Every definitions table entry the template names, including through the nested templates it carries. + pub fn named_definitions(&self, named: &mut Vec) { + match &self.implementation { + NodeTemplateImplementation::Definition(id) => named.push(*id), + NodeTemplateImplementation::Network(network_template) => network_template.nodes.values().for_each(|nested_template| nested_template.named_definitions(named)), + NodeTemplateImplementation::ProtoNode(_) | NodeTemplateImplementation::Extract => {} + } + } + + /// Points every table entry the template names at its new ID in `renamed`, including through the nested templates it carries. + pub fn rename_definitions(&mut self, renamed: &HashMap) { + match &mut self.implementation { + NodeTemplateImplementation::Definition(id) => { + if let Some(new_id) = renamed.get(id) { + *id = *new_id; + } + } + NodeTemplateImplementation::Network(network_template) => network_template.nodes.values_mut().for_each(|nested_template| nested_template.rename_definitions(renamed)), + NodeTemplateImplementation::ProtoNode(_) | NodeTemplateImplementation::Extract => {} + } + } + /// Resizes `input_metadata` to match `inputs` at every nesting level, filling gaps with defaults. pub fn normalize_input_metadata(&mut self) { self.input_metadata.resize_with(self.inputs.len(), InputMetadata::default); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs index 502ac61859..e994e6fed5 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs @@ -504,6 +504,14 @@ impl<'de> serde::Deserialize<'de> for Previewing { } } +/// A definitions table entry carried by a copy, so a paste into a document that lacks it can add it. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct CopiedDefinition { + pub id: NetworkId, + pub network: NodeNetwork, + pub metadata: NodeNetworkMetadata, +} + /// All fields in NetworkMetadata should automatically be updated by using the network interface API. If a field is none then it should be calculated based on the network state. #[derive(Debug, Default, serde::Serialize, serde::Deserialize)] pub struct NodeNetworkMetadata { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs index 67eb6dc553..f1fbe207ea 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs @@ -456,49 +456,10 @@ impl<'a, 'p> NetworkView<'a, 'p> { pinned_nodes } - /// Create a node template from an existing node, carrying a copy of every definition it reaches so the template stands alone. + /// Create a node template from an existing node. A node that names a table entry keeps naming it, so a copy shares the entry. pub fn create_node_template(&self, node_id: &NodeId) -> Result { - let mut node = self.node(node_id)?.clone(); - let mut node_metadata = self.node_metadata(node_id)?.persistent_metadata.clone(); - self.interface.inline_node_definitions(&mut node, &mut node_metadata); - + let node = self.node(node_id)?.clone(); + let node_metadata = self.node_metadata(node_id)?.persistent_metadata.clone(); Ok(NodeTemplate::from_parts(node, node_metadata)) } } - -impl NodeNetworkInterface { - fn inline_node_definitions(&self, node: &mut DocumentNode, metadata: &mut DocumentNodePersistentMetadata) { - self.inline_node_definitions_within(node, metadata, &mut Vec::new()); - } - - fn inline_node_definitions_within(&self, node: &mut DocumentNode, metadata: &mut DocumentNodePersistentMetadata, enclosing: &mut Vec) { - let inlined = match node.implementation { - DocumentNodeImplementation::Definition(id) => { - if enclosing.contains(&id) { - log::error!("Definition {id:?} reaches itself, so a template of it cannot carry a copy"); - return; - } - let (Some(definition), Some(definition_metadata)) = (self.document_network().definitions.get(&id), self.network_metadata.persistent_metadata.definitions.get(&id)) else { - log::error!("Definition {id:?} is missing from the definitions table"); - return; - }; - node.implementation = DocumentNodeImplementation::Network(definition.clone()); - metadata.network_metadata = Some(definition_metadata.clone()); - enclosing.push(id); - Some(id) - } - _ => None, - }; - - if let (DocumentNodeImplementation::Network(network), Some(network_metadata)) = (&mut node.implementation, &mut metadata.network_metadata) { - for (child_id, child) in &mut network.nodes { - let child_metadata = network_metadata.persistent_metadata.node_metadata.entry(*child_id).or_default(); - self.inline_node_definitions_within(child, &mut child_metadata.persistent_metadata, enclosing); - } - } - - if inlined.is_some() { - enclosing.pop(); - } - } -} diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index c08e5ec069..0a8930f250 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -379,6 +379,17 @@ disabled={!$nodeGraph.contextMenuInformation.contextMenuData.data.canBeLayer} flush={true} /> + {#if $nodeGraph.contextMenuInformation.contextMenuData.data.isShared} + {@const nodeId = $nodeGraph.contextMenuInformation.contextMenuData.data.nodeId} + { + editor.makeNodeUnique(nodeId); + closeContextMenu(); + }} + flush={true} + /> + {/if} {#if $nodeGraph.contextMenuInformation.contextMenuData.data.hasSelectedLayers} {@const allLocked = $nodeGraph.contextMenuInformation.contextMenuData.data.allSelectedLayersLocked} {@const nodeId = $nodeGraph.contextMenuInformation.contextMenuData.data.nodeId} diff --git a/frontend/wrapper/src/editor_commands.rs b/frontend/wrapper/src/editor_commands.rs index a9f2d20164..a9a609c173 100644 --- a/frontend/wrapper/src/editor_commands.rs +++ b/frontend/wrapper/src/editor_commands.rs @@ -756,6 +756,11 @@ mod editor_commands { DocumentMessage::SetActivePanel { active_panel: panel.into() }.into() } + /// Give a node its own copy of the network it shares with other nodes + fn make_node_unique(id: u64) -> Message { + DocumentMessage::MakeNodeUnique { node_id: NodeId(id) }.into() + } + /// Toggle display type for a layer fn set_to_node_or_layer(id: u64, is_layer: bool) -> Message { DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()