diff --git a/Cargo.lock b/Cargo.lock index 53d40c8184..7b89c356b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2912,6 +2912,7 @@ dependencies = [ "glam", "graph-craft", "graph-layout", + "graph-ui", "graphene-hash", "graphene-std", "graphite-proc-macros", diff --git a/editor/Cargo.toml b/editor/Cargo.toml index 96fd16e294..bab20f065e 100644 --- a/editor/Cargo.toml +++ b/editor/Cargo.toml @@ -14,7 +14,7 @@ publish.workspace = true workspace = true [features] -wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"] +wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "graph-ui/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"] [dependencies] # Local dependencies @@ -35,6 +35,7 @@ preprocessor = { workspace = true } math-parser = { workspace = true } snapping = { workspace = true } wgpu-executor = { workspace = true } +graph-ui = { workspace = true, features = ["serde"] } # Workspace dependencies js-sys = { workspace = true } diff --git a/editor/src/consts.rs b/editor/src/consts.rs index 10259f30ec..33c06404fc 100644 --- a/editor/src/consts.rs +++ b/editor/src/consts.rs @@ -1,5 +1,5 @@ // GRAPH -pub const GRID_SIZE: u32 = 24; +pub const GRID_SIZE: u32 = graph_ui::metrics::GRID_SIZE as u32; pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2; pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72; pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120; @@ -11,8 +11,6 @@ pub const STACK_VERTICAL_GAP: i32 = 3; pub const LAYER_INDENT_OFFSET: i32 = 8; /// Horizontal grid width of a non-layer node in a chain. pub const NODE_CHAIN_WIDTH: i32 = 7; -/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance. -pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.; // VIEWPORT pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.; diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index 77e22afd16..83d8c8211e 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -80,10 +80,8 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[ MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( NodeGraphMessageDiscriminant::UpdateLayerPanel, ))), - MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))), - MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))), MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( - NodeGraphMessageDiscriminant::UpdateVisibleNodes, + NodeGraphMessageDiscriminant::UpdateLayersInView, ))), MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( NodeGraphMessageDiscriminant::SendSelectedNodes, diff --git a/editor/src/messages/dialog/preferences_dialog/preferences_dialog_message_handler.rs b/editor/src/messages/dialog/preferences_dialog/preferences_dialog_message_handler.rs index 2edeb78534..c9a9bf5140 100644 --- a/editor/src/messages/dialog/preferences_dialog/preferences_dialog_message_handler.rs +++ b/editor/src/messages/dialog/preferences_dialog/preferences_dialog_message_handler.rs @@ -1,8 +1,8 @@ use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE}; use crate::messages::layout::utility_types::widget_prelude::*; -use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::messages::preferences::SelectionMode; use crate::messages::prelude::*; +use graph_ui::wire::WireStyle; #[derive(ExtractField)] pub struct PreferencesDialogMessageContext<'a> { @@ -254,16 +254,16 @@ impl PreferencesDialogMessageHandler { .widget_instance(), ]; let graph_wire_style = RadioInput::new(vec![ - RadioEntryData::new(GraphWireStyle::Direct.to_string()) - .label(GraphWireStyle::Direct.to_string()) - .tooltip_label(GraphWireStyle::Direct.to_string()) - .tooltip_description(GraphWireStyle::Direct.tooltip_description()) - .on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::Direct }.into()), - RadioEntryData::new(GraphWireStyle::GridAligned.to_string()) - .label(GraphWireStyle::GridAligned.to_string()) - .tooltip_label(GraphWireStyle::GridAligned.to_string()) - .tooltip_description(GraphWireStyle::GridAligned.tooltip_description()) - .on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()), + RadioEntryData::new("Direct") + .label("Direct") + .tooltip_label("Direct") + .tooltip_description("Wires bend to run at an angle directly between nodes.") + .on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::Direct }.into()), + RadioEntryData::new("Grid-Aligned") + .label("Grid-Aligned") + .tooltip_label("Grid-Aligned") + .tooltip_description("Wires follow the grid, running in straight lines between nodes.") + .on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::GridAligned }.into()), ]) .selected_index(Some(preferences.graph_wire_style as u32)) .sizing(WidgetSizing::default().shrink(false)) diff --git a/editor/src/messages/frontend/frontend_message.rs b/editor/src/messages/frontend/frontend_message.rs index dbbe23cac6..ad449d6ce2 100644 --- a/editor/src/messages/frontend/frontend_message.rs +++ b/editor/src/messages/frontend/frontend_message.rs @@ -5,11 +5,9 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm use crate::messages::input_mapper::utility_types::misc::ActionShortcut; use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions; use crate::messages::layout::utility_types::widget_prelude::*; -use crate::messages::portfolio::document::node_graph::utility_types::{ - BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic, -}; +use crate::messages::portfolio::document::node_graph::graph_ui::GraphNameField; +use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuInformation, FrontendNodeType, FrontendRemoteCursor}; use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry}; -use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate}; use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction}; use crate::messages::portfolio::utility_types::WorkspacePanelLayout; use crate::messages::prelude::*; @@ -65,8 +63,6 @@ pub enum FrontendMessage { SendUIMetadata { #[serde(rename = "nodeDescriptions")] node_descriptions: Vec<(String, String)>, - #[serde(rename = "nodeIcons")] - node_icons: Vec<(String, IconName)>, #[serde(rename = "nodeTypes")] node_types: Vec, }, @@ -121,11 +117,6 @@ pub enum FrontendMessage { preferences: PreferencesMessageHandler, }, TriggerTextCommit, - /// Asks the frontend to enter inline-rename mode for a layer in the graph view. - TriggerEditLayerNameInGraph { - #[serde(rename = "nodeId")] - node_id: NodeId, - }, TriggerVisitLink { url: String, }, @@ -158,34 +149,11 @@ pub enum FrontendMessage { ColorPickerStartHistoryTransaction, /// The Rust color picker handler is committing the in-flight undo transaction. The frontend `` forwards this as its `commitHistoryTransaction` event. ColorPickerCommitHistoryTransaction, - UpdateImportsExports { - /// If the primary import is not visible, then it is None. - imports: Vec>, - /// If the primary export is not visible, then it is None. - exports: Vec>, - /// The primary import location. - #[serde(rename = "importPosition")] - import_position: (i32, i32), - /// The primary export location. - #[serde(rename = "exportPosition")] - export_position: (i32, i32), - /// The document network does not have an add import or export button. - #[serde(rename = "addImportExport")] - add_import_export: bool, - }, - UpdateInSelectedNetwork { - #[serde(rename = "inSelectedNetwork")] - in_selected_network: bool, - }, /// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable. UpdateNetworkReadOnly { #[serde(rename = "readOnly")] read_only: bool, }, - UpdateBox { - #[serde(rename = "box")] - box_selection: Option, - }, UpdateRemoteCursors { cursors: Vec, }, @@ -199,6 +167,14 @@ pub enum FrontendMessage { UpdateGraphViewOverlay { open: bool, }, + UpdateGraphTooltip { + label: String, + description: String, + }, + UpdateGraphNameField { + field: Option, + opens: bool, + }, UpdateWorkspacePanelLayout { #[serde(rename = "panelLayout")] panel_layout: WorkspacePanelLayout, @@ -225,36 +201,6 @@ pub enum FrontendMessage { source: String, result: Option, }, - UpdateImportReorderIndex { - #[serde(rename = "importIndex")] - index: Option, - }, - UpdateExportReorderIndex { - #[serde(rename = "exportIndex")] - index: Option, - }, - /// The wire a dragged node would be inserted onto if dropped now, keyed by the node and index of the input it feeds (the max node ID for an export). - UpdateWireInsertionPreview { - wire: Option<(NodeId, usize)>, - }, - /// How far each node, and the imports and exports, gliding into the place it moved to is drawn from that place, in node graph space. - UpdateGlideOffsets { - nodes: Vec<(NodeId, (f64, f64))>, - imports: (f64, f64), - exports: (f64, f64), - }, - /// The connector a press at the pointer would grab, by its center in node graph space. - UpdateHoveredConnector { - center: Option<(f64, f64)>, - }, - UpdateLayerWidths { - #[serde(rename = "layerWidths")] - layer_widths: HashMap, - #[serde(rename = "chainWidths")] - chain_widths: HashMap, - #[serde(rename = "hasLeftInputWire")] - has_left_input_wire: HashMap, - }, UpdateDocumentArtwork { svg: String, }, @@ -300,25 +246,9 @@ pub enum FrontendMessage { #[serde(rename = "setColorChoice")] set_color_choice: Option, }, - UpdateGraphFadeArtwork { - percentage: f64, - }, UpdateMouseCursor { cursor: MouseCursorIcon, }, - UpdateNodeGraphNodes { - nodes: Vec, - }, - UpdateNodeGraphErrorDiagnostics { - errors: Vec, - }, - UpdateVisibleNodes { - nodes: Vec, - }, - UpdateNodeGraphWires { - wires: Vec, - }, - ClearAllNodeGraphWires, UpdateNodeGraphSelection { selected: Vec, }, @@ -335,27 +265,15 @@ pub enum FrontendMessage { height: u32, pixels: serde_bytes::ByteBuf, }, - UpdateNodeThumbnailCanvases { + UpdateNodeThumbnailCanvas { id: NodeId, - #[serde(rename = "layersPanelCanvasId")] - layers_panel_canvas_id: u64, - #[serde(rename = "nodeGraphCanvasId")] - node_graph_canvas_id: u64, + #[serde(rename = "canvasId")] + canvas_id: u64, }, UpdateOpenDocumentsList { #[serde(rename = "openDocuments")] open_documents: Vec, }, - UpdateWirePathInProgress { - #[serde(rename = "wirePath")] - wire_path: Option, - /// Where the wire meets the connector it's dragged from, in node graph space. - #[serde(rename = "draggedFrom")] - dragged_from: Option<(f64, f64)>, - /// Where the wire's loose end meets a connector it has snapped onto, in node graph space. - #[serde(rename = "snappedTo")] - snapped_to: Option<(f64, f64)>, - }, UpdatePlatform { platform: AppWindowPlatform, }, diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index 03ee519ce7..c1b5248faa 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -211,11 +211,6 @@ pub enum DocumentMessage { SetGraphFadeArtwork { percentage: f64, }, - /// Renames a layer in the network the node graph is showing, which may be a subgraph. - SetLayerNameInGraph { - node_id: NodeId, - name: String, - }, SetLayersPanelHoveredLayer { id: Option, }, diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 68b13500b1..dd542fb41b 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -1,4 +1,5 @@ use super::DocumentHistory; +use super::node_graph::graph_ui::GraphUiPart; use super::node_graph::{document_node_definitions, node_inspector}; use super::utility_types::error::EditorError; use super::utility_types::layers_in_view::LayersInView; @@ -199,7 +200,7 @@ pub struct DocumentMessageHandler { /// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport. #[serde(skip)] layers_panel_hovered_layer: Option, - /// The layers the frontend shows in view, the only ones it's sent the details and thumbnails of. + /// The layers in view in the Layers panel or the node graph, the only ones thumbnails are rendered for. #[serde(skip)] pub layers_in_view: LayersInView, /// Whether or not the editor has executed the network to render the document yet. If this is opened as an inactive tab, it won't be loaded initially because the active tab is prioritized. @@ -680,7 +681,6 @@ impl MessageHandler> for DocumentMes self.breadcrumb_network_path.push(node_id); self.selection_network_path.clone_from(&self.breadcrumb_network_path); self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path); - responses.add(NodeGraphMessage::UnloadWires); responses.add(NodeGraphMessage::SendGraph); responses.add(DocumentMessage::ZoomCanvasToFitAll); responses.add(NodeGraphMessage::UpdateNodeGraphWidth); @@ -699,20 +699,19 @@ impl MessageHandler> for DocumentMes self.network_interface.cancel_drag(&self.selection_network_path); self.node_graph_handler.select_if_not_dragged = None; self.node_graph_handler.nodes_added_in_drag = false; - self.node_graph_handler.stop_gliding(&self.network_interface, responses); responses.add(NodeGraphMessage::UpdateWireInsertionPreview); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); } // Abort dragging a dot out of a connector, before the dot has appeared else if self.node_graph_handler.dot_drag_out.is_some() { self.node_graph_handler.dot_drag_out = None; } // Abort box selection - else if self.node_graph_handler.box_selection_start.is_some() { - self.node_graph_handler.box_selection_start = None; + else if self.node_graph_handler.box_selection.is_some() { responses.add(NodeGraphMessage::SelectedNodesSet { nodes: self.node_graph_handler.selection_before_pointer_down.clone(), }); - responses.add(FrontendMessage::UpdateBox { box_selection: None }); + self.node_graph_handler.set_box_selection(None, responses); } // Abort wire in progress of being connected else if self.node_graph_handler.wire_in_progress_from_connector.is_some() { @@ -744,7 +743,6 @@ impl MessageHandler> for DocumentMes self.selection_network_path.clone_from(&self.breadcrumb_network_path); } self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path); - responses.add(NodeGraphMessage::UnloadWires); responses.add(NodeGraphMessage::SendGraph); responses.add(DocumentMessage::PTZUpdate); responses.add(NodeGraphMessage::UpdateNodeGraphWidth); @@ -800,24 +798,21 @@ impl MessageHandler> for DocumentMes DocumentMessage::GraphViewOverlay { open } => { let opened = !self.graph_view_overlay_open && open; self.graph_view_overlay_open = open; + self.node_graph_handler.graph_ui.graph_view_toggled(responses); responses.add(FrontendMessage::UpdateGraphViewOverlay { open }); - responses.add(FrontendMessage::UpdateGraphFadeArtwork { - percentage: self.graph_fade_artwork_percentage, - }); // Update the tilt menu bar buttons to be disabled when the graph is open responses.add(MenuBarMessage::SendLayout); responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderScrollbars); + responses.add(PortfolioMessage::SubmitActiveGraphRender); if opened { - responses.add(NodeGraphMessage::UnloadWires); responses.add(NodeGraphMessage::UpdateNodeGraphWidth); } if open { responses.add(ToolMessage::DeactivateTools); - responses.add(OverlaysMessage::Draw); // Clear the overlays responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. }); responses.add(NodeGraphMessage::UpdateGraphBarRight); responses.add(NodeGraphMessage::SendGraph); @@ -827,6 +822,7 @@ impl MessageHandler> for DocumentMes if self.end_node_graph_wire_in_progress(responses) { responses.add(DocumentMessage::AbortTransaction); } + self.node_graph_handler.abort_node_drag(&mut self.network_interface, &self.selection_network_path, responses); responses.add(ToolMessage::ActivateTool { tool_type: *current_tool }); responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed @@ -1545,6 +1541,7 @@ impl MessageHandler> for DocumentMes self.chain_node_range_selection_reference = Some(node_id); } DocumentMessage::SetActivePanel { active_panel } => { + let selection_network_path = self.selection_network_path.clone(); match active_panel { PanelType::Document => { if self.graph_view_overlay_open { @@ -1558,7 +1555,9 @@ impl MessageHandler> for DocumentMes } responses.add(InspectorMessage::Refresh); responses.add(NodeGraphMessage::UpdateLayerPanel); - responses.add(NodeGraphMessage::UpdateInSelectedNetwork); + if self.graph_view_overlay_open && self.selection_network_path != selection_network_path { + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); + } } DocumentMessage::SetBlendModeForSelectedLayers { blend_mode } => { for layer in self.network_interface.selected_nodes().selected_layers_except_artboards(&self.network_interface) { @@ -1567,15 +1566,7 @@ impl MessageHandler> for DocumentMes } DocumentMessage::SetGraphFadeArtwork { percentage } => { self.graph_fade_artwork_percentage = percentage; - responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage }); - } - DocumentMessage::SetLayerNameInGraph { node_id, name } => { - responses.add(NodeGraphMessage::SetDisplayName { - node_id, - network_path: self.breadcrumb_network_path.clone(), - alias: name, - skip_adding_history_step: false, - }); + responses.add(PortfolioMessage::SubmitActiveGraphRender); } DocumentMessage::SetLayersPanelHoveredLayer { id } => { let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked); @@ -2087,6 +2078,7 @@ impl MessageHandler> for DocumentMes responses.add(NodeGraphMessage::UpdateBoxSelection); responses.add(NodeGraphMessage::UpdateHoveredConnector); responses.add(NodeGraphMessage::UpdateImportsExports); + responses.add(PortfolioMessage::SubmitActiveGraphRender); responses.add(FrontendMessage::UpdateNodeGraphTransform { translation: transform.translation.into(), @@ -2711,8 +2703,6 @@ impl DocumentMessageHandler { responses.add(PortfolioMessage::UpdateOpenDocumentsList); responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::ForceRunDocumentGraph); - responses.add(NodeGraphMessage::UnloadWires); - responses.add(NodeGraphMessage::SendWires); } /// Keeps the graph showing the open network across a reconcile, which can rebuild its view state or remove it. @@ -2768,8 +2758,6 @@ impl DocumentMessageHandler { responses.add(PortfolioMessage::UpdateOpenDocumentsList); responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::ForceRunDocumentGraph); - responses.add(NodeGraphMessage::UnloadWires); - responses.add(NodeGraphMessage::SendWires); } pub fn serialize_document(&self) -> String { @@ -3067,9 +3055,6 @@ impl DocumentMessageHandler { } pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque) { - // Settled before storage moves, so the glide's offsets don't outlive the step - self.node_graph_handler.stop_gliding(&self.network_interface, responses); - let stored_name = self.stored_name().map(str::to_string); // Alone, the step enters history first so it stays on the History panel once undone if !self.is_in_session() { @@ -3082,8 +3067,6 @@ impl DocumentMessageHandler { } pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque) { - self.node_graph_handler.stop_gliding(&self.network_interface, responses); - let stored_name = self.stored_name().map(str::to_string); if self.history.redo() { self.follow_storage_changes(stored_name, responses); @@ -3093,8 +3076,6 @@ impl DocumentMessageHandler { /// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo. fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque) { - self.node_graph_handler.stop_gliding(&self.network_interface, responses); - let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified; if open_transaction_has_edits { // Staged so they are taken back with the steps before them @@ -3123,7 +3104,6 @@ impl DocumentMessageHandler { return; } self.end_history_preview(viewport, responses); - self.node_graph_handler.stop_gliding(&self.network_interface, responses); responses.add(EventMessage::ToolAbort); self.apply_history_line_change(document_id, rev, change, byte_store, responses); } @@ -3138,7 +3118,6 @@ impl DocumentMessageHandler { } let Some(past) = self.history.interface_at(rev) else { return }; - self.node_graph_handler.stop_gliding(&self.network_interface, responses); responses.add(EventMessage::ToolAbort); let replaced = self.install_history_snapshot(past, viewport); let current = self.history_preview.take().map_or(replaced, |preview| preview.current); @@ -3191,8 +3170,6 @@ impl DocumentMessageHandler { fn show_installed_interface(&self, responses: &mut VecDeque) { responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::ForceRunDocumentGraph); - responses.add(NodeGraphMessage::UnloadWires); - responses.add(NodeGraphMessage::SendWires); responses.add(DocumentMessage::DocumentStructureChanged); responses.add(OverlaysMessage::Draw); responses.add(EventMessage::SelectionChanged); @@ -5128,7 +5105,7 @@ mod document_message_handler_tests { let document = portfolio.documents.get_mut(&document_id).unwrap(); portfolio .executor - .submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO) + .submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO, None) .unwrap(); editor.runtime.update(); editor.runtime.run().await; diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 814d6f76d1..27761503de 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -3,7 +3,6 @@ mod document_node_derive; use super::node_inspector::choice::enum_choice; use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange}; use super::utility_types::{FrontendNodeType, InputTypeConstraint}; -use crate::messages::frontend::IconName; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::utility_types::network_interface::{ InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride, @@ -1641,13 +1640,6 @@ pub fn network_node_identifiers() -> impl Iterator { }) } -pub fn collect_node_icons() -> Vec<(String, IconName)> { - DOCUMENT_NODE_TYPES - .iter() - .filter_map(|(identifier, definition)| Some((identifier.serialized(), definition.icon?.to_string()))) - .collect() -} - impl DocumentNodeDefinition { /// Converts the [DocumentNodeDefinition] type to a [NodeTemplate], using the provided `input_override` and falling back to the default inputs. /// `input_override` does not have to be the correct length. diff --git a/editor/src/messages/portfolio/document/node_graph/graph_ui.rs b/editor/src/messages/portfolio/document/node_graph/graph_ui.rs new file mode 100644 index 0000000000..41d3259c66 --- /dev/null +++ b/editor/src/messages/portfolio/document/node_graph/graph_ui.rs @@ -0,0 +1,502 @@ +mod name_field; +mod pointer; + +pub use name_field::{GraphName, GraphNameField, edited_name}; +pub use pointer::{PointerHits, connector_under_pointer, tooltip_target}; + +use super::node_graph_message_handler::NodeGraphMessageHandler; +use super::utility_types::FrontendGraphDataType; +use crate::messages::portfolio::document::DocumentMessageHandler; +use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NetworkConnectorKey, NodeNetworkInterface, OutputConnector, Previewing}; +use crate::messages::prelude::{Message, PortfolioMessage, Responses}; +use glam::DVec2; +use graph_craft::document::NodeId; +use graph_ui::GraphUiConfig; +use graph_ui::card::{Card, Connector, DataType, Selection}; +use graph_ui::dot::Dot; +use graph_ui::error_badge::ErrorBadge; +use graph_ui::geometry::NodeGeometry; +use graph_ui::highlights::{self, Highlights, NodePart}; +use graph_ui::layer::Layer; +use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind, network_connector_row_offset}; +use graph_ui::placed::Placed; +use graph_ui::replicated_map::{Keyed, ReplicatedMap, ReplicatedMapEdit}; +use graph_ui::scene::GraphUiSceneEdit; +use graph_ui::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle}; +use pointer::TooltipTarget; +use std::collections::{BTreeSet, HashMap, VecDeque}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ConnectorKey { + Input(InputConnector), + Output(OutputConnector), +} + +impl From for ConnectorKey { + fn from(connector: NetworkConnectorKey) -> Self { + match connector { + NetworkConnectorKey::Import(index) => ConnectorKey::Output(OutputConnector::Import(index)), + NetworkConnectorKey::Export(index) => ConnectorKey::Input(InputConnector::Export(index)), + } + } +} + +impl From for highlights::ConnectorKey { + fn from(connector: ConnectorKey) -> Self { + match connector { + ConnectorKey::Input(input) => highlights::ConnectorKey::Input(input_key(input)), + ConnectorKey::Output(output) => highlights::ConnectorKey::Output(output_key(output)), + } + } +} + +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum GraphUiPart { + All, + NetworkConnectors, + Errors, + InsertionTarget, + Moved { nodes: Vec }, +} + +pub struct GraphUiSceneBuilder<'a> { + network_interface: &'a NodeNetworkInterface, + network_path: &'a [NodeId], + node_graph_handler: &'a NodeGraphMessageHandler, + selected_nodes: Vec, + selected: Selection, +} + +impl<'a> GraphUiSceneBuilder<'a> { + pub fn of(document: &'a DocumentMessageHandler) -> Self { + let network_interface = &document.network_interface; + let network_path = document.breadcrumb_network_path(); + Self { + network_interface, + network_path, + node_graph_handler: &document.node_graph_handler, + selected_nodes: network_interface.selected_nodes_in_nested_network(network_path).unwrap_or_default().0, + selected: if network_path == document.selection_network_path() { + Selection::Active + } else { + Selection::Inactive + }, + } + } + + pub fn update(&self, part: GraphUiPart, scene: &mut GraphUiSceneEdit) { + match part { + GraphUiPart::All => { + let dragging = self.network_interface.dragging(self.network_path); + replace_rows(self.cards(), dragging, &mut scene.settled.cards, &mut scene.moving.cards); + replace_rows(self.layers(), dragging, &mut scene.settled.layers, &mut scene.moving.layers); + replace_rows(self.dots(), dragging, &mut scene.settled.dots, &mut scene.moving.dots); + place_wires(self.wires(), scene); + scene.network_connectors.replace_all(self.network_connectors()); + scene.errors.replace_all(self.errors()); + } + GraphUiPart::NetworkConnectors => scene.network_connectors.replace_all(self.network_connectors()), + GraphUiPart::Errors => scene.errors.replace_all(self.errors()), + GraphUiPart::InsertionTarget => self.update_insertion_target(scene), + GraphUiPart::Moved { nodes } => self.update_moved(scene, nodes), + } + } + + fn nodes(&self) -> impl Iterator + '_ { + self.network_interface.nested_network(self.network_path).into_iter().flat_map(|network| network.nodes.keys().copied()) + } + + fn selection(&self, key: NodeId) -> Selection { + if self.selected_nodes.contains(&key) { self.selected } else { Selection::None } + } + + fn cards(&self) -> Vec> { + self.nodes().filter_map(|key| self.card(key)).collect() + } + + fn card(&self, key: NodeId) -> Option> { + let (network_interface, network_path) = (self.network_interface, self.network_path); + if network_interface.is_layer(&key, network_path) || network_interface.is_redirect_dot(&key, network_path) { + return None; + } + let NodeGeometry { cell, shape, .. } = self.geometry(key)?; + let name = network_interface.display_name(&key, network_path); + let look = Card { + key, + shape, + name, + icon: network_interface.node_icon(&key, network_path), + primary_input: self.input(key, 0), + primary_output: self.output(key, 0), + secondary_inputs: (1..network_interface.number_of_inputs(&key, network_path)).filter_map(|index| self.input(key, index)).collect(), + secondary_outputs: (1..network_interface.number_of_outputs(&key, network_path)).filter_map(|index| self.output(key, index)).collect(), + selection: self.selection(key), + visible: network_interface.is_visible(&key, network_path), + previewed: network_interface.previewing(network_path).previews(key), + }; + Some(Placed { cell, look }) + } + + fn geometry(&self, key: NodeId) -> Option { + self.network_interface.with_layout(self.network_path, |layout| layout.geometry(&key)).flatten() + } + + fn layers(&self) -> Vec> { + self.nodes().filter_map(|key| self.layer(key)).collect() + } + + fn layer(&self, key: NodeId) -> Option> { + let (network_interface, network_path) = (self.network_interface, self.network_path); + if !network_interface.is_layer(&key, network_path) { + return None; + } + let NodeGeometry { cell, chain_length, shape, .. } = self.geometry(key)?; + let look = Layer { + key, + shape, + chain_length, + name: network_interface.display_name(&key, network_path), + renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::Layer(key)), + has_left_input_wire: network_interface.has_left_input_wire(&key, network_path), + primary_input: self.input(key, 0), + primary_output: self.output(key, 0), + secondary_input: (1..network_interface.number_of_inputs(&key, network_path)).find_map(|index| self.input(key, index)), + primary_input_connected_to_layer: network_interface.primary_input_connected_to_layer(&key, network_path), + primary_output_connected_to_layer: network_interface.primary_output_connected_to_layer(&key, network_path), + visible: network_interface.is_visible(&key, network_path), + read_only: network_interface.is_read_only(network_path), + selection: self.selection(key), + previewed: network_interface.previewing(network_path).previews(key), + }; + Some(Placed { cell, look }) + } + + fn dots(&self) -> Vec> { + self.nodes().filter_map(|key| self.dot(key)).collect() + } + + fn dot(&self, key: NodeId) -> Option> { + let (network_interface, network_path) = (self.network_interface, self.network_path); + if !network_interface.is_redirect_dot(&key, network_path) { + return None; + } + let input = self.input(key, 0); + let output = self.output(key, 0); + let NodeGeometry { cell, shape, .. } = self.geometry(key)?; + let look = Dot { + key, + shape, + data_type: output.as_ref().map_or(DataType::General, |output| output.data_type), + wired: input.is_some_and(|input| input.connected) || output.is_some_and(|output| output.connected), + selected: self.selected_nodes.contains(&key), + previewed: network_interface.previewing(network_path).previews(key), + }; + Some(Placed { cell, look }) + } + + fn wires(&self) -> Vec { + let inputs = self.network_interface.node_graph_input_connectors(self.network_path).into_iter(); + inputs.filter_map(|input| self.wire(input)).chain(self.preview_wire()).collect() + } + + fn wire(&self, input: InputConnector) -> Option { + let output = self.network_interface.upstream_output_connector(&input, self.network_path)?; + let to = input_key(input); + Some(self.wire_row(WireKey::Input(to), output, to)) + } + + fn preview_wire(&self) -> Option { + let (network_interface, network_path) = (self.network_interface, self.network_path); + let input = InputConnector::Export(0); + + let Previewing::Yes { previewed } = network_interface.previewing(network_path) else { return None }; + + if network_interface.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) { + return None; + } + Some(self.wire_row(WireKey::Preview, previewed.to_connector(), input_key(input))) + } + + fn wire_row(&self, key: WireKey, output: OutputConnector, to: InputKey) -> Wire { + let output_type = self.network_interface.output_type(&output, self.network_path); + Wire { + key, + from: output_key(output), + to, + data_type: data_type(output_type.displayed_type()), + list: output_type.is_list(), + insertion_target: Some(key) == self.insertion_target(), + } + } + + fn insertion_target(&self) -> Option { + self.node_graph_handler.wire_insertion_preview.map(|input| WireKey::Input(input_key(input))) + } + + fn network_connectors(&self) -> Vec { + [NetworkConnectorKind::Import, NetworkConnectorKind::Export] + .into_iter() + .flat_map(|kind| self.network_connectors_of(kind)) + .collect() + } + + fn network_connectors_of(&self, kind: NetworkConnectorKind) -> Vec { + let (network_interface, network_path) = (self.network_interface, self.network_path); + let count = match kind { + NetworkConnectorKind::Import => network_interface.number_of_imports(network_path), + NetworkConnectorKind::Export => network_interface.number_of_exports(network_path), + }; + let row = |key: NetworkConnectorKey, position: DVec2, connector: Option| NetworkConnector { + key, + position: position.as_ivec2(), + connector, + editable: !network_path.is_empty(), + renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::NetworkConnector(key)), + }; + let named = (0..count).filter_map(|index| { + let key = NetworkConnectorKey::new(kind, index); + Some(row(key, self.position(key.into())?, Some(self.connector(key.into())?))) + }); + let empty = network_interface.empty_import_export_connectors(kind == NetworkConnectorKind::Import, network_path); + named + .chain(empty.into_iter().map(|(index, position)| row(NetworkConnectorKey::new(kind, index), position, None))) + .collect() + } + + fn errors(&self) -> Vec { + let errors = self.node_graph_handler.node_graph_errors(self.network_interface, self.network_path); + errors.into_iter().map(|(key, text)| ErrorBadge { key, text }).collect() + } + + fn update_moved(&self, scene: &mut GraphUiSceneEdit, nodes: Vec) { + let (network_interface, network_path) = (self.network_interface, self.network_path); + let downstream_layers = nodes.iter().filter_map(|node| network_interface.downstream_layer_for_chain_node(node, network_path)); + let rows: BTreeSet = nodes.iter().copied().chain(downstream_layers).collect(); + self.place_node_rows(rows, scene); + scene.network_connectors.replace_all(self.network_connectors()); + place_wires(all_wires(scene), scene); + } + + fn place_node_rows(&self, nodes: impl IntoIterator, scene: &mut GraphUiSceneEdit) { + let (network_interface, network_path) = (self.network_interface, self.network_path); + let dragging = network_interface.dragging(network_path); + for node in nodes { + let Some(NodeGeometry { cell, chain_length, .. }) = self.geometry(node) else { continue }; + + let placed = replace_row(node, dragging, &mut scene.settled.cards, &mut scene.moving.cards, |card| { + (card.cell != cell).then(|| Placed { cell, look: card.look.clone() }) + }) || replace_row(node, dragging, &mut scene.settled.layers, &mut scene.moving.layers, |layer| { + let has_left_input_wire = network_interface.has_left_input_wire(&node, network_path); + let changed = (layer.cell, layer.look.chain_length, layer.look.has_left_input_wire) != (cell, chain_length, has_left_input_wire); + let look = || Layer { + chain_length, + has_left_input_wire, + ..layer.look.clone() + }; + changed.then(|| Placed { cell, look: look() }) + }) || replace_row(node, dragging, &mut scene.settled.dots, &mut scene.moving.dots, |dot| { + (dot.cell != cell).then(|| Placed { cell, look: dot.look.clone() }) + }); + if !placed { + self.put_node_rows(node, dragging, scene); + } + } + } + + fn put_node_rows(&self, node: NodeId, dragging: bool, scene: &mut GraphUiSceneEdit) { + if let Some(card) = self.card(node) { + place_row(card, dragging, &mut scene.settled.cards, &mut scene.moving.cards); + } + if let Some(layer) = self.layer(node) { + place_row(layer, dragging, &mut scene.settled.layers, &mut scene.moving.layers); + } + if let Some(dot) = self.dot(node) { + place_row(dot, dragging, &mut scene.settled.dots, &mut scene.moving.dots); + } + } + + fn input(&self, node: NodeId, index: usize) -> Option { + self.connector(ConnectorKey::Input(InputConnector::node_at_index(node, index))) + } + + fn output(&self, node: NodeId, index: usize) -> Option { + self.connector(ConnectorKey::Output(OutputConnector::node(node, index))) + } + + fn connector(&self, key: ConnectorKey) -> Option { + let (network_interface, network_path) = (self.network_interface, self.network_path); + let (name, connector_type, connected) = match key { + ConnectorKey::Input(input) => network_interface.graph_ui_input(&input, network_path), + ConnectorKey::Output(output) => network_interface.graph_ui_output(&output, network_path), + }?; + Some(Connector { + index: match key { + ConnectorKey::Input(input) => input.input_index(), + ConnectorKey::Output(output) => output.index(), + } as u32, + name, + data_type: data_type(connector_type.displayed_type()), + connected, + }) + } + + fn position(&self, key: ConnectorKey) -> Option { + match key { + ConnectorKey::Input(input) => self.network_interface.input_position(&input, self.network_path), + ConnectorKey::Output(output) => self.network_interface.output_position(&output, self.network_path), + } + } + + fn update_insertion_target(&self, scene: &mut GraphUiSceneEdit) { + let target = self.insertion_target(); + let wires = all_wires(scene).into_iter().map(|wire| Wire { + insertion_target: Some(wire.key) == target, + ..wire + }); + place_wires(wires.collect(), scene); + } +} + +fn stays + PartialEq>(row: &T, dragging: bool, settled: &ReplicatedMap) -> bool { + !dragging || settled.get(&row.key()) == Some(row) +} + +fn replace_rows + PartialEq>(rows: Vec, dragging: bool, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit) { + let (still, moved): (Vec, Vec) = rows.into_iter().partition(|row| stays(row, dragging, settled)); + settled.replace_all(still); + moving.replace_all(moved); +} + +fn place_row + PartialEq>(row: T, dragging: bool, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit) { + let key = row.key(); + if stays(&row, dragging, settled) { + moving.remove(&key); + settled.put(row); + } else { + settled.remove(&key); + moving.put(row); + } +} + +fn replace_row + PartialEq>( + node: NodeId, + dragging: bool, + settled: &mut ReplicatedMapEdit, + moving: &mut ReplicatedMapEdit, + replaced: impl FnOnce(&T) -> Option, +) -> bool { + let Some(row) = moving.get(&node).or_else(|| settled.get(&node)) else { return false }; + if let Some(row) = replaced(row) { + place_row(row, dragging, settled, moving); + } + true +} + +fn all_wires(scene: &GraphUiSceneEdit) -> Vec { + scene.settled.wires.iter().chain(scene.moving.wires.iter()).cloned().collect() +} + +fn place_wires(wires: Vec, scene: &mut GraphUiSceneEdit) { + let settled = |node: NodeId| scene.settled.cards.get(&node).is_some() || scene.settled.layers.get(&node).is_some() || scene.settled.dots.get(&node).is_some(); + let between_settled_nodes = |wire: &Wire| match (wire.from, wire.to) { + (OutputKey::Node { node: from, .. }, InputKey::Node { node: to, .. }) => settled(from) && settled(to), + _ => false, + }; + let (tiled, loose): (Vec, Vec) = wires.into_iter().partition(|wire| !wire.insertion_target && between_settled_nodes(wire)); + scene.settled.wires.replace_all(tiled); + scene.moving.wires.replace_all(loose); +} + +#[derive(Clone, Debug, Default)] +pub struct GraphUiState { + highlights: Highlights, + tooltip: Option<(Option, String, String)>, + editing_name: Option, + name_field: Option<(GraphName, GraphNameField)>, + error_text_sizes: HashMap, +} + +impl GraphUiState { + pub fn change_highlights(&mut self, change: impl FnOnce(&mut Highlights), responses: &mut VecDeque) { + let mut highlights = self.highlights; + change(&mut highlights); + if self.highlights != highlights { + self.highlights = highlights; + responses.add(PortfolioMessage::SubmitActiveGraphRender); + } + } +} + +pub fn config(document: &DocumentMessageHandler, wire_style: WireStyle) -> Option { + let node_graph_handler = &document.node_graph_handler; + let graph_metadata = document.network_interface.network_metadata(document.breadcrumb_network_path()); + graph_metadata.filter(|_| document.graph_view_overlay_open).map(|metadata| { + let view = metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport; + GraphUiConfig { + view, + fade_artwork: document.graph_fade_artwork_percentage / 100., + wire_in_progress: wire_in_progress(node_graph_handler), + reorder_bar: reorder_bar(document), + box_selection: node_graph_handler + .box_selection + .filter(|(_, dragged)| *dragged) + .map(|(corners, _)| corners.map(|corner| view.transform_point2(corner).max(DVec2::ZERO).floor())), + highlights: node_graph_handler.graph_ui.highlights, + wire_style, + } + }) +} + +fn reorder_bar(document: &DocumentMessageHandler) -> Option<(NetworkConnectorKind, DVec2)> { + let node_graph_handler = &document.node_graph_handler; + let index = node_graph_handler.end_index?; + let kind = if node_graph_handler.reordering_import.is_some() { + NetworkConnectorKind::Import + } else if node_graph_handler.reordering_export.is_some() { + NetworkConnectorKind::Export + } else { + return None; + }; + let (imports, exports) = document.network_interface.import_export_position(document.breadcrumb_network_path())?; + let first_row_center = match kind { + NetworkConnectorKind::Import => imports, + NetworkConnectorKind::Export => exports, + }; + Some((kind, first_row_center.as_dvec2() + DVec2::new(0., network_connector_row_offset(index)))) +} + +fn wire_in_progress(node_graph_handler: &NodeGraphMessageHandler) -> Option { + Some(WireInProgress { + ends: node_graph_handler.wire_in_progress_ends?, + data_type: data_type(node_graph_handler.wire_in_progress_type), + }) +} + +fn output_key(output: OutputConnector) -> OutputKey { + match output { + OutputConnector::Node { node_id, output_index } => OutputKey::Node { node: node_id, index: output_index }, + OutputConnector::Import(index) => OutputKey::Import(index), + } +} + +fn input_key(input: InputConnector) -> InputKey { + match input { + InputConnector::Node { node_id, input_index } => InputKey::Node { node: node_id, index: input_index }, + InputConnector::Export(index) => InputKey::Export(index), + } +} + +fn data_type(data_type: FrontendGraphDataType) -> DataType { + match data_type { + FrontendGraphDataType::General => DataType::General, + FrontendGraphDataType::Number => DataType::Number, + FrontendGraphDataType::Artboard => DataType::Artboard, + FrontendGraphDataType::Graphic => DataType::Graphic, + FrontendGraphDataType::Raster => DataType::Raster, + FrontendGraphDataType::Vector => DataType::Vector, + FrontendGraphDataType::Color => DataType::Color, + FrontendGraphDataType::Gradient => DataType::Gradient, + FrontendGraphDataType::Typography => DataType::Typography, + FrontendGraphDataType::Invalid => DataType::Invalid, + } +} diff --git a/editor/src/messages/portfolio/document/node_graph/graph_ui/name_field.rs b/editor/src/messages/portfolio/document/node_graph/graph_ui/name_field.rs new file mode 100644 index 0000000000..5d87550b97 --- /dev/null +++ b/editor/src/messages/portfolio/document/node_graph/graph_ui/name_field.rs @@ -0,0 +1,108 @@ +use super::*; +use crate::messages::prelude::FrontendMessage; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum GraphName { + Layer(NodeId), + NetworkConnector(NetworkConnectorKey), +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct GraphNameField { + pub name: String, + pub x: f64, + pub top: f64, + #[serde(rename = "alignRight")] + pub align_right: bool, + pub dimmed: bool, +} + +impl GraphUiSceneBuilder<'_> { + fn name_field(&self, name: GraphName) -> Option { + match name { + GraphName::Layer(key) => { + let layer = self.layer(key)?; + let [top_left, _] = layer.name_box(); + Some(GraphNameField { + name: layer.look.name, + x: top_left.x, + top: top_left.y, + align_right: false, + dimmed: !layer.look.visible, + }) + } + GraphName::NetworkConnector(key) => self.network_connector_name_field(key), + } + } + + fn network_connector_name_field(&self, key: NetworkConnectorKey) -> Option { + let row = self.network_connectors().into_iter().find(|row| row.key == key && row.editable)?; + let connector = row.connector.as_ref()?; + let [top_left, _] = row.name_box(0.); + Some(GraphNameField { + name: connector.name.clone(), + x: top_left.x, + top: top_left.y, + align_right: key.kind() == NetworkConnectorKind::Import, + dimmed: false, + }) + } +} + +impl GraphUiState { + pub fn begin_name_edit(&mut self, name: GraphName, responses: &mut VecDeque) { + if self.editing_name != Some(name) { + self.editing_name = Some(name); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); + } + } + + pub fn end_name_edit(&mut self) -> Option { + self.editing_name.take() + } + + pub fn update_name_field(&mut self, field: Option, responses: &mut VecDeque) { + let shown = self.name_field.as_ref(); + let same_row = |(name, field): &(GraphName, GraphNameField)| match (name, shown) { + (GraphName::NetworkConnector(_), Some((shown, shown_field))) if shown == name => shown_field.name == field.name, + _ => true, + }; + let edited = self.editing_name.zip(field).filter(same_row); + if edited.is_none() { + self.editing_name = None; + } + if edited == self.name_field { + return; + } + let sent = self.name_field.as_ref().map(|(name, _)| *name); + let opens = edited.as_ref().is_some_and(|(name, _)| sent != Some(*name)); + self.name_field.clone_from(&edited); + responses.add(FrontendMessage::UpdateGraphNameField { + field: edited.map(|(_, field)| field), + opens, + }); + } + + pub fn leave_network(&mut self, responses: &mut VecDeque) { + if self.editing_name.is_some() || self.name_field.is_some() { + self.drop_name_edit(responses); + } + } + + pub fn graph_view_toggled(&mut self, responses: &mut VecDeque) { + self.tooltip = None; + self.drop_name_edit(responses); + } + + fn drop_name_edit(&mut self, responses: &mut VecDeque) { + self.editing_name = None; + self.name_field = None; + responses.add(FrontendMessage::UpdateGraphNameField { field: None, opens: false }); + } +} + +pub fn edited_name(document: &DocumentMessageHandler) -> Option { + let name = document.node_graph_handler.graph_ui.editing_name?; + GraphUiSceneBuilder::of(document).name_field(name) +} diff --git a/editor/src/messages/portfolio/document/node_graph/graph_ui/pointer.rs b/editor/src/messages/portfolio/document/node_graph/graph_ui/pointer.rs new file mode 100644 index 0000000000..bdd9abf356 --- /dev/null +++ b/editor/src/messages/portfolio/document/node_graph/graph_ui/pointer.rs @@ -0,0 +1,260 @@ +use super::*; +use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type; +use crate::messages::portfolio::document::utility_types::network_interface::LayerClickTargetTypes; +use crate::messages::prelude::FrontendMessage; +use graph_ui::metrics::{CARD_ROW_PADDING, GRID_SIZE}; +use graph_ui::{error_badge, error_text_size}; +use std::cell::OnceCell; + +impl GraphUiState { + pub fn part_under_pointer(&mut self, hits: &PointerHits, errors: &[(NodeId, String)], pointer_free: bool) -> Option { + if let Some(badge) = self.error_badge_under(hits, errors) { + return Some(NodePart::ErrorBadge(badge)); + } + + let (network_interface, network_path) = (hits.network_interface, hits.network_path); + let dot = hits.node().filter(|node_id| network_interface.is_redirect_dot(node_id, network_path)); + if let Some(dot) = dot { + if !pointer_free { + return None; + } + if hits.output() == Some(OutputConnector::node(dot, 0)) { + return Some(NodePart::DotOutput(dot)); + } + let pulls_a_wire_in = hits.input() == Some(InputConnector::node_at_index(dot, 0)); + return (!pulls_a_wire_in).then_some(NodePart::Dot(dot)); + } + + let visibility = hits.visibility().map(NodePart::Visibility); + let lock = || hits.lock().map(NodePart::Lock); + let grip = || hits.grip().map(NodePart::Grip); + visibility.or_else(lock).or_else(grip) + } + + fn error_badge_under(&mut self, hits: &PointerHits, errors: &[(NodeId, String)]) -> Option { + let mut badges: Vec<&(NodeId, String)> = errors.iter().collect(); + badges.sort_by_key(|(key, _)| (self.highlights.badge_hovered(*key), *key)); + let text_sizes = &mut self.error_text_sizes; + text_sizes.retain(|text, _| badges.iter().any(|(_, badge_text)| badge_text == text)); + let mut text_size = |text: &String| match text_sizes.get(text) { + Some(size) => *size, + None => *text_sizes.entry(text.clone()).or_insert_with(|| error_text_size(text)), + }; + let geometry = |key: &NodeId| hits.network_interface.with_layout(hits.network_path, |layout| layout.geometry(key)).flatten(); + let mut covers = |(key, text): &(NodeId, String)| geometry(key).is_some_and(|geometry| error_badge::covers(geometry.error_badge_anchor(), text_size(text), hits.point)); + badges.into_iter().rev().find(|badge| covers(badge)).map(|(key, _)| *key) + } + + pub fn set_tooltip(&mut self, target: Option, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque) { + let (label, description) = target.map(|target| tooltip_text(target, network_interface, network_path)).unwrap_or_default(); + let tooltip = (target, label, description); + if self.tooltip.as_ref() == Some(&tooltip) { + return; + } + let (_, label, description) = self.tooltip.insert(tooltip).clone(); + responses.add(FrontendMessage::UpdateGraphTooltip { label, description }); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TooltipTarget { + Name(NetworkConnectorKey), + AddConnector(NetworkConnectorKey), + Connector(ConnectorKey), + Visibility(NodeId), + Lock(NodeId), + Grip(NodeId), + Dot(NodeId), + Row { node: NodeId, row: usize }, + Node(NodeId), +} + +pub struct PointerHits<'a> { + network_interface: &'a NodeNetworkInterface, + network_path: &'a [NodeId], + viewport_location: DVec2, + point: DVec2, + found: FoundHits, +} + +#[derive(Default)] +struct FoundHits { + name: OnceCell>, + empty_connector: OnceCell>, + node: OnceCell>, + visibility: OnceCell>, + lock: OnceCell>, + grip: OnceCell>, + input: OnceCell>, + output: OnceCell>, +} + +impl<'a> PointerHits<'a> { + pub fn new(network_interface: &'a NodeNetworkInterface, network_path: &'a [NodeId], viewport_location: DVec2, point: DVec2) -> Self { + Self { + network_interface, + network_path, + viewport_location, + point, + found: FoundHits::default(), + } + } + + fn name(&self) -> Option { + *self.found.name.get_or_init(|| self.network_interface.import_export_name_from_point(self.point, self.network_path)) + } + + fn empty_connector(&self) -> Option { + *self.found.empty_connector.get_or_init(|| { + let empty = |is_import| self.network_interface.empty_import_export_connector_at(self.point, is_import, self.network_path); + let import = empty(true).map(|(index, _)| NetworkConnectorKey::Import(index)); + import.or_else(|| empty(false).map(|(index, _)| NetworkConnectorKey::Export(index))) + }) + } + + fn node(&self) -> Option { + *self.found.node.get_or_init(|| self.network_interface.node_from_click(self.viewport_location, self.network_path)) + } + + fn visibility(&self) -> Option { + self.layer_button(&self.found.visibility, LayerClickTargetTypes::Visibility) + } + + fn lock(&self) -> Option { + self.layer_button(&self.found.lock, LayerClickTargetTypes::Lock) + } + + fn grip(&self) -> Option { + self.layer_button(&self.found.grip, LayerClickTargetTypes::Grip) + } + + fn layer_button(&self, found: &OnceCell>, button: LayerClickTargetTypes) -> Option { + *found.get_or_init(|| self.network_interface.layer_click_target_from_click(self.viewport_location, button, self.network_path)) + } + + fn input(&self) -> Option { + *self.found.input.get_or_init(|| self.network_interface.input_port_from_click(self.viewport_location, self.network_path)) + } + + fn output(&self) -> Option { + *self + .found + .output + .get_or_init(|| self.network_interface.output_port_from_click(self.viewport_location, self.network_path)) + } +} + +pub fn connector_under_pointer(hits: &PointerHits) -> Option { + if hits.name().is_some() || hits.visibility().is_some() || hits.lock().is_some() { + return None; + } + + let input = || hits.input().map(ConnectorKey::Input); + let output = || hits.output().map(ConnectorKey::Output); + hits.empty_connector().map(ConnectorKey::from).or_else(input).or_else(output) +} + +pub fn tooltip_target(hits: &PointerHits) -> Option { + let (network_interface, network_path) = (hits.network_interface, hits.network_path); + if let Some(name) = hits.name() { + return Some(TooltipTarget::Name(name)); + } + if let Some(add) = hits.empty_connector() { + return Some(TooltipTarget::AddConnector(add)); + } + + let node = hits.node(); + if let Some(dot) = node.filter(|node| network_interface.is_redirect_dot(node, network_path)) { + return Some(TooltipTarget::Dot(dot)); + } + let input = || hits.input().map(|input| TooltipTarget::Connector(ConnectorKey::Input(input))); + let output = || hits.output().map(|output| TooltipTarget::Connector(ConnectorKey::Output(output))); + let part = hits + .visibility() + .map(TooltipTarget::Visibility) + .or_else(|| hits.lock().map(TooltipTarget::Lock)) + .or_else(input) + .or_else(output) + .or_else(|| hits.grip().map(TooltipTarget::Grip)); + if part.is_some() { + return part; + } + + let node = node?; + if network_interface.is_layer(&node, network_path) { + return Some(TooltipTarget::Node(node)); + } + let point = hits.point; + let [min, max] = network_interface.node_bounding_box(&node, network_path)?; + let row = ((point.y - min.y) / GRID_SIZE).floor(); + let on_row_name = point.x >= min.x + CARD_ROW_PADDING && point.x <= max.x - CARD_ROW_PADDING; + Some(if row >= 1. && on_row_name { + TooltipTarget::Row { node, row: row as usize } + } else { + TooltipTarget::Node(node) + }) +} + +fn tooltip_text(target: TooltipTarget, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (String, String) { + let input = |input: InputConnector| network_interface.input_tooltip(&input, network_path); + let output = |output: OutputConnector| network_interface.output_tooltip(&output, network_path); + let input_tooltip = |key: InputConnector| { + let lists_no_types = matches!(key, InputConnector::Node { .. }); + input(key).map(|input| connector_tooltip(input.name, &input.description, input.resolved_type, &input.valid_types, input.connected, lists_no_types)) + }; + let output_tooltip = |key: OutputConnector| output(key).map(|output| connector_tooltip(output.name, &output.description, output.resolved_type, &output.possible_types, output.connected, false)); + let label_only = |text: &str| (text.to_string(), String::new()); + + match target { + TooltipTarget::Name(NetworkConnectorKey::Import(index)) => (network_interface.displayed_import_name(index, network_path), network_interface.import_description(index, network_path)), + TooltipTarget::Name(NetworkConnectorKey::Export(index)) => (network_interface.displayed_export_name(index, network_path), network_interface.export_description(index, network_path)), + TooltipTarget::AddConnector(add) => { + let (label, description) = match add { + NetworkConnectorKey::Import(index) => ( + if index == 0 { "Add Primary Import" } else { "Add Import" }, + "Drag a wire from here and connect it to an input, or drop one here from an input.", + ), + NetworkConnectorKey::Export(index) => ( + if index == 0 { "Add Primary Export" } else { "Add Export" }, + "Drag a wire from here and connect it to an output, or drop one here from an output.", + ), + }; + (label.to_string(), description.to_string()) + } + TooltipTarget::Connector(ConnectorKey::Input(key)) => input_tooltip(key).unwrap_or_default(), + TooltipTarget::Connector(ConnectorKey::Output(key)) => output_tooltip(key).unwrap_or_default(), + TooltipTarget::Visibility(layer) => label_only(if network_interface.is_visible(&layer, network_path) { "Hide" } else { "Show" }), + TooltipTarget::Lock(_) => label_only("Unlock"), + TooltipTarget::Grip(_) => (String::new(), "Drag only this layer without pushing others outside the stack".to_string()), + TooltipTarget::Dot(dot) => output_tooltip(OutputConnector::node(dot, 0)).unwrap_or_else(|| label_only(&network_interface.display_name(&dot, network_path))), + TooltipTarget::Row { node, row } => { + let exposed = |index: &usize| network_interface.graph_ui_input(&InputConnector::node_at_index(node, *index), network_path).is_some(); + let input_index = (1..network_interface.number_of_inputs(&node, network_path)).filter(exposed).nth(row - 1); + let named_input = input_index.map(|index| network_interface.displayed_input_name_and_description(&node, index, network_path)); + let named_output = || { + network_interface + .graph_ui_output(&OutputConnector::node(node, row), network_path) + .map(|(name, ..)| (name, network_interface.output_description(&node, row, network_path))) + }; + named_input.or_else(named_output).unwrap_or_default() + } + TooltipTarget::Node(node) => { + let (name, implementation_name) = (network_interface.display_name(&node, network_path), network_interface.implementation_name(&node, network_path)); + let label = if name == implementation_name { name } else { format!("{implementation_name} ({name})") }; + let definition = network_interface.reference(&node, network_path).and_then(|reference| resolve_document_node_type(&reference)); + (label, definition.map(|definition| definition.description.trim().to_string()).unwrap_or_default()) + } + } +} + +fn connector_tooltip(name: String, description: &str, resolved_type: String, types: &[String], connected: bool, lists_no_types: bool) -> (String, String) { + let wired_type = connected.then(|| format!("Wired Type:\n`{resolved_type}`")); + let possible_types = if types.is_empty() { + lists_no_types.then(|| "Possible Types:\nNone".to_string()) + } else { + Some(format!("Possible Types:\n{}", types.iter().map(|name| format!("`{name}`")).collect::>().join("\n"))) + }; + let types = [wired_type, possible_types].into_iter().flatten().collect::>().join("\n\n"); + let description = [description.trim().to_string(), types].into_iter().filter(|part| !part.is_empty()).collect::>().join("\n---\n"); + (if name.is_empty() { resolved_type } else { name }, description) +} diff --git a/editor/src/messages/portfolio/document/node_graph/mod.rs b/editor/src/messages/portfolio/document/node_graph/mod.rs index 6f1f480319..2671dbb1b7 100644 --- a/editor/src/messages/portfolio/document/node_graph/mod.rs +++ b/editor/src/messages/portfolio/document/node_graph/mod.rs @@ -1,4 +1,5 @@ pub mod document_node_definitions; +pub mod graph_ui; mod node_graph_message; mod node_graph_message_handler; pub mod node_inspector; 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 ac7ab82ed2..73bad156e0 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 @@ -1,8 +1,9 @@ +use super::graph_ui::GraphName; use super::utility_types::{Direction, NodeEvaluationError}; use crate::messages::input_mapper::utility_types::keyboard::Key; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; -use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector}; +use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, InputConnector, NetworkConnectorKey, NodeTemplate, OutputConnector}; use crate::messages::prelude::*; use glam::IVec2; use graph_craft::document::value::TaggedValue; @@ -78,7 +79,7 @@ pub enum NodeGraphMessage { }, /// Disconnects every wire an import feeds, or the wire feeding an export. DisconnectImportExport { - index: ImportOrExport, + index: NetworkConnectorKey, }, EnterNestedNetwork, DuplicateSelectedNodes, @@ -174,10 +175,6 @@ pub enum NodeGraphMessage { MiddleClick, /// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes. WireHoverTick, - /// Sends where everything gliding into place is drawn, along with the wires that follow it. - SendGlide, - /// Sent every frame while nodes glide into their grid cells, to bring them closer. - GlideTick, ShakeNode, UpdateNodeGraphWidth, RemoveImport { @@ -188,7 +185,7 @@ pub enum NodeGraphMessage { }, /// Removes an import or export, or hides it if it's the primary, since the primary slot always remains. RemoveImportExport { - index: ImportOrExport, + index: NetworkConnectorKey, }, ReorderImport { start_index: usize, @@ -209,11 +206,8 @@ pub enum NodeGraphMessage { SelectedNodesSet { nodes: Vec, }, - UnloadWires, - SendWires, - UpdateVisibleNodes, + UpdateLayersInView, SendGraph, - SendNodePositions, SetInputValue { node_id: NodeId, input_index: usize, @@ -223,10 +217,11 @@ pub enum NodeGraphMessage { input_connector: InputConnector, input: NodeInput, }, - /// Asks the frontend to enter inline-rename mode for the given layer's display name in the graph view. - /// Triggered by double-clicking the layer's name area. - BeginEditLayerName { - node_id: NodeId, + BeginEditName { + name: GraphName, + }, + EndEditName { + name: Option, }, SetDisplayName { node_id: NodeId, @@ -258,15 +253,11 @@ pub enum NodeGraphMessage { NudgeSelectedNodes { direction: Direction, }, - /// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there. ShiftSelectedNodes { direction: Direction, - glide: bool, }, - /// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there. ShiftSelectedNodesByAmount { graph_delta: IVec2, - glide: bool, }, /// Draws the dragged nodes `offset` grid cells from where the drag started, stored once the drag finishes. DragSelectedNodes { @@ -280,19 +271,19 @@ pub enum NodeGraphMessage { }, SetImportExportName { name: String, - index: ImportOrExport, + index: NetworkConnectorKey, }, SetImportExportNameImpl { name: String, - index: ImportOrExport, + index: NetworkConnectorKey, }, SetImportExportDescription { description: String, - index: ImportOrExport, + index: NetworkConnectorKey, }, SetImportExportDescriptionImpl { description: String, - index: ImportOrExport, + index: NetworkConnectorKey, }, ToggleSelectedAsLayersOrNodes, ToggleSelectedLocked, @@ -329,7 +320,6 @@ pub enum NodeGraphMessage { network_path: Vec, }, UpdateBoxSelection, - /// Shows hovered the connector a press at the pointer would grab, or none. UpdateHoveredConnector, /// Highlights the wire a dragged node would be inserted onto if dropped where it is, or stops highlighting one. UpdateWireInsertionPreview, @@ -354,7 +344,6 @@ pub enum NodeGraphMessage { }, UpdateActionButtons, UpdateGraphBarRight, - UpdateInSelectedNetwork, UpdateHints, SendSelectedNodes, } @@ -382,6 +371,7 @@ impl NodeGraphMessage { | Self::MergeSelectedNodes | Self::ReorderImport { .. } | Self::ReorderExport { .. } + | Self::BeginEditName { .. } | Self::SetImportExportName { .. } | Self::SetImportExportNameImpl { .. } | Self::SetImportExportDescription { .. } @@ -418,7 +408,6 @@ impl NodeGraphMessage { | Self::RemoveImportExport { .. } | Self::SetInputValue { .. } | Self::SetInput { .. } - | Self::BeginEditLayerName { .. } | Self::MakeUnique { .. } | Self::SetToNodeOrLayer { .. } | Self::ShiftNodePosition { .. } @@ -441,19 +430,15 @@ impl NodeGraphMessage { | Self::PointerOutsideViewport { .. } | Self::MiddleClick | Self::WireHoverTick - | Self::SendGlide - | Self::GlideTick | Self::UpdateNodeGraphWidth | Self::RunDocumentGraph | Self::ForceRunDocumentGraph | Self::SelectedNodesAdd { .. } | Self::SelectedNodesRemove { .. } | Self::SelectedNodesSet { .. } - | Self::UnloadWires - | Self::SendWires - | Self::UpdateVisibleNodes + | Self::UpdateLayersInView | Self::SendGraph - | Self::SendNodePositions + | Self::EndEditName { .. } | Self::TogglePreview { .. } | Self::TogglePreviewImpl { .. } | Self::UpdateBoxSelection @@ -467,7 +452,6 @@ impl NodeGraphMessage { | Self::UpdateEvaluationErrors { .. } | Self::UpdateActionButtons | Self::UpdateGraphBarRight - | Self::UpdateInSelectedNetwork | Self::UpdateHints | Self::SendSelectedNodes => None, } 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 333a79b488..b6e2eed189 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 @@ -1,21 +1,21 @@ +use super::graph_ui::{self, ConnectorKey, GraphName, GraphUiPart, GraphUiState, PointerHits}; use super::node_inspector; -use super::utility_types::{BoxSelection, ContextMenuInformation, DragStart, FrontendNode}; -use crate::consts::{DOUBLE_CLICK_ALLOWED_TRAVEL, DOUBLE_CLICK_MILLISECONDS, GRID_SIZE, NODE_GLIDE_TIME_CONSTANT_MILLISECONDS, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; +use super::utility_types::{ContextMenuInformation, DragStart}; +use crate::consts::{DOUBLE_CLICK_ALLOWED_TRAVEL, DOUBLE_CLICK_MILLISECONDS, GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual}; 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}; -use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic}; +use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError}; 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, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, + self, FlowType, InputConnector, LayerClickTargetTypes, NetworkConnectorKey, 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}; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::edit_target::{EditTarget, ResolvedEditTarget}; @@ -24,6 +24,10 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion}; use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo}; use crate::messages::viewport::Position; +use ::graph_ui::geometry::WireEnd; +use ::graph_ui::highlights::NodePart; +use ::graph_ui::metrics::{INPUT_CONNECTOR_LEFT, OUTPUT_CONNECTOR_RIGHT}; +use ::graph_ui::wire::WireStyle; use glam::{DVec2, IVec2}; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput}; @@ -78,13 +82,11 @@ pub struct NodeGraphMessageHandler { pub drag_start: Option<(DragStart, bool)>, // Store the selected chain nodes on drag start so they can be reconnected if shaken pub drag_start_chain_nodes: Vec, - /// The wire a dragged node would be inserted onto if dropped now, which the frontend shows undimmed. - wire_insertion_preview: Option, - /// The center of the connector a press at the pointer would grab, in node graph space, which the frontend shows hovered. - hovered_connector: Option, - /// If dragging the background to create a box selection, this stores its starting point in node graph coordinates, + /// The wire a dragged node would be inserted onto if dropped now, which is drawn undimmed. + pub(super) wire_insertion_preview: Option, + /// If dragging the background to create a box selection, this stores its starting point and the pointer's latest position in node graph coordinates, /// plus a flag indicating if it has been dragged since the mousedown began. - pub box_selection_start: Option<(DVec2, bool)>, + pub box_selection: Option<([DVec2; 2], bool)>, /// Restore the selection before box selection if it is aborted pub selection_before_pointer_down: Vec, keep_upstream_in_place: bool, @@ -100,6 +102,8 @@ pub struct NodeGraphMessageHandler { pub wire_in_progress_to_connector: Option, /// The data type determining the color of the wire being dragged. pub wire_in_progress_type: FrontendGraphDataType, + /// The wire in progress as drawn between its two ends, in node graph coordinates. + pub(super) wire_in_progress_ends: Option<[WireEnd; 2]>, /// The import a wire dragged from a dimmed connector for adding one would add, which only happens once it connects to something. wire_in_progress_from_new_import: Option, /// The empty input or export a wire is dragged backward from, which stays its end while its other end is taken to an output. @@ -112,12 +116,6 @@ pub struct NodeGraphMessageHandler { wire_expanded_node: Option<(NodeId, Vec, TransactionCheckpoint)>, /// Whether [`NodeGraphMessage::WireHoverTick`] is subscribed to animation frames. wire_hover_tick_subscribed: bool, - /// The network with whatever is gliding into the place it moved to, which keeps its own glide offsets. - glide_network_path: Vec, - /// When the gliding nodes were last brought closer to their grid cells, in milliseconds, once an animation frame has arrived. - glide_last_tick_time: Option, - /// Whether [`NodeGraphMessage::GlideTick`] is subscribed to animation frames. - glide_tick_subscribed: bool, /// State for the context menus. pub context_menu: Option, /// Index of selected node to be deselected on pointer up when shift clicking an already selected node @@ -127,15 +125,13 @@ pub struct NodeGraphMessageHandler { /// The node to preview on mouse up if alt-clicked preview_on_mouse_up: Option, /// The index of the import that is being moved - reordering_import: Option, + pub(super) reordering_import: Option, /// The index of the export that is being moved - reordering_export: Option, + pub(super) reordering_export: Option, /// The end index of the moved connector - end_index: Option, - /// The nodes the frontend currently knows about - frontend_nodes: Vec, - frontend_wires: HashMap<(NodeId, usize), WirePath>, + pub(super) end_index: Option, evaluation_errors: Vec, + pub(crate) graph_ui: GraphUiState, } /// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network. @@ -496,10 +492,10 @@ impl<'a> MessageHandler> for NodeG } NodeGraphMessage::DisconnectImportExport { index } => { match index { - ImportOrExport::Import(import_index) => { + NetworkConnectorKey::Import(import_index) => { network_interface.disconnect_import_wires(import_index, breadcrumb_network_path); } - ImportOrExport::Export(export_index) => network_interface.disconnect_input(&InputConnector::Export(export_index), breadcrumb_network_path), + NetworkConnectorKey::Export(export_index) => network_interface.disconnect_input(&InputConnector::Export(export_index), breadcrumb_network_path), } network_interface.remove_orphaned_dots(breadcrumb_network_path); @@ -514,6 +510,22 @@ impl<'a> MessageHandler> for NodeG return; } + let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else { + return; + }; + let point = network_metadata + .persistent_metadata + .navigation_metadata + .node_graph_to_viewport + .inverse() + .transform_point2(ipp.mouse.position); + if let Some(name) = network_interface.import_export_name_from_point(point, selection_network_path) { + responses.add(NodeGraphMessage::BeginEditName { + name: GraphName::NetworkConnector(name), + }); + return; + } + let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, selection_network_path) else { return; }; @@ -539,15 +551,33 @@ impl<'a> MessageHandler> for NodeG }; // Double-clicking the layer's name area triggers inline rename instead of drilling into the subgraph. if let Some(layer_id) = network_interface.layer_click_target_from_click(ipp.mouse.position, network_interface::LayerClickTargetTypes::Name, selection_network_path) { - responses.add(NodeGraphMessage::BeginEditLayerName { node_id: layer_id }); + responses.add(NodeGraphMessage::BeginEditName { name: GraphName::Layer(layer_id) }); return; } if let Some(DocumentNodeImplementation::Definition(_)) = network_interface.implementation(&node_id, selection_network_path) { responses.add(DocumentMessage::EnterNestedNetwork { node_id }); } } - NodeGraphMessage::BeginEditLayerName { node_id } => { - responses.add(FrontendMessage::TriggerEditLayerNameInGraph { node_id }); + NodeGraphMessage::BeginEditName { name } => self.graph_ui.begin_name_edit(name, responses), + NodeGraphMessage::EndEditName { name } => { + let Some(edited) = self.graph_ui.end_name_edit() else { return }; + match (edited, name) { + (GraphName::Layer(node_id), Some(name)) if name != network_interface.display_name(&node_id, breadcrumb_network_path) => { + responses.add(NodeGraphMessage::SetDisplayName { + node_id, + network_path: breadcrumb_network_path.to_vec(), + alias: name, + skip_adding_history_step: false, + }); + } + (GraphName::NetworkConnector(index @ NetworkConnectorKey::Import(i)), Some(name)) if name != network_interface.displayed_import_name(i, breadcrumb_network_path) => { + responses.add(NodeGraphMessage::SetImportExportName { name, index }) + } + (GraphName::NetworkConnector(index @ NetworkConnectorKey::Export(i)), Some(name)) if name != network_interface.displayed_export_name(i, breadcrumb_network_path) => { + responses.add(NodeGraphMessage::SetImportExportName { name, index }) + } + _ => responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }), + } } NodeGraphMessage::ExposeInput { input_connector, @@ -639,7 +669,6 @@ impl<'a> MessageHandler> for NodeG network_interface.remove_orphaned_dots(breadcrumb_network_path); responses.add(NodeGraphMessage::UpdateImportsExports); - responses.add(NodeGraphMessage::SendWires); responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::RunDocumentGraph); } @@ -813,7 +842,6 @@ impl<'a> MessageHandler> for NodeG // Shift the nodes back to the origin responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta: -center_of_selected_nodes_grid_space - IVec2::new(2, 2), - glide: false, }); for (input_connector, import_index) in import_connections { @@ -934,6 +962,9 @@ impl<'a> MessageHandler> for NodeG alt_click, right_click, } => { + self.graph_ui + .change_highlights(|highlights| highlights.pressed_part = if right_click { None } else { highlights.hovered_part }, responses); + responses.add(NodeGraphMessage::UpdateHoveredConnector); if selection_network_path != breadcrumb_network_path { log::error!("Selection network path does not match breadcrumb network path in PointerDown"); return; @@ -962,13 +993,7 @@ impl<'a> MessageHandler> for NodeG // Abort dragging a node if self.drag_start.is_some() { - self.drag_start = None; - network_interface.cancel_drag(selection_network_path); - self.select_if_not_dragged = None; - self.nodes_added_in_drag = false; - self.clear_wire_insertion_preview(responses); - self.stop_gliding(network_interface, responses); - responses.add(DocumentMessage::AbortTransaction); + self.abort_node_drag(network_interface, selection_network_path, responses); responses.add(NodeGraphMessage::SelectedNodesSet { nodes: self.selection_before_pointer_down.clone(), }); @@ -986,12 +1011,11 @@ impl<'a> MessageHandler> for NodeG return; } // Abort a box selection - if self.box_selection_start.is_some() { - self.box_selection_start = None; + if self.box_selection.is_some() { responses.add(NodeGraphMessage::SelectedNodesSet { nodes: self.selection_before_pointer_down.clone(), }); - responses.add(FrontendMessage::UpdateBox { box_selection: None }); + self.set_box_selection(None, responses); return; } // Abort dragging a wire @@ -1013,14 +1037,15 @@ impl<'a> MessageHandler> for NodeG let clicked_import_export = network_interface .import_export_name_from_point(node_graph_point, selection_network_path) .or(match (clicked_input, clicked_output) { - (Some(InputConnector::Export(export_index)), _) if !selection_network_path.is_empty() => Some(ImportOrExport::Export(export_index)), - (_, Some(OutputConnector::Import(import_index))) => Some(ImportOrExport::Import(import_index)), + (Some(InputConnector::Export(export_index)), _) if !selection_network_path.is_empty() => Some(NetworkConnectorKey::Export(export_index)), + (_, Some(OutputConnector::Import(import_index))) => Some(NetworkConnectorKey::Import(import_index)), _ => None, }); let context_menu_data = if let Some(import_or_export) = clicked_import_export { - let (is_import, index, exposed, connected) = match import_or_export { - ImportOrExport::Import(import_index) => { + const DESCRIPTION_POPOVER_GAP: f64 = 2.; + let (is_import, index, exposed, connected, description, anchor) = match import_or_export { + NetworkConnectorKey::Import(import_index) => { let exposed = selection_network_path.split_last().is_some_and(|(encapsulating_node, encapsulating_path)| { let encapsulating_input = InputConnector::node_at_index(*encapsulating_node, import_index); network_interface.input_from_connector(&encapsulating_input, encapsulating_path).is_some_and(|input| input.is_exposed()) @@ -1030,11 +1055,17 @@ impl<'a> MessageHandler> for NodeG outward_wires.get(&OutputConnector::Import(import_index)).is_some_and(|fed_inputs| !fed_inputs.is_empty()) }) .unwrap_or_default(); - (true, import_index, exposed, connected) + let description = network_interface.import_description(import_index, selection_network_path); + let connector = network_interface.output_position(&OutputConnector::Import(import_index), selection_network_path); + let anchor = connector.map(|connector| connector + DVec2::X * (OUTPUT_CONNECTOR_RIGHT + DESCRIPTION_POPOVER_GAP)); + (true, import_index, exposed, connected, description, anchor) } - ImportOrExport::Export(export_index) => { + NetworkConnectorKey::Export(export_index) => { let connected = network_interface.upstream_output_connector(&InputConnector::Export(export_index), selection_network_path).is_some(); - (false, export_index, true, connected) + let description = network_interface.export_description(export_index, selection_network_path); + let connector = network_interface.input_position(&InputConnector::Export(export_index), selection_network_path); + let anchor = connector.map(|connector| connector + DVec2::X * (INPUT_CONNECTOR_LEFT - DESCRIPTION_POPOVER_GAP)); + (false, export_index, true, connected, description, anchor) } }; ContextMenuData::ModifyImportExport { @@ -1042,6 +1073,8 @@ impl<'a> MessageHandler> for NodeG index: index as u32, exposed, connected, + description, + description_anchor: anchor.unwrap_or_default().into(), } } else if let Some(node_id) = clicked_id { let currently_is_node = !network_interface.is_layer(&node_id, breadcrumb_network_path); @@ -1132,8 +1165,8 @@ impl<'a> MessageHandler> for NodeG if !read_only && let Some(dragged_name) = network_interface.import_export_name_from_point(node_graph_point, selection_network_path) { responses.add(DocumentMessage::StartTransaction); match dragged_name { - ImportOrExport::Import(import_index) => self.reordering_import = Some(import_index), - ImportOrExport::Export(export_index) => self.reordering_export = Some(export_index), + NetworkConnectorKey::Import(import_index) => self.reordering_import = Some(import_index), + NetworkConnectorKey::Export(export_index) => self.reordering_export = Some(export_index), } // Nothing moves until the pointer does, so a click alone (like the start of a double-click to rename) leaves it in place self.end_index = None; @@ -1147,7 +1180,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_from_connector = Some(connector_position); self.wire_in_progress_type = FrontendGraphDataType::General; self.wire_in_progress_from_new_import = Some(import_index); - Self::keep_pressed_connector_lit(Some(connector_position), responses); + self.keep_pressed_connector_lit(ConnectorKey::Output(OutputConnector::Import(import_index)), responses); self.update_node_graph_hints(responses); return; @@ -1161,7 +1194,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_to_connector = Some(connector_position); self.wire_in_progress_type = FrontendGraphDataType::General; self.wire_in_progress_from_new_export = Some(export_index); - Self::keep_pressed_connector_lit(Some(connector_position), responses); + self.keep_pressed_connector_lit(ConnectorKey::Input(InputConnector::Export(export_index)), responses); self.update_node_graph_hints(responses); return; @@ -1189,16 +1222,14 @@ impl<'a> MessageHandler> for NodeG // Alt-click sets the clicked node as previewed if alt_click - && !read_only - && let Some(clicked_node) = clicked_id + && !read_only && let Some(clicked_node) = clicked_id { self.preview_on_mouse_up = Some(clicked_node); } // The second press of a double-click on a connector with wires drags a redirect dot out of it, once the pointer moves far enough to place the dot if is_double_press - && !read_only - && let Some(source) = Self::dot_drag_out_source(clicked_input, clicked_output, network_interface, selection_network_path) + && !read_only && let Some(source) = Self::dot_drag_out_source(clicked_input, clicked_output, network_interface, selection_network_path) { self.dot_drag_out = Some((source, node_graph_point)); self.double_click_used_by_press = true; @@ -1208,7 +1239,7 @@ impl<'a> MessageHandler> for NodeG // Begin moving an existing wire, or drag a new one backward out of an empty input toward an output if !read_only && let Some(clicked_input) = &clicked_input { responses.add(DocumentMessage::StartTransaction); - Self::keep_pressed_connector_lit(network_interface.input_position(clicked_input, breadcrumb_network_path), responses); + self.keep_pressed_connector_lit(ConnectorKey::Input(*clicked_input), responses); let output_connector = if *clicked_input == InputConnector::Export(0) { network_interface.root_node(breadcrumb_network_path).map(|root_node| root_node.to_connector()) @@ -1244,7 +1275,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_from_connector = network_interface.output_position(&clicked_output, selection_network_path); let output_type = network_interface.output_type(&clicked_output, breadcrumb_network_path); self.wire_in_progress_type = output_type.displayed_type(); - Self::keep_pressed_connector_lit(self.wire_in_progress_from_connector, responses); + self.keep_pressed_connector_lit(ConnectorKey::Output(clicked_output), responses); self.update_node_graph_hints(responses); return; @@ -1321,8 +1352,7 @@ impl<'a> MessageHandler> for NodeG // The second press of a double-click on a wire splits it with a redirect dot, which the press goes on to drag if is_double_press - && !read_only - && let Some(input_connector) = Self::wire_at_point(node_graph_point, network_interface, preferences.graph_wire_style, selection_network_path) + && !read_only && let Some(input_connector) = Self::wire_at_point(node_graph_point, network_interface, preferences.graph_wire_style, selection_network_path) { let dot = NodeId::new(); let center = (node_graph_point / GRID_SIZE as f64).round().as_ivec2(); @@ -1343,7 +1373,7 @@ impl<'a> MessageHandler> for NodeG if !shift_click && !alt_click { responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }) } - self.box_selection_start = Some((node_graph_point, false)); + self.box_selection = Some(([node_graph_point; 2], false)); self.update_node_graph_hints(responses); } NodeGraphMessage::PointerMove { shift } => { @@ -1356,7 +1386,7 @@ impl<'a> MessageHandler> for NodeG }; // Auto-panning, only while dragging since hovering also moves the pointer here - if self.drag_start.is_some() || self.box_selection_start.is_some() || self.wire_in_progress_from_connector.is_some() { + if self.drag_start.is_some() || self.box_selection.is_some() || self.wire_in_progress_from_connector.is_some() { let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()]; self.auto_panning.setup_by_mouse_position(ipp, viewport, &messages, responses); } @@ -1395,21 +1425,29 @@ impl<'a> MessageHandler> for NodeG } } else if self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() && self.wire_in_progress_is_backward() { // A wire dragged backward keeps its input end in place and snaps its loose end to an output, or to a dimmed connector for adding an import - let output_position = network_interface - .output_connector_from_click(ipp.mouse.position, selection_network_path) - .and_then(|output_connector| network_interface.output_position(&output_connector, selection_network_path)); - let empty_import_position = || network_interface.empty_import_export_connector_at(point, true, selection_network_path).map(|(_, position)| position); - let snapped_position = output_position.or_else(empty_import_position); - self.wire_in_progress_from_connector = Some(snapped_position.unwrap_or(point)); + let output = network_interface.output_connector_from_click(ipp.mouse.position, selection_network_path); + let output = output.and_then(|output_connector| Some((ConnectorKey::Output(output_connector), network_interface.output_position(&output_connector, selection_network_path)?))); + let empty_import = || { + let (index, position) = network_interface.empty_import_export_connector_at(point, true, selection_network_path)?; + Some((ConnectorKey::Output(OutputConnector::Import(index)), position)) + }; + let snapped = output.or_else(empty_import); + self.wire_in_progress_from_connector = Some(snapped.map_or(point, |(_, position)| position)); - self.send_wire_in_progress(self.wire_in_progress_from_input, snapped_position.is_some(), network_interface, selection_network_path, responses); + self.update_wire_in_progress( + self.wire_in_progress_from_input, + snapped.map(|(connector, _)| connector), + network_interface, + selection_network_path, + responses, + ); } else if self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() { let to_connector = network_interface.input_connector_from_click(ipp.mouse.position, selection_network_path); - let empty_export_position = to_connector + let empty_export = to_connector .is_none() .then(|| network_interface.empty_import_export_connector_at(point, false, selection_network_path)) - .flatten() - .map(|(_, position)| position); + .flatten(); + let empty_export_position = empty_export.map(|(_, position)| position); if let Some(to_connector) = &to_connector { let Some(input_position) = network_interface.input_position(to_connector, selection_network_path) else { log::error!("Could not get input position for connector: {to_connector:?}"); @@ -1436,8 +1474,10 @@ impl<'a> MessageHandler> for NodeG } } - let loose_end_snapped = to_connector.is_some() || empty_export_position.is_some(); - self.send_wire_in_progress(to_connector, loose_end_snapped, network_interface, selection_network_path, responses); + let snapped_to = to_connector + .map(ConnectorKey::Input) + .or(empty_export.map(|(index, _)| ConnectorKey::Input(InputConnector::Export(index)))); + self.update_wire_in_progress(to_connector, snapped_to, network_interface, selection_network_path, responses); // Input connectors stick out past their node's edge, so hovering one counts as hovering its node let wire_hovered_node = to_connector @@ -1458,10 +1498,7 @@ impl<'a> MessageHandler> for NodeG // rolls back both the duplication and the move with a single plain AbortTransaction. if ipp.keyboard.get(Key::Alt as usize) && Self::duplicate_selected_nodes(network_interface, selection_network_path, responses) { // Duplicating sets a 2x2 offset, so shift the nodes back to the original position - responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { - graph_delta: IVec2::new(-2, -2), - glide: false, - }); + responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta: IVec2::new(-2, -2) }); self.preview_on_mouse_up = None; self.nodes_added_in_drag = true; } @@ -1482,25 +1519,28 @@ impl<'a> MessageHandler> for NodeG } self.update_node_graph_hints(responses); - } else if let Some((_, box_selection_dragged)) = &mut self.box_selection_start { + } else if let Some((_, box_selection_dragged)) = &mut self.box_selection { *box_selection_dragged = true; responses.add(NodeGraphMessage::UpdateBoxSelection); self.update_node_graph_hints(responses); } else if self.is_reordering_import_export() { let reordering_import = self.reordering_import.is_some(); - self.end_index = network_interface.import_export_drop_position(point.y, reordering_import, selection_network_path); - - if reordering_import { - responses.add(FrontendMessage::UpdateImportReorderIndex { index: self.end_index }); - } else { - responses.add(FrontendMessage::UpdateExportReorderIndex { index: self.end_index }); - } + let end_index = network_interface.import_export_drop_position(point.y, reordering_import, selection_network_path); + self.set_end_index(end_index, responses); self.update_node_graph_hints(responses); } responses.add(NodeGraphMessage::UpdateHoveredConnector); } NodeGraphMessage::PointerUp => { + self.graph_ui.change_highlights( + |highlights| { + let pressed_part = highlights.pressed_part.take(); + highlights.clicked |= matches!(pressed_part, Some(NodePart::Visibility(_) | NodePart::Lock(_))) && pressed_part == highlights.hovered_part; + }, + responses, + ); + responses.add(NodeGraphMessage::UpdateHoveredConnector); // A press released where it was made is a click, which a second press soon after can make a double-click if let Some(press) = &mut self.latest_left_press { press.is_click = press.position.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL; @@ -1729,22 +1769,19 @@ impl<'a> MessageHandler> for NodeG self.begin_dragging = false; self.nodes_added_in_drag = false; self.clear_wire_insertion_preview(responses); - self.box_selection_start = None; self.end_wire_in_progress(network_interface, selection_network_path, responses); self.reordering_export = None; self.reordering_import = None; - self.end_index = None; + self.set_end_index(None, responses); responses.add(DocumentMessage::EndTransaction); - responses.add(FrontendMessage::UpdateBox { box_selection: None }); - responses.add(FrontendMessage::UpdateImportReorderIndex { index: None }); - responses.add(FrontendMessage::UpdateExportReorderIndex { index: None }); + self.set_box_selection(None, responses); self.update_node_graph_hints(responses); } NodeGraphMessage::PointerOutsideViewport { shift } => { - if self.drag_start.is_some() || self.box_selection_start.is_some() || (self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none()) { + if self.drag_start.is_some() || self.box_selection.is_some() || (self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none()) { let _ = self.auto_panning.shift_viewport(ipp, viewport, responses); } else { // Auto-panning @@ -1769,42 +1806,6 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::WireHoverTick => { self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses); } - NodeGraphMessage::SendGlide => { - let glide_offsets = network_interface.glide_offsets(&self.glide_network_path); - Self::send_glide(&glide_offsets, &glide_offsets, network_interface, preferences.graph_wire_style, &self.glide_network_path, responses); - } - NodeGraphMessage::GlideTick => { - // A document switched to from one that was gliding inherits its frame subscription, which it ends - if !self.glide_tick_subscribed { - responses.add(BroadcastMessage::UnsubscribeEvent { - on: EventMessage::AnimationFrame, - send: Box::new(NodeGraphMessage::GlideTick.into()), - }); - return; - } - - if !graph_view_overlay_open || self.glide_network_path != breadcrumb_network_path { - self.stop_gliding(network_interface, responses); - return; - } - - // Whatever settles this frame still needs its wires sent once more, to meet it where it sits - let was_gliding = network_interface.glide_offsets(&self.glide_network_path); - let mut glide_offsets = was_gliding.clone(); - - // Each offset shrinks exponentially, which eases the node in and keeps up with a drag that moves it again before it settles - if let Some(last_tick_time) = self.glide_last_tick_time { - let elapsed = ipp.time.saturating_sub(last_tick_time) as f64; - glide_offsets.shrink((-elapsed / NODE_GLIDE_TIME_CONSTANT_MILLISECONDS).exp()); - } - self.glide_last_tick_time = Some(ipp.time); - network_interface.set_glide_offsets(glide_offsets.clone(), &self.glide_network_path); - - Self::send_glide(&glide_offsets, &was_gliding, network_interface, preferences.graph_wire_style, &self.glide_network_path, responses); - if glide_offsets.is_empty() { - self.set_glide_tick_subscribed(false, responses); - } - } NodeGraphMessage::ShakeNode => { let Some((drag_start, _)) = &mut self.drag_start else { log::error!("Drag start should be initialized when shaking a node"); @@ -1932,7 +1933,7 @@ impl<'a> MessageHandler> for NodeG // } } if !self.nodes_added_in_drag { - responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, glide: false }); + responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta }); } // A dot left with nothing to carry, like one fed by a shaken generator, goes along with its wire responses.add(NodeGraphMessage::RemoveOrphanedDots); @@ -1958,10 +1959,10 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::RunDocumentGraph); } NodeGraphMessage::RemoveImportExport { index } => responses.add(match index { - ImportOrExport::Import(0) => NodeGraphMessage::ExposeEncapsulatingInput { input_index: 0, exposed: false }, - ImportOrExport::Export(0) => NodeGraphMessage::ExposePrimaryExport { exposed: false }, - ImportOrExport::Import(import_index) => NodeGraphMessage::RemoveImport { import_index }, - ImportOrExport::Export(export_index) => NodeGraphMessage::RemoveExport { export_index }, + NetworkConnectorKey::Import(0) => NodeGraphMessage::ExposeEncapsulatingInput { input_index: 0, exposed: false }, + NetworkConnectorKey::Export(0) => NodeGraphMessage::ExposePrimaryExport { exposed: false }, + NetworkConnectorKey::Import(import_index) => NodeGraphMessage::RemoveImport { import_index }, + NetworkConnectorKey::Export(export_index) => NodeGraphMessage::RemoveExport { export_index }, }), NodeGraphMessage::ReorderImport { start_index, end_index } => { let primary_was_empty = network_interface.hidden_primary_import(breadcrumb_network_path); @@ -2037,28 +2038,10 @@ impl<'a> MessageHandler> for NodeG selected_nodes.set_selected_nodes(nodes); responses.add(EventMessage::SelectionChanged); } - NodeGraphMessage::UnloadWires => { - self.frontend_wires.clear(); - responses.add(FrontendMessage::ClearAllNodeGraphWires); - } - NodeGraphMessage::SendWires => { - let mut wires = self.collect_wires(network_interface, preferences.graph_wire_style, breadcrumb_network_path); - - // The dispatcher defers this past any glide update in the same batch, so the wires following whatever glides must come last here too - let glide_offsets = network_interface.glide_offsets(breadcrumb_network_path); - if !glide_offsets.is_empty() { - wires.extend(Self::gliding_wires( - &glide_offsets, - &glide_offsets, - network_interface, - preferences.graph_wire_style, - breadcrumb_network_path, - )); + NodeGraphMessage::UpdateLayersInView => { + if !graph_view_overlay_open { + return; } - - responses.add(FrontendMessage::UpdateNodeGraphWires { wires }); - } - NodeGraphMessage::UpdateVisibleNodes => { let Some(network_metadata) = network_interface.network_metadata(breadcrumb_network_path) else { return; }; @@ -2066,93 +2049,49 @@ impl<'a> MessageHandler> for NodeG let viewport_bbox = [DVec2::ZERO, viewport.size().into_dvec2()]; let document_bbox: [DVec2; 2] = viewport_bbox.map(|p| network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(p)); - let mut nodes = Vec::new(); - for node_id in self.frontend_nodes.iter().map(|node| &node.id) { - let Some(node_bbox) = network_interface.node_bounding_box(node_id, breadcrumb_network_path) else { + let network_layers = network_interface + .nested_network(breadcrumb_network_path) + .into_iter() + .flat_map(|network| network.nodes.keys().copied()) + .filter(|node_id| network_interface.is_layer(node_id, breadcrumb_network_path)); + let mut layers = HashSet::new(); + for node_id in network_layers { + let Some(node_bbox) = network_interface.node_bounding_box(&node_id, breadcrumb_network_path) else { log::error!("Could not get bbox for node: {node_id:?}"); continue; }; - // Expand the cull box by a grid cell so a node stays rendered until its connectors, which reach beyond its bounding box, also leave the viewport + // A grid cell of margin has a layer's thumbnail ready as it comes into view let cull_margin = 24.; if node_bbox[1].x + cull_margin >= document_bbox[0].x && node_bbox[0].x - cull_margin <= document_bbox[1].x && node_bbox[1].y + cull_margin >= document_bbox[0].y && node_bbox[0].y - cull_margin <= document_bbox[1].y { - nodes.push(*node_id); - } - let resolved_types = &network_interface.resolved_types; - for error in resolved_types.node_graph_errors.iter().chain(&resolved_types.node_graph_warnings) { - if error.node_path.contains(node_id) { - nodes.push(*node_id); - } - } - if self.evaluation_errors.iter().any(|error| error.node_path.contains(node_id)) { - nodes.push(*node_id); + layers.insert(node_id); } } - layers_in_view.set_node_graph(nodes.iter().copied().collect(), responses); - responses.add(FrontendMessage::UpdateVisibleNodes { nodes }); + layers_in_view.set_node_graph(layers, responses); } NodeGraphMessage::SendGraph => { responses.add(NodeGraphMessage::UpdateLayerPanel); responses.add(DocumentMessage::DocumentStructureChanged); responses.add(InspectorMessage::Refresh); responses.add(EventMessage::GraphChanged); + if graph_view_overlay_open { + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); + responses.add(NodeGraphMessage::UpdateLayersInView); + } if breadcrumb_network_path == selection_network_path && graph_view_overlay_open { - self.frontend_nodes = self.collect_nodes(network_interface, breadcrumb_network_path); - responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() }); - - let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); - responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); responses.add(FrontendMessage::UpdateNetworkReadOnly { read_only: network_interface.is_read_only(breadcrumb_network_path), }); - let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path); - - responses.add(NodeGraphMessage::UpdateImportsExports); - responses.add(FrontendMessage::UpdateLayerWidths { - layer_widths, - chain_widths, - has_left_input_wire, - }); responses.add(NodeGraphMessage::SendSelectedNodes); responses.add(NodeGraphMessage::UpdateHoveredConnector); self.update_node_graph_hints(responses); } } - NodeGraphMessage::SendNodePositions => { - if breadcrumb_network_path != selection_network_path || !graph_view_overlay_open { - return; - } - - let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { return }; - let same_nodes = network.nodes.len() == self.frontend_nodes.len() && self.frontend_nodes.iter().all(|node| network.nodes.contains_key(&node.id)); - if !same_nodes { - responses.add(NodeGraphMessage::SendGraph); - return; - } - - for node in &mut self.frontend_nodes { - if let Some(position) = network_interface.position(&node.id, breadcrumb_network_path) { - node.position = position.into(); - } - } - responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() }); - - let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); - responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); - - let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path); - responses.add(FrontendMessage::UpdateLayerWidths { - layer_widths, - chain_widths, - has_left_input_wire, - }); - responses.add(NodeGraphMessage::UpdateImportsExports); - } NodeGraphMessage::SetInputValue { node_id, input_index, value } => { use graphene_std::vector::generator_nodes::*; @@ -2193,26 +2132,15 @@ impl<'a> MessageHandler> for NodeG } NodeGraphMessage::NudgeSelectedNodes { direction } => { responses.add(DocumentMessage::StartTransaction); - responses.add(NodeGraphMessage::ShiftSelectedNodes { direction, glide: true }); + responses.add(NodeGraphMessage::ShiftSelectedNodes { direction }); responses.add(DocumentMessage::EndTransaction); } - NodeGraphMessage::ShiftSelectedNodes { direction, glide } => { - responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { - graph_delta: direction.offset(), - glide, - }); + NodeGraphMessage::ShiftSelectedNodes { direction } => { + responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta: direction.offset() }); } - NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, glide } => { - let positions_before = (glide && graph_view_overlay_open).then(|| Self::glide_positions(network_interface, selection_network_path)); - + NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta } => { network_interface.shift_selected_nodes(graph_delta, self.keep_upstream_in_place, selection_network_path); - if let Some(positions_before) = positions_before { - self.begin_glide(positions_before, network_interface, selection_network_path, responses); - responses.add(NodeGraphMessage::SendGlide); - } - - responses.add(NodeGraphMessage::SendWires); if graph_view_overlay_open { responses.add(NodeGraphMessage::SendGraph); responses.add(DocumentMessage::RenderRulers); @@ -2225,17 +2153,22 @@ impl<'a> MessageHandler> for NodeG return; } - let positions_before = graph_view_overlay_open.then(|| Self::glide_positions(network_interface, selection_network_path)); + let positions_before = graph_view_overlay_open.then(|| Self::node_positions(network_interface, selection_network_path)); network_interface.drag_selected_nodes(offset, keep_upstream, selection_network_path); if let Some(positions_before) = positions_before { - self.begin_glide(positions_before, network_interface, selection_network_path, responses); - responses.add(NodeGraphMessage::SendGlide); + let moved = Self::node_positions(network_interface, selection_network_path) + .into_iter() + .filter(|(node_id, position)| positions_before.get(node_id).is_some_and(|before| before != position)) + .map(|(node_id, _)| node_id) + .collect(); + responses.add(PortfolioMessage::UpdateGraphUi { + part: GraphUiPart::Moved { nodes: moved }, + }); + responses.add(NodeGraphMessage::UpdateLayersInView); } - responses.add(NodeGraphMessage::SendWires); if graph_view_overlay_open { - responses.add(NodeGraphMessage::SendNodePositions); responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderScrollbars); } @@ -2259,7 +2192,11 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::ShiftNodePosition { node_id, x, y } => { network_interface.shift_node(&node_id, IVec2::new(x, y), selection_network_path); - responses.add(NodeGraphMessage::SendWires); + if graph_view_overlay_open { + responses.add(PortfolioMessage::UpdateGraphUi { + part: GraphUiPart::Moved { nodes: vec![node_id] }, + }); + } } NodeGraphMessage::MakeUnique { node_id } => { if !network_interface.make_unique(&node_id, selection_network_path) { @@ -2285,7 +2222,6 @@ impl<'a> MessageHandler> for NodeG }); responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::SendGraph); - responses.add(NodeGraphMessage::SendWires); } NodeGraphMessage::SetDisplayName { node_id, @@ -2488,13 +2424,28 @@ impl<'a> MessageHandler> for NodeG .inverse() .transform_point2(viewport_location); - // Moving nodes or drawing a selection box can't grab a connector, so none is shown hovered meanwhile - let can_grab_connector = graph_view_overlay_open && self.drag_start.is_none() && self.box_selection_start.is_none() && !network_interface.is_read_only(breadcrumb_network_path); let in_viewport = viewport.is_in_bounds(viewport.logical(viewport_location) + viewport.offset()); - let hovered_connector = (can_grab_connector && in_viewport) - .then(|| Self::connector_under_pointer(viewport_location, point, network_interface, breadcrumb_network_path)) - .flatten(); - self.set_hovered_connector(hovered_connector, responses); + let shown = graph_view_overlay_open && in_viewport; + let pointer_free = ipp.mouse.mouse_keys.is_empty(); + // Moving nodes or drawing a selection box can't grab a connector, so none is shown hovered meanwhile + let can_grab_connector = shown && pointer_free && self.drag_start.is_none() && self.box_selection.is_none() && !network_interface.is_read_only(breadcrumb_network_path); + let hits = PointerHits::new(network_interface, breadcrumb_network_path, viewport_location, point); + let hovered_connector = can_grab_connector.then(|| graph_ui::connector_under_pointer(&hits)).flatten(); + + let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); + let hovered_part = shown.then(|| self.graph_ui.part_under_pointer(&hits, &errors, pointer_free)).flatten(); + self.graph_ui.change_highlights( + |highlights| { + highlights.clicked &= hovered_part == highlights.hovered_part; + highlights.hovered_connector = hovered_connector.map(Into::into); + highlights.hovered_part = hovered_part; + }, + responses, + ); + + let under_badge = matches!(hovered_part, Some(NodePart::ErrorBadge(_))); + let tooltip = (shown && !under_badge).then(|| graph_ui::tooltip_target(&hits)).flatten(); + self.graph_ui.set_tooltip(tooltip, network_interface, breadcrumb_network_path, responses); } NodeGraphMessage::UpdateWireInsertionPreview => { // Only a drag in progress inserts anything on drop, and one that hasn't started moving yet inserts nothing @@ -2508,28 +2459,15 @@ impl<'a> MessageHandler> for NodeG } self.wire_insertion_preview = target; - let wire = target.map(|input_connector| match input_connector { - InputConnector::Node { node_id, input_index } => (node_id, input_index), - // Wires into exports are keyed under the max node ID, as in the wires sent to the frontend - InputConnector::Export(export_index) => (NodeId(u64::MAX), export_index), - }); - responses.add(FrontendMessage::UpdateWireInsertionPreview { wire }); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::InsertionTarget }); } NodeGraphMessage::UpdateBoxSelection => { - if let Some((box_selection_start, _)) = self.box_selection_start { + if let Some(([box_selection_start, _], box_selection_dragged)) = self.box_selection { let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else { log::error!("Could not get network metadata in UpdateBoxSelection"); return; }; - let box_selection_start_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.transform_point2(box_selection_start); - - let box_selection = Some(BoxSelection { - start_x: box_selection_start_viewport.x.max(0.) as u32, - start_y: box_selection_start_viewport.y.max(0.) as u32, - end_x: ipp.mouse.position.x.max(0.) as u32, - end_y: ipp.mouse.position.y.max(0.) as u32, - }); let box_selection_end_graph = network_metadata .persistent_metadata .navigation_metadata @@ -2553,7 +2491,7 @@ impl<'a> MessageHandler> for NodeG let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::>(); let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)]; for node_id in all_nodes { - let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else { + let Some(body) = network_interface.with_layout(selection_network_path, |layout| Some(layout.geometry(&node_id)?.body())).flatten() else { log::error!("Could not get the body of node {node_id}"); continue; }; @@ -2589,30 +2527,14 @@ impl<'a> MessageHandler> for NodeG nodes: nodes.into_iter().collect::>(), }); } - responses.add(FrontendMessage::UpdateBox { box_selection }) + self.set_box_selection(Some(([box_selection_start, box_selection_end_graph], box_selection_dragged)), responses); } } NodeGraphMessage::UpdateImportsExports => { - let imports = network_interface.frontend_imports(breadcrumb_network_path); - let exports = network_interface.frontend_exports(breadcrumb_network_path); - - let Some((import_position, export_position)) = network_interface.import_export_position(breadcrumb_network_path) else { - log::error!("Could not get import export positions"); - return; - }; - - // Do not show the add import or add export button in the document network; - let add_import_export = !breadcrumb_network_path.is_empty(); - - responses.add(NodeGraphMessage::UpdateVisibleNodes); - responses.add(NodeGraphMessage::SendWires); - responses.add(FrontendMessage::UpdateImportsExports { - imports, - exports, - import_position: import_position.into(), - export_position: export_position.into(), - add_import_export, - }); + responses.add(NodeGraphMessage::UpdateLayersInView); + if graph_view_overlay_open { + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::NetworkConnectors }); + } } NodeGraphMessage::UpdateLayerPanel => { @@ -2660,10 +2582,8 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::UpdateEvaluationErrors { errors } => { if self.evaluation_errors != errors { self.evaluation_errors = errors; - if breadcrumb_network_path == selection_network_path && graph_view_overlay_open { - let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); - responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); - responses.add(NodeGraphMessage::UpdateVisibleNodes); + if graph_view_overlay_open { + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::Errors }); } } } @@ -2677,9 +2597,6 @@ impl<'a> MessageHandler> for NodeG self.update_graph_bar_right(graph_fade_artwork_percentage, network_interface, breadcrumb_network_path, navigation_handler); self.send_node_bar_layout(responses); } - NodeGraphMessage::UpdateInSelectedNetwork => responses.add(FrontendMessage::UpdateInSelectedNetwork { - in_selected_network: selection_network_path == breadcrumb_network_path, - }), NodeGraphMessage::UpdateHints => { self.update_node_graph_hints(responses); } @@ -2719,12 +2636,10 @@ impl NodeGraphMessageHandler { self.wire_in_progress_from_input = None; self.wire_in_progress_from_new_export = None; self.disconnecting = None; - - responses.add(FrontendMessage::UpdateWirePathInProgress { - wire_path: None, - dragged_from: None, - snapped_to: None, - }); + if self.wire_in_progress_ends.take().is_some() { + responses.add(PortfolioMessage::SubmitActiveGraphRender); + } + self.graph_ui.change_highlights(|highlights| (highlights.dragged_from, highlights.snapped_to) = (None, None), responses); } pub fn is_reordering_import_export(&self) -> bool { @@ -2746,7 +2661,7 @@ impl NodeGraphMessageHandler { } /// The wire a press at the point (in node graph space) lands on, within a few pixels at the graph's zoom. - fn wire_at_point(point: DVec2, network_interface: &NodeNetworkInterface, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option { + fn wire_at_point(point: DVec2, network_interface: &NodeNetworkInterface, wire_style: WireStyle, network_path: &[NodeId]) -> Option { let zoom = network_interface .network_metadata(network_path)? .persistent_metadata @@ -2821,48 +2736,38 @@ impl NodeGraphMessageHandler { self.update_node_graph_hints(responses); } - /// The center of the connector a press at the pointer would grab, in node graph space, as `PointerDown` decides what lies under it. - fn connector_under_pointer(viewport_location: DVec2, point: DVec2, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option { - // Names and layer buttons take presses before the connectors beneath them - let layer_button_under_pointer = |target_type| network_interface.layer_click_target_from_click(viewport_location, target_type, network_path).is_some(); - if network_interface.import_export_name_from_point(point, network_path).is_some() - || layer_button_under_pointer(network_interface::LayerClickTargetTypes::Visibility) - || layer_button_under_pointer(network_interface::LayerClickTargetTypes::Lock) - { - return None; - } - - // Centered where it's drawn, even while gliding into place - let glide_offsets = network_interface.glide_offsets(network_path); - let empty_connector = |is_import| { - let (_, center) = network_interface.empty_import_export_connector_at(point, is_import, network_path)?; - Some(center + if is_import { glide_offsets.imports } else { glide_offsets.exports }) - }; - let input = || { - let input = network_interface.input_port_from_click(viewport_location, network_path)?; - Some(network_interface.input_position(&input, network_path)? + glide_offsets.input(&input)) - }; - let output = || { - let output = network_interface.output_port_from_click(viewport_location, network_path)?; - Some(network_interface.output_position(&output, network_path)? + glide_offsets.output(&output)) - }; - empty_connector(true).or_else(|| empty_connector(false)).or_else(input).or_else(output) - } - - /// Tells the frontend which connector to show hovered, given by its center in node graph space. - fn set_hovered_connector(&mut self, hovered_connector: Option, responses: &mut VecDeque) { - if self.hovered_connector != hovered_connector { - self.hovered_connector = hovered_connector; - responses.add(FrontendMessage::UpdateHoveredConnector { - center: hovered_connector.map(|center| (center.x, center.y)), - }); + pub fn abort_node_drag(&mut self, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque) -> bool { + if self.drag_start.take().is_none() { + return false; } + network_interface.cancel_drag(network_path); + self.select_if_not_dragged = None; + self.nodes_added_in_drag = false; + self.clear_wire_insertion_preview(responses); + responses.add(DocumentMessage::AbortTransaction); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); + true } /// Stops highlighting the wire a dragged node would be inserted onto. fn clear_wire_insertion_preview(&mut self, responses: &mut VecDeque) { if self.wire_insertion_preview.take().is_some() { - responses.add(FrontendMessage::UpdateWireInsertionPreview { wire: None }); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::InsertionTarget }); + } + } + + pub(crate) fn set_box_selection(&mut self, box_selection: Option<([DVec2; 2], bool)>, responses: &mut VecDeque) { + let drawn = |box_selection: Option<([DVec2; 2], bool)>| box_selection.filter(|(_, dragged)| *dragged); + if drawn(box_selection) != drawn(self.box_selection) { + responses.add(PortfolioMessage::SubmitActiveGraphRender); + } + self.box_selection = box_selection; + } + + fn set_end_index(&mut self, end_index: Option, responses: &mut VecDeque) { + if end_index != self.end_index { + self.end_index = end_index; + responses.add(PortfolioMessage::SubmitActiveGraphRender); } } @@ -2870,26 +2775,25 @@ impl NodeGraphMessageHandler { pub fn abort_import_export_reorder(&mut self, responses: &mut VecDeque) { self.reordering_import = None; self.reordering_export = None; - self.end_index = None; + self.set_end_index(None, responses); responses.add(DocumentMessage::AbortTransaction); - responses.add(FrontendMessage::UpdateImportReorderIndex { index: None }); - responses.add(FrontendMessage::UpdateExportReorderIndex { index: None }); self.update_node_graph_hints(responses); } - /// Ends the wire in progress and closes the context menu, both of which belong to the network being left. + /// Ends the wire in progress and any drag of nodes and closes the context menu, all of which belong to the network being left. pub fn leave_network(&mut self, network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque) { if self.wire_in_progress_from_connector.is_some() { self.end_wire_in_progress(network_interface, network_path, responses); responses.add(DocumentMessage::AbortTransaction); self.update_node_graph_hints(responses); } + self.abort_node_drag(network_interface, network_path, responses); self.clear_wire_insertion_preview(responses); - self.stop_gliding(network_interface, responses); if self.context_menu.take().is_some() { responses.add(FrontendMessage::UpdateContextMenuInformation { context_menu_information: None }); } + self.graph_ui.leave_network(responses); } /// Whether the wire in progress is dragged backward from an input or export end, leaving its output end loose. @@ -2898,17 +2802,21 @@ impl NodeGraphMessageHandler { } /// Keeps a pressed connector lit as the source of the wire about to be dragged out of it, since the press ends its hover before the pointer moves far enough to draw the wire. - fn keep_pressed_connector_lit(center: Option, responses: &mut VecDeque) { - responses.add(FrontendMessage::UpdateWirePathInProgress { - wire_path: None, - dragged_from: center.map(|center| (center.x, center.y)), - snapped_to: None, - }); + fn keep_pressed_connector_lit(&mut self, pressed: ConnectorKey, responses: &mut VecDeque) { + self.graph_ui + .change_highlights(|highlights| (highlights.dragged_from, highlights.snapped_to) = (Some(pressed.into()), None), responses); } - /// Draws the wire in progress between its two ends, where `input_end` is the input it meets at its input end, if any, - /// and `loose_end_snapped` is whether the end following the pointer has snapped to a connector. - fn send_wire_in_progress(&self, input_end: Option, loose_end_snapped: bool, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque) { + /// Draws the wire in progress between its two ends, where `met_input` is the input it meets at its input end, if any, + /// and `snapped_to` is the connector the end following the pointer has snapped to, if any. + fn update_wire_in_progress( + &mut self, + met_input: Option, + snapped_to: Option, + network_interface: &NodeNetworkInterface, + network_path: &[NodeId], + responses: &mut VecDeque, + ) { let (Some(from_connector), Some(to_connector)) = (self.wire_in_progress_from_connector, self.wire_in_progress_to_connector) else { return; }; @@ -2916,34 +2824,31 @@ impl NodeGraphMessageHandler { // Layer outputs and the stack inputs of layers leave and enter vertically let from_connector_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.transform_point2(from_connector); - let from_connector_is_layer = network_interface - .output_connector_from_click(from_connector_viewport, network_path) - .is_some_and(|output_connector| matches!(output_connector, OutputConnector::Node { node_id, .. } if network_interface.is_layer(&node_id, network_path))); - let to_connector_is_layer = - input_end.is_some_and(|input_connector| matches!(input_connector, InputConnector::Node { node_id, input_index: 0 } if network_interface.is_layer(&node_id, network_path))); + let from_output = network_interface.output_connector_from_click(from_connector_viewport, network_path); + let leaves_vertically = from_output + .and_then(|output_connector| network_interface.output_end(&output_connector, network_path)) + .is_some_and(|end| end.vertical); + let enters_vertically = met_input + .and_then(|input_connector| network_interface.input_end(&input_connector, network_path)) + .is_some_and(|end| end.vertical); - let vector_wire = build_vector_wire(from_connector, to_connector, from_connector_is_layer, to_connector_is_layer, GraphWireStyle::Direct); - let wire_path = WirePath { - path_string: vector_wire.to_svg(), - data_type: self.wire_in_progress_type, - thick: false, - dashed: false, - is_list: false, - center_path_string: String::new(), + let end = |position, vertical| WireEnd { position, vertical }; + self.wire_in_progress_ends = Some([end(from_connector, leaves_vertically), end(to_connector, enters_vertically)]); + let dragged_from = match self.wire_in_progress_is_backward() { + true => { + let new_export = self.wire_in_progress_from_new_export.map(|index| ConnectorKey::Input(InputConnector::Export(index))); + self.wire_in_progress_from_input.map(ConnectorKey::Input).or(new_export) + } + false => { + let new_import = self.wire_in_progress_from_new_import.map(|index| ConnectorKey::Output(OutputConnector::Import(index))); + from_output.map(ConnectorKey::Output).or(new_import) + } }; - - // The end it's dragged from always meets a connector, while the loose end does once it snaps to one - let (dragged_from, loose_end) = if self.wire_in_progress_is_backward() { - (to_connector, from_connector) - } else { - (from_connector, to_connector) - }; - - responses.add(FrontendMessage::UpdateWirePathInProgress { - wire_path: Some(wire_path), - dragged_from: Some((dragged_from.x, dragged_from.y)), - snapped_to: loose_end_snapped.then_some((loose_end.x, loose_end.y)), - }); + self.graph_ui.change_highlights( + |highlights| (highlights.dragged_from, highlights.snapped_to) = (dragged_from.map(Into::into), snapped_to.map(Into::into)), + responses, + ); + responses.add(PortfolioMessage::SubmitActiveGraphRender); } /// The output the wire in progress is dragged from. @@ -3064,136 +2969,12 @@ impl NodeGraphMessageHandler { network_interface.set_input(&input_connector, input, network_path); } - /// Where each node and the imports and exports sit, to find what a shift moves. - fn glide_positions(network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (HashMap, Option<(IVec2, IVec2)>) { + fn node_positions(network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> HashMap { let node_ids = network_interface .nested_network(network_path) .map(|network| network.nodes.keys().copied().collect::>()) .unwrap_or_default(); - let node_positions = network_interface.positions(node_ids, network_path).into_iter().collect(); - - (node_positions, network_interface.import_export_position(network_path)) - } - - /// Lets everything that moved away from `positions_before` glide to where it now sits from where it was drawn, so it doesn't jump. - fn begin_glide( - &mut self, - positions_before: (HashMap, Option<(IVec2, IVec2)>), - network_interface: &NodeNetworkInterface, - network_path: &[NodeId], - responses: &mut VecDeque, - ) { - if self.glide_network_path != network_path { - self.stop_gliding(network_interface, responses); - self.glide_network_path = network_path.to_vec(); - } - - let (node_positions_before, import_export_position_before) = positions_before; - let (node_positions, import_export_position) = Self::glide_positions(network_interface, network_path); - let mut glide_offsets = network_interface.glide_offsets(network_path); - - for (node_id, position) in node_positions { - if let Some(position_before) = node_positions_before.get(&node_id) - && *position_before != position - { - *glide_offsets.nodes.entry(node_id).or_default() += (*position_before - position).as_dvec2() * GRID_SIZE as f64; - } - } - - if let (Some((imports_before, exports_before)), Some((imports, exports))) = (import_export_position_before, import_export_position) { - glide_offsets.imports += (imports_before - imports).as_dvec2(); - glide_offsets.exports += (exports_before - exports).as_dvec2(); - } - - self.set_glide_tick_subscribed(!glide_offsets.is_empty(), responses); - network_interface.set_glide_offsets(glide_offsets, network_path); - } - - /// Sends where everything gliding into place is drawn, along with the wires meeting whatever was gliding, which follow it rather than where it sits. - fn send_glide( - glide_offsets: &GlideOffsets, - was_gliding: &GlideOffsets, - network_interface: &NodeNetworkInterface, - wire_style: GraphWireStyle, - network_path: &[NodeId], - responses: &mut VecDeque, - ) { - responses.add(FrontendMessage::UpdateGlideOffsets { - nodes: glide_offsets.nodes.iter().map(|(node_id, offset)| (*node_id, (offset.x, offset.y))).collect(), - imports: (glide_offsets.imports.x, glide_offsets.imports.y), - exports: (glide_offsets.exports.x, glide_offsets.exports.y), - }); - - let wires = Self::gliding_wires(glide_offsets, was_gliding, network_interface, wire_style, network_path); - responses.add(FrontendMessage::UpdateNodeGraphWires { wires }); - } - - /// The wires meeting whatever was gliding, drawn to follow it rather than where it sits. - fn gliding_wires(glide_offsets: &GlideOffsets, was_gliding: &GlideOffsets, network_interface: &NodeNetworkInterface, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Vec { - // The inputs of the nodes and exports that were gliding, and those fed by the nodes and imports that were gliding (leaving out any node deleted meanwhile) - let mut inputs = HashSet::new(); - let mut outputs = Vec::new(); - let network = network_interface.nested_network(network_path); - for node_id in was_gliding.nodes.keys().filter(|node_id| network.is_some_and(|network| network.nodes.contains_key(node_id))) { - inputs.extend((0..network_interface.number_of_inputs(node_id, network_path)).map(|input_index| InputConnector::node_at_index(*node_id, input_index))); - outputs.extend((0..network_interface.number_of_outputs(node_id, network_path)).map(|output_index| OutputConnector::node(*node_id, output_index))); - } - - if was_gliding.exports != DVec2::ZERO { - inputs.extend((0..network_interface.number_of_exports(network_path)).map(InputConnector::Export)); - } - if was_gliding.imports != DVec2::ZERO { - outputs.extend((0..network_interface.number_of_imports(network_path)).map(OutputConnector::Import)); - } - - network_interface.with_outward_wires(network_path, |outward_wires| { - for output in &outputs { - inputs.extend(outward_wires.get(output).into_iter().flatten().copied()); - } - }); - - let mut wires = inputs - .iter() - .filter(|input| network_interface.input_from_connector(input, network_path).is_some_and(|input| input.is_exposed())) - .filter_map(|input| network_interface.wire_update_from_input(input, wire_style, glide_offsets, network_path)) - .collect::>(); - wires.extend(network_interface.wire_to_preview(wire_style, glide_offsets, network_path)); - wires - } - - /// Settles whatever is gliding into place at once, such as when the drag moving it is aborted. - pub fn stop_gliding(&mut self, network_interface: &NodeNetworkInterface, responses: &mut VecDeque) { - if !self.glide_tick_subscribed { - return; - } - - network_interface.set_glide_offsets(GlideOffsets::default(), &self.glide_network_path); - responses.add(FrontendMessage::UpdateGlideOffsets { - nodes: Vec::new(), - imports: (0., 0.), - exports: (0., 0.), - }); - self.set_glide_tick_subscribed(false, responses); - } - - fn set_glide_tick_subscribed(&mut self, subscribed: bool, responses: &mut VecDeque) { - if self.glide_tick_subscribed == subscribed { - return; - } - self.glide_tick_subscribed = subscribed; - self.glide_last_tick_time = None; - - let send = Box::new(NodeGraphMessage::GlideTick.into()); - responses.add(match subscribed { - true => BroadcastMessage::SubscribeEvent { - on: EventMessage::AnimationFrame, - send, - }, - false => BroadcastMessage::UnsubscribeEvent { - on: EventMessage::AnimationFrame, - send, - }, - }); + network_interface.positions(node_ids, network_path).into_iter().collect() } fn set_wire_hover_tick_subscribed(&mut self, subscribed: bool, responses: &mut VecDeque) { @@ -3245,7 +3026,7 @@ impl NodeGraphMessageHandler { /// The wire a single dragged node would be inserted onto if dropped where it is, with the node and the index of its input the wire would feed. /// A node is only inserted when it's alone in the selection, has nothing wired out of its primary output, has a free first exposed input, and overlaps exactly one fitting wire. // O(wires), since each wire's path is intersected with the node's bounds - pub(crate) fn wire_to_insert_on(network_interface: &mut NodeNetworkInterface, graph_wire_style: GraphWireStyle, selection_network_path: &[NodeId]) -> Option<(NodeId, usize, InputConnector)> { + pub(crate) fn wire_to_insert_on(network_interface: &mut NodeNetworkInterface, graph_wire_style: WireStyle, selection_network_path: &[NodeId]) -> Option<(NodeId, usize, InputConnector)> { let selected_nodes = network_interface.selected_nodes_in_nested_network(selection_network_path)?; let [selected_node_id] = *selected_nodes.selected_nodes_ref().as_slice() else { return None }; @@ -3288,7 +3069,7 @@ impl NodeGraphMessageHandler { return None; } - let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, graph_wire_style, selection_network_path)?; + let (wire, is_stack) = network_interface.vector_wire_from_input(&input, graph_wire_style, selection_network_path)?; let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None); let intersect = wire @@ -3762,112 +3543,6 @@ impl NodeGraphMessageHandler { } } - fn collect_wires(&mut self, network_interface: &mut NodeNetworkInterface, graph_wire_style: GraphWireStyle, breadcrumb_network_path: &[NodeId]) -> Vec { - let drawn_wires: HashMap<(NodeId, usize), WirePath> = network_interface - .node_graph_input_connectors(breadcrumb_network_path) - .iter() - .filter_map(|connector| network_interface.wire_update_from_input(connector, graph_wire_style, &GlideOffsets::default(), breadcrumb_network_path)) - .filter_map(|update| Some(((update.id, update.input_index), update.wire_path_update?))) - .collect(); - - let removed_wires = self.frontend_wires.keys().filter(|wire| !drawn_wires.contains_key(wire)).map(|(id, input_index)| WirePathUpdate { - id: *id, - input_index: *input_index, - wire_path_update: None, - }); - let changed_wires = drawn_wires - .iter() - .filter(|(wire, path)| self.frontend_wires.get(wire) != Some(path)) - .map(|((id, input_index), path)| WirePathUpdate { - id: *id, - input_index: *input_index, - wire_path_update: Some(path.clone()), - }); - let mut added_wires: Vec = removed_wires.chain(changed_wires).collect(); - self.frontend_wires = drawn_wires; - - if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, &GlideOffsets::default(), breadcrumb_network_path) { - added_wires.push(wire_to_preview); - } else { - added_wires.push(WirePathUpdate { - id: NodeId(u64::MAX), - input_index: u32::MAX as usize, - wire_path_update: None, - }) - } - - added_wires - } - - pub(crate) fn collect_nodes(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec { - let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { - log::error!("Could not get nested network when collecting nodes"); - return Vec::new(); - }; - let mut nodes = Vec::new(); - for (node_id, visible) in network.nodes.iter().map(|(node_id, node)| (*node_id, node.visible)).collect::>() { - let primary_input_connector = InputConnector::primary_input(node_id); - - let primary_input = if network_interface - .input_from_connector(&primary_input_connector, breadcrumb_network_path) - .is_some_and(|input| input.is_exposed()) - { - network_interface.frontend_input_from_connector(&primary_input_connector, breadcrumb_network_path) - } else { - None - }; - let exposed_inputs = (1..network_interface.number_of_inputs(&node_id, breadcrumb_network_path)) - .filter_map(|input_index| network_interface.frontend_input_from_connector(&InputConnector::node_at_index(node_id, input_index), breadcrumb_network_path)) - .collect(); - - let primary_output = network_interface.frontend_output_from_connector(&OutputConnector::primary_output(node_id), breadcrumb_network_path); - - let exposed_outputs = (1..network_interface.number_of_outputs(&node_id, breadcrumb_network_path)) - .filter_map(|output_index| network_interface.frontend_output_from_connector(&OutputConnector::node(node_id, output_index), breadcrumb_network_path)) - .collect(); - let (primary_output_connected_to_layer, primary_input_connected_to_layer) = if network_interface.is_layer(&node_id, breadcrumb_network_path) { - ( - network_interface.primary_output_connected_to_layer(&node_id, breadcrumb_network_path), - network_interface.primary_input_connected_to_layer(&node_id, breadcrumb_network_path), - ) - } else { - (false, false) - }; - - let Some(position) = network_interface.position(&node_id, breadcrumb_network_path) else { - log::error!("Could not get position for node: {node_id}"); - continue; - }; - let previewed = network_interface.previewing(breadcrumb_network_path).previews(node_id); - - let locked = network_interface.is_locked(&node_id, breadcrumb_network_path); - - nodes.push(FrontendNode { - id: node_id, - is_layer: network_interface - .node_metadata(&node_id, breadcrumb_network_path) - .is_some_and(|node_metadata| node_metadata.persistent_metadata.is_layer()), - can_be_layer: network_interface.is_eligible_to_be_layer(&node_id, breadcrumb_network_path), - is_redirect_dot: network_interface.is_redirect_dot(&node_id, breadcrumb_network_path), - reference: network_interface.reference(&node_id, breadcrumb_network_path).map(|reference| reference.serialized()), - display_name: network_interface.display_name(&node_id, breadcrumb_network_path), - implementation_name: network_interface.implementation_name(&node_id, breadcrumb_network_path), - primary_input, - exposed_inputs, - primary_output, - exposed_outputs, - primary_output_connected_to_layer, - primary_input_connected_to_layer, - position: position.into(), - previewed, - visible, - locked, - }); - } - - nodes - } - fn collect_subgraph_names(network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Option> { let mut current_network_path = vec![]; let mut current_network = network_interface.nested_network(¤t_network_path).unwrap(); @@ -3883,7 +3558,7 @@ impl NodeGraphMessageHandler { Some(subgraph_names) } - fn node_graph_errors(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec { + pub(crate) fn node_graph_errors(&self, network_interface: &NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec<(NodeId, String)> { let depth = breadcrumb_network_path.len(); let inside = |path: &[NodeId]| path.starts_with(breadcrumb_network_path) && path.len() > depth; let graph_errors: Vec<_> = network_interface @@ -3918,23 +3593,7 @@ impl NodeGraphMessageHandler { errors.extend(warnings); let mut shown = HashSet::new(); - errors - .into_iter() - .filter(|(node, _)| shown.insert(*node)) - .filter_map(|(node, error)| { - let mut position = network_interface.position(&node, breadcrumb_network_path)?; - // Convert to graph space - position *= 24; - if network_interface.is_layer(&node, breadcrumb_network_path) { - position += IVec2::new(12, -12) - } - Some(NodeGraphErrorDiagnostic { - node_id: node, - position: position.into(), - error, - }) - }) - .collect() + errors.into_iter().filter(|(node, _)| shown.insert(*node)).collect() } /// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view. @@ -4058,7 +3717,7 @@ impl NodeGraphMessageHandler { let dragging_nodes = self.drag_start.as_ref().is_some_and(|(_, dragged)| *dragged); // A box selection is in progress - let dragging_box_selection = self.box_selection_start.is_some_and(|(_, box_selection_dragged)| box_selection_dragged); + let dragging_box_selection = self.box_selection.is_some_and(|(_, box_selection_dragged)| box_selection_dragged); // An import or export is being dragged to a new position let reordering_import_export = self.is_reordering_import_export() && self.end_index.is_some(); @@ -4123,10 +3782,9 @@ impl Default for NodeGraphMessageHandler { double_click_used_by_press: false, dot_drag_out: None, keep_upstream_in_place: false, - box_selection_start: None, + box_selection: None, drag_start_chain_nodes: Vec::new(), wire_insertion_preview: None, - hovered_connector: None, selection_before_pointer_down: Vec::new(), disconnecting: None, initial_disconnecting: false, @@ -4135,15 +3793,13 @@ impl Default for NodeGraphMessageHandler { wire_in_progress_from_connector: None, wire_in_progress_to_connector: None, wire_in_progress_type: FrontendGraphDataType::General, + wire_in_progress_ends: None, wire_in_progress_from_new_import: None, wire_in_progress_from_input: None, wire_in_progress_from_new_export: None, wire_hovered_node: None, wire_expanded_node: None, wire_hover_tick_subscribed: false, - glide_network_path: Vec::new(), - glide_last_tick_time: None, - glide_tick_subscribed: false, context_menu: None, deselect_on_pointer_up: None, auto_panning: Default::default(), @@ -4151,9 +3807,8 @@ impl Default for NodeGraphMessageHandler { reordering_export: None, reordering_import: None, end_index: None, - frontend_nodes: Vec::new(), - frontend_wires: HashMap::new(), evaluation_errors: Vec::new(), + graph_ui: GraphUiState::default(), } } } @@ -4171,7 +3826,7 @@ impl PartialEq for NodeGraphMessageHandler { && self.latest_left_press == other.latest_left_press && self.double_click_used_by_press == other.double_click_used_by_press && self.dot_drag_out == other.dot_drag_out - && self.box_selection_start == other.box_selection_start + && self.box_selection == other.box_selection && self.initial_disconnecting == other.initial_disconnecting && self.select_if_not_dragged == other.select_if_not_dragged && self.layer_button_press == other.layer_button_press 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 efa78006c1..f05bde08b4 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -43,71 +43,27 @@ impl FrontendGraphDataType { } } -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct FrontendGraphInput { - #[serde(rename = "dataType")] - pub data_type: FrontendGraphDataType, +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct InputTooltip { pub name: String, pub description: String, - #[serde(rename = "resolvedType")] pub resolved_type: String, - #[serde(rename = "validTypes")] pub valid_types: Vec, /// Whether a wire feeds this input. pub connected: bool, } -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct FrontendGraphOutput { - #[serde(rename = "dataType")] - pub data_type: FrontendGraphDataType, +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct OutputTooltip { pub name: String, pub description: String, - #[serde(rename = "resolvedType")] pub resolved_type: String, /// Every type this output could produce given its node's current inputs, or empty where that isn't known. - #[serde(rename = "possibleTypes")] pub possible_types: Vec, /// Whether this output feeds at least one wire. pub connected: bool, } -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct FrontendNode { - pub id: graph_craft::document::NodeId, - #[serde(rename = "isLayer")] - pub is_layer: bool, - #[serde(rename = "canBeLayer")] - pub can_be_layer: bool, - /// Whether the node is a redirect dot, which is a Passthrough node drawn as a small dot bending the wire running through it. - #[serde(rename = "isRedirectDot")] - pub is_redirect_dot: bool, - pub reference: Option, - #[serde(rename = "displayName")] - pub display_name: String, - #[serde(rename = "implementationName")] - pub implementation_name: String, - #[serde(rename = "primaryInput")] - pub primary_input: Option, - #[serde(rename = "exposedInputs")] - pub exposed_inputs: Vec, - #[serde(rename = "primaryOutput")] - pub primary_output: Option, - #[serde(rename = "exposedOutputs")] - pub exposed_outputs: Vec, - #[serde(rename = "primaryInputConnectedToLayer")] - pub primary_input_connected_to_layer: bool, - #[serde(rename = "primaryOutputConnectedToLayer")] - pub primary_output_connected_to_layer: bool, - pub position: (i32, i32), - pub previewed: bool, - pub visible: bool, - pub locked: bool, -} - #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum InputTypeConstraint { @@ -135,19 +91,6 @@ pub struct DragStart { pub stored: IVec2, } -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct BoxSelection { - #[serde(rename = "startX")] - pub start_x: u32, - #[serde(rename = "startY")] - pub start_y: u32, - #[serde(rename = "endX")] - pub end_x: u32, - #[serde(rename = "endY")] - pub end_y: u32, -} - #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data")] @@ -180,6 +123,10 @@ pub enum ContextMenuData { exposed: bool, /// Whether any wire is attached to it within the subgraph. connected: bool, + description: String, + /// Where the description popover points, in node graph coordinates. + #[serde(rename = "descriptionAnchor")] + description_anchor: (f64, f64), }, } @@ -196,16 +143,6 @@ pub struct ContextMenuInformation { pub context_menu_data: ContextMenuData, } -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)] -pub struct NodeGraphErrorDiagnostic { - /// The node the error is shown beside, which it follows as the node glides into place. - #[serde(rename = "nodeId")] - pub node_id: NodeId, - pub position: (i32, i32), - pub error: String, -} - #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct NodeEvaluationError { pub node_path: Vec, diff --git a/editor/src/messages/portfolio/document/overlays/overlays_message_handler.rs b/editor/src/messages/portfolio/document/overlays/overlays_message_handler.rs index ee74380950..0e4ee567cf 100644 --- a/editor/src/messages/portfolio/document/overlays/overlays_message_handler.rs +++ b/editor/src/messages/portfolio/document/overlays/overlays_message_handler.rs @@ -24,9 +24,12 @@ impl MessageHandler> for OverlaysMes OverlaysMessage::Draw => { use super::utility_types::OverlayContext; + if context.graph_open { + return; + } let overlay_context = OverlayContext::new(*viewport, visibility_settings); - if visibility_settings.all() && !context.graph_open { + if visibility_settings.all() { responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() }); responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() }); diff --git a/editor/src/messages/portfolio/document/storage_tests/layout_pass_tests.rs b/editor/src/messages/portfolio/document/storage_tests/layout_pass_tests.rs index 4df7059a17..a83249d1d6 100644 --- a/editor/src/messages/portfolio/document/storage_tests/layout_pass_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/layout_pass_tests.rs @@ -1,9 +1,11 @@ //! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand. use super::test_support::open_demo; -use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part}; -use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; +use crate::messages::portfolio::document::utility_types::network_interface::Part; use glam::DVec2; +use graph_ui::geometry::WireEnd; +use graph_ui::router::route; +use graph_ui::wire::WireStyle; use graphene_std::uuid::NodeId; use std::time::Instant; @@ -19,38 +21,6 @@ const DEMOS: [&str; 8] = [ ]; const REPETITIONS: u32 = 200; -#[test] -fn wire_anchors_lie_on_the_ports_of_every_demo_node() { - for demo in DEMOS { - let document = open_demo(demo); - let interface = &document.network_interface; - - for node_id in interface.document_network().nodes.keys() { - // A redirect dot's wires attach at its center, between the gutters they're grabbed from - let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body"); - let is_redirect_dot = interface.is_redirect_dot(node_id, &[]); - let on_port = |wanted: Part, anchor: Option| { - let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target)); - match (port, anchor) { - (Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2., - (Some(port), Some(anchor)) => port.contains(anchor), - (None, None) => true, - _ => false, - } - }; - - for index in 0..interface.number_of_inputs(node_id, &[]) { - let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]); - assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}"); - } - for index in 0..interface.number_of_outputs(node_id, &[]) { - let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]); - assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}"); - } - } - } -} - #[test] #[ignore] fn time_the_layout_click_targets_and_hit_tests() { @@ -81,7 +51,7 @@ fn time_the_layout_click_targets_and_hit_tests() { let start = Instant::now(); for _ in 0..REPETITIONS { for input in &inputs { - std::hint::black_box(interface.wire_update_from_input(input, GraphWireStyle::default(), &GlideOffsets::default(), &[])); + std::hint::black_box(interface.vector_wire_from_input(input, WireStyle::default(), &[])); } } let all_wires = start.elapsed() / REPETITIONS; @@ -104,25 +74,16 @@ fn time_the_layout_click_targets_and_hit_tests() { let types = start.elapsed() / REPETITIONS; let endpoints: Vec<_> = connected .iter() - .filter_map(|(input, output)| Some((interface.output_position(output, &[])?, interface.input_position(input, &[])?))) + .filter_map(|(input, output)| Some([interface.output_position(output, &[])?, interface.input_position(input, &[])?].map(|position| WireEnd { position, vertical: false }))) .collect(); let start = Instant::now(); for _ in 0..REPETITIONS { - for (output, input) in &endpoints { - std::hint::black_box(crate::messages::portfolio::document::utility_types::wires::build_vector_wire( - *output, - *input, - false, - false, - GraphWireStyle::default(), - )); + for ends in &endpoints { + std::hint::black_box(route(*ends, WireStyle::default())); } } let paths = start.elapsed() / REPETITIONS; - let built: Vec<_> = endpoints - .iter() - .map(|(output, input)| crate::messages::portfolio::document::utility_types::wires::build_vector_wire(*output, *input, false, false, GraphWireStyle::default())) - .collect(); + let built: Vec<_> = endpoints.iter().map(|ends| route(*ends, WireStyle::default())).collect(); let start = Instant::now(); for _ in 0..REPETITIONS { for path in &built { diff --git a/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs b/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs index 8695b2cdec..0d20c001db 100644 --- a/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs +++ b/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs @@ -2,13 +2,13 @@ use crate::messages::prelude::*; use graph_craft::document::NodeId; use std::collections::{HashMap, HashSet}; -/// The layers the frontend shows in view, as rows of the Layers panel and as nodes in the node graph, which are the only ones it's sent the thumbnails of. -/// The latest thumbnail of every layer waits here for whenever the layer comes into view. +/// The layers in view in the Layers panel and the node graph, which the graph runtime renders thumbnails for. +/// The latest thumbnail of each waits here, and goes to the frontend while its layer has a row in view in the Layers panel. #[derive(Debug, Clone, Default)] pub struct LayersInView { /// The layers with a row in view in the Layers panel, which is also sent their details. layers_panel: HashSet, - /// The nodes in view in the node graph while it's open. + /// The layers in view in the node graph while it's open. node_graph: HashSet, /// The message with the latest thumbnail of each layer, as rendered by the graph runtime. thumbnails: HashMap, @@ -29,27 +29,26 @@ impl LayersInView { /// Sets the layers with a row in view in the Layers panel, sending the thumbnails it lacks for them. pub fn set_layers_panel(&mut self, layers: HashSet, responses: &mut VecDeque) { self.layers_panel = layers; - self.send_thumbnails_in_view(responses); + self.send_thumbnails_in_layers_panel(responses); responses.add(PortfolioMessage::SubmitThumbnailsInView); } - /// Sets the nodes in view in the node graph, sending the thumbnails it lacks for those that are layers. + /// Sets the nodes in view in the node graph, which draws the thumbnails of those that are layers itself. pub fn set_node_graph(&mut self, nodes: HashSet, responses: &mut VecDeque) { self.node_graph = nodes; - self.send_thumbnails_in_view(responses); responses.add(PortfolioMessage::SubmitThumbnailsInView); } pub fn thumbnail_layer(message: &FrontendMessage) -> Option { match message { - FrontendMessage::UpdateNodeThumbnailCanvases { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id), + FrontendMessage::UpdateNodeThumbnailCanvas { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id), _ => None, } } - /// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view. + /// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view in the Layers panel. pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: FrontendMessage, responses: &mut VecDeque) { - if self.in_view(&layer) { + if self.layers_panel.contains(&layer) { responses.add(thumbnail.clone()); self.thumbnails_sent.insert(layer); } else { @@ -79,13 +78,8 @@ impl LayersInView { } } - fn in_view(&self, layer: &NodeId) -> bool { - self.layers_panel.contains(layer) || self.node_graph.contains(layer) - } - - // O(layers in view) - fn send_thumbnails_in_view(&mut self, responses: &mut VecDeque) { - for &layer in self.layers_panel.iter().chain(&self.node_graph) { + fn send_thumbnails_in_layers_panel(&mut self, responses: &mut VecDeque) { + for &layer in &self.layers_panel { if self.thumbnails_sent.contains(&layer) { continue; } @@ -136,7 +130,7 @@ mod tests { assert_eq!(thumbnails_sent(responses), vec![(layer, "latest".to_string())], "coming into view, only the latest thumbnail is sent"); let mut responses = VecDeque::new(); - layers_in_view.set_node_graph(HashSet::from([layer]), &mut responses); + layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses); assert!(thumbnails_sent(responses).is_empty(), "a thumbnail the frontend already has isn't sent again"); } diff --git a/editor/src/messages/portfolio/document/utility_types/mod.rs b/editor/src/messages/portfolio/document/utility_types/mod.rs index 141690238d..87f1cf751d 100644 --- a/editor/src/messages/portfolio/document/utility_types/mod.rs +++ b/editor/src/messages/portfolio/document/utility_types/mod.rs @@ -6,4 +6,3 @@ pub mod network_interface; pub mod nodes; pub mod text_metrics; pub mod transformation; -pub mod wires; 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 a7c35b2994..283171f450 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -9,12 +9,12 @@ pub(crate) use catalog::shipped_node_id; pub(crate) use derived_ids::derived_node_id; #[cfg(test)] mod characterization_tests; +mod connectors; mod derived_ids; mod deserialization; pub mod editor_delta; #[cfg(test)] mod editor_delta_tests; -mod frontend; mod geometry; mod hit_tests; mod invalidation; @@ -22,7 +22,6 @@ mod layout; mod layout_pass; mod memo_network; mod mutations; -mod node_parts; mod queries; mod reconcile; mod resolved_types; @@ -36,8 +35,8 @@ mod validation; mod view; pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange}; +pub use graph_ui::geometry::{Part, PartTarget}; pub use layout_pass::NetworkLayout; -pub use node_parts::{Part, PartTarget}; pub use reconcile::{ReconcileError, Reconciled}; use store::Guarded; pub use store::NodeLocator; @@ -50,14 +49,11 @@ use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelati use super::misc::PTZ; use super::nodes::SelectedNodes; use crate::consts::{ - EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, HALF_GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, - STACK_VERTICAL_GAP, + EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, STACK_VERTICAL_GAP, }; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type}; -use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput}; +use crate::messages::portfolio::document::node_graph::utility_types::{InputTooltip, OutputTooltip}; use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes; -use crate::messages::portfolio::document::utility_types::text_metrics::text_width; -use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode; use deserialization::deserialize_node_persistent_metadata; @@ -66,6 +62,9 @@ use graph_craft::Type; use graph_craft::application_io::resource::ResourceId; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, LiftedNetwork, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork}; +use graph_ui::geometry::is_thick_wire; +use graph_ui::router::route; +use graph_ui::wire::WireStyle; use graphene_std::Appearance; use graphene_std::math::quad::Quad; use graphene_std::registry::MULTI_OUTPUT_NODES; @@ -479,8 +478,8 @@ mod network_interface_tests { let mut interface = NodeNetworkInterface::from_trees(network, network_metadata); assert_eq!(interface.validate_invariants(), Vec::::new()); - interface.set_import_export_name("Shared".into(), ImportOrExport::Import(0), &[NodeId(10)]); - interface.set_import_export_name("Result".into(), ImportOrExport::Export(0), &[NodeId(10)]); + interface.set_import_export_name("Shared".into(), NetworkConnectorKey::Import(0), &[NodeId(10)]); + interface.set_import_export_name("Result".into(), NetworkConnectorKey::Export(0), &[NodeId(10)]); let view = interface.view(&[]).unwrap(); assert_eq!(view.persistent_input_metadata(&NodeId(11), 0).unwrap().input_name, "Shared"); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs index 7e39dedf4d..487bcb2b03 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs @@ -74,20 +74,6 @@ impl NodeNetworkInterface { } } - pub fn glide_offsets(&self, network_path: &[NodeId]) -> GlideOffsets { - self.network_metadata(network_path) - .map(|network_metadata| network_metadata.transient_metadata.glide_offsets.borrow().clone()) - .unwrap_or_default() - } - - pub fn set_glide_offsets(&self, glide_offsets: GlideOffsets, network_path: &[NodeId]) { - let Some(network_metadata) = self.network_metadata(network_path) else { - log::error!("Could not get nested network_metadata in set_glide_offsets"); - return; - }; - *network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets; - } - /// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed. pub(crate) fn with_import_export_ports(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option { let generation = self.with_layout(network_path, NetworkLayout::generation)?; @@ -279,10 +265,6 @@ impl NodeNetworkInterface { } } - pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option { - self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width) - } - pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> { let Some(node_metadata) = self.node_metadata(node_id, network_path) else { log::error!("Could not get nested node_metadata in layer_width"); @@ -312,29 +294,6 @@ impl NodeNetworkInterface { } } - pub fn get_input_center(&self, input: &InputConnector, network_path: &[NodeId]) -> Option { - self.input_position(input, network_path) - } - - pub fn get_output_center(&self, output: &OutputConnector, network_path: &[NodeId]) -> Option { - self.output_position(output, network_path) - } - - /// The wire into the input as the frontend draws it, with its ends following anything drawn gliding into place. - pub fn wire_update_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option { - let wire = self.wire_path_from_input(input, graph_wire_style, false, glide_offsets, network_path)?; - let (id, input_index) = match input { - InputConnector::Node { node_id, input_index } => (*node_id, *input_index), - InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index), - }; - - Some(WirePathUpdate { - id, - input_index, - wire_path_update: Some(wire), - }) - } - pub fn all_input_connectors(&self, network_path: &[NodeId]) -> Vec { let mut input_connectors = Vec::new(); let Some(network) = self.nested_network(network_path) else { @@ -359,119 +318,24 @@ impl NodeNetworkInterface { .collect() } - /// Maps to the frontend representation of a wire start. Includes disconnected value wire inputs. - pub fn node_graph_wire_inputs(&self, network_path: &[NodeId]) -> Vec<(NodeId, usize)> { - self.node_graph_input_connectors(network_path) - .iter() - .map(|input| match input { - InputConnector::Node { node_id, input_index } => (*node_id, *input_index), - InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index), - }) - .chain(std::iter::once((NodeId(u64::MAX), u32::MAX as usize))) - .collect() - } - - /// The dashed wire from the previewed node to the export, drawn alongside the export's own wire. - pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option { - let input = InputConnector::Export(0); - - let Previewing::Yes { previewed } = self.previewing(network_path) else { return None }; - - if self.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) { - return None; - } - let Some(input_position) = self.get_input_center(&input, network_path) else { - log::error!("Could not get input position for wire end in preview: {input:?}"); - return None; - }; - let input_position = input_position + glide_offsets.input(&input); - let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index); - let Some(output_position) = self.get_output_center(&upstream_output, network_path) else { - log::error!("Could not get output position for wire start in preview: {upstream_output:?}"); - return None; - }; - let output_position = output_position + glide_offsets.output(&upstream_output); - let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0); - let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path)); - let thick = vertical_end && vertical_start; - let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style); - let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style); - - let path_string = vector_wire.to_svg(); - let center_path_string = center_line.to_svg(); - let output_type = self.output_type(&upstream_output, network_path); - let data_type = output_type.displayed_type(); - let is_list = output_type.is_list(); - let wire_path_update = Some(WirePath { - path_string, - data_type, - thick, - dashed: true, - is_list, - center_path_string, - }); - - Some(WirePathUpdate { - id: NodeId(u64::MAX), - input_index: u32::MAX as usize, - wire_path_update, - }) - } - - /// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick. - pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> { - self.gliding_vector_wire_from_input(input, wire_style, &GlideOffsets::default(), network_path) - } - - /// Like [`Self::vector_wire_from_input`], but with its ends following anything drawn gliding into place. - pub(crate) fn gliding_vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> { - let Some(input_position) = self.get_input_center(input, network_path) else { + /// Returns the wire subpath and whether the wire should be thick, or None if nothing feeds the input. + pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: WireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> { + let Some(to) = self.input_end(input, network_path) else { log::error!("Could not get dom rect for wire end: {input:?}"); return None; }; - let input_position = input_position + glide_offsets.input(input); - // An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector - let Some(upstream_output) = self.upstream_output_connector(input, network_path) else { - return Some((BezPath::new(), BezPath::new(), false)); - }; - let Some(output_position) = self.get_output_center(&upstream_output, network_path) else { + let upstream_output = self.upstream_output_connector(input, network_path)?; + let Some(from) = self.output_end(&upstream_output, network_path) else { log::error!("Could not get output port for wire start: {upstream_output:?}"); return None; }; - let output_position = output_position + glide_offsets.output(&upstream_output); - let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0); - let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path)); - let thick = vertical_end && vertical_start; - let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style); - let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style); - Some((vector_wire, center_line, thick)) - } - - pub fn wire_path_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option { - let (vector_wire, center_line, thick) = self.gliding_vector_wire_from_input(input, graph_wire_style, glide_offsets, network_path)?; - let path_string = vector_wire.to_svg(); - let center_path_string = center_line.to_svg(); - let (data_type, is_list) = self - .upstream_output_connector(input, network_path) - .map(|output| { - let output_type = self.output_type(&output, network_path); - (output_type.displayed_type(), output_type.is_list()) - }) - .unwrap_or((FrontendGraphDataType::General, false)); - Some(WirePath { - path_string, - data_type, - thick, - dashed, - is_list, - center_path_string, - }) + Some((route([from, to], wire_style), is_thick_wire([from, to]))) } /// The node's body, ports, and handles, built where it is drawn now. /// The box around the node's body where it sits in its grid cell, in node graph space. pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> { - let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?; + let body = self.with_layout(network_path, |layout| layout.geometry(node_id)).flatten()?.body(); Some([body.min, body.max]) } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs index c066c3f044..1769b7895e 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs @@ -1,16 +1,15 @@ use super::{ - ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, + ChainInsertionPoint, FlowType, InputConnector, LayerClickTargetTypes, NetworkConnectorKey, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus, }; use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; -use crate::messages::input_mapper::utility_types::pointer::EditorPointerState; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction}; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; -use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::test_utils::test_prelude::*; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNodeImplementation, NodeInput}; +use graph_ui::wire::WireStyle; use graphene_std::uuid::NodeId; fn assert_invariants(editor: &EditorTestUtils, context: &str) { @@ -1190,12 +1189,7 @@ async fn a_stack_closes_up_over_a_deleted_layer_and_a_nudge_moves_the_rest_one_r editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third] }).await; let network_interface = &editor.active_document().network_interface; let before = network_interface.position(&third, &[]).expect("Surviving layer should have a position"); - editor - .handle_message(NodeGraphMessage::ShiftSelectedNodes { - direction: Direction::Down, - glide: false, - }) - .await; + editor.handle_message(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down }).await; let network_interface = &editor.active_document().network_interface; let after = network_interface.position(&third, &[]).expect("Surviving layer should have a position"); assert_eq!(after.y - before.y, 1, "A single nudge should move the layer exactly one unit"); @@ -1452,13 +1446,13 @@ async fn editing_import_and_export_descriptions_stores_them_on_the_subgraph_node editor .handle_message(NodeGraphMessage::SetImportExportDescription { description: "The artwork to add.".to_string(), - index: ImportOrExport::Import(1), + index: NetworkConnectorKey::Import(1), }) .await; editor .handle_message(NodeGraphMessage::SetImportExportDescription { description: "The combined result.".to_string(), - index: ImportOrExport::Export(0), + index: NetworkConnectorKey::Export(0), }) .await; @@ -2442,14 +2436,14 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() { // Level with the wire between the other two network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]); assert_eq!( - NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), + NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]), Some((dragged, 0, InputConnector::node_at_index(consumer, 0))), "the wire it overlaps is the one a drop would insert it onto" ); network_interface.set_absolute_position(&dragged, IVec2::new(8, 10), &[]); assert_eq!( - NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), + NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]), None, "clear of every wire it previews nothing" ); @@ -2457,7 +2451,7 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() { // With a node already taking its output, a drop would not insert it network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]); network_interface.set_input(&InputConnector::node_at_index(source, 0), NodeInput::node(dragged, 0), &[]); - assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), None); + assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]), None); } fn passthrough_definition() -> DefinitionIdentifier { @@ -2864,7 +2858,7 @@ async fn double_click_in_graph(editor: &mut EditorTestUtils, point: DVec2, secon fn wire_middle(network_interface: &NodeNetworkInterface, input: InputConnector) -> DVec2 { use kurbo::ParamCurveArclen; - let (wire, _, _) = network_interface.vector_wire_from_input(&input, GraphWireStyle::Direct, &[]).expect("the wire should have a path"); + let (wire, _) = network_interface.vector_wire_from_input(&input, WireStyle::Direct, &[]).expect("the wire should have a path"); let longest_segment = wire .segments() .max_by(|a, b| a.arclen(kurbo::DEFAULT_ACCURACY).total_cmp(&b.arclen(kurbo::DEFAULT_ACCURACY))) @@ -3711,96 +3705,18 @@ fn a_wire_is_found_near_its_path_but_not_away_from_it() { let input = InputConnector::node_at_index(consumer, 0); let on_wire = wire_middle(&network_interface, input); - assert_eq!(network_interface.wire_input_from_point(on_wire, 6., GraphWireStyle::Direct, &[]), Some(input)); - assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., GraphWireStyle::Direct, &[]), None); -} - -#[tokio::test] -async fn a_dragged_layer_keeps_its_wires_where_it_is_drawn_in_the_frame_it_moves() { - let mut editor = EditorTestUtils::create(); - editor.new_document().await; - let (layer, ..) = layer_with_chain(&mut editor).await; - editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await; - - let left_input = InputConnector::layer_secondary_input(layer); - let network_interface = &editor.active_document().network_interface; - let wire_before = network_interface.wire_path_from_input(&left_input, GraphWireStyle::default(), false, &GlideOffsets::default(), &[]); - let bounds = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds"); - let press = DVec2::new(bounds[1].x - 30., (bounds[0].y + bounds[1].y) / 2.); - let node_graph_to_viewport = network_interface - .network_metadata(&[]) - .expect("the network should have metadata") - .persistent_metadata - .navigation_metadata - .node_graph_to_viewport; - - let pressed = node_graph_to_viewport.transform_point2(press); - editor.move_mouse(pressed.x, pressed.y, ModifierKeys::empty(), MouseKeys::empty()).await; - editor - .handle_message(NodeGraphMessage::PointerDown { - shift_click: false, - control_click: false, - alt_click: false, - right_click: false, - }) - .await; - - // One grid cell right, through the input preprocessor so the frontend messages of the move itself are returned - let moved = node_graph_to_viewport.transform_point2(press + DVec2::new(GRID_SIZE as f64, 0.)); - let editor_mouse_state = EditorPointerState { - editor_position: moved, - mouse_keys: MouseKeys::LEFT, - ..Default::default() - }; - let messages = editor - .handle_message(InputPreprocessorMessage::PointerMove { - editor_mouse_state, - modifier_keys: ModifierKeys::empty(), - }) - .await; - - // Still drawn a whole cell back as it starts gliding, so the last wire sent to its left input is the one from before the move - let last_wire_sent = messages - .into_iter() - .filter_map(|message| match message { - FrontendMessage::UpdateNodeGraphWires { wires } => Some(wires), - _ => None, - }) - .flatten() - .rfind(|wire| wire.id == layer && wire.input_index == 1) - .and_then(|wire| wire.wire_path_update); - assert_eq!(last_wire_sent.map(|wire| wire.path_string), wire_before.map(|wire| wire.path_string)); -} - -/// Nudges the only node of a new document while its graph is open, so the node starts gliding into the cell it moved to. -async fn gliding_nudged_node(editor: &mut EditorTestUtils) -> NodeId { - editor.new_document().await; - let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; - editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await; - editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; - editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; - assert!( - !editor.active_document().network_interface.glide_offsets(&[]).is_empty(), - "the nudged node should be gliding: fixture is wrong" - ); - node -} - -#[tokio::test] -async fn redoing_a_nudge_undone_while_it_glides_leaves_nothing_gliding() { - let mut editor = EditorTestUtils::create(); - gliding_nudged_node(&mut editor).await; - - editor.handle_message(DocumentMessage::Undo).await; - editor.handle_message(DocumentMessage::Redo).await; - - assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty()); + assert_eq!(network_interface.wire_input_from_point(on_wire, 6., WireStyle::Direct, &[]), Some(input)); + assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., WireStyle::Direct, &[]), None); } #[tokio::test] async fn undoing_a_nudge_keeps_the_node_it_moved() { let mut editor = EditorTestUtils::create(); - let node = gliding_nudged_node(&mut editor).await; + editor.new_document().await; + let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; editor.handle_message(DocumentMessage::Undo).await; assert_eq!(editor.active_document().network_interface.position(&node, &[]), Some(IVec2::ZERO)); @@ -3822,17 +3738,6 @@ async fn undoing_right_after_creating_a_node_removes_only_that_node() { assert_eq!(nodes.keys().copied().collect::>(), vec![kept]); } -#[tokio::test] -async fn entering_a_node_while_its_network_glides_settles_it() { - let mut editor = EditorTestUtils::create(); - gliding_nudged_node(&mut editor).await; - let merge = editor.create_node_by_name_at(merge_definition(), 20, 0).await; - - editor.enter_editable_network(merge).await; - - assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty()); -} - #[tokio::test] async fn resting_a_wire_on_an_exposed_input_reveals_nothing_that_would_move_it_from_under_the_pointer() { let mut editor = EditorTestUtils::create(); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/frontend.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/connectors.rs similarity index 66% rename from editor/src/messages/portfolio/document/utility_types/network_interface/frontend.rs rename to editor/src/messages/portfolio/document/utility_types/network_interface/connectors.rs index bb600723bd..2ce815a6f2 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/frontend.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/connectors.rs @@ -1,56 +1,20 @@ -//! The shapes the node graph frontend is sent: one entry per visible port, carrying its type, its -//! name and whether it's connected. Read-only projections of the graph, rather than a source of truth. +//! The connectors the graph UI's rows and tooltips are built from: one entry per visible port, carrying its type, +//! its name and whether it's connected. Read-only projections of the graph, rather than a source of truth. use super::resolved_types::TypeSource; use super::*; impl NodeNetworkInterface { - pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec> { - 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::>(); - 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> { - 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::>(); - 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 { - // 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 = self.upstream_output_connector(input_connector, network_path).is_some(); - - 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) => (self.displayed_export_name(*export_index, network_path), self.export_description(*export_index, network_path)), + /// Returns None if there is an error, it is a hidden primary export, or a hidden or missing input + pub fn input_tooltip(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option { + let (name, input_type, connected) = self.graph_ui_input(input_connector, network_path)?; + let description = match input_connector { + InputConnector::Node { node_id, input_index } => self + .persistent_input_metadata(node_id, *input_index, network_path) + .map(|metadata| metadata.input_description.clone()) + .unwrap_or_default(), + InputConnector::Export(export_index) => self.export_description(*export_index, network_path), }; - let valid_types = match input_connector { InputConnector::Node { .. } => self.potential_valid_input_types(input_connector, network_path), // An export takes any type itself, so it's limited only by what its subgraph node's output feeds, or at the document's root, what can be rendered @@ -60,22 +24,47 @@ impl NodeNetworkInterface { .filter(|valid_type| !valid_type.nested_type().is_generic()) .collect(), }; - let valid_types = distinct_type_names(&valid_types); - - Some(FrontendGraphInput { - data_type, - resolved_type, + Some(InputTooltip { + resolved_type: input_type.resolved_type_node_string(), name, description, - valid_types, + valid_types: distinct_type_names(&valid_types), connected, }) } /// 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 { + pub fn output_tooltip(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option { + let (name, output_type, connected) = self.graph_ui_output(output_connector, network_path)?; + let description = match output_connector { + OutputConnector::Node { node_id, output_index } => self.output_description(node_id, *output_index, network_path), + OutputConnector::Import(import_index) => self.import_description(*import_index, network_path), + }; + Some(OutputTooltip { + resolved_type: output_type.resolved_type_node_string(), + name, + description, + possible_types: distinct_type_names(&self.possible_output_types(output_connector, network_path)), + connected, + }) + } + + pub fn graph_ui_input(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> { + // Return None if it is a hidden or missing input + if !self.input_from_connector(input_connector, network_path).is_some_and(|input| input.is_exposed()) { + return None; + } + let name = match input_connector { + InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path).0, + InputConnector::Export(export_index) => self.displayed_export_name(*export_index, network_path), + }; + let connected = self.upstream_output_connector(input_connector, network_path).is_some(); + Some((name, self.input_type(input_connector, network_path), connected)) + } + + pub fn graph_ui_output(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> { let output_type = self.output_type(output_connector, network_path); - let (name, description) = match output_connector { + let name = 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) { @@ -85,8 +74,7 @@ impl NodeNetworkInterface { let output_names = self.view(network_path).ok()?.output_names(node_id).ok()?; let output_name = 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, self.output_description(node_id, *output_index, network_path)) + if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() } } OutputConnector::Import(import_index) => { // Return None if it is an import in the document network @@ -98,24 +86,13 @@ impl NodeNetworkInterface { return None; }; - (self.displayed_import_name(*import_index, network_path), self.import_description(*import_index, network_path)) + self.displayed_import_name(*import_index, network_path) } }; - let data_type = output_type.displayed_type(); - let resolved_type = output_type.resolved_type_node_string(); - let possible_types = distinct_type_names(&self.possible_output_types(output_connector, network_path)); let connected = self .with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).is_some_and(|inputs| !inputs.is_empty())) .unwrap_or_default(); - - Some(FrontendGraphOutput { - data_type, - resolved_type, - name, - description, - possible_types, - connected, - }) + Some((name, output_type, connected)) } /// Returns the input name to display in the Inspector. If the input has no name then its type is used. diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs index 6fd39ca099..f80fb5d7b6 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs @@ -4,56 +4,13 @@ //! the caller decides whether to cache the result. use super::*; +use graph_ui::label_width; +use graph_ui::metrics::{LAYER_GRIP_WIDTH, LAYER_NAME_LEFT}; +use graph_ui::network_connector::{NetworkConnectorKind, network_connector_name_box, network_connector_row_offset}; impl NodeNetworkInterface { - pub(super) fn node_input_anchor(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> Option { - let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64; - let grid = GRID_SIZE as f64; - let inputs = &self.document_node(node_id, network_path)?.inputs; - - if self.is_redirect_dot(node_id, network_path) { - return (input_index == 0).then_some(top_left + DVec2::new(0., grid)); - } - - if self.is_layer(node_id, network_path) { - return match input_index { - 0 => Some(top_left + DVec2::new(2. * grid, 2. * grid + 8.)), - 1 if inputs.iter().filter(|input| input.is_exposed()).count() > 1 => Some(top_left + DVec2::new(0., grid)), - _ => None, - }; - } - - if !inputs.get(input_index)?.is_exposed() { - return None; - } - let row = inputs.iter().take(input_index).enumerate().filter(|(index, input)| *index == 0 || input.is_exposed()).count(); - Some(top_left + DVec2::new(0., grid * (row as f64 + 1.))) - } - - pub(super) fn node_output_anchor(&self, node_id: &NodeId, output_index: usize, network_path: &[NodeId]) -> Option { - let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64; - let grid = GRID_SIZE as f64; - - if self.is_redirect_dot(node_id, network_path) { - return (output_index == 0).then_some(top_left + DVec2::new(0., grid)); - } - - if self.is_layer(node_id, network_path) { - return (output_index == 0).then_some(top_left + DVec2::new(2. * grid, -8.)); - } - - let hidden = output_index == 0 && self.hidden_primary_output(node_id, network_path); - (!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.))) - } - /// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu. - /// Laid out as the frontend draws them, just past the connector. - pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> { - // How far past the port's center the name begins - const IMPORT_NAME_INSET: f64 = 8.; - const EXPORT_NAME_INSET: f64 = 9.; - const FONT_SIZE: f64 = 14.; - + pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(NetworkConnectorKey, [DVec2; 2])> { if network_path.is_empty() { return Vec::new(); } @@ -72,16 +29,13 @@ impl NodeNetworkInterface { return Vec::new(); }; - let half_row = DVec2::new(0., HALF_GRID_SIZE as f64); let imports = import_centers.into_iter().map(|(import_index, center)| { - let name_width = text_width(&self.displayed_import_name(import_index, network_path), FONT_SIZE); - let name_right = center - DVec2::new(IMPORT_NAME_INSET, 0.); - (ImportOrExport::Import(import_index), [name_right - DVec2::new(name_width, 0.) - half_row, name_right + half_row]) + let name_width = label_width(&self.displayed_import_name(import_index, network_path)); + (NetworkConnectorKey::Import(import_index), network_connector_name_box(NetworkConnectorKind::Import, center, name_width)) }); let exports = export_centers.into_iter().map(|(export_index, center)| { - let name_width = text_width(&self.displayed_export_name(export_index, network_path), FONT_SIZE); - let name_left = center + DVec2::new(EXPORT_NAME_INSET, 0.); - (ImportOrExport::Export(export_index), [name_left - half_row, name_left + DVec2::new(name_width, 0.) + half_row]) + let name_width = label_width(&self.displayed_export_name(export_index, network_path)); + (NetworkConnectorKey::Export(export_index), network_connector_name_box(NetworkConnectorKind::Export, center, name_width)) }); imports.chain(exports).collect() } @@ -98,13 +52,13 @@ impl NodeNetworkInterface { 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_export_row_offset(import_index))); + import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., network_connector_row_offset(import_index))); } } 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., import_export_row_offset(export_index))); + import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., network_connector_row_offset(export_index))); } Some(import_export_ports) @@ -133,7 +87,7 @@ impl NodeNetworkInterface { connectors.push((0, first_row_center)); } let next_index = count.max(1); - connectors.push((next_index, first_row_center + DVec2::new(0., import_export_row_offset(next_index) + GRID_SIZE as f64))); + connectors.push((next_index, first_row_center + DVec2::new(0., network_connector_row_offset(next_index) + GRID_SIZE as f64))); connectors } @@ -149,26 +103,21 @@ impl NodeNetworkInterface { if y < first_row_center + GRID_SIZE as f64 { return Some(0); } - Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count)) + Some((1..row_count).find(|&row| first_row_center + network_connector_row_offset(row) > y).unwrap_or(row_count)) } /// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached /// because measuring the name's text is slow. pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) { - 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 text_width = label_width(&layer_text); 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_pixels = LAYER_NAME_LEFT + text_width + grip_padding + LAYER_GRIP_WIDTH + lock_icon_width + icon_overhang_width; (((layer_width_pixels / 24.).ceil() as u32).max(8), text_width) } pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> { @@ -258,9 +207,3 @@ impl NodeNetworkInterface { Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2())) } } - -/// How far below the first import or export the one at `index` sits, with a grid cell of space separating the primary from the secondary ones. -fn import_export_row_offset(index: usize) -> f64 { - let rows = if index == 0 { 0 } else { index + 1 }; - (rows * GRID_SIZE as usize) as f64 -} diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs index 8619642b76..8cde401455 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs @@ -1,4 +1,5 @@ use super::*; +use graph_ui::geometry::WireEnd; use graphene_std::vector::misc::dvec2_to_point; use kurbo::{DEFAULT_ACCURACY, ParamCurveNearest}; @@ -51,13 +52,10 @@ impl NodeNetworkInterface { /// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its /// grid cell, and an input by its index rather than the row a node draws it in. pub(crate) fn find_node_part(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option) -> Option { - let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path); - let inputs = &self.document_node(node_id, network_path)?.inputs; - self.with_layout(network_path, |layout| { - layout.find_part(node_id, |target| { + layout.find_part(node_id, |geometry, target| { let part = match target.part { - Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32), + Part::Input(place) => Part::Input(geometry.input_at(place)? as u32), part => part, }; find(part, target) @@ -74,13 +72,11 @@ impl NodeNetworkInterface { }; let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); - // Each node is pressed where it's drawn, even while gliding into its grid cell - let glide_offsets = self.glide_offsets(network_path); let reaching = self.nodes_reaching(point, network_path); let clicked_nodes = self.with_layout(network_path, |layout| { reaching .into_iter() - .filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id)))) + .filter(|node_id| layout.geometry(node_id).is_some_and(|geometry| geometry.body().contains(point))) .collect::>() })?; // Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order @@ -103,7 +99,6 @@ impl NodeNetworkInterface { }; let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); - let glide_offsets = self.glide_offsets(network_path); let wanted = match click_target_type { LayerClickTargetTypes::Visibility => Part::Visibility, @@ -113,7 +108,6 @@ impl NodeNetworkInterface { }; self.nodes_reaching(point, network_path).into_iter().find(|node_id| { - let point = point - glide_offsets.node(node_id); self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(())) .is_some() }) @@ -121,28 +115,18 @@ impl NodeNetworkInterface { /// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center. pub fn empty_import_export_connector_at(&self, point: DVec2, is_import: bool, network_path: &[NodeId]) -> Option<(usize, DVec2)> { - let glide_offsets = self.glide_offsets(network_path); - let point = point - if is_import { glide_offsets.imports } else { glide_offsets.exports }; - // The same reach as an import (output) or export (input) port's click target - self.empty_import_export_connectors(is_import, network_path) - .into_iter() - .find(|(_, center)| port_click_target(side_port_bounds(*center, !is_import)).intersect_point_no_stroke(point)) + self.empty_import_export_connectors(is_import, network_path).into_iter().find(|(index, center)| match is_import { + true => PartTarget::output_port(*center, *index as u32).contains(point), + false => PartTarget::input_port(*center, *index as u32).contains(point), + }) } /// The import or export with its name under `point`, given in node graph space. - pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option { - let glide_offsets = self.glide_offsets(network_path); + pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option { self.import_export_name_bounds(network_path) .into_iter() - .find(|(import_or_export, [name_min, name_max])| { - let point = point - - match import_or_export { - ImportOrExport::Import(_) => glide_offsets.imports, - ImportOrExport::Export(_) => glide_offsets.exports, - }; - name_min.cmple(point).all() && point.cmple(*name_max).all() - }) + .find(|(_, [name_min, name_max])| name_min.cmple(point).all() && point.cmple(*name_max).all()) .map(|(import_or_export, _)| import_or_export) } @@ -170,14 +154,13 @@ impl NodeNetworkInterface { } /// The input fed by a wire passing within `tolerance` of the point (in node graph space), for placing a dot on it. Only wires a dot can bend are found. - pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option { + pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: WireStyle, network_path: &[NodeId]) -> Option { let target = dvec2_to_point(point); - let glide_offsets = self.glide_offsets(network_path); self.node_graph_input_connectors(network_path) .into_iter() .filter(|input| self.can_bend_wire_into(input, network_path)) .filter_map(|input| { - let (wire, _, _) = self.gliding_vector_wire_from_input(&input, wire_style, &glide_offsets, network_path)?; + let (wire, _) = self.vector_wire_from_input(&input, wire_style, network_path)?; let distance = wire .segments() .map(|segment| segment.nearest(target, DEFAULT_ACCURACY).distance_sq.sqrt()) @@ -196,13 +179,11 @@ impl NodeNetworkInterface { }; let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); - let glide_offsets = self.glide_offsets(network_path); let covering_dot = self.redirect_dot_from_click(click, network_path); self.nodes_reaching(point, network_path) .iter() .filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id)) .filter_map(|node_id| { - let point = point - glide_offsets.node(node_id); self.find_node_part(node_id, network_path, |part, target| match part { Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)), _ => None, @@ -210,11 +191,9 @@ impl NodeNetworkInterface { }) .find(|input_connector| !self.is_wired_dot_input(input_connector, network_path)) .or_else(|| { - self.with_import_export_ports(network_path, |import_export_ports| { - import_export_ports.clicked_input_port_from_point(point - glide_offsets.exports).map(InputConnector::Export) - }) - .flatten() - .filter(|_| covering_dot.is_none()) + self.with_import_export_ports(network_path, |import_export_ports| import_export_ports.clicked_input_port_from_point(point).map(InputConnector::Export)) + .flatten() + .filter(|_| covering_dot.is_none()) }) } @@ -226,14 +205,12 @@ impl NodeNetworkInterface { }; let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); - let glide_offsets = self.glide_offsets(network_path); // A redirect dot is drawn above everything else, so where it covers other ports, only its own can be pressed let covering_dot = self.redirect_dot_from_click(click, network_path); self.nodes_reaching(point, network_path) .iter() .filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id)) .filter_map(|node_id| { - let point = point - glide_offsets.node(node_id); self.find_node_part(node_id, network_path, |part, target| match part { Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)), _ => None, @@ -242,7 +219,7 @@ impl NodeNetworkInterface { .next() .or_else(|| { self.with_import_export_ports(network_path, |import_export_ports| { - import_export_ports.clicked_output_port_from_point(point - glide_offsets.imports).map(OutputConnector::Import) + import_export_ports.clicked_output_port_from_point(point).map(OutputConnector::Import) }) .flatten() .filter(|_| covering_dot.is_none()) @@ -250,20 +227,30 @@ impl NodeNetworkInterface { } pub fn input_position(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option { - match input_connector { - InputConnector::Node { node_id, input_index } => self.node_input_anchor(node_id, *input_index, network_path), - InputConnector::Export(export_index) => self - .with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index)) - .flatten(), - } + Some(self.input_end(input_connector, network_path)?.position) } pub fn output_position(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option { + Some(self.output_end(output_connector, network_path)?.position) + } + + pub fn input_end(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option { + match input_connector { + InputConnector::Node { node_id, input_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.input_end(*input_index)).flatten(), + InputConnector::Export(export_index) => self + .with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index)) + .flatten() + .map(|position| WireEnd { position, vertical: false }), + } + } + + pub fn output_end(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option { match output_connector { - OutputConnector::Node { node_id, output_index } => self.node_output_anchor(node_id, *output_index, network_path), + OutputConnector::Node { node_id, output_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.output_end(*output_index)).flatten(), OutputConnector::Import(import_index) => self .with_import_export_ports(network_path, |import_export_ports| import_export_ports.output_port_position(*import_index)) - .flatten(), + .flatten() + .map(|position| WireEnd { position, vertical: false }), } } @@ -323,49 +310,10 @@ impl NodeNetworkInterface { Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box()) } - pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap, HashMap, HashMap) { - let Some(network_metadata) = self.network_metadata(network_path) else { - log::error!("Could not get nested network_metadata in collect_layer_widths"); - return (HashMap::new(), HashMap::new(), HashMap::new()); - }; - let nodes = network_metadata - .persistent_metadata - .node_metadata - .keys() - .filter_map(|node_id| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None }) - .collect::>(); - let layer_widths = nodes - .iter() - .filter_map(|node_id| self.layer_width(node_id, network_path).map(|layer_width| (*node_id, layer_width))) - .collect::>(); - let chain_widths = nodes.iter().map(|node_id| (*node_id, self.chain_width(node_id, network_path))).collect::>(); - let has_left_input_wire = nodes - .iter() - .map(|node_id| { - ( - *node_id, - !self - .upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow) - .skip(1) - .all(|node_id| self.is_chain(&node_id, network_path)), - ) - }) - .collect::>(); - - (layer_widths, chain_widths, has_left_input_wire) + pub fn has_left_input_wire(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool { + !self + .upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow) + .skip(1) + .all(|node_id| self.is_chain(&node_id, network_path)) } } - -/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port. -fn input_in_row(inputs: &[NodeInput], row: usize) -> Option { - let mut current_row = 0; - for (index, input) in inputs.iter().enumerate() { - if input.is_exposed() && current_row == row { - return Some(index); - } - if index == 0 || input.is_exposed() { - current_row += 1; - } - } - None -} diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/layout_pass.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/layout_pass.rs index 6e23645595..bacf47589b 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/layout_pass.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/layout_pass.rs @@ -1,7 +1,8 @@ -use super::node_parts::{NodeShape, PartTarget, PlacedNode}; use super::*; use glam::UVec2; use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire}; +use graph_ui::geometry::{NodeGeometry, NodeShape}; +use graph_ui::metrics::CARD_GRID_WIDTH; use std::cell::RefCell; use std::sync::atomic::{AtomicU64, Ordering}; @@ -90,11 +91,6 @@ impl NetworkLayout { .sum() } - /// How many nodes the layer's chain holds. - pub fn chain_length(&self, layer: &NodeId) -> u32 { - self.node(layer).map_or(0, |node| node.chain_length) - } - /// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network. pub fn bounds(&self) -> [DVec2; 2] { self.bounds @@ -105,18 +101,17 @@ impl NetworkLayout { self.clearance } - /// The node's body where it sits in its grid cell, in node graph space. - pub fn body(&self, node_id: &NodeId) -> Option { - Some(self.placed(*self.indices.get(node_id)?).body()) + pub fn geometry(&self, node_id: &NodeId) -> Option { + Some(self.geometry_at(*self.indices.get(node_id)?)) } /// The first of the node's parts, its body last, that `find` picks something from. - pub fn find_part(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option) -> Option { - let placed = self.placed(*self.indices.get(node_id)?); + pub fn find_part(&self, node_id: &NodeId, mut find: impl FnMut(&NodeGeometry, &PartTarget) -> Option) -> Option { + let geometry = self.geometry(node_id)?; let mut found = None; - placed.parts(|target| { + geometry.parts(|target| { if found.is_none() { - found = find(&target); + found = find(&geometry, &target); } }); found @@ -131,13 +126,13 @@ impl NetworkLayout { point.cmpge(min).all() && point.cmplt(max).all() } - fn placed(&self, index: NodeIndex) -> PlacedNode<'_> { - let node_layout = self.layout.node(index); - PlacedNode { - node: &self.graph[index], - shape: &self.shapes[index.index()], - position: node_layout.position, - chain_length: node_layout.chain_length, + fn geometry_at(&self, index: NodeIndex) -> NodeGeometry { + let node = self.layout.node(index); + NodeGeometry { + cell: node.position, + kind: self.graph[index].kind, + chain_length: node.chain_length, + shape: self.shapes[index.index()].clone(), } } @@ -148,7 +143,7 @@ impl NetworkLayout { let mut bounds: Option<[DVec2; 2]> = None; let mut clearance = ImportExportClearance::default(); for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) { - let body = self.placed(index).body(); + let body = self.geometry_at(index).body(); bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)])); if self.graph[index].kind == NodeKind::Waypoint { @@ -220,11 +215,8 @@ impl NodeNetworkInterface { } pub(crate) fn nodes_reaching(&self, point: DVec2, network_path: &[NodeId]) -> Vec { - let glide_offsets = self.glide_offsets(network_path); - self.with_layout(network_path, |layout| { - layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point - glide_offsets.node(node_id))).copied().collect() - }) - .unwrap_or_default() + self.with_layout(network_path, |layout| layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point)).copied().collect()) + .unwrap_or_default() } pub(crate) fn drag_preview(&self, network_path: &[NodeId]) -> (IVec2, bool) { @@ -260,6 +252,10 @@ impl NodeNetworkInterface { transient.layout.unload(); } + pub(crate) fn dragging(&self, network_path: &[NodeId]) -> bool { + self.network_metadata(network_path).is_some_and(|network_metadata| network_metadata.transient_metadata.drag.is_some()) + } + /// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag. pub fn shift_selected_nodes(&mut self, offset: IVec2, keep_upstream: bool, network_path: &[NodeId]) { self.cancel_drag(network_path); @@ -420,11 +416,12 @@ impl NodeNetworkInterface { }; let (kind, size) = match (is_layer, is_redirect_dot) { (true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)), - (false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))), - (false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))), + (false, true) => (NodeKind::Waypoint, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))), + (false, false) => (NodeKind::Node, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))), }; let primary_output_hidden = self.hidden_primary_output(node_id, network_path); + let inputs = &self.document_node(node_id, network_path)?.inputs; let node = Node { placement, kind, @@ -433,9 +430,9 @@ impl NodeNetworkInterface { held: false, }; let shape = NodeShape { - inputs: self.number_of_displayed_inputs(node_id, network_path) as u32, + size, + exposed_inputs: inputs.iter().enumerate().filter(|(_, input)| input.is_exposed()).map(|(index, _)| index).collect(), outputs: self.number_of_outputs(node_id, network_path) as u32, - primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()), primary_output_hidden, name_width, locked: self.is_locked(node_id, network_path), @@ -444,7 +441,6 @@ impl NodeNetworkInterface { } } -/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout. pub(crate) struct LaidOutNodes { pub(crate) node_ids: Vec, pub(crate) indices: HashMap, 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 7c44a450ac..402ca749ad 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 @@ -827,10 +827,10 @@ impl NodeNetworkInterface { /// Wires the output into the inputs through one new redirect dot placed midway between them, which fans out to the inputs. fn create_wires_through_dot(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) { - let output_center = self.get_output_center(output_connector, network_path); + let output_center = self.output_position(output_connector, network_path); let input_centers = input_connectors .iter() - .map(|input_connector| self.get_input_center(input_connector, network_path)) + .map(|input_connector| self.input_position(input_connector, network_path)) .collect::>>(); let center = match output_center.zip(input_centers) { Some((output_center, input_centers)) => { @@ -1164,7 +1164,7 @@ impl NodeNetworkInterface { self.invalidate_node_appearance(node_id, network_path); } - pub fn set_import_export_name(&mut self, name: String, index: ImportOrExport, network_path: &[NodeId]) { + pub fn set_import_export_name(&mut self, name: String, index: NetworkConnectorKey, network_path: &[NodeId]) { let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else { log::error!("Could not get encapsulating network in set_import_export_name"); return; @@ -1176,8 +1176,8 @@ impl NodeNetworkInterface { }; let name_changed = match index { - ImportOrExport::Import(import_index) => node.set_input_name(import_index, name), - ImportOrExport::Export(export_index) => node.set_output_name(export_index, name), + NetworkConnectorKey::Import(import_index) => node.set_input_name(import_index, name), + NetworkConnectorKey::Export(export_index) => node.set_output_name(export_index, name), }; if name_changed { @@ -1185,7 +1185,7 @@ impl NodeNetworkInterface { } } - pub fn set_import_export_description(&mut self, description: String, index: ImportOrExport, network_path: &[NodeId]) { + pub fn set_import_export_description(&mut self, description: String, index: NetworkConnectorKey, network_path: &[NodeId]) { let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else { log::error!("Could not get encapsulating network in set_import_export_description"); return; @@ -1197,8 +1197,8 @@ impl NodeNetworkInterface { }; let description_changed = match index { - ImportOrExport::Import(import_index) => node.set_input_description(import_index, description), - ImportOrExport::Export(export_index) => node.set_output_description(export_index, description), + NetworkConnectorKey::Import(import_index) => node.set_input_description(import_index, description), + NetworkConnectorKey::Export(export_index) => node.set_output_description(export_index, description), }; if description_changed { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/node_parts.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/node_parts.rs deleted file mode 100644 index b27c45ae26..0000000000 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/node_parts.rs +++ /dev/null @@ -1,231 +0,0 @@ -//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around -//! everything the node draws, and builds the exact parts of only the nodes it lands in. - -use crate::consts::{GRID_SIZE, HALF_GRID_SIZE}; -use glam::{DVec2, IVec2}; -use graph_layout::{CHAIN_WIDTH, Node, NodeKind}; - -const GRID: f64 = GRID_SIZE as f64; -const HALF_GRID: f64 = HALF_GRID_SIZE as f64; -/// How far a port on a node's side reaches outward, away from the node, and inward over it. -const SIDE_PORT_OUTWARD_REACH: f64 = 12.; -const SIDE_PORT_INWARD_REACH: f64 = 8.; -const SIDE_PORT_HALF_HEIGHT: f64 = 12.; -const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.); -/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port. -const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.); -/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it. -const WAYPOINT_GUTTER_OFFSET: f64 = 10.; -const WAYPOINT_GUTTER_RADIUS: f64 = 5.; -const GRIP_WIDTH: f64 = 8.; -const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.; - -/// What a node draws beyond the size the layout gives it. -#[derive(Clone, Copy, Debug, Default)] -pub struct NodeShape { - /// How many inputs have a port, which doesn't count a hidden primary input. - pub inputs: u32, - pub outputs: u32, - /// Whether a node's primary input has no port, though its row is still drawn. - pub primary_input_hidden: bool, - pub primary_output_hidden: bool, - /// The width of a layer's name in pixels. - pub name_width: f64, - pub locked: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Part { - Body, - /// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1. - Input(u32), - Output(u32), - Visibility, - Lock, - Grip, - Name, -} - -/// A rounded rectangle of a node that reacts to the pointer. -#[derive(Clone, Copy, Debug)] -pub struct PartTarget { - pub min: DVec2, - pub max: DVec2, - pub corner_radius: f64, - pub part: Part, -} - -impl PartTarget { - fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self { - Self { - min: center - half_size, - max: center + half_size, - corner_radius, - part, - } - } - - /// A port on the left side of a node, reaching further out than over the node. - fn input_port(center: DVec2, input: u32) -> Self { - Self { - min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT), - max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT), - corner_radius: 4., - part: Part::Input(input), - } - } - - /// A port on the right side of a node, reaching further out than over the node. - fn output_port(center: DVec2, output: u32) -> Self { - Self { - min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT), - max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT), - corner_radius: 4., - part: Part::Output(output), - } - } - - /// Whether the rounded rectangle shares any area with the box from `min` to `max`. - pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool { - if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() { - return false; - } - - let radius = self.clamped_radius(); - let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO); - gap == DVec2::ZERO || gap.length_squared() < radius * radius - } - - /// Whether `point` is inside the rounded rectangle. - pub fn contains(&self, point: DVec2) -> bool { - if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() { - return false; - } - - let radius = self.clamped_radius(); - let inner = point.clamp(self.min + radius, self.max - radius); - point.distance_squared(inner) <= radius * radius - } - - fn clamped_radius(&self) -> f64 { - self.corner_radius.min((self.max - self.min).min_element() / 2.) - } -} - -/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer. -#[derive(Clone, Copy, Debug)] -pub struct PlacedNode<'a> { - pub node: &'a Node, - pub shape: &'a NodeShape, - pub position: IVec2, - pub chain_length: u32, -} - -impl PlacedNode<'_> { - /// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint. - pub fn body(&self) -> PartTarget { - let top_left = self.top_left(); - let size = self.node.size.as_dvec2() * GRID; - - match self.node.kind { - NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body), - NodeKind::Layer => PartTarget { - min: top_left - DVec2::new(self.chain_width(), 0.), - max: top_left + size, - corner_radius: 10., - part: Part::Body, - }, - NodeKind::Node => { - let body_top_left = top_left + DVec2::new(0., HALF_GRID); - PartTarget { - min: body_top_left, - max: body_top_left + size - DVec2::new(0., GRID), - corner_radius: 3., - part: Part::Body, - } - } - } - } - - /// Calls `visit` with each part, the body last. - pub fn parts(&self, mut visit: impl FnMut(PartTarget)) { - match self.node.kind { - NodeKind::Waypoint => self.waypoint_ports(&mut visit), - NodeKind::Layer => self.layer_parts(&mut visit), - NodeKind::Node => self.node_ports(&mut visit), - } - visit(self.body()); - } - - fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) { - let center = self.top_left() + DVec2::new(0., GRID); - let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part); - visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0))); - visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0))); - } - - fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) { - let top_left = self.top_left(); - let width = self.node.size.x as f64 * GRID; - let row_center = |row: u32| GRID * (row as f64 + 1.); - - let first_input_row = u32::from(self.shape.primary_input_hidden); - for row in first_input_row..first_input_row + self.shape.inputs { - visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row)); - } - for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs { - visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output)); - } - } - - fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) { - let top_left = self.top_left(); - let size = self.node.size.as_dvec2() * GRID; - - visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0))); - if self.has_side_input() { - visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1)); - } - visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0))); - - let icon_half_size = DVec2::splat(HALF_GRID); - visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility)); - if self.shape.locked { - visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock)); - } - - let icons_width = if self.shape.locked { GRID } else { 0. }; - let grip_right = top_left.x + size.x - HALF_GRID - icons_width; - let handle_top = top_left.y + HALF_GRID; - let handle_bottom = top_left.y + GRID + HALF_GRID; - visit(PartTarget { - min: DVec2::new(grip_right - GRIP_WIDTH, handle_top), - max: DVec2::new(grip_right, handle_bottom), - corner_radius: 0., - part: Part::Grip, - }); - - let name_left = top_left.x + NAME_LEFT_OFFSET; - let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH); - if name_right > name_left { - visit(PartTarget { - min: DVec2::new(name_left, handle_top), - max: DVec2::new(name_right, handle_bottom), - corner_radius: 3., - part: Part::Name, - }); - } - } - - fn top_left(&self) -> DVec2 { - self.position.as_dvec2() * GRID - } - - fn has_side_input(&self) -> bool { - self.shape.inputs > 1 - } - - fn chain_width(&self) -> f64 { - if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. } - } -} 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 588217afab..5b2e043bf0 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 @@ -264,16 +264,6 @@ impl NodeNetworkInterface { layers } - /// The width in grid cells of a layer's chain area: one cell plus a chain width per chained node, or zero for a layer without a displayed chain input. - pub fn chain_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 { - if self.number_of_displayed_inputs(node_id, network_path) <= 1 { - return 0; - } - - let chain_length = self.with_layout(network_path, |layout| layout.chain_length(node_id)).unwrap_or_default(); - chain_length * NODE_CHAIN_WIDTH as u32 + 1 - } - /// Check if the specified node id is connected to the output pub fn connected_to_output(&self, target_node_id: &NodeId, network_path: &[NodeId]) -> bool { self.query(network_path, "connected_to_output", |view| Ok(view.connected_to_output(target_node_id))).unwrap_or_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 caaf3489c3..251d5aef18 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 @@ -116,12 +116,7 @@ impl Iterator for FlowIter<'_> { } } -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum ImportOrExport { - Import(usize), - Export(usize), -} +pub use graph_ui::network_connector::NetworkConnectorKey; /// The primary input (index 0) of any node: a chain node's horizontal wire continuing from the left, or a layer's vertical stack wire from the sibling rendered below it. pub const PRIMARY_INPUT_INDEX: usize = 0; @@ -265,29 +260,10 @@ pub(crate) enum DotSide { Outgoing, } -/// The corners of the click target for a connector on a node or layer's left or right side, or an import or export. -/// It fills its row's height and reaches further away from the node than into it, leaving the node body grabbable. -pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] { - const INWARD_REACH: f64 = 8.; - const OUTWARD_REACH: f64 = 12.; - const HALF_HEIGHT: f64 = 12.; - - // Inputs face left and outputs face right - let (left_reach, right_reach) = if is_input { (OUTWARD_REACH, INWARD_REACH) } else { (INWARD_REACH, OUTWARD_REACH) }; - [center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)] -} - -pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget { - const CORNER_RADIUS: f64 = 4.; - - let path = rounded_rectangle_path(corner1, corner2, [CORNER_RADIUS; 4]); - ClickTarget::new_with_path(path, 0.) -} - #[derive(Debug, Clone)] pub struct Ports { - pub(crate) input_ports: Vec<(usize, ClickTarget)>, - pub(crate) output_ports: Vec<(usize, ClickTarget)>, + pub(crate) input_ports: Vec<(usize, PartTarget)>, + pub(crate) output_ports: Vec<(usize, PartTarget)>, /// Where a wire attaches to an input port with a click target not centered on that point. pub(crate) input_anchors: Vec<(usize, DVec2)>, /// Where a wire attaches to an output port with a click target not centered on that point. @@ -310,30 +286,30 @@ impl Ports { } } - pub fn input_ports(&self) -> impl Iterator { + pub fn input_ports(&self) -> impl Iterator { self.input_ports.iter() } - pub fn output_ports(&self) -> impl Iterator { + pub fn output_ports(&self) -> impl Iterator { self.output_ports.iter() } pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) { - self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true)))); + self.input_ports.push((input_index, PartTarget::input_port(center, input_index as u32))); self.input_anchors.push((input_index, center)); } pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) { - self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false)))); + self.output_ports.push((output_index, PartTarget::output_port(center, output_index as u32))); self.output_anchors.push((output_index, center)); } pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option { - self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port)) + self.input_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port)) } pub fn clicked_output_port_from_point(&self, point: DVec2) -> Option { - self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port)) + self.output_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port)) } pub fn input_port_position(&self, index: usize) -> Option { @@ -663,57 +639,6 @@ pub struct NodeNetworkTransientMetadata { pub(crate) drag: Option, /// The import and export connector click targets, with the generation of the layout they were placed by. pub(crate) import_export_ports: TransientCache<(u64, Ports)>, - - /// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for. - pub(crate) glide_offsets: std::cell::RefCell, -} - -/// How far the nodes, imports, and exports gliding into the grid cells they just moved to are drawn from those cells, in node graph space. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct GlideOffsets { - pub nodes: HashMap, - pub imports: DVec2, - pub exports: DVec2, -} - -impl GlideOffsets { - pub fn is_empty(&self) -> bool { - self.nodes.is_empty() && self.imports == DVec2::ZERO && self.exports == DVec2::ZERO - } - - pub fn node(&self, node_id: &NodeId) -> DVec2 { - self.nodes.get(node_id).copied().unwrap_or_default() - } - - pub fn input(&self, input: &InputConnector) -> DVec2 { - match input { - InputConnector::Node { node_id, .. } => self.node(node_id), - InputConnector::Export(_) => self.exports, - } - } - - pub fn output(&self, output: &OutputConnector) -> DVec2 { - match output { - OutputConnector::Node { node_id, .. } => self.node(node_id), - OutputConnector::Import(_) => self.imports, - } - } - - /// Shrinks every offset to the given fraction of itself, settling those left too small to see. - pub fn shrink(&mut self, remaining_fraction: f64) { - const SMALLEST_VISIBLE_OFFSET: f64 = 0.5; - - let shrink = |offset: &mut DVec2| { - *offset *= remaining_fraction; - if offset.length() < SMALLEST_VISIBLE_OFFSET { - *offset = DVec2::ZERO; - } - }; - self.nodes.values_mut().for_each(shrink); - self.nodes.retain(|_, offset| *offset != DVec2::ZERO); - shrink(&mut self.imports); - shrink(&mut self.exports); - } } /// What the imports and exports keep their distance from horizontally, in node graph space. They keep a few grid cells from the sides of a node, diff --git a/editor/src/messages/portfolio/document/utility_types/wires.rs b/editor/src/messages/portfolio/document/utility_types/wires.rs deleted file mode 100644 index c175cf9fea..0000000000 --- a/editor/src/messages/portfolio/document/utility_types/wires.rs +++ /dev/null @@ -1,636 +0,0 @@ -use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType; -use glam::{DVec2, IVec2}; -use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point}; -use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2}; - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct WirePath { - #[serde(rename = "pathString")] - pub path_string: String, - #[serde(rename = "dataType")] - pub data_type: FrontendGraphDataType, - pub thick: bool, - pub dashed: bool, - // A rank-1 `List` wire renders as a doubled-up pair of parallel lines to distinguish it from a rank-0 `Item` wire - #[serde(rename = "isList")] - pub is_list: bool, - // A thick wire's center line reaches past the wire into the cleaved connector slots, so it needs its own longer path; empty otherwise - #[serde(rename = "centerPathString")] - pub center_path_string: String, -} - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct WirePathUpdate { - pub id: NodeId, - #[serde(rename = "inputIndex")] - pub input_index: usize, - // If none, then remove the wire from the map - #[serde(rename = "wirePathUpdate")] - pub wire_path_update: Option, -} - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Copy, Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)] -pub enum GraphWireStyle { - #[default] - Direct = 0, - GridAligned = 1, -} - -impl std::fmt::Display for GraphWireStyle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - GraphWireStyle::GridAligned => write!(f, "Grid-Aligned"), - GraphWireStyle::Direct => write!(f, "Direct"), - } - } -} - -impl GraphWireStyle { - pub fn tooltip_description(&self) -> &'static str { - match self { - GraphWireStyle::GridAligned => "Wires follow the grid, running in straight lines between nodes.", - GraphWireStyle::Direct => "Wires bend to run at an angle directly between nodes.", - } - } - - pub fn is_direct(&self) -> bool { - *self == GraphWireStyle::Direct - } -} - -pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath { - let grid_spacing = 24.; - - // A thick layer-stack wire (vertical at both ends) is skipped across a single straight grid cell where its connectors - // already meet, and otherwise trimmed 3px inward at each end since it overshoots the connectors. - let (output_position, input_position) = if vertical_out && vertical_in { - if thick_wire_spans_single_cell(output_position, input_position) { - return BezPath::new(); - } - let trim = 3. * (input_position.y - output_position.y).signum(); - (output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim)) - } else { - (output_position, input_position) - }; - - match graph_wire_style { - GraphWireStyle::Direct => { - let horizontal_gap = (output_position.x - input_position.x).abs(); - let vertical_gap = (output_position.y - input_position.y).abs(); - - let curve_length = grid_spacing; - let curve_falloff_rate = curve_length * std::f64::consts::TAU; - - let horizontal_curve_amount = -(2_f64.powf((-10. * horizontal_gap) / curve_falloff_rate)) + 1.; - let vertical_curve_amount = -(2_f64.powf((-10. * vertical_gap) / curve_falloff_rate)) + 1.; - let horizontal_curve = horizontal_curve_amount * curve_length; - let vertical_curve = vertical_curve_amount * curve_length; - - let locations = [ - output_position, - DVec2::new( - if vertical_out { output_position.x } else { output_position.x + horizontal_curve }, - if vertical_out { output_position.y - vertical_curve } else { output_position.y }, - ), - DVec2::new( - if vertical_in { input_position.x } else { input_position.x - horizontal_curve }, - if vertical_in { input_position.y + vertical_curve } else { input_position.y }, - ), - DVec2::new(input_position.x, input_position.y), - ]; - - let smoothing = 0.5; - let delta01 = DVec2::new((locations[1].x - locations[0].x) * smoothing, (locations[1].y - locations[0].y) * smoothing); - let delta23 = DVec2::new((locations[3].x - locations[2].x) * smoothing, (locations[3].y - locations[2].y) * smoothing); - - let mut wire = BezPath::new(); - wire.move_to(dvec2_to_point(locations[0])); - wire.line_to(dvec2_to_point(locations[1])); - wire.curve_to(dvec2_to_point(locations[1] + delta01), dvec2_to_point(locations[2] - delta23), dvec2_to_point(locations[2])); - wire.line_to(dvec2_to_point(locations[3])); - wire - } - GraphWireStyle::GridAligned => { - let locations = straight_wire_path(output_position, input_position, vertical_out, vertical_in); - straight_wire_to_bezpath(locations) - } - } -} - -fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool { - let grid_spacing = 24.; - (output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing -} - -/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the -/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires. -pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath { - if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) { - return BezPath::new(); - } - - let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style); - let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else { - return BezPath::new(); - }; - - // The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead - let sign = (input_position.y - output_position.y).signum(); - let mut center_line = BezPath::new(); - center_line.move_to(start - Vec2::new(0., 1.5 * sign)); - center_line.line_to(start); - for element in wire.elements().iter().skip(1) { - center_line.push(*element); - } - center_line.line_to(end + Vec2::new(0., 2. * sign)); - center_line -} - -fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec { - let grid_spacing = 24; - let line_width = 2; - - let in_x = input_position.x.floor() as i32; - let in_y = input_position.y.floor() as i32; - let out_x = output_position.x.floor() as i32; - let out_y = output_position.y.floor() as i32; - - let mid_x = (in_x + out_x).div_euclid(2) + (in_x + out_x).div_euclid(2).rem_euclid(grid_spacing); - let mid_y = (in_y + out_y).div_euclid(2) + (in_y + out_y).div_euclid(2).rem_euclid(grid_spacing); - let mid_y_alternate = in_y - in_y.rem_euclid(grid_spacing); - - let x1 = out_x; - let x2 = out_x + grid_spacing; - let x3 = in_x - 2 * grid_spacing; - let x4 = in_x; - let x5 = in_x - 2 * grid_spacing + line_width; - let x6 = out_x + grid_spacing + line_width; - let x7 = out_x + 2 * grid_spacing + line_width; - let x8 = in_x + line_width; - let x9 = out_x + 2 * grid_spacing; - let x10 = mid_x + line_width; - let x11 = out_x - grid_spacing; - let x12 = out_x - 4 * grid_spacing; - let x13 = mid_x; - let x14 = in_x + grid_spacing; - let x15 = in_x - 4 * grid_spacing; - let x16 = in_x + 8 * grid_spacing; - let x17 = mid_x - 2 * line_width; - let x18 = out_x + grid_spacing - 2 * line_width; - let x19 = out_x - 2 * line_width; - let x20 = mid_x - line_width; - - let y1 = out_y; - let y2 = out_y - grid_spacing; - let y3 = in_y; - let y4 = out_y - grid_spacing + 5 * line_width + 1; - let y5 = in_y - 2 * grid_spacing; - let y6 = out_y + 4 * line_width; - let y7 = out_y + 5 * line_width; - let y8 = out_y - 2 * grid_spacing + 5 * line_width + 1; - let y9 = out_y + 6 * line_width; - let y10 = in_y + 2 * grid_spacing; - let y111 = in_y + grid_spacing + 6 * line_width + 1; - let y12 = in_y + grid_spacing - 5 * line_width + 1; - let y13 = in_y - grid_spacing; - let y14 = in_y + grid_spacing; - let y15 = mid_y; - let y16 = mid_y_alternate; - - let wire1 = vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x5, y4), IVec2::new(x5, y3), IVec2::new(x4, y3)]; - - let wire2 = vec![IVec2::new(x1, y1), IVec2::new(x1, y16), IVec2::new(x3, y16), IVec2::new(x3, y3), IVec2::new(x4, y3)]; - - let wire3 = vec![ - IVec2::new(x1, y1), - IVec2::new(x1, y4), - IVec2::new(x12, y4), - IVec2::new(x12, y10), - IVec2::new(x3, y10), - IVec2::new(x3, y3), - IVec2::new(x4, y3), - ]; - - let wire4 = vec![ - IVec2::new(x1, y1), - IVec2::new(x1, y4), - IVec2::new(x13, y4), - IVec2::new(x13, y10), - IVec2::new(x3, y10), - IVec2::new(x3, y3), - IVec2::new(x4, y3), - ]; - - if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) { - return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)]; - } - - // `outConnector` point and `inConnector` point lying on the same horizontal grid line and `outConnector` point lies to the right of `inConnector` point - if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) { - return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)]; - }; - - // Handle straight lines - if out_y == in_y || (out_x == in_x && vertical_out) { - return vec![IVec2::new(x1, y1), IVec2::new(x4, y3)]; - }; - - // Handle standard right-angle paths - // Start vertical, then horizontal - - // `outConnector` point lies to the left of `inConnector` point - if vertical_out && in_x > out_x { - // `outConnector` point lies above `inConnector` point - if out_y < in_y { - // `outConnector` point lies on the vertical grid line 4 units to the left of `inConnector` point point - if -4 * grid_spacing <= out_x - in_x && out_x - in_x < -3 * grid_spacing { - return wire1; - }; - - // `outConnector` point lying on vertical grid lines 3 and 2 units to the left of `inConnector` point - if -3 * grid_spacing <= out_x - in_x && out_x - in_x <= -grid_spacing { - if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing { - return vec![IVec2::new(x1, y1), IVec2::new(x1, y2), IVec2::new(x2, y2), IVec2::new(x2, y3), IVec2::new(x4, y3)]; - }; - - if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 { - return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x6, y4), IVec2::new(x6, y3), IVec2::new(x4, y3)]; - }; - - return vec![ - IVec2::new(x1, y1), - IVec2::new(x1, y4), - IVec2::new(x7, y4), - IVec2::new(x7, y5), - IVec2::new(x3, y5), - IVec2::new(x3, y3), - IVec2::new(x4, y3), - ]; - } - - // `outConnector` point lying on vertical grid line 1 units to the left of `inConnector` point - if -grid_spacing < out_x - in_x && out_x - in_x <= 0 { - // `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point - if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing { - return vec![IVec2::new(x1, y6), IVec2::new(x2, y6), IVec2::new(x8, y3)]; - }; - - // `outConnector` point lying on the same horizontal grid line as `inConnector` point - if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 { - return vec![IVec2::new(x1, y7), IVec2::new(x4, y3)]; - }; - - return vec![ - IVec2::new(x1, y1), - IVec2::new(x1, y2), - IVec2::new(x9, y2), - IVec2::new(x9, y5), - IVec2::new(x3, y5), - IVec2::new(x3, y3), - IVec2::new(x4, y3), - ]; - } - - return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x10, y4), IVec2::new(x10, y3), IVec2::new(x4, y3)]; - } - - // `outConnector` point lies below `inConnector` point - // `outConnector` point lying on vertical grid line 1 unit to the left of `inConnector` point - if -grid_spacing <= out_x - in_x && out_x - in_x <= 0 { - // `outConnector` point lying on the horizontal grid lines 1 and 2 units below the `inConnector` point - if 0 <= out_y - in_y && out_y - in_y <= 2 * grid_spacing { - return vec![IVec2::new(x1, y6), IVec2::new(x11, y6), IVec2::new(x11, y3), IVec2::new(x4, y3)]; - }; - - return wire2; - } - - return vec![IVec2::new(x1, y1), IVec2::new(x1, y3), IVec2::new(x4, y3)]; - } - - // `outConnector` point lies to the right of `inConnector` point - if vertical_out && in_x <= out_x { - // `outConnector` point lying on any horizontal grid line above `inConnector` point - if out_y < in_y { - // `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point - if -2 * grid_spacing < out_y - in_y && out_y - in_y <= -grid_spacing { - return wire1; - }; - - // `outConnector` point lying on the same horizontal grid line as `inConnector` point - if -grid_spacing < out_y - in_y && out_y - in_y <= 0 { - return vec![IVec2::new(x1, y1), IVec2::new(x1, y8), IVec2::new(x5, y8), IVec2::new(x5, y3), IVec2::new(x4, y3)]; - }; - - // `outConnector` point lying on vertical grid lines 1 and 2 units to the right of `inConnector` point - if grid_spacing <= out_x - in_x && out_x - in_x <= 3 * grid_spacing { - return vec![ - IVec2::new(x1, y1), - IVec2::new(x1, y4), - IVec2::new(x9, y4), - IVec2::new(x9, y5), - IVec2::new(x3, y5), - IVec2::new(x3, y3), - IVec2::new(x4, y3), - ]; - } - - return vec![ - IVec2::new(x1, y1), - IVec2::new(x1, y4), - IVec2::new(x10, y4), - IVec2::new(x10, y5), - IVec2::new(x5, y5), - IVec2::new(x5, y3), - IVec2::new(x4, y3), - ]; - } - - // `outConnector` point lies below `inConnector` point - if out_y - in_y <= grid_spacing { - // `outConnector` point lies on the horizontal grid line 1 unit below the `inConnector` Point - if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing { - return vec![IVec2::new(x1, y9), IVec2::new(x3, y9), IVec2::new(x3, y3), IVec2::new(x4, y3)]; - }; - - if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing { - return wire3; - }; - - return wire4; - } - - // `outConnector` point lies on the horizontal grid line 2 units below `outConnector` point - if grid_spacing <= out_y - in_y && out_y - in_y <= 2 * grid_spacing { - if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing { - return vec![IVec2::new(x1, y7), IVec2::new(x5, y7), IVec2::new(x5, y3), IVec2::new(x4, y3)]; - }; - - if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing { - return wire3; - }; - - return wire4; - } - - // 0 to 4 units below the `outConnector` Point - if out_y - in_y <= 4 * grid_spacing { - return wire1; - }; - - return wire2; - } - - // Start horizontal, then vertical - if vertical_in { - // when `outConnector` lies below `inConnector` - if out_y > in_y { - // `out_x` lies to the left of `in_x` - if out_x < in_x { - return vec![IVec2::new(x1, y1), IVec2::new(x4, y1), IVec2::new(x4, y3)]; - }; - - // `out_x` lies to the right of `in_x` - if out_y - in_y <= grid_spacing { - // `outConnector` point directly below `inConnector` point - if 0 <= out_x - in_x && out_x - in_x <= grid_spacing { - return vec![IVec2::new(x1, y1), IVec2::new(x14, y1), IVec2::new(x14, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)]; - }; - - // `outConnector` point lies below `inConnector` point and strictly to the right of `inConnector` point - return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y111), IVec2::new(x4, y111), IVec2::new(x4, y3)]; - } - - return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)]; - } - - // `out_y` lies on or above the `in_y` point - if -6 * grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing { - // edge case: `outConnector` point lying on vertical grid lines ranging from 4 units to left to 5 units to right of `inConnector` point - if -grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing { - return vec![ - IVec2::new(x1, y1), - IVec2::new(x2, y1), - IVec2::new(x2, y2), - IVec2::new(x15, y2), - IVec2::new(x15, y12), - IVec2::new(x4, y12), - IVec2::new(x4, y3), - ]; - } - - return vec![IVec2::new(x1, y1), IVec2::new(x16, y1), IVec2::new(x16, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)]; - } - - // left of edge case: `outConnector` point lying on vertical grid lines more than 4 units to left of `inConnector` point - if 4 * grid_spacing < in_x - out_x { - return vec![IVec2::new(x1, y1), IVec2::new(x17, y1), IVec2::new(x17, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)]; - }; - - // right of edge case: `outConnector` point lying on the vertical grid lines more than 5 units to right of `inConnector` point - if 6 * grid_spacing > in_x - out_x { - return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)]; - }; - } - - // Both horizontal - use horizontal middle point - // When `inConnector` point is one of the two closest diagonally opposite points - if 0 <= in_x - out_x && in_x - out_x <= grid_spacing && in_y - out_y >= -grid_spacing && in_y - out_y <= grid_spacing { - return vec![IVec2::new(x19, y1), IVec2::new(x19, y3), IVec2::new(x4, y3)]; - } - - // When `inConnector` point lies on the horizontal line 1 unit above and below the `outConnector` point - if -grid_spacing <= out_y - in_y && out_y - in_y <= grid_spacing && out_x > in_x { - // Horizontal line above `out_y` - if in_y < out_y { - return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y13), IVec2::new(x3, y13), IVec2::new(x3, y3), IVec2::new(x4, y3)]; - }; - - // Horizontal line below `out_y` - return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y14), IVec2::new(x3, y14), IVec2::new(x3, y3), IVec2::new(x4, y3)]; - } - - // `outConnector` point to the right of `inConnector` point - if out_x > in_x - grid_spacing { - return vec![ - IVec2::new(x1, y1), - IVec2::new(x18, y1), - IVec2::new(x18, y15), - IVec2::new(x5, y15), - IVec2::new(x5, y3), - IVec2::new(x4, y3), - ]; - }; - - // When `inConnector` point lies on the vertical grid line two units to the right of `outConnector` point - if grid_spacing <= in_x - out_x && in_x - out_x <= 2 * grid_spacing { - return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y3), IVec2::new(x4, y3)]; - }; - - vec![IVec2::new(x1, y1), IVec2::new(x20, y1), IVec2::new(x20, y3), IVec2::new(x4, y3)] -} - -fn straight_wire_to_bezpath(locations: Vec) -> BezPath { - if locations.is_empty() { - return BezPath::new(); - } - - let to_point = |location: IVec2| Point::new(location.x as f64, location.y as f64); - - if locations.len() == 2 { - let p1 = to_point(locations[0]); - let p2 = to_point(locations[1]); - return Line::new(p1, p2).to_path(DEFAULT_ACCURACY); - } - - let corner_radius = 10; - - // Create path with rounded corners - let mut path = BezPath::new(); - path.move_to(to_point(locations[0])); - - for i in 1..(locations.len() - 1) { - let prev = locations[i - 1]; - let curr = locations[i]; - let next = locations[i + 1]; - - let corner_start = IVec2::new( - curr.x - + if curr.x == prev.x { - 0 - } else if prev.x > curr.x { - corner_radius - } else { - -corner_radius - }, - curr.y - + if curr.y == prev.y { - 0 - } else if prev.y > curr.y { - corner_radius - } else { - -corner_radius - }, - ); - - let corner_start_mid = IVec2::new( - curr.x - + if curr.x == prev.x { - 0 - } else if prev.x > curr.x { - corner_radius / 2 - } else { - -corner_radius / 2 - }, - curr.y - + if curr.y == prev.y { - 0 - } else { - match prev.y > curr.y { - true => corner_radius / 2, - false => -corner_radius / 2, - } - }, - ); - - let corner_end = IVec2::new( - curr.x - + if curr.x == next.x { - 0 - } else if next.x > curr.x { - corner_radius - } else { - -corner_radius - }, - curr.y - + if curr.y == next.y { - 0 - } else if next.y > curr.y { - corner_radius - } else { - -corner_radius - }, - ); - - let corner_end_mid = IVec2::new( - curr.x - + if curr.x == next.x { - 0 - } else if next.x > curr.x { - corner_radius / 2 - } else { - -corner_radius / 2 - }, - curr.y - + if curr.y == next.y { - 0 - } else if next.y > curr.y { - 10 / 2 - } else { - -corner_radius / 2 - }, - ); - - path.line_to(to_point(corner_start)); - path.curve_to(to_point(corner_start_mid), to_point(corner_end_mid), to_point(corner_end)); - } - path.line_to(to_point(*locations.last().unwrap())); - path -} - -#[cfg(test)] -mod tests { - use super::*; - use kurbo::{Affine, ParamCurveNearest}; - - #[test] - fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() { - let ends = [ - (DVec2::new(120., 24.), DVec2::new(480., 96.), false, false), - (DVec2::new(-120., 48.), DVec2::new(240., -72.), false, false), - (DVec2::new(48., -8.), DVec2::new(48., 104.), true, true), - (DVec2::new(-312., 200.), DVec2::new(-24., 24.), true, false), - (DVec2::new(600., 24.), DVec2::new(-96., 48.), false, true), - (DVec2::new(130.5, 31.25), DVec2::new(-410.75, 77.5), false, false), - ]; - let shifts = [DVec2::new(-24. * 50., 24. * 37.), DVec2::new(24. * 13., -24. * 90.), DVec2::new(-24., -24.)]; - - for (output, input, vertical_out, vertical_in) in ends { - let wire = build_vector_wire(output, input, vertical_out, vertical_in, GraphWireStyle::GridAligned); - for shift in shifts { - let shifted = build_vector_wire(output + shift, input + shift, vertical_out, vertical_in, GraphWireStyle::GridAligned); - let moved = Affine::translate(Vec2::new(shift.x, shift.y)) * wire.clone(); - assert_eq!(shifted, moved, "the wire from {output} to {input} should keep its shape when moved by {shift}"); - } - } - } - - #[test] - fn the_center_line_of_a_stack_wire_runs_inside_it() { - let ends = [ - (DVec2::new(48., 12.), DVec2::new(48., 84.)), - (DVec2::new(240., 12.), DVec2::new(48., 132.)), - (DVec2::new(48., 0.), DVec2::new(0., 27.)), - ]; - let half_wire_width = 4.; - - for (output, input) in ends { - for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] { - let wire = build_vector_wire(output, input, true, true, style); - let center_line = build_thick_wire_center_line(output, input, true, true, style); - - let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.))); - for sample in samples { - let distance = wire - .segments() - .map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt()) - .fold(f64::INFINITY, f64::min); - assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}"); - } - } - } - } -} diff --git a/editor/src/messages/portfolio/portfolio_message.rs b/editor/src/messages/portfolio/portfolio_message.rs index 6cfd1a9d68..f6a0fe974f 100644 --- a/editor/src/messages/portfolio/portfolio_message.rs +++ b/editor/src/messages/portfolio/portfolio_message.rs @@ -1,3 +1,4 @@ +use super::document::node_graph::graph_ui::GraphUiPart; use super::document::utility_types::document_metadata::LayerNodeIdentifier; use super::history::HistoryMessage; use super::persistent_state::PersistentStateMessage; @@ -157,11 +158,6 @@ pub enum PortfolioMessage { artboard_name: Option, artboard_count: usize, }, - RenderOverlays { - #[serde(skip, default = "OverlayContext::default")] - #[derivative(Debug = "ignore", PartialEq = "ignore")] - context: OverlayContext, - }, SubmitActiveGraphRender, SubmitGraphRender { document_id: DocumentId, @@ -175,6 +171,14 @@ pub enum PortfolioMessage { SubmitInspectContextOverrides { overrides: graphene_std::ContextOverrides, }, + UpdateGraphUi { + part: GraphUiPart, + }, + RenderOverlays { + #[serde(skip, default = "OverlayContext::default")] + #[derivative(Debug = "ignore", PartialEq = "ignore")] + context: OverlayContext, + }, PollNodeGraphEvaluation, ToggleResetNodesToDefinitionsOnOpen, ToggleRulers, diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index 3d503fa5ff..efcd0713a4 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -14,6 +14,7 @@ use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::DocumentMessageContext; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; use crate::messages::portfolio::document::node_graph::document_node_definitions; +use crate::messages::portfolio::document::node_graph::graph_ui; use crate::messages::portfolio::document_storage_io::{ DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, remove_stored_document, @@ -216,7 +217,6 @@ impl MessageHandler> for Portfolio // Send the information for tooltips and categories for each node/input. responses.add(FrontendMessage::SendUIMetadata { node_descriptions: document_node_definitions::collect_node_descriptions(), - node_icons: document_node_definitions::collect_node_icons(), node_types: document_node_definitions::collect_node_types(), }); @@ -898,18 +898,16 @@ impl MessageHandler> for Portfolio // The document we are leaving won't get the pointer up that ends a wire drag in its graph, so abort the drag there before switching if self.active_document_id != Some(document_id) && let Some(document) = self.active_document_mut() - && document.end_node_graph_wire_in_progress(responses) { - responses.add(DocumentMessage::AbortTransaction); - responses.add(PortfolioMessage::SelectDocument { document_id }); - return; - } - - // The document we are leaving won't get the frames that settle what glides in its graph, so it settles at once - if self.active_document_id != Some(document_id) - && let Some(document) = self.active_document_mut() - { - document.node_graph_handler.stop_gliding(&document.network_interface, responses); + let wire_ended = document.end_node_graph_wire_in_progress(responses); + if wire_ended { + responses.add(DocumentMessage::AbortTransaction); + } + let network_path = document.selection_network_path().to_vec(); + if wire_ended || document.node_graph_handler.abort_node_drag(&mut document.network_interface, &network_path, responses) { + responses.add(PortfolioMessage::SelectDocument { document_id }); + return; + } } // Auto-save the document we are leaving @@ -958,8 +956,6 @@ impl MessageHandler> for Portfolio responses.add(DocumentMessage::GraphViewOverlay { open: node_graph_open }); if node_graph_open { responses.add(NodeGraphMessage::UpdateGraphBarRight); - responses.add(NodeGraphMessage::UnloadWires); - responses.add(NodeGraphMessage::SendWires) } else { responses.add(PortfolioMessage::UpdateDocumentWidgets); } @@ -1012,6 +1008,17 @@ impl MessageHandler> for Portfolio #[cfg(not(target_family = "wasm"))] responses.add(FrontendMessage::WakeNodeRuntime); } + PortfolioMessage::UpdateGraphUi { part } => { + let Some(document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else { + return; + }; + let edited = graph_ui::edited_name(document); + document.node_graph_handler.graph_ui.update_name_field(edited, responses); + let builder = graph_ui::GraphUiSceneBuilder::of(document); + if self.executor.update_graph_ui(|scene| builder.update(part, scene)) { + responses.add(PortfolioMessage::SubmitActiveGraphRender); + } + } PortfolioMessage::SubmitActiveGraphRender => { if let Some(document_id) = self.active_document_id { responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false }); @@ -1025,9 +1032,8 @@ impl MessageHandler> for Portfolio return; }; - // Skip rendering while a resource is still loading, so its error isn't shown in the meantime. - // Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left. - if document.resources.awaiting_resources() { + let graph_ui_config = graph_ui::config(document, preferences.graph_wire_style); + if graph_ui_config.is_none() && document.resources.awaiting_resources() { return; } @@ -1051,12 +1057,20 @@ impl MessageHandler> for Portfolio // TODO: See #3796. #[cfg(not(target_family = "wasm"))] responses.add_front(FrontendMessage::UpdateViewportHolePunch { - active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview, + active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview || graph_ui_config.is_some(), }); - let result = self - .executor - .submit_node_graph_evaluation(document, document_id, physical_resolution, scale, timing_information, node_to_inspect, ignore_hash, pointer_position); + let result = self.executor.submit_node_graph_evaluation( + document, + document_id, + physical_resolution, + scale, + timing_information, + node_to_inspect, + ignore_hash, + pointer_position, + graph_ui_config, + ); match result { Err(description) => { diff --git a/editor/src/messages/preferences/preferences_message.rs b/editor/src/messages/preferences/preferences_message.rs index c29fa84bec..cc55411053 100644 --- a/editor/src/messages/preferences/preferences_message.rs +++ b/editor/src/messages/preferences/preferences_message.rs @@ -1,6 +1,6 @@ -use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::messages::preferences::SelectionMode; use crate::messages::prelude::*; +use graph_ui::wire::WireStyle; #[impl_message(Message, Preferences)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] @@ -22,7 +22,7 @@ pub enum PreferencesMessage { zoom_with_scroll: bool, }, GraphWireStyle { - style: GraphWireStyle, + style: WireStyle, }, ViewportZoomWheelRate { rate: f64, diff --git a/editor/src/messages/preferences/preferences_message_handler.rs b/editor/src/messages/preferences/preferences_message_handler.rs index 95efb57b79..03cbc4cc1f 100644 --- a/editor/src/messages/preferences/preferences_message_handler.rs +++ b/editor/src/messages/preferences/preferences_message_handler.rs @@ -1,9 +1,9 @@ use crate::consts::{UI_SCALE_DEFAULT, VIEWPORT_ZOOM_WHEEL_RATE}; use crate::messages::input_mapper::key_mapping::MappingVariant; -use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::messages::preferences::SelectionMode; use crate::messages::prelude::*; use crate::messages::tool::utility_types::ToolType; +use graph_ui::wire::WireStyle; #[derive(ExtractField)] pub struct PreferencesMessageContext<'a> { @@ -17,7 +17,7 @@ pub struct PreferencesMessageHandler { pub selection_mode: SelectionMode, pub zoom_with_scroll: bool, pub brush_tool: bool, - pub graph_wire_style: GraphWireStyle, + pub graph_wire_style: WireStyle, pub viewport_zoom_wheel_rate: f64, pub ui_scale: f64, pub disable_ui_acceleration: bool, @@ -51,7 +51,7 @@ impl Default for PreferencesMessageHandler { selection_mode: SelectionMode::Touched, zoom_with_scroll: matches!(MappingVariant::default(), MappingVariant::ZoomWithScroll), brush_tool: false, - graph_wire_style: GraphWireStyle::default(), + graph_wire_style: WireStyle::default(), viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE, ui_scale: UI_SCALE_DEFAULT, disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably @@ -126,8 +126,7 @@ impl MessageHandler> for Prefe } PreferencesMessage::GraphWireStyle { style } => { self.graph_wire_style = style; - responses.add(NodeGraphMessage::UnloadWires); - responses.add(NodeGraphMessage::SendWires); + responses.add(PortfolioMessage::SubmitActiveGraphRender); } PreferencesMessage::ViewportZoomWheelRate { rate } => { self.viewport_zoom_wheel_rate = rate; diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 988dee3d63..3bb083b805 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -11,6 +11,8 @@ use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; use graph_craft::list; use graph_craft::proto::GraphErrors; +use graph_ui::GraphUiConfig; +use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit}; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::color::SRGBA8; @@ -36,6 +38,7 @@ pub use runtime::*; pub struct ExecutionRequest { execution_id: u64, render_config: RenderConfig, + graph_ui_config: Option, } pub struct ExecutionResponse { @@ -137,6 +140,7 @@ pub struct NodeGraphExecutor { exports: HashMap, node_graph_hash: u64, + graph_ui_scene: GraphUiScene, /// The document whose network the graph runtime was last sent. node_graph_document: Option, /// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected. @@ -202,6 +206,7 @@ impl NodeGraphExecutor { current_export_id: 0, exports: HashMap::new(), node_graph_hash: 0, + graph_ui_scene: GraphUiScene::default(), node_graph_document: None, previous_node_to_inspect: Vec::new(), inspect_context_overrides: ContextOverrides::default(), @@ -214,16 +219,15 @@ impl NodeGraphExecutor { (node_executor, node_runtime) } - /// Forgets which canvas images the frontend holds, for a frontend that started over without them. - pub fn forget_canvas_images(&mut self) { - self.canvas_images_sent.clear(); - } - /// Execute the network by flattening it and creating a borrow stack. - fn queue_execution(&mut self, render_config: RenderConfig) -> u64 { + fn queue_execution(&mut self, render_config: RenderConfig, graph_ui_config: Option) -> u64 { let execution_id = self.current_execution_id; self.current_execution_id += 1; - let request = ExecutionRequest { execution_id, render_config }; + let request = ExecutionRequest { + execution_id, + render_config, + graph_ui_config, + }; self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); execution_id @@ -294,8 +298,9 @@ impl NodeGraphExecutor { } let layers = document.layers_in_view.all_in_view(); + let layers_panel = document.layers_in_view.layers_panel().clone(); self.sender - .send(GraphRuntimeRequest::ThumbnailsInView { layers, document_id }) + .send(GraphRuntimeRequest::ThumbnailsInView { layers, layers_panel, document_id }) .expect("Failed to send the thumbnails in view"); } @@ -356,6 +361,7 @@ impl NodeGraphExecutor { } /// Adds an evaluate request for whatever current network is cached. + #[allow(clippy::too_many_arguments)] pub(crate) fn submit_current_node_graph_evaluation( &mut self, document: &mut DocumentMessageHandler, @@ -364,6 +370,7 @@ impl NodeGraphExecutor { viewport_scale: f64, time: TimingInformation, pointer: DVec2, + graph_ui_config: Option, ) -> Result { let viewport = Footprint { transform: document.metadata().document_to_viewport, @@ -382,7 +389,7 @@ impl NodeGraphExecutor { }; // Execute the node graph - let execution_id = self.queue_execution(render_config); + let execution_id = self.queue_execution(render_config, graph_ui_config); self.futures.push_back(( execution_id, @@ -408,9 +415,10 @@ impl NodeGraphExecutor { node_to_inspect: Vec, ignore_hash: bool, pointer: DVec2, + graph_ui_config: Option, ) -> Result { self.update_node_graph(document, document_id, node_to_inspect, ignore_hash)?; - self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer) + self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer, graph_ui_config) } #[allow(clippy::too_many_arguments)] @@ -448,7 +456,7 @@ impl NodeGraphExecutor { }; // Execute the node graph - let execution_id = self.queue_execution(render_config); + let execution_id = self.queue_execution(render_config, None); self.futures.push_back(( execution_id, @@ -564,7 +572,9 @@ impl NodeGraphExecutor { if let Some(bake_target) = execution_context.measure_fill { if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) { let measured = observations.remove(&ObservationKey::FillMeasurement); - let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten(); + let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Fallback(..)) + .then_some(measured) + .flatten(); self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses); } continue; @@ -595,8 +605,8 @@ impl NodeGraphExecutor { responses.add(OverlaysMessage::Draw); - // A pending graph keeps the last frame, and the errors shown with it - if !matches!(result, ExecutionResult::Pending) { + // A pending graph keeps the last frame, and the errors shown with it; a provisional frame keeps the errors + if !matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) { let errors = match &result { ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => { let in_document = |path: &&[NodeId]| { @@ -819,6 +829,23 @@ impl NodeGraphExecutor { true } + pub fn update_graph_ui(&mut self, change: impl FnOnce(&mut GraphUiSceneEdit)) -> bool { + let mut edit = std::mem::take(&mut self.graph_ui_scene).edit(); + change(&mut edit); + let (scene, delta) = edit.finish(); + self.graph_ui_scene = scene; + + let changed = !delta.is_empty(); + if changed { + self.sender.send(GraphRuntimeRequest::GraphUi(delta)).expect("Failed to send the graph UI delta"); + } + changed + } + + pub fn forget_canvas_images(&mut self) { + self.canvas_images_sent.clear(); + } + // TODO: Eventually remove this document upgrade code /// Run the graph with its export chain redirected down to the (possibly nested) Fill at `network_path`/`fill_node_id` /// (so its branch evaluates even when hidden or orphaned) and that node inspected, so its evaluated geometry returns @@ -897,7 +924,7 @@ impl NodeGraphExecutor { for_export: false, for_eyedropper: false, }; - let execution_id = self.queue_execution(render_config); + let execution_id = self.queue_execution(render_config, None); self.futures.push_back(( execution_id, ExecutionContext { @@ -1337,6 +1364,10 @@ mod test { self.evaluation_errors.take() } + pub fn graph_ui_scene(&self) -> &GraphUiScene { + &self.graph_ui_scene + } + /// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received. pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result { // We should always invalidate the cache. diff --git a/editor/src/node_graph_executor/recompile_tests.rs b/editor/src/node_graph_executor/recompile_tests.rs index faaf1f31ea..20fcce86c9 100644 --- a/editor/src/node_graph_executor/recompile_tests.rs +++ b/editor/src/node_graph_executor/recompile_tests.rs @@ -11,7 +11,7 @@ async fn compile_and_run(editor: &mut EditorTestUtils) { let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let document = documents.get_mut(&document_id).unwrap(); executor - .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO) + .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None) .unwrap(); editor.runtime.update(); editor.runtime.run().await; diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 46251c59c5..608c516c3c 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -8,6 +8,7 @@ use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler}; use graph_craft::proto::GraphErrors; +use graph_ui::scene::{GraphUiScene, GraphUiSceneDelta}; use graphene_hash::CacheHash; use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture}; use graphene_std::ops::ConvertAsync; @@ -18,7 +19,7 @@ use graphene_std::runtime::AsyncRuntime; use graphene_std::vector::style::RenderMode; use graphene_std::{Context, NodeError, Poll}; use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle}; -use interpreted_executor::util::wrap_network_with_render_node_in_scope; +use interpreted_executor::util::{wrap_network_in_scope, wrap_network_with_render_node_in_scope}; use observer::Observer; pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue}; use std::sync::Arc; @@ -71,7 +72,6 @@ pub struct NodeRuntime { thumbnails: Thumbnails, observer: Observer, - /// Whether an observation changed since its results were last sent. observations_changed: bool, preprocessor: preprocessor::Preprocessor, @@ -87,6 +87,12 @@ pub struct NodeRuntime { /// The latest rendered overlays. overlays_texture: Option, + graph_ui_scene: GraphUiScene, + graph_ui_output: OutputHandle, + graph_ui_network_hash: Option, + graph_ui_texture: Option, + graph_ui_redrawn: bool, + /// Cached surface for Wasm viewport rendering (reused across frames) #[cfg(all(target_family = "wasm", feature = "wasm"))] wasm_canvas_cache: CanvasSurfaceHandle, @@ -113,6 +119,7 @@ pub enum GraphRuntimeRequest { }, ThumbnailsInView { layers: HashSet, + layers_panel: HashSet, document_id: DocumentId, }, RenderOverlays(OverlayContext), @@ -120,6 +127,7 @@ pub enum GraphRuntimeRequest { key: ObservationKey, observation: Option, }, + GraphUi(GraphUiSceneDelta), } #[derive(Debug)] @@ -192,6 +200,12 @@ impl NodeRuntime { overlays_canvas: VelloCanvas::default(), overlays_texture: None, + graph_ui_scene: GraphUiScene::default(), + graph_ui_output: OutputHandle::default(), + graph_ui_network_hash: None, + graph_ui_texture: None, + graph_ui_redrawn: false, + #[cfg(all(target_family = "wasm", feature = "wasm"))] wasm_canvas_cache: CanvasSurfaceHandle::new(), } @@ -254,8 +268,8 @@ impl NodeRuntime { None => self.send_export(id, ExecutionResult::Uncompiled), } } - GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => { - self.thumbnails.set_in_view(layers); + GraphRuntimeRequest::ThumbnailsInView { layers, layers_panel, document_id } => { + self.thumbnails.set_in_view(layers, layers_panel); self.pending_thumbnails = Some(document_id); } GraphRuntimeRequest::Observe { key, observation } => { @@ -266,13 +280,13 @@ impl NodeRuntime { self.overlays = Some(context); self.overlays_stale = true; } + GraphRuntimeRequest::GraphUi(delta) => self.graph_ui_scene.apply(delta), } } } pub async fn run(&mut self) -> Option { let dirty = self.dirty.swap(false, Ordering::Acquire); - let mut texture = None; if dirty { for (id, render_config, output) in std::mem::take(&mut self.exports) { @@ -287,7 +301,10 @@ impl NodeRuntime { && self.output.is_some() { let mut responses = VecDeque::new(); - self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await; + let rendered = self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await; + if rendered && let Some(request) = self.pending.filter(|request| request.graph_ui_config.is_some()) { + self.draw_graph_ui(request); + } if !responses.is_empty() { self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response"); } @@ -306,10 +323,7 @@ impl NodeRuntime { self.run_viewport(viewport).await; } - // Overlays that changed without new artwork are drawn over the artwork already shown - if self.overlays_stale { - texture = self.composite_viewport_frame(); - } + let texture = self.composite_viewport_frame(); (self.editor_wake)(); texture @@ -340,11 +354,65 @@ impl NodeRuntime { } self.respond(request, result, observations).await; + self.draw_graph_ui(request); + } + + fn draw_graph_ui(&mut self, request: ExecutionRequest) { + self.graph_ui_redrawn = true; + let Some(mut config) = request.graph_ui_config else { + self.graph_ui_texture = None; + self.graph_ui_network_hash = None; + self.graph_ui_output = OutputHandle::default(); + return; + }; + if !matches!(self.viewport_artwork, Some(ViewportArtwork::Texture(_))) { + config.fade_artwork = 1.; + } + + let scene = self.graph_ui_scene.clone(); + let thumbnails = self.thumbnails.graphics(); + let graph_ui_network = graph_ui::network(&scene, &config, &thumbnails); + let hash = graph_ui_network.current_hash(); + if self.graph_ui_network_hash != Some(hash) { + let mut graph_ui_network = wrap_network_in_scope(graph_ui_network, self.editor_api.clone(), self.async_runtime().handle()); + self.preprocessor.preprocess(&mut graph_ui_network, &|_| None).expect("The network of the node graph preprocesses"); + let graph_ui_network = Compiler {}.compile_single(graph_ui_network).expect("The network of the node graph compiles").network; + let replaced = std::mem::take(&mut self.graph_ui_output); + self.graph_ui_output = self.executor.replace(replaced, graph_ui_network).expect("The network of the node graph is typed"); + self.graph_ui_network_hash = Some(hash); + self.async_runtime().update_sources(self.executor.sources()); + } + + let context = graph_ui::render_config(config.view, request.render_config).into_context(); + self.graph_ui_texture = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.graph_ui_output, context))) { + Ok(Ok(Poll::Final(TaggedValue::RenderOutput(RenderOutput { + data: RenderOutputType::Texture(frame), + .. + })))) => Some(frame), + Ok(Ok(Poll::Error(error))) => { + log::error!("Failed to draw the node graph: {}", error.error()); + None + } + Ok(Ok(_)) => None, + Ok(Err(error)) => { + log::error!("Failed to draw the node graph: {error}"); + None + } + Err(payload) => { + let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::().map(String::as_str)); + log::error!("Panicked while drawing the node graph: {}", message.unwrap_or("no message")); + None + } + }; } - /// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web. fn composite_viewport_frame(&mut self) -> Option { - let artwork = self.viewport_artwork.as_ref()?; + if !std::mem::take(&mut self.graph_ui_redrawn) && !self.overlays_stale { + return None; + } + if self.viewport_artwork.is_none() && self.graph_ui_texture.is_none() { + return None; + } let executor = self.editor_api.application_io.as_ref().and_then(|application_io| application_io.gpu_executor())?; if std::mem::take(&mut self.overlays_stale) @@ -356,24 +424,34 @@ impl NodeRuntime { .ok(); } - let frame = match (artwork, &self.overlays_texture) { - (ViewportArtwork::Texture(artwork), Some(overlays)) => { - let (width, height) = (artwork.width(), artwork.height()); + let artwork = match &self.viewport_artwork { + Some(ViewportArtwork::Texture(artwork)) => Some(artwork), + Some(ViewportArtwork::Svg) | None => None, + }; + let overlays = self.overlays_texture.as_ref().filter(|_| self.graph_ui_texture.is_none()); + let frame = match (artwork, &self.graph_ui_texture, overlays) { + (None, None, None) => return None, + (Some(frame), None, None) | (None, Some(frame), None) | (None, None, Some(frame)) => frame.clone(), + (artwork, graph_ui, overlays) => { + // The node graph is drawn at the viewport's size, which artwork from before a resize doesn't have + let base = graph_ui.as_ref().or(artwork).or(overlays)?; + let (width, height) = (base.width(), base.height()); let max_texture_size = executor.context().device.limits().max_texture_dimension_2d; - let overlays_to_artwork = kurbo::Affine::scale_non_uniform(width as f64 / overlays.width() as f64, height as f64 / overlays.height() as f64); let mut scene = VelloSceneBuilder::new(width as u16, height as u16, kurbo::Affine::IDENTITY, max_texture_size); - scene.draw_texture(artwork.clone(), ImageSampler::new(), kurbo::Affine::IDENTITY); - scene.draw_texture(overlays.clone(), ImageSampler::new(), overlays_to_artwork); + for layer in [artwork, graph_ui.as_ref()].into_iter().flatten() { + scene.draw_texture(layer.clone(), ImageSampler::new(), kurbo::Affine::IDENTITY); + } + if let Some(overlays) = overlays { + let overlays_to_frame = kurbo::Affine::scale_non_uniform(width as f64 / overlays.width() as f64, height as f64 / overlays.height() as f64); + scene.draw_texture(overlays.clone(), ImageSampler::new(), overlays_to_frame); + } executor .render_vello_scene_on_canvas(&mut self.overlays_canvas, scene) - .inspect_err(|error| log::error!("Failed to draw the overlays over the artwork: {error:?}")) - .unwrap_or_else(|_| artwork.clone()) + .inspect_err(|error| log::error!("Failed to draw the viewport's frame: {error:?}")) + .unwrap_or_else(|_| base.clone()) } - (ViewportArtwork::Texture(artwork), None) => artwork.clone(), - (ViewportArtwork::Svg, Some(overlays)) => overlays.clone(), - (ViewportArtwork::Svg, None) => return None, }; #[cfg(all(target_family = "wasm", feature = "wasm"))] @@ -418,10 +496,14 @@ impl NodeRuntime { } fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option { - let ExecutionRequest { execution_id, mut render_config } = request; + let ExecutionRequest { + execution_id, + mut render_config, + graph_ui_config, + } = request; - // Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active - if render_config.export_format == ExportFormat::Raster && render_config.render_mode == RenderMode::SvgPreview { + // Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active and the graph, isn't open + if render_config.export_format == ExportFormat::Raster && render_config.render_mode == RenderMode::SvgPreview && graph_ui_config.is_none() { render_config.export_format = ExportFormat::Svg; } @@ -483,7 +565,7 @@ impl NodeRuntime { RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster, RenderOutputType::Buffer { .. } => false, }, - None => false, + None => request.graph_ui_config.is_some(), }) .then(|| ViewportCanvasInfo { id: self.wasm_canvas_cache.id(), @@ -502,14 +584,6 @@ impl NodeRuntime { self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); } - /// Reads one observation from the last evaluation, apart from the observations the runtime keeps. - #[cfg(test)] - pub(crate) fn observe(&self, observation: Observation) -> Option { - let mut observer = Observer::default(); - observer.set((), Some(observation)); - observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data - } - async fn read_back(&self, texture: Texture) -> Raster { let application_io = self.editor_api.application_io.as_ref().unwrap(); let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture"); @@ -581,6 +655,14 @@ impl NodeRuntime { dropped_thumbnails } + + /// Reads one observation from the last evaluation, apart from the observations the runtime keeps. + #[cfg(test)] + pub(crate) fn observe(&self, observation: Observation) -> Option { + let mut observer = Observer::default(); + observer.set((), Some(observation)); + observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data + } } impl ExecutionResult { @@ -677,12 +759,16 @@ mod tests { /// Sends a network update and a request to evaluate it at a viewport of `resolution` pixels. fn send_update_at(editor: &mut EditorTestUtils, resolution: UVec2) { + send_update_with_graph_ui(editor, resolution, None); + } + + fn send_update_with_graph_ui(editor: &mut EditorTestUtils, resolution: UVec2, graph_ui_config: Option) { let portfolio = editor.portfolio_message_handler_mut(); let document_id = portfolio.active_document_id.unwrap(); let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let document = documents.get_mut(&document_id).unwrap(); executor - .submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO) + .submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO, graph_ui_config) .unwrap(); } @@ -763,7 +849,7 @@ mod tests { let document = portfolio.documents.get_mut(&document_id).unwrap(); portfolio .executor - .submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) + .submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO, None) .unwrap(); } @@ -774,7 +860,7 @@ mod tests { /// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one. fn last_request(editor: &EditorTestUtils) -> Option { - editor.runtime.pending.map(|request| request.execution_id) + editor.runtime.pending.as_ref().map(|request| request.execution_id) } fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec { @@ -831,7 +917,7 @@ mod tests { let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let document = documents.get_mut(&document_id).unwrap(); let message = executor - .submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, scale, Default::default(), DVec2::ZERO) + .submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, scale, Default::default(), DVec2::ZERO, None) .unwrap(); editor.dispatch(message); } @@ -911,7 +997,7 @@ mod tests { let mut editor = editor().await; let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node(); - editor.runtime.thumbnails.set_in_view(HashSet::from([layer])); + editor.runtime.thumbnails.set_in_view(HashSet::from([layer]), HashSet::from([layer])); send_update(&mut editor); assert!(!thumbnail_stale(&mut editor, layer).await); diff --git a/editor/src/node_graph_executor/runtime/thumbnails.rs b/editor/src/node_graph_executor/runtime/thumbnails.rs index 8306f23019..5804de42bb 100644 --- a/editor/src/node_graph_executor/runtime/thumbnails.rs +++ b/editor/src/node_graph_executor/runtime/thumbnails.rs @@ -17,7 +17,7 @@ use graphene_std::transform::Footprint; use graphene_std::vector::Vector; use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic}; use interpreted_executor::dynamic_executor::DynamicExecutor; -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::sync::Arc; mod atlas; @@ -40,22 +40,17 @@ pub struct Thumbnails { sources: HashMap, /// The layers whose content changed since their thumbnail was last rendered. stale: HashSet, - /// The layers whose thumbnails the frontend shows, the only ones rendered. + unshown: HashSet, in_view: HashSet, + in_layers_panel: HashSet, /// The device pixel ratio thumbnails are rendered at. scale: f64, #[cfg(all(target_family = "wasm", feature = "wasm"))] - canvases: HashMap, + canvases: HashMap, /// The layers whose thumbnails were sent to a page that can't show the runtime's canvases. #[cfg(not(all(target_family = "wasm", feature = "wasm")))] sent: HashSet, -} - -/// A layer's thumbnail is shown in both the Layers panel and the node graph, but a canvas element can only be in one place. -#[cfg(all(target_family = "wasm", feature = "wasm"))] -struct ThumbnailCanvases { - layers_panel: CanvasHandle, - node_graph: CanvasHandle, + graphics: Arc>, } impl Thumbnails { @@ -63,8 +58,14 @@ impl Thumbnails { Self { scale: 1., ..Default::default() } } - pub fn set_in_view(&mut self, layers: HashSet) { + pub fn set_in_view(&mut self, layers: HashSet, layers_panel: HashSet) { + self.stale.extend(self.unshown.extract_if(|layer| layers_panel.contains(layer))); self.in_view = layers; + self.in_layers_panel = layers_panel; + } + + pub fn graphics(&self) -> Arc> { + self.graphics.clone() } /// Whether the layer's thumbnail is waiting to be rendered. @@ -90,6 +91,7 @@ impl Thumbnails { let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source)); self.stale.extend(changed.map(|(layer, _)| *layer)); self.stale.retain(|layer| sources.contains_key(layer)); + self.unshown.retain(|layer| sources.contains_key(layer)); self.sources = sources; } @@ -111,11 +113,13 @@ impl Thumbnails { #[cfg(not(all(target_family = "wasm", feature = "wasm")))] self.sent.retain(|layer| keep_sourced(layer)); + Arc::make_mut(&mut self.graphics).retain(|layer, _| sources.contains_key(layer)); + dropped } /// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view. - pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque) { + pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque) -> bool { let mut contents = HashMap::new(); for layer in std::mem::take(&mut self.stale) { let Some(&source) = self.sources.get(&layer) else { continue }; @@ -132,10 +136,12 @@ impl Thumbnails { contents.insert(layer, content); } if contents.is_empty() { - return; + return false; } + self.unshown.extend(contents.keys().filter(|layer| !self.in_layers_panel.contains(layer))); self.render_with_vello(&contents, editor_api, responses).await; + true } /// Renders the thumbnails into atlases with Vello and shows them. @@ -163,39 +169,55 @@ impl Thumbnails { } }; - self.show_atlas(&layout, texture, executor, responses).await; + self.keep_cells(&layout, &texture, executor); + let shown: Vec<(usize, NodeId)> = layout.layers.iter().copied().enumerate().filter(|(_, layer)| self.in_layers_panel.contains(layer)).collect(); + if !shown.is_empty() { + self.show_atlas(&layout, &shown, texture, executor, responses).await; + } } } - /// Reads the atlas back and draws each cell into the canvases the layer's rows show. + /// Copies each layer's cell out of the atlas into a texture of its own for the node graph. + fn keep_cells(&mut self, layout: &ThumbnailAtlasLayout, atlas: &Texture, executor: &wgpu_executor::WgpuExecutor) { + let mut encoder = executor.context().device.create_command_encoder(&Default::default()); + for (index, &layer) in layout.layers.iter().enumerate() { + let cell = executor.request_texture(layout.cell_size); + let mut source = atlas.as_image_copy(); + let origin = layout.cell_origin(index); + (source.origin.x, source.origin.y) = (origin.x, origin.y); + encoder.copy_texture_to_texture(source, cell.as_image_copy(), cell.size()); + Arc::make_mut(&mut self.graphics).insert(layer, Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(cell)))); + } + executor.context().queue.submit([encoder.finish()]); + } + + /// Reads the atlas back and draws each shown cell into the canvas the layer's row in the Layers panel shows. #[cfg(all(target_family = "wasm", feature = "wasm"))] - async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque) { + async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque) { let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await; let (pixels, _, _) = raster.to_flat_u8(); - for (index, &layer) in layout.layers.iter().enumerate() { + for &(index, layer) in shown { let cell_pixels = layout.cell_pixels(&pixels, index); let Ok(image) = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&cell_pixels), layout.cell_size.x, layout.cell_size.y) else { continue; }; - let canvases = self.canvases(layer); - for canvas in [&mut canvases.layers_panel, &mut canvases.node_graph] { - canvas.set_resolution(layout.cell_size); - let _ = canvas.context().put_image_data(&image, 0, 0); - } + let canvas = self.canvas(layer); + canvas.set_resolution(layout.cell_size); + let _ = canvas.context().put_image_data(&image, 0, 0); - responses.push_back(canvases.update_message(layer)); + responses.push_back(canvas_message(layer, canvas)); } } - /// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each layer its cell's pixels. + /// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each shown layer its cell's pixels. #[cfg(not(all(target_family = "wasm", feature = "wasm")))] - async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque) { + async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque) { let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await; let (pixels, _, _) = raster.to_flat_u8(); - for (index, &layer) in layout.layers.iter().enumerate() { + for &(index, layer) in shown { self.sent.insert(layer); responses.push_back(FrontendMessage::UpdateNodeThumbnailPixels { id: layer, @@ -207,23 +229,14 @@ impl Thumbnails { } #[cfg(all(target_family = "wasm", feature = "wasm"))] - fn canvases(&mut self, layer: NodeId) -> &mut ThumbnailCanvases { - self.canvases.entry(layer).or_insert_with(|| ThumbnailCanvases { - layers_panel: CanvasHandle::new(), - node_graph: CanvasHandle::new(), - }) + fn canvas(&mut self, layer: NodeId) -> &mut CanvasHandle { + self.canvases.entry(layer).or_insert_with(CanvasHandle::new) } } #[cfg(all(target_family = "wasm", feature = "wasm"))] -impl ThumbnailCanvases { - fn update_message(&mut self, layer: NodeId) -> FrontendMessage { - FrontendMessage::UpdateNodeThumbnailCanvases { - id: layer, - layers_panel_canvas_id: self.layers_panel.id(), - node_graph_canvas_id: self.node_graph.id(), - } - } +fn canvas_message(layer: NodeId, canvas: &mut CanvasHandle) -> FrontendMessage { + FrontendMessage::UpdateNodeThumbnailCanvas { id: layer, canvas_id: canvas.id() } } enum ThumbnailContent { @@ -368,7 +381,7 @@ mod tests { let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let document = documents.get_mut(&document_id).unwrap(); executor - .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO) + .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None) .unwrap(); editor.runtime.update(); editor.runtime.run().await; diff --git a/editor/src/test_utils.rs b/editor/src/test_utils.rs index dfa5f4cb17..20344091ba 100644 --- a/editor/src/test_utils.rs +++ b/editor/src/test_utils.rs @@ -75,7 +75,7 @@ impl EditorTestUtils { Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))), }; - if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) { + if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO, None) { return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}"))); } self.runtime.update(); @@ -90,13 +90,22 @@ impl EditorTestUtils { return Err(TestGraphError::Evaluation(errors)); } - for message in frontend_messages { - message.check_node_graph_error(); - } + self.check_node_graph_errors(); Ok(instrumented) } + fn check_node_graph_errors(&self) { + let document = self.active_document(); + if !document.graph_view_overlay_open { + return; + } + let errors = document.node_graph_handler.node_graph_errors(&document.network_interface, document.breadcrumb_network_path()); + if !errors.is_empty() { + panic!("errors: {errors:?}"); + } + } + /// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages. pub async fn eval_graph_until_finished(&mut self) -> Result { const MAX_ITERATIONS: usize = 16; @@ -283,12 +292,11 @@ impl EditorTestUtils { /// Sets the clock to a time in milliseconds and runs one animation frame, as the frontend does on each `requestAnimationFrame`. pub async fn animation_frame(&mut self, timestamp: u64) { - let messages = Box::new([ - InputPreprocessorMessage::CurrentTime { timestamp }.into(), - AnimationMessage::IncrementFrameCounter.into(), - BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(), - ]); - self.handle_message(Message::Batched { messages }).await; + self.handle_message(animation_frame_batch(timestamp)).await; + } + + pub fn dispatch_animation_frame(&mut self, timestamp: u64) { + self.dispatch(animation_frame_batch(timestamp)); } pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) { @@ -447,17 +455,13 @@ impl EditorTestUtils { } } -pub trait FrontendMessageTestUtils { - fn check_node_graph_error(&self); -} - -impl FrontendMessageTestUtils for FrontendMessage { - fn check_node_graph_error(&self) { - let FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors } = self else { return }; - if !errors.is_empty() { - panic!("errors: {errors:?}"); - } - } +fn animation_frame_batch(timestamp: u64) -> Message { + let messages = Box::new([ + InputPreprocessorMessage::CurrentTime { timestamp }.into(), + AnimationMessage::IncrementFrameCounter.into(), + BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(), + ]); + Message::Batched { messages } } #[derive(Debug)] @@ -554,7 +558,6 @@ impl Spawn for BlockingSpawner { #[cfg(test)] pub mod test_prelude { - pub use super::FrontendMessageTestUtils; pub use crate::application::Editor; pub use crate::float_eq; pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys}; diff --git a/frontend/src/components/panels/Document.svelte b/frontend/src/components/panels/Document.svelte index a2e6df6cc3..67e041bc55 100644 --- a/frontend/src/components/panels/Document.svelte +++ b/frontend/src/components/panels/Document.svelte @@ -680,7 +680,7 @@ {:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
{/if} - {#if $document.renderStatus === "Error"} + {#if $document.renderStatus === "Error" && !$document.graphViewOverlayOpen}

@@ -703,7 +703,7 @@ {/if} -

+
@@ -1005,7 +1005,6 @@ .graph-view { pointer-events: none; - transition: opacity 0.2s; opacity: 0; &.open { @@ -1013,21 +1012,8 @@ pointer-events: auto; opacity: 1; } - - &::before { - content: ""; - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: var(--color-2-mildblack); - opacity: var(--fade-artwork); - pointer-events: none; - } } - .fade-artwork, .graph { position: absolute; top: 0; diff --git a/frontend/src/components/panels/Layers.svelte b/frontend/src/components/panels/Layers.svelte index 4636f824cf..4e97cf2352 100644 --- a/frontend/src/components/panels/Layers.svelte +++ b/frontend/src/components/panels/Layers.svelte @@ -1247,7 +1247,7 @@ {/if}
{#if $nodeGraph.thumbnailCanvases.has(listing.id)} - + {:else if $thumbnailImages.has(listing.id)} {/if} diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index 513fddc94d..615439ad08 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -1,14 +1,8 @@ -
-
+
+
{#if $nodeGraph.readOnly}
@@ -419,12 +194,13 @@ {@const isImport = $nodeGraph.contextMenuInformation.contextMenuData.data.isImport} {@const index = $nodeGraph.contextMenuInformation.contextMenuData.data.index} {@const exposed = $nodeGraph.contextMenuInformation.contextMenuData.data.exposed} + {@const description = $nodeGraph.contextMenuInformation.contextMenuData.data.description} + {@const descriptionAnchor = $nodeGraph.contextMenuInformation.contextMenuData.data.descriptionAnchor} { - const currentName = (isImport ? $nodeGraphImportsExports?.imports[index]?.name : $nodeGraphImportsExports?.exports[index]?.name) || ""; - startEditingName({ kind: isImport ? "Import" : "Export", index }, currentName); + editor.beginNetworkConnectorNameEdit(isImport, index); closeContextMenu(); }} flush={true} @@ -432,7 +208,7 @@ { - editDescription(isImport, index); + editDescription(isImport, index, description, descriptionAnchor); closeContextMenu(); }} flush={true} @@ -522,608 +298,25 @@ {/if} - {#if $nodeGraph.errors.length > 0} -
- {#each $nodeGraph.errors as error} - {@const glideOffset = $nodeGlideOffsets.nodes.get(error.nodeId)} - {@const left = `${error.position[0] + (glideOffset?.[0] || 0)}px`} - {@const top = `${error.position[1] + (glideOffset?.[1] || 0)}px`} - - {error.error} - - - {error.error} - - {/each} + {#if nameField} +
+ endNameEdit(nameFieldText)} + on:keydown={onNameFieldKeyDown} + />
{/if} - - -
- - {#each $nodeGraphWires.entries() as [nodeId, map]} - {#each map.entries() as [inputIndex, wire]} - - {/each} - {/each} - -
- - -
- {#if $nodeGraphImportsExports} - {#each $nodeGraphImportsExports.imports as frontendOutput, index} - {#if frontendOutput} - - {#if frontendOutput.connected} - - {:else} - - {/if} - - -
- {#if editingName?.kind === "Import" && editingName.index === index} - - {:else} -

{ - if (!$nodeGraph.readOnly) startEditingName({ kind: "Import", index }, frontendOutput.name); - }} - > - {frontendOutput.name} -

- {/if} -
- {:else if $nodeGraphImportsExports.addImportExport && !$nodeGraph.readOnly} - - - - {/if} - {/each} - - {#each $nodeGraphImportsExports.exports as frontendInput, index} - {#if frontendInput} - - {#if frontendInput.connected} - - {:else} - - {/if} - -
- {#if editingName?.kind === "Export" && editingName.index === index} - - {:else} - -

{ - if ($nodeGraphImportsExports?.addImportExport && !$nodeGraph.readOnly) startEditingName({ kind: "Export", index }, frontendInput.name); - }} - > - {frontendInput.name} -

- {/if} -
- {:else if $nodeGraphImportsExports.addImportExport && !$nodeGraph.readOnly} - - - - {/if} - {/each} - - - {#if $nodeGraphImportsExports.addImportExport && !$nodeGraph.readOnly} - - - - - - - {/if} - - {#if $nodeGraph.reorderImportIndex !== undefined} - {@const position = { - x: Number($nodeGraphImportsExports.importPosition[0]), - y: Number($nodeGraphImportsExports.importPosition[1]) + reorderLineTop(Number($nodeGraph.reorderImportIndex)), - }} -
- {/if} - - {#if $nodeGraph.reorderExportIndex !== undefined} - {@const position = { - x: Number($nodeGraphImportsExports.exportPosition[0]), - y: Number($nodeGraphImportsExports.exportPosition[1]) + reorderLineTop(Number($nodeGraph.reorderExportIndex)), - }} -
- {/if} - {/if} -
- - -
- - {#each Array.from($nodeGraph.nodes.values()).filter((node) => node.isLayer) as node (node.id)} - {#if $visibleNodes.has(node.id)} - {@const clipPathId = String(Math.random()).substring(2)} - {@const stackDataInput = node.exposedInputs[0]} - {@const layerAreaWidth = $nodeGraph.layerWidths.get(node.id) || 8} - {@const layerChainWidth = $nodeGraph.chainWidths.get(node.id) || 0} - {@const hasLeftInputWire = $nodeGraph.hasLeftInputWire.get(node.id) || false} - {@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined} -
-
- {#if $nodeGraph.thumbnailCanvases.has(node.id)} - - {:else if $thumbnailImages.has(node.id)} - - {/if} - - {#if node.primaryOutput} - - {#if node.primaryOutput.connected} - - {#if node.primaryOutputConnectedToLayer} - - {/if} - {:else} - - {/if} - - {/if} - - - {#if node.primaryInput?.connected} - - {#if node.primaryInputConnectedToLayer} - - {/if} - {:else} - - {/if} - -
- - {#if node.exposedInputs.length > 0} -
- - {#if stackDataInput.connected} - - {:else} - - {/if} - -
- {/if} -
- {#if editingName?.kind === "Layer" && editingName.nodeId === node.id} - - {:else} - {node.displayName} - {/if} -
-
- {#if node.locked} - { - /* Button is purely visual, clicking is handled in NodeGraphMessage::PointerUp */ - }} - tooltipLabel="Unlock" - /> - {/if} - { - /* Button is purely visual, clicking is handled in NodeGraphMessage::PointerUp */ - }} - tooltipLabel={node.visible ? "Hide" : "Show"} - /> - - - - - - - - - -
- {/if} - {/each} - - -
- - {#each $nodeGraphWires.entries() as [nodeId, map]} - {#each map.entries() as [inputIndex, wire]} - - {/each} - {/each} - {#if $nodeGraph.wirePathInProgress} - - {/if} - -
- - - {#each Array.from($nodeGraph.nodes.values()).filter((node) => !node.isLayer && !node.isRedirectDot) as node (node.id)} - {#if $visibleNodes.has(node.id)} - {@const exposedInputsOutputs = zipWithUndefined(node.exposedInputs, node.exposedOutputs)} - {@const clipPathId = String(Math.random()).substring(2)} - {@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined} - {@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"} -
- -
- - - {node.displayName} -
- - {#if exposedInputsOutputs.length > 0} -
- {#each exposedInputsOutputs as [input, output]} -
- - {input !== undefined ? input.name : output.name} - -
- {/each} -
- {/if} - -
- {#if node.primaryInput?.dataType} - - {#if node.primaryInput.connected} - - {:else} - - {/if} - - {/if} - {#each node.exposedInputs as secondary, index} - {#if index < node.exposedInputs.length} - - {#if secondary.connected} - - {:else} - - {/if} - - {/if} - {/each} -
- -
- {#if node.primaryOutput} - - {#if node.primaryOutput.connected} - - {:else} - - {/if} - - {/if} - {#each node.exposedOutputs as secondary} - - {#if secondary.connected} - - {:else} - - {/if} - - {/each} -
- - - - - - - -
- {/if} - {/each} - - - {#each Array.from($nodeGraph.nodes.values()).filter((node) => node.isRedirectDot) as node (node.id)} - {#if $visibleNodes.has(node.id)} -
- -
- {#if !node.primaryInput?.connected} -
- {/if} -
- -
- - - -
- {/if} - {/each} -
- -{#if $nodeGraph.box} -
-{/if} - diff --git a/frontend/src/components/views/NodeGraphWire.svelte b/frontend/src/components/views/NodeGraphWire.svelte deleted file mode 100644 index a07d451a51..0000000000 --- a/frontend/src/components/views/NodeGraphWire.svelte +++ /dev/null @@ -1,28 +0,0 @@ - - -{#if $wire.thick === thick} - - {#if thick} - - - - {:else if $wire.isList} - - - - {:else} - - {/if} - -{/if} diff --git a/frontend/src/stores/document.ts b/frontend/src/stores/document.ts index 0358d9a821..7bff868277 100644 --- a/frontend/src/stores/document.ts +++ b/frontend/src/stores/document.ts @@ -14,7 +14,6 @@ type DocumentStoreState = { workingColorsLayout: Layout; nodeGraphControlBarLayout: Layout; graphViewOverlayOpen: boolean; - fadeArtwork: number; renderStatus: RenderStatus; }; const initialState: DocumentStoreState = { @@ -24,7 +23,6 @@ const initialState: DocumentStoreState = { workingColorsLayout: createLayout(), nodeGraphControlBarLayout: createLayout(), graphViewOverlayOpen: false, - fadeArtwork: 100, renderStatus: "Rendering", }; @@ -44,13 +42,6 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) { subscriptionsRouter = subscriptions; - subscriptions.subscribeFrontendMessage("UpdateGraphFadeArtwork", (data) => { - update((state) => { - state.fadeArtwork = data.percentage; - return state; - }); - }); - subscriptions.subscribeLayoutUpdate("ToolOptions", (data) => { patchLayout(get(store).toolOptionsLayout, data); }); @@ -99,7 +90,6 @@ export function destroyDocumentStore() { const subscriptions = subscriptionsRouter; if (!subscriptions) return; - subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork"); subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay"); subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus"); subscriptions.unsubscribeFrontendMessage("UpdateRemoteCursors"); diff --git a/frontend/src/stores/node-graph.ts b/frontend/src/stores/node-graph.ts index 6e34046cbe..fe0396178c 100644 --- a/frontend/src/stores/node-graph.ts +++ b/frontend/src/stores/node-graph.ts @@ -1,59 +1,27 @@ import { get, writable } from "svelte/store"; import type { Writable } from "svelte/store"; -import type { IconName } from "/src/icons"; import type { SubscriptionsRouter } from "/src/subscriptions-router"; -import type { MessageBody } from "/src/subscriptions-router"; -import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper"; +import type { ContextMenuInformation, FrontendNodeType } from "/wrapper/pkg/graphite_wasm_wrapper"; export type NodeGraphStore = ReturnType; export type NodeGraphTransform = { scale: number; x: number; y: number }; -export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId: number }; - type NodeGraphStoreState = { - box: BoxSelection | undefined; contextMenuInformation: ContextMenuInformation | undefined; - errors: NodeGraphErrorDiagnostic[]; - layerWidths: Map; - chainWidths: Map; - hasLeftInputWire: Map; - nodes: Map; - wirePathInProgress: WirePath | undefined; - wireInProgressDraggedFrom: [number, number] | undefined; - wireInProgressSnappedTo: [number, number] | undefined; - hoveredConnector: [number, number] | undefined; nodeDescriptions: Map; - nodeIcons: Map; nodeTypes: FrontendNodeType[]; - thumbnailCanvases: Map; + thumbnailCanvases: Map; selected: bigint[]; - inSelectedNetwork: boolean; readOnly: boolean; - reorderImportIndex: number | undefined; - reorderExportIndex: number | undefined; }; const initialState: NodeGraphStoreState = { - box: undefined, contextMenuInformation: undefined, - errors: [], - layerWidths: new Map(), - chainWidths: new Map(), - hasLeftInputWire: new Map(), - nodes: new Map(), - wirePathInProgress: undefined, - wireInProgressDraggedFrom: undefined, - wireInProgressSnappedTo: undefined, - hoveredConnector: undefined, nodeDescriptions: new Map(), - nodeIcons: new Map(), nodeTypes: [], thumbnailCanvases: new Map(), selected: [], - inSelectedNetwork: true, readOnly: false, - reorderImportIndex: undefined, - reorderExportIndex: undefined, }; let subscriptionsRouter: SubscriptionsRouter | undefined = undefined; @@ -83,36 +51,14 @@ const store: Writable = import.meta.hot?.data?.store || wri if (import.meta.hot) import.meta.hot.data.store = store; const { subscribe, update } = store; -// Separate transform store so pan/zoom updates don't trigger re-rendering the entire node graph +// Separate transform store so a pan or zoom re-renders only the menus and fields placed in graph space const transformStore: Writable = import.meta.hot?.data?.transformStore || writable({ scale: 1, x: 0, y: 0 }); if (import.meta.hot) import.meta.hot.data.transformStore = transformStore; -// Separate imports/exports store so viewport-anchored position updates don't trigger node re-renders -const importsExportsStore: Writable | undefined> = import.meta.hot?.data?.importsExportsStore || writable(undefined); -if (import.meta.hot) import.meta.hot.data.importsExportsStore = importsExportsStore; - -// Kept apart from the node graph state so a thumbnail update doesn't re-render every node +// Kept apart from the node graph state so a thumbnail update doesn't re-render every row of the Layers panel const thumbnailImagesStore: Writable> = import.meta.hot?.data?.thumbnailImagesStore || writable(new Map()); if (import.meta.hot) import.meta.hot.data.thumbnailImagesStore = thumbnailImagesStore; -// Separate visible nodes store so viewport culling changes don't trigger full node re-renders -const visibleNodesStore: Writable> = import.meta.hot?.data?.visibleNodesStore || writable(new Set()); -if (import.meta.hot) import.meta.hot.data.visibleNodesStore = visibleNodesStore; - -// Separate wires store so wire path updates (e.g. export connector movement during pan) don't trigger node re-renders. -// It only changes when wires are added or removed, since each wire's path is kept in its own store so updating it only re-renders that wire. -const wiresStore: Writable>>> = import.meta.hot?.data?.wiresStore || writable(new Map()); -if (import.meta.hot) import.meta.hot.data.wiresStore = wiresStore; - -// Separate wire insertion preview store so the wires don't re-render with every node graph update -const wireInsertionPreviewStore: Writable<[bigint, number] | undefined> = import.meta.hot?.data?.wireInsertionPreviewStore || writable(undefined); -if (import.meta.hot) import.meta.hot.data.wireInsertionPreviewStore = wireInsertionPreviewStore; - -// Separate glide offsets store so the per-frame offsets of whatever is gliding into the place it moved to don't trigger full node re-renders -export type GlideOffsets = { nodes: Map; imports: [number, number]; exports: [number, number] }; -const glideOffsetsStore: Writable = import.meta.hot?.data?.glideOffsetsStore || writable({ nodes: new Map(), imports: [0, 0], exports: [0, 0] }); -if (import.meta.hot) import.meta.hot.data.glideOffsetsStore = glideOffsetsStore; - export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { destroyNodeGraphStore(); @@ -121,19 +67,11 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { subscriptions.subscribeFrontendMessage("SendUIMetadata", (data) => { update((state) => { state.nodeDescriptions = new Map(data.nodeDescriptions); - state.nodeIcons = new Map(data.nodeIcons); state.nodeTypes = data.nodeTypes; return state; }); }); - subscriptions.subscribeFrontendMessage("UpdateBox", (data) => { - update((state) => { - state.box = data.box; - return state; - }); - }); - subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => { update((state) => { state.contextMenuInformation = data.contextMenuInformation; @@ -141,42 +79,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); - subscriptions.subscribeFrontendMessage("UpdateImportReorderIndex", (data) => { - update((state) => { - state.reorderImportIndex = data.importIndex; - return state; - }); - }); - - subscriptions.subscribeFrontendMessage("UpdateExportReorderIndex", (data) => { - update((state) => { - state.reorderExportIndex = data.exportIndex; - return state; - }); - }); - - subscriptions.subscribeFrontendMessage("UpdateWireInsertionPreview", (data) => { - wireInsertionPreviewStore.set(data.wire); - }); - - subscriptions.subscribeFrontendMessage("UpdateHoveredConnector", (data) => { - update((state) => { - state.hoveredConnector = data.center; - return state; - }); - }); - - subscriptions.subscribeFrontendMessage("UpdateImportsExports", (data) => { - importsExportsStore.set(data); - }); - - subscriptions.subscribeFrontendMessage("UpdateInSelectedNetwork", (data) => { - update((state) => { - state.inSelectedNetwork = data.inSelectedNetwork; - return state; - }); - }); - subscriptions.subscribeFrontendMessage("UpdateNetworkReadOnly", (data) => { update((state) => { state.readOnly = data.readOnly; @@ -184,86 +86,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); - subscriptions.subscribeFrontendMessage("UpdateLayerWidths", (data) => { - update((state) => { - state.layerWidths = data.layerWidths; - state.chainWidths = data.chainWidths; - state.hasLeftInputWire = data.hasLeftInputWire; - return state; - }); - }); - - subscriptions.subscribeFrontendMessage("UpdateNodeGraphNodes", (data) => { - update((state) => { - state.nodes.clear(); - data.nodes.forEach((node) => { - state.nodes.set(node.id, node); - }); - return state; - }); - }); - - subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics", (data) => { - update((state) => { - state.errors = data.errors; - return state; - }); - }); - - subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => { - const newNodes = new Set(data.nodes); - - // Short-circuit when the visible set hasn't changed to avoid unnecessary re-renders - let changed = false; - const unsubscribe = visibleNodesStore.subscribe((current) => { - if (current.size !== newNodes.size) { - changed = true; - } else { - newNodes.forEach((node) => { - if (!current.has(node)) changed = true; - }); - } - }); - unsubscribe(); - - if (!changed) return; - - visibleNodesStore.set(newNodes); - }); - - subscriptions.subscribeFrontendMessage("UpdateGlideOffsets", (data) => { - glideOffsetsStore.set({ nodes: new Map(data.nodes), imports: data.imports, exports: data.exports }); - }); - - subscriptions.subscribeFrontendMessage("UpdateNodeGraphWires", (data) => { - const wires = get(wiresStore); - let wiresChanged = false; - - data.wires.forEach(({ id, inputIndex, wirePathUpdate }) => { - let inputMap = wires.get(id); - const wire = inputMap?.get(inputIndex); - - if (wirePathUpdate === undefined) { - if (inputMap?.delete(inputIndex)) wiresChanged = true; - } else if (wire) { - wire.set(wirePathUpdate); - } else { - if (!inputMap) { - inputMap = new Map(); - wires.set(id, inputMap); - } - inputMap.set(inputIndex, writable(wirePathUpdate)); - wiresChanged = true; - } - }); - - if (wiresChanged) wiresStore.set(wires); - }); - - subscriptions.subscribeFrontendMessage("ClearAllNodeGraphWires", () => { - wiresStore.set(new Map()); - }); - subscriptions.subscribeFrontendMessage("UpdateNodeGraphSelection", (data) => { update((state) => { state.selected = data.selected; @@ -275,14 +97,11 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { transformStore.set({ scale: data.scale, x: data.translation[0], y: data.translation[1] }); }); - subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvases", (data) => { - const { id, ...canvases } = data; - - const current = get(store).thumbnailCanvases.get(id); - if (current?.layersPanelCanvasId === canvases.layersPanelCanvasId && current?.nodeGraphCanvasId === canvases.nodeGraphCanvasId) return; + subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvas", (data) => { + if (get(store).thumbnailCanvases.get(data.id) === data.canvasId) return; update((state) => { - state.thumbnailCanvases.set(id, canvases); + state.thumbnailCanvases.set(data.id, data.canvasId); return state; }); }); @@ -303,16 +122,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); - subscriptions.subscribeFrontendMessage("UpdateWirePathInProgress", (data) => { - update((state) => { - state.wirePathInProgress = data.wirePath; - state.wireInProgressDraggedFrom = data.draggedFrom; - state.wireInProgressSnappedTo = data.snappedTo; - return state; - }); - }); - - return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore }; + return { subscribe, transformStore, thumbnailImagesStore }; } export function destroyNodeGraphStore() { @@ -320,28 +130,13 @@ export function destroyNodeGraphStore() { if (!subscriptions) return; subscriptions.unsubscribeFrontendMessage("SendUIMetadata"); - subscriptions.unsubscribeFrontendMessage("UpdateBox"); subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation"); - subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex"); - subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex"); - subscriptions.unsubscribeFrontendMessage("UpdateWireInsertionPreview"); - subscriptions.unsubscribeFrontendMessage("UpdateHoveredConnector"); - subscriptions.unsubscribeFrontendMessage("UpdateImportsExports"); - subscriptions.unsubscribeFrontendMessage("UpdateInSelectedNetwork"); subscriptions.unsubscribeFrontendMessage("UpdateNetworkReadOnly"); - subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths"); - subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes"); - subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics"); - subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes"); - subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets"); - subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires"); - subscriptions.unsubscribeFrontendMessage("ClearAllNodeGraphWires"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphSelection"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphTransform"); - subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvases"); + subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvas"); subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailPixels"); subscriptions.unsubscribeFrontendMessage("ClearNodeThumbnails"); - subscriptions.unsubscribeFrontendMessage("UpdateWirePathInProgress"); } export function closeContextMenu() { diff --git a/frontend/src/stores/tooltip.ts b/frontend/src/stores/tooltip.ts index b8ba1e4c7b..9f788b0e9b 100644 --- a/frontend/src/stores/tooltip.ts +++ b/frontend/src/stores/tooltip.ts @@ -29,7 +29,7 @@ type Listener = { eventName: keyof DocumentEventMap; action(event: Event): void; const tooltipEventListeners: Listener[] = [ { eventName: "mouseover", action: onMouseOver }, { eventName: "mousemove", action: onMouseMove }, - { eventName: "mouseleave", action: onMouseLeave }, + { eventName: "mouseleave", action: closeTooltip }, { eventName: "mousedown", action: closeTooltip }, // Heard on the way down, since a floating menu or a field with its menu open stops these from bubbling up { eventName: "keydown", action: closeTooltip, capture: true }, @@ -38,6 +38,7 @@ const tooltipEventListeners: Listener[] = [ let subscriptionsRouter: SubscriptionsRouter | undefined = undefined; let tooltipTimeout: ReturnType | undefined = undefined; +let latestMouseMove: MouseEvent | undefined = undefined; // Store state persisted across HMR to maintain reactive subscriptions in the component tree const store: Writable = import.meta.hot?.data?.store || writable(initialState); @@ -107,12 +108,29 @@ function onMouseOver(e: MouseEvent) { // Listen for mouse movements to schedule and position the tooltip, or hide it immediately upon further movement function onMouseMove(e: MouseEvent) { + latestMouseMove = e; + // Hide the tooltip now that the cursor has moved update((state) => { state.visible = false; return state; }); + scheduleTooltip(e); +} + +// For an element whose tooltip changes while the cursor rests on it +export function retargetTooltip(element: Element | undefined) { + update((state) => { + state.visible = false; + state.element = element; + return state; + }); + + if (latestMouseMove) scheduleTooltip(latestMouseMove); +} + +function scheduleTooltip(e: MouseEvent) { // Before we schedule a new future tooltip appearance, we clear the existing one if (tooltipTimeout) clearTimeout(tooltipTimeout); @@ -131,14 +149,11 @@ function onMouseMove(e: MouseEvent) { }, SHOW_TOOLTIP_DELAY_MS); } -// Hide tooltip and cancel any pending timeout when the mouse leaves the application window -function onMouseLeave() { - if (tooltipTimeout) clearTimeout(tooltipTimeout); - closeTooltip(); -} - // Stop showing a tooltip if the user clicks or presses a key, and require the user to first move out of the element before it can re-appear function closeTooltip() { + if (tooltipTimeout) clearTimeout(tooltipTimeout); + latestMouseMove = undefined; + update((state) => { state.visible = false; state.element = undefined; diff --git a/frontend/src/utility-functions/input.ts b/frontend/src/utility-functions/input.ts index b31fd6754f..96bb1036d3 100644 --- a/frontend/src/utility-functions/input.ts +++ b/frontend/src/utility-functions/input.ts @@ -188,9 +188,9 @@ export function onPointerUp(e: PointerEvent, editor: EditorWrapper) { export function onPotentialDoubleClick(e: MouseEvent, editor: EditorWrapper) { if (isObserveOnly(e) || textToolInteractiveInputElement || inPointerLock) return; - // Allow only events within the viewport or node graph boundaries + // Allow only events within the viewport or node graph boundaries, but not in a text field laid over them const isTargetingCanvas = e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]"); - if (!(isTargetingCanvas instanceof Element)) return; + if (!(isTargetingCanvas instanceof Element) || targetIsTextField(e.target || undefined)) return; // Allow only double-clicks (2, 4, etc.), not 0 for a canceled click if (e.detail === 0 || e.detail % 2 === 1) return; diff --git a/frontend/wrapper/src/editor_commands.rs b/frontend/wrapper/src/editor_commands.rs index c32ce127e3..33d6747ddd 100644 --- a/frontend/wrapper/src/editor_commands.rs +++ b/frontend/wrapper/src/editor_commands.rs @@ -19,8 +19,9 @@ mod editor_commands { use editor::messages::input_mapper::utility_types::keyboard::ModifierKeys; use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta}; use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; + use editor::messages::portfolio::document::node_graph::graph_ui::GraphName; use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; - use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport; + use editor::messages::portfolio::document::utility_types::network_interface::NetworkConnectorKey; use editor::messages::portfolio::ingest::utility_types::DataTransferItem; use editor::messages::portfolio::utility_types::PanelGroupId; use editor::messages::prelude::*; @@ -673,11 +674,6 @@ mod editor_commands { .into() } - /// Set the name for a layer in the network shown by the node graph, which may be a subgraph - fn set_layer_name_in_graph(id: u64, name: String) -> Message { - DocumentMessage::SetLayerNameInGraph { node_id: NodeId(id), name }.into() - } - /// Translates document (in viewport coords) fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message { NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into() @@ -800,29 +796,20 @@ mod editor_commands { DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into() } - /// Set the name of an import. - fn set_import_name(index: usize, name: String) -> Message { - NodeGraphMessage::SetImportExportName { - name, - index: ImportOrExport::Import(index), - } - .into() + fn begin_network_connector_name_edit(is_import: bool, index: usize) -> Message { + let name = GraphName::NetworkConnector(if is_import { NetworkConnectorKey::Import(index) } else { NetworkConnectorKey::Export(index) }); + NodeGraphMessage::BeginEditName { name }.into() } - /// Set the name of an export. - fn set_export_name(index: usize, name: String) -> Message { - NodeGraphMessage::SetImportExportName { - name, - index: ImportOrExport::Export(index), - } - .into() + fn end_graph_name_edit(name: Option) -> Message { + NodeGraphMessage::EndEditName { name }.into() } /// Set the description of an import. fn set_import_description(index: usize, description: String) -> Message { NodeGraphMessage::SetImportExportDescription { description, - index: ImportOrExport::Import(index), + index: NetworkConnectorKey::Import(index), } .into() } @@ -831,7 +818,7 @@ mod editor_commands { fn set_export_description(index: usize, description: String) -> Message { NodeGraphMessage::SetImportExportDescription { description, - index: ImportOrExport::Export(index), + index: NetworkConnectorKey::Export(index), } .into() } @@ -841,7 +828,10 @@ mod editor_commands { Message::Batched { messages: Box::new([ DocumentMessage::AddTransaction.into(), - NodeGraphMessage::RemoveImportExport { index: ImportOrExport::Import(index) }.into(), + NodeGraphMessage::RemoveImportExport { + index: NetworkConnectorKey::Import(index), + } + .into(), ]), } } @@ -851,7 +841,10 @@ mod editor_commands { Message::Batched { messages: Box::new([ DocumentMessage::AddTransaction.into(), - NodeGraphMessage::RemoveImportExport { index: ImportOrExport::Export(index) }.into(), + NodeGraphMessage::RemoveImportExport { + index: NetworkConnectorKey::Export(index), + } + .into(), ]), } } @@ -899,7 +892,10 @@ mod editor_commands { Message::Batched { messages: Box::new([ DocumentMessage::AddTransaction.into(), - NodeGraphMessage::DisconnectImportExport { index: ImportOrExport::Import(index) }.into(), + NodeGraphMessage::DisconnectImportExport { + index: NetworkConnectorKey::Import(index), + } + .into(), ]), } } @@ -909,7 +905,10 @@ mod editor_commands { Message::Batched { messages: Box::new([ DocumentMessage::AddTransaction.into(), - NodeGraphMessage::DisconnectImportExport { index: ImportOrExport::Export(index) }.into(), + NodeGraphMessage::DisconnectImportExport { + index: NetworkConnectorKey::Export(index), + } + .into(), ]), } }