Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -139,18 +139,6 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
},
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
xy: Option<(i32, i32)>,
add_transaction: bool,
},
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
CreateEmptySubgraph {
node_id: Option<NodeId>,
xy: Option<(i32, i32)>,
},
CreateWire {
output_connector: OutputConnector,
input_connector: InputConnector,
Expand Down Expand Up @@ -383,6 +388,7 @@ impl NodeGraphMessage {
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
Self::AddNodes { .. }
| Self::CreateNodeFromContextMenu { .. }
| Self::CreateEmptySubgraph { .. }
| Self::CreateWire { .. }
| Self::CreateWires { .. }
| Self::ConnectUpstreamOutputToInput { .. }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
TransactionStatus,
};
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
Expand Down Expand Up @@ -422,6 +423,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
});
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
let node_id = node_id.unwrap_or_else(NodeId::new);
let (x, y) = xy.unwrap_or_else(|| {
network_interface
.node_graph_ptz(breadcrumb_network_path)
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
});

responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id,
node_template: Box::new(NodeTemplate::empty_subgraph()),
});
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
log::error!("Failed to find upstream node for downstream_input");
Expand Down Expand Up @@ -769,24 +787,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}

// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
let encapsulating_node_id = NodeId::new();
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
let mut subgraph_template = NodeTemplate::empty_subgraph();
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
log::error!("Could not get center of selected_nodes");
return;
};
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id: encapsulating_node_id,
node_template: Box::new(default_node_template),
});
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: encapsulating_node_id,
network_path: selection_network_path.to_vec(),
alias: "Untitled Node".to_string(),
node_template: Box::new(subgraph_template),
});

responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
Expand Down Expand Up @@ -3426,6 +3439,13 @@ impl NodeGraphMessageHandler {
})
.disabled(read_only)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("New Custom Node")
.tooltip_label("New Custom Node")
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
.disabled(read_only)
.widget_instance(),
//
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
//
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::template::NodeTemplateImplementation;
use super::template::{NodeTemplate, NodeTemplateImplementation};
use super::{InputConnector, OutputConnector, catalog};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
Expand Down Expand Up @@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);

Expand Down Expand Up @@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
let custom = NodeId::new();
let blend = NodeId::new();
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
panic!("the Blend should name a table entry")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;

let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let path = [subgraph];
editor.enter_editable_network(subgraph).await;

Expand Down Expand Up @@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire

/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddImport).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
Expand Down Expand Up @@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
);
}

#[tokio::test]
async fn a_new_subgraph_is_its_own_definition() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;

let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &editor.active_document().network_interface;
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
}

#[tokio::test]
async fn cannot_preview_node_without_outputs() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;

let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;

assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);

// Attempting to toggle preview on a node without outputs should not enable previewing
network_interface.toggle_preview(custom_node, &[]);
network_interface.toggle_preview(subgraph, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 +802,7 @@ impl NodeNetworkInterface {
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
}

/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
self.reference(node_id, network_path)
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
Expand Down Expand Up @@ -875,16 +875,16 @@ impl NodeNetworkInterface {
node.set_widget_override(index, widget_override);
}

/// 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.
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string())
.unwrap_or_else(|| "Subgraph".to_string())
}

/// The uneditable name in the Inspector which represents the function name of the node implementation.
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string())
.unwrap_or_else(|| "Subgraph".to_string())
}

pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ pub struct NodeTemplate {
}

impl NodeTemplate {
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
pub fn empty_subgraph() -> Self {
Self {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
}
}

/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
self.inputs.get(P::INDEX)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
.ok()
.flatten()
.map(|identifier| identifier.implementation_name_from_identifier())
.unwrap_or("Custom Node".to_string())
.unwrap_or("Subgraph".to_string())
}

/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
Expand Down
62 changes: 61 additions & 1 deletion editor/src/messages/portfolio/document_migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}

// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
.network_interface
Expand Down Expand Up @@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.collect();

migrate_custom_node_subgraphs(document);

// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
let nodes = document
.network_interface
Expand Down Expand Up @@ -4045,6 +4047,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(())
}

/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
.map(|(node_id, _, path)| (*node_id, path))
.collect();

for (node_id, network_path) in subgraphs {
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
document.network_interface.set_reference(&node_id, &network_path, None);
}
}

/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
Expand Down Expand Up @@ -4597,6 +4618,45 @@ mod tests {
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
}

#[tokio::test]
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;

let mut editor = EditorTestUtils::create();
editor.new_document().await;
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
let document = editor.active_document_mut();
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
panic!("the subgraph should name a definitions table entry")
};

// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
let from_merging = NodeId::new();
let instance = NodeTemplate {
implementation: NodeTemplateImplementation::Definition(shared),
..Default::default()
};
document.network_interface.insert_node(from_merging, instance, &[]);
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
let serialized = document.serialize_document();

let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
for node_id in [from_catalog, from_merging] {
assert!(
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
"the subgraph should still exist"
);
assert_eq!(interface.reference(&node_id, &[]), None);
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
}
}

#[tokio::test]
async fn a_rasterize_node_on_the_export_compiles() {
use crate::test_utils::test_prelude::*;
Expand Down
11 changes: 11 additions & 0 deletions editor/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,17 @@ impl EditorTestUtils {
self.create_node(node_type, Some((x, y))).await
}

/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
node_id: Some(node_id),
xy: Some((x, y)),
})
.await;
node_id
}

async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
Expand Down
Loading
Loading