diff --git a/editor/src/messages/clipboard/clipboard_message_handler.rs b/editor/src/messages/clipboard/clipboard_message_handler.rs index bef1099778..e80e480228 100644 --- a/editor/src/messages/clipboard/clipboard_message_handler.rs +++ b/editor/src/messages/clipboard/clipboard_message_handler.rs @@ -665,6 +665,18 @@ mod test { assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}"); } + #[cfg_attr(miri, ignore)] + #[tokio::test] + async fn copied_svg_leaves_out_the_layers_that_are_not_copied() { + let mut editor = create_editor_with_three_layers().await; + let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node(); + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await; + + let clipboard = copy_layers_to_clipboard(&mut editor).await; + let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG"); + assert_eq!(svg.matches("> for Portfolio artboard_name, artboard_count, }; - let result = self.executor.submit_document_export(document, document_id, export_config); + let result = self.executor.submit_document_export(document, export_config); if let Err(description) = result { responses.add(DialogMessage::DisplayDialogError { @@ -1124,18 +1124,14 @@ impl MessageHandler> for Portfolio } } PortfolioMessage::SubmitClipboardSvg { id } => { - let layers = self.active_document().map(|document| { - let selected = document.partition_selection().layers; - let mut layers = document - .metadata() - .all_layers() - .filter(|layer| selected.contains(layer)) - .map(|layer| layer.to_node()) - .collect::>(); - layers.reverse(); - layers - }); - responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default())); + let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else { + responses.add(ClipboardMessage::Rendered { id, svg: None }); + return; + }; + let selected = document.partition_selection().layers; + let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::>(); + layers.reverse(); + responses.add(self.executor.submit_clipboard_svg(document, id, &layers)); } PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => { self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open; diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 34c8720baf..988dee3d63 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -1,23 +1,28 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::node_graph::utility_types::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::network_interface::{InputConnector, NodeNetworkInterface}; +use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode}; use crate::messages::prelude::*; use glam::{DAffine2, DVec2, UVec2}; +use graph_craft::application_io::resource::ResourceRegistry; 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 graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::color::SRGBA8; use graphene_std::list::{Item, List}; +use graphene_std::math::quad::Quad; use graphene_std::raster::{CPU, Raster}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::transform::Footprint; use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes}; -use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter}; +use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter}; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; +use interpreted_executor::layer_paths::{layer_content, write_layer_paths}; use std::any::Any; use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender}; @@ -97,7 +102,8 @@ impl std::fmt::Display for EvaluationErrors { #[derive(serde::Serialize, serde::Deserialize)] pub struct CompilationResponse { - result: Result, + result: Result<(), String>, + resolved_types: ResolvedDocumentNodeTypesDelta, node_graph_errors: GraphErrors, node_graph_warnings: GraphErrors, } @@ -112,19 +118,24 @@ pub enum NodeGraphUpdate { }, /// The latest result of each observation, sent outside an execution after one of them changed. Observations(HashMap), - ClipboardSvg { + Export { id: u64, - svg: Option, + result: Box, }, } #[derive(Debug)] pub struct NodeGraphExecutor { sender: Sender, + receiver: Receiver, current_execution_id: u64, futures: VecDeque<(u64, ExecutionContext)>, pending: Option<(u64, ExecutionContext)>, + + current_export_id: u64, + exports: HashMap, + node_graph_hash: u64, /// The document whose network the graph runtime was last sent. node_graph_document: Option, @@ -146,9 +157,14 @@ pub struct NodeGraphExecutor { gradient_migration_attempted: HashSet, } +#[derive(Debug)] +enum ExportTarget { + File(ExportConfig), + Clipboard(u64), +} + #[derive(Debug, Clone)] struct ExecutionContext { - export_config: Option, document_id: DocumentId, /// The view the render was asked for, which the footprints it reports back are measured in. document_to_viewport: DAffine2, @@ -183,6 +199,8 @@ impl NodeGraphExecutor { futures: Default::default(), pending: None, current_execution_id: 0, + current_export_id: 0, + exports: HashMap::new(), node_graph_hash: 0, node_graph_document: None, previous_node_to_inspect: Vec::new(), @@ -211,6 +229,21 @@ impl NodeGraphExecutor { execution_id } + fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> { + let id = self.current_export_id; + self.current_export_id += 1; + let request = GraphRuntimeRequest::Export { + id, + render_config, + network, + resources, + }; + self.sender.send(request).map_err(|e| e.to_string())?; + self.exports.insert(id, target); + + Ok(()) + } + pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) { if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) { log::error!("Failed to send the overlays: {error}"); @@ -229,13 +262,29 @@ impl NodeGraphExecutor { .expect("Failed to send the context overrides"); } - pub fn submit_clipboard_svg(&self, document_id: Option, id: u64, layers: Vec) -> Message { - if document_id.is_none() || self.node_graph_document != document_id { - return ClipboardMessage::Rendered { id, svg: None }.into(); - } + pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message { + let no_svg = ClipboardMessage::Rendered { id, svg: None }.into(); + let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else { + return no_svg; + }; - self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request"); - Message::NoOp + let viewport = Footprint { + resolution: (max - min).round().as_uvec2(), + transform: DAffine2::from_translation(-min), + ..Default::default() + }; + let render_config = RenderConfig { + viewport, + scale: 1., + export_format: ExportFormat::Svg, + for_export: true, + ..Default::default() + }; + + match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) { + Ok(()) => Message::NoOp, + Err(_) => no_svg, + } } pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) { @@ -260,9 +309,11 @@ impl NodeGraphExecutor { let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash()); if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash { - let network = document.network_interface.document_network().clone(); + let mut network = document.network_interface.document_network().clone(); let previewed = document.network_interface.previewed_nodes(); let layers = document.network_interface.layer_paths(); + prepare_network(&mut network, &previewed, &layers); + let thumbnails = thumbnail_sources(&network, &layers); self.node_graph_hash = graph_hash; self.node_graph_document = Some(document_id); @@ -272,8 +323,7 @@ impl NodeGraphExecutor { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, - previewed, - layers, + thumbnails, observations: self.observations(&document.network_interface), })) .map_err(|e| e.to_string())?; @@ -337,7 +387,6 @@ impl NodeGraphExecutor { self.futures.push_back(( execution_id, ExecutionContext { - export_config: None, document_id, document_to_viewport: viewport.transform, measure_fill: None, @@ -404,7 +453,6 @@ impl NodeGraphExecutor { self.futures.push_back(( execution_id, ExecutionContext { - export_config: None, document_id, document_to_viewport: viewport.transform, measure_fill: None, @@ -415,10 +463,9 @@ impl NodeGraphExecutor { } /// Evaluates a node graph for export - pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> { - let network = document.network_interface.document_network().clone(); - let previewed = document.network_interface.previewed_nodes(); - let resources = document.resources.registry.clone(); + pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> { + let mut network = document.network_interface.document_network().clone(); + prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths()); let export_format = if export_config.file_type == FileType::Svg { graphene_std::application_io::ExportFormat::Svg @@ -452,34 +499,12 @@ impl NodeGraphExecutor { time: Default::default(), pointer: DVec2::ZERO, export_format, - // The viewport's render mode is only a way of viewing the artwork, which exports show as it is render_mode: graphene_std::vector::style::RenderMode::Normal, for_export: true, for_eyedropper: false, }; - // Execute the node graph - self.sender - .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { - network, - resources, - previewed, - layers: document.network_interface.layer_paths(), - observations: self.observations(&document.network_interface), - })) - .map_err(|e| e.to_string())?; - let execution_id = self.queue_execution(render_config); - self.futures.push_back(( - execution_id, - ExecutionContext { - export_config: Some(export_config), - document_id, - document_to_viewport: viewport.transform, - measure_fill: None, - }, - )); - - Ok(()) + self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config)) } /// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile. @@ -491,8 +516,8 @@ impl NodeGraphExecutor { } let mut all_dropped_thumbnails = Vec::new(); - let mut results = self.receiver.try_iter().collect::>().into_iter(); - for response in results.by_ref() { + let results = self.receiver.try_iter().collect::>(); + for response in results { match response { NodeGraphUpdate::ExecutionResponse(execution_response) => { let ExecutionResponse { @@ -516,7 +541,7 @@ impl NodeGraphExecutor { let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) { let (_, execution_context) = self.futures.pop_front().expect("the front was just checked"); - if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { + if execution_context.measure_fill.is_none() { self.pending = Some((execution_id, execution_context.clone())); } execution_context @@ -571,7 +596,7 @@ impl NodeGraphExecutor { responses.add(OverlaysMessage::Draw); // A pending graph keeps the last frame, and the errors shown with it - if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) { + if !matches!(result, ExecutionResult::Pending) { let errors = match &result { ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => { let in_document = |path: &&[NodeId]| { @@ -644,11 +669,8 @@ impl NodeGraphExecutor { log::error!("Node graph evaluation failed:\n{message}"); } - if execution_context.export_config.is_some() { - responses.add(export_failure_dialog(message)); - } responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); - break; + continue; } }; @@ -666,10 +688,8 @@ impl NodeGraphExecutor { } document.network_interface.update_vector_modify(path_contents(&observations)); - match (node_graph_output, execution_context.export_config) { - (Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), - (Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses), - (None, _) => {} + if let Some(node_graph_output) = node_graph_output { + self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses); } responses.add(DeferMessage::TriggerGraphRun { execution_id, @@ -691,49 +711,42 @@ impl NodeGraphExecutor { node_graph_errors, node_graph_warnings, result, + resolved_types, } = execution_response; // TODO: Eventually remove this document upgrade code // The migration's temporary redirected-export compilations must not push types or a graph view to the frontend if self.gradient_migration.is_some() { - if let Err((_, e)) = &result { + if let Err(e) = &result { log::trace!("Gradient migration measurement compile: {e}"); } continue; } - let type_delta = match result { - Err((incomplete_delta, e)) => { - // Clear the click targets while the graph is in an un-renderable state + if let Err(e) = &result { + // Clear the click targets while the graph is in an un-renderable state - document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); - document.network_interface.update_outlines(HashMap::new()); - document.network_interface.update_vector_modify(HashMap::new()); + document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); + document.network_interface.update_outlines(HashMap::new()); + document.network_interface.update_vector_modify(HashMap::new()); - // The graph only shows errors tied to nodes, so the console gets the others - if node_graph_errors.is_empty() { - log::error!("The node graph failed to compile:\n{e}"); - } else { - log::trace!("{e}"); - } - - responses.add(NodeGraphMessage::UpdateTypes { - resolved_types: incomplete_delta, - node_graph_errors, - node_graph_warnings, - }); - - responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); - break; + // The graph only shows errors tied to nodes, so the console gets the others + if node_graph_errors.is_empty() { + log::error!("The node graph failed to compile:\n{e}"); + } else { + log::trace!("{e}"); } - Ok(result) => result, - }; + } responses.add(NodeGraphMessage::UpdateTypes { - resolved_types: type_delta, + resolved_types, node_graph_errors, node_graph_warnings, }); + + if result.is_err() { + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + } } NodeGraphUpdate::EyedropperPreview(raster) => { let (data, width, height) = raster.to_flat_u8(); @@ -756,33 +769,7 @@ impl NodeGraphExecutor { Self::receive_thumbnails(document, thumbnails, responses); } } - NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }), - } - } - - // An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails - for response in results { - match response { - NodeGraphUpdate::ExecutionResponse(execution_response) => { - let execution_context = self.execution_context(execution_response.execution_id); - - if execution_context.is_some_and(|context| context.document_id == document_id) { - document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses); - } - if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) { - responses.add(export_failure_dialog(None)); - } - - all_dropped_thumbnails.extend(execution_response.dropped_thumbnails); - } - NodeGraphUpdate::Thumbnails { - responses: thumbnails, - document_id: thumbnails_document, - } if thumbnails_document == document_id => { - Self::receive_thumbnails(document, thumbnails, responses); - } - NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }), - _ => {} + NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses), } } @@ -798,15 +785,6 @@ impl NodeGraphExecutor { } } - /// What an execution was submitted for, while it's still queued or pending. - fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> { - self.futures - .iter() - .chain(&self.pending) - .find(|(queued_execution_id, _)| *queued_execution_id == execution_id) - .map(|(_, execution_context)| execution_context) - } - // TODO: Eventually remove this document upgrade code /// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running. /// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still @@ -876,6 +854,10 @@ impl NodeGraphExecutor { return; } + let layers = document.network_interface.layer_paths(); + prepare_network(&mut network, &[], &layers); + let thumbnails = thumbnail_sources(&network, &layers); + let resources = document.resources.registry.clone(); let fill_measurement = Observation { node_path: full_path, @@ -887,8 +869,7 @@ impl NodeGraphExecutor { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, - previewed: Vec::new(), - layers: document.network_interface.layer_paths(), + thumbnails, observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]), })) .is_err() @@ -920,7 +901,6 @@ impl NodeGraphExecutor { self.futures.push_back(( execution_id, ExecutionContext { - export_config: None, document_id, document_to_viewport: viewport.transform, measure_fill: Some((network_path, fill_node_id, gradient)), @@ -1080,6 +1060,51 @@ impl NodeGraphExecutor { responses.add(FrontendMessage::UpdateRenderStatus { status: render_status }); } + fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque) { + let Some(target) = self.exports.remove(&export_id) else { return }; + + let failure = match (result, &target) { + (ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => { + return match target { + ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses), + ExportTarget::Clipboard(id) => { + let svg = match value { + TaggedValue::RenderOutput(RenderOutput { + data: RenderOutputType::Svg { svg, .. }, + .. + }) => Some(svg), + _ => None, + }; + responses.add(ClipboardMessage::Rendered { id, svg }); + } + }; + } + (ExecutionResult::Error(errors), _) => Some(errors.to_string()), + (ExecutionResult::Panic(payload), _) => { + let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::().map(String::as_str)); + Some(format!("Panicked: {}", message.unwrap_or("no message"))) + } + (ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None, + }; + if let Some(message) = &failure { + log::error!("Node graph evaluation failed:\n{message}"); + } + + match target { + ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError { + title: "Unable to export document".to_string(), + description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()), + }), + ExportTarget::Clipboard(id) => { + responses.add(ClipboardMessage::Rendered { id, svg: None }); + if let Some(description) = failure { + let title = "Unable to copy as SVG".to_string(); + responses.add(DialogMessage::DisplayDialogError { title, description }); + } + } + } + } + fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque) { let ExportConfig { file_type, @@ -1179,6 +1204,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node } } +fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec, RootNode)], layers: &[Vec]) { + apply_previews(network, previewed); + write_layer_paths(network, layers); +} + +/// Replaces each network's primary export with its previewed node. +pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec, RootNode)]) { + for (network_path, previewed) in previewed { + let Some(nested) = network.nested_network_mut(network_path) else { continue }; + let Some(export) = nested.exports.first_mut() else { continue }; + *export = NodeInput::node(previewed.node_id, previewed.output_index); + } +} + +/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it. +fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec]) -> Vec<(NodeId, Vec)> { + // O(layers * depth) + let source = |layer: &Vec| Some((*layer.last()?, layer_content(layer, network)?.source(network)?)); + + layers.iter().filter_map(source).collect() +} + +fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> { + let metadata = interface.document_metadata(); + let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]); + let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() { + 0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic), + artboards if artboards == layers.len() => list!(Artboard), + _ => return None, + }; + + let mut network = interface.document_network().clone(); + prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths()); + let mut below = NodeInput::type_default(stack, true); + let mut bounds = None; + for &layer in layers { + let mut node = network.nodes.get(&layer.to_node())?.clone(); + *node.inputs.first_mut()? = below; + let copy = NodeId::new(); + network.nodes.insert(copy, node); + below = NodeInput::node(copy, 0); + + let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) { + true => metadata.downstream_transform_to_document(layer).inverse(), + false => DAffine2::IDENTITY, + }; + let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer); + let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box()); + bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds); + } + network.exports = vec![below]; + + Some((network, bounds?)) +} + // TODO: Eventually remove this document upgrade code /// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform. fn measure_fill_geometry(data: &Arc) -> Option<(DAffine2, DAffine2)> { @@ -1200,14 +1280,6 @@ fn measure_fill_geometry(data: &Arc) -> Option<(DAffine2, None } -/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile. -fn export_failure_dialog(evaluation_error: Option) -> DialogMessage { - DialogMessage::DisplayDialogError { - title: "Unable to export document".to_string(), - description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()), - } -} - fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator { let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER)); @@ -1273,14 +1345,17 @@ mod test { network.inline_definitions().map_err(|error| error.to_string())?; let instrumented = Instrumented::new(&network); + let layers = document.network_interface.layer_paths(); + prepare_network(&mut network, &[], &layers); + let thumbnails = thumbnail_sources(&network, &layers); + let resources = document.resources.registry.clone(); self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, - previewed: Vec::new(), - layers: document.network_interface.layer_paths(), + thumbnails, observations: self.observations(&document.network_interface), })) .map_err(|e| e.to_string())?; diff --git a/editor/src/node_graph_executor/recompile_tests.rs b/editor/src/node_graph_executor/recompile_tests.rs index c395f3b7bf..faaf1f31ea 100644 --- a/editor/src/node_graph_executor/recompile_tests.rs +++ b/editor/src/node_graph_executor/recompile_tests.rs @@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) { editor.dispatch(Message::Wake); } -/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops -/// for one more update, so a first update clears those of the graph before it. +/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network +/// an update replaces for one more update, so a first update clears the nodes of the graph before it. async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet { compile_and_run(editor).await; compile_and_run(editor).await; diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index ff91d41604..46251c59c5 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -1,7 +1,6 @@ use super::*; use crate::messages::frontend::utility_types::{ExportBounds, FileType}; use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers}; -use crate::messages::portfolio::document::utility_types::network_interface::RootNode; use crate::task::{Spawn, Spawner, Task}; use graph_craft::application_io::resource::ResourceRegistry; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; @@ -18,8 +17,7 @@ use graphene_std::raster_types::Raster; use graphene_std::runtime::AsyncRuntime; use graphene_std::vector::style::RenderMode; use graphene_std::{Context, NodeError, Poll}; -use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta}; -use interpreted_executor::layer_paths::write_layer_paths; +use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle}; use interpreted_executor::util::wrap_network_with_render_node_in_scope; use observer::Observer; pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue}; @@ -43,25 +41,34 @@ pub struct NodeRuntime { pub(super) executor: DynamicExecutor, #[cfg(not(test))] executor: DynamicExecutor, - output: OutputHandle, + receiver: Receiver, sender: Sender, + editor_wake: Wake, dirty: Arc, + + output: Option, + previous: Option, + pending: Option, - pending_export: Option, pending_eyedropper: Option, pending_thumbnails: Option, + + viewport_artwork: Option, + + exports: Vec<(u64, RenderConfig, OutputHandle)>, + /// The network the executor last compiled successfully, with previews applied. old_graph: Option, - /// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place. - compile_failed: bool, - async_runtime: Option, + async_runtime: Option, editor_api: Arc, resources: ResourceRegistry, + node_graph_errors: GraphErrors, node_graph_warnings: GraphErrors, + thumbnails: Thumbnails, observer: Observer, /// Whether an observation changed since its results were last sent. @@ -69,13 +76,9 @@ pub struct NodeRuntime { preprocessor: preprocessor::Preprocessor, - /// Cached surface for Wasm viewport rendering (reused across frames) - #[cfg(all(target_family = "wasm", feature = "wasm"))] - wasm_canvas_cache: CanvasSurfaceHandle, - /// The viewport's latest artwork. - viewport_artwork: Option, /// The layers from the render of the viewport's latest artwork. rendered_layers: RenderedLayers, + /// The latest overlays, rendered again over each new artwork. overlays: Option, /// Whether the overlays or the artwork changed since the overlays were last rendered. @@ -83,6 +86,10 @@ pub struct NodeRuntime { overlays_canvas: VelloCanvas, /// The latest rendered overlays. overlays_texture: Option, + + /// Cached surface for Wasm viewport rendering (reused across frames) + #[cfg(all(target_family = "wasm", feature = "wasm"))] + wasm_canvas_cache: CanvasSurfaceHandle, } /// What the viewport shows beneath its overlays. @@ -98,43 +105,32 @@ enum ViewportArtwork { pub enum GraphRuntimeRequest { GraphUpdate(GraphUpdate), ExecutionRequest(ExecutionRequest), + Export { + id: u64, + render_config: RenderConfig, + network: NodeNetwork, + resources: ResourceRegistry, + }, ThumbnailsInView { layers: HashSet, document_id: DocumentId, }, - /// Starts, changes, or with `None` stops one observation without a graph update. + RenderOverlays(OverlayContext), Observe { key: ObservationKey, observation: Option, }, - ClipboardSvg { - id: u64, - layers: Vec, - }, - RenderOverlays(OverlayContext), } #[derive(Debug)] pub struct GraphUpdate { pub(super) network: NodeNetwork, pub(super) resources: ResourceRegistry, - /// The node each network renders in place of its export, paired with that network's path. - pub(super) previewed: Vec<(Vec, RootNode)>, - /// Full path from the root network to every layer, which are the nodes with thumbnails. - pub(super) layers: Vec>, + pub(super) thumbnails: Vec<(NodeId, Vec)>, /// The connectors whose values are sent back after each evaluation, replacing those observed before. pub(super) observations: HashMap, } -/// Replaces each network's primary export with its previewed node. -pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec, RootNode)]) { - for (network_path, previewed) in previewed { - let Some(nested) = network.nested_network_mut(network_path) else { continue }; - let Some(export) = nested.exports.first_mut() else { continue }; - *export = NodeInput::node(previewed.node_id, previewed.output_index); - } -} - #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ExportConfig { pub name: String, @@ -149,20 +145,27 @@ impl NodeRuntime { pub fn new(receiver: Receiver, sender: Sender, editor_wake: Wake) -> Self { Self { executor: DynamicExecutor::default(), - output: OutputHandle::default(), + receiver, sender, + editor_wake, dirty: Default::default(), + + output: None, + previous: None, + pending: None, - pending_export: None, pending_eyedropper: None, pending_thumbnails: None, - old_graph: None, - compile_failed: false, - resources: ResourceRegistry::default(), - async_runtime: None, + viewport_artwork: None, + + exports: Vec::new(), + + old_graph: None, + + async_runtime: None, editor_api: PlatformEditorApi { #[cfg(not(test))] application_io: None, @@ -171,61 +174,93 @@ impl NodeRuntime { application_io: Some(PlatformApplicationIo::default().into()), } .into(), + resources: ResourceRegistry::default(), node_graph_errors: Vec::new(), node_graph_warnings: Vec::new(), + thumbnails: Thumbnails::new(), observer: Observer::default(), observations_changed: false, preprocessor: preprocessor::Preprocessor::new(), - #[cfg(all(target_family = "wasm", feature = "wasm"))] - wasm_canvas_cache: CanvasSurfaceHandle::new(), - viewport_artwork: None, rendered_layers: RenderedLayers::default(), + overlays: None, overlays_stale: false, overlays_canvas: VelloCanvas::default(), overlays_texture: None, + + #[cfg(all(target_family = "wasm", feature = "wasm"))] + wasm_canvas_cache: CanvasSurfaceHandle::new(), } } pub fn update(&mut self) { - if self.pending_export.is_some() { - return; - } - - let mut graph = None; - for request in self.receiver.try_iter() { + while let Ok(request) = self.receiver.try_recv() { match request { - GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update), - GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request), - GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => { - self.pending_export = Some(request); - self.dirty.store(true, Ordering::Release); - break; + GraphRuntimeRequest::GraphUpdate(GraphUpdate { + network, + resources, + thumbnails, + observations, + }) => { + self.observer.replace_all(observations); + self.resources = resources; + + self.node_graph_errors.clear(); + self.node_graph_warnings.clear(); + let result = self.update_network(network.clone()); + if result.is_ok() { + self.thumbnails.update_sources(&thumbnails, &self.executor); + self.old_graph = Some(network); + } + + let node_graph_errors = self.node_graph_errors.clone(); + let node_graph_warnings = self.node_graph_warnings.clone(); + let resolved_types = self.executor.take_type_deltas().unwrap_or_default(); + + self.sender + .send(NodeGraphUpdate::CompilationResponse(CompilationResponse { + result, + resolved_types, + node_graph_errors, + node_graph_warnings, + })) + .expect("Failed to send response"); } + GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request), GraphRuntimeRequest::ExecutionRequest(request) => { self.pending = Some(request); self.dirty.store(true, Ordering::Release); } + GraphRuntimeRequest::Export { + id, + render_config, + network, + resources, + } => { + let mut scoped_network = wrap_network_with_render_node_in_scope(network, self.editor_api.clone(), self.async_runtime().handle()); + let preprocessed = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)).ok(); + let compiled = preprocessed.and_then(|_| Compiler {}.compile_single(scoped_network).ok()); + let inserted = compiled.and_then(|compiled| self.executor.insert(compiled.network).ok()); + self.async_runtime().update_sources(self.executor.sources()); + match inserted { + Some(output) => { + self.exports.push((id, render_config, output)); + self.dirty.store(true, Ordering::Release); + } + None => self.send_export(id, ExecutionResult::Uncompiled), + } + } GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => { self.thumbnails.set_in_view(layers); self.pending_thumbnails = Some(document_id); } - // A graph update applied after this loop would otherwise replace this with what it observed before - GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) { - (Some(update), Some(observation)) => _ = update.observations.insert(key, observation), - (Some(update), None) => _ = update.observations.remove(&key), - (None, observation) => { - self.observer.set(key, observation); - self.observations_changed = true; - } - }, - GraphRuntimeRequest::ClipboardSvg { id, layers } => { - let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor)); - self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response"); + GraphRuntimeRequest::Observe { key, observation } => { + self.observer.set(key, observation); + self.observations_changed = true; } GraphRuntimeRequest::RenderOverlays(context) => { self.overlays = Some(context); @@ -233,82 +268,47 @@ impl NodeRuntime { } } } - - let Some(GraphUpdate { - mut network, - resources, - previewed, - layers, - observations, - }) = graph - else { - return; - }; - - apply_previews(&mut network, &previewed); - write_layer_paths(&mut network, &layers); - self.observer.replace_all(observations); - self.resources = resources; - - self.node_graph_errors.clear(); - self.node_graph_warnings.clear(); - let result = self.update_network(network.clone()); - self.compile_failed = result.is_err(); - if result.is_ok() { - self.thumbnails.update_sources(&layers, &network, &self.executor); - self.old_graph = Some(network); - } - let node_graph_errors = self.node_graph_errors.clone(); - let node_graph_warnings = self.node_graph_warnings.clone(); - - self.sender - .send(NodeGraphUpdate::CompilationResponse(CompilationResponse { - result, - node_graph_errors, - node_graph_warnings, - })) - .expect("Failed to send response"); } pub async fn run(&mut self) -> Option { let dirty = self.dirty.swap(false, Ordering::Acquire); let mut texture = None; - if let Some(export) = self.pending_export { - if dirty { - self.run_export(export).await; + if dirty { + for (id, render_config, output) in std::mem::take(&mut self.exports) { + self.run_export(id, render_config, output).await; } - } else { - let viewport = if dirty { self.pending } else { None }; + } - if let Some(document_id) = self.pending_thumbnails.take() - && viewport.is_none() - && !self.compile_failed - { - let mut responses = VecDeque::new(); - self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await; - if !responses.is_empty() { - self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response"); - } - } + let viewport = if dirty { self.pending } else { None }; - if std::mem::take(&mut self.observations_changed) && viewport.is_none() { - let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); - self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response"); + if let Some(document_id) = self.pending_thumbnails.take() + && viewport.is_none() + && self.output.is_some() + { + let mut responses = VecDeque::new(); + self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await; + if !responses.is_empty() { + self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response"); } + } - if let Some(eyedropper) = self.pending_eyedropper.take() { - self.run_eyedropper(eyedropper).await; - } + if std::mem::take(&mut self.observations_changed) && viewport.is_none() { + let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); + self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response"); + } - if let Some(viewport) = viewport { - self.run_viewport(viewport).await; - } + if let Some(eyedropper) = self.pending_eyedropper.take() { + self.run_eyedropper(eyedropper).await; + } - // Overlays that changed without new artwork are drawn over the artwork already shown - if self.overlays_stale { - texture = self.composite_viewport_frame(); - } + if let Some(viewport) = viewport { + 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(); } (self.editor_wake)(); @@ -318,7 +318,11 @@ impl NodeRuntime { async fn run_viewport(&mut self, request: ExecutionRequest) { self.thumbnails.set_scale(request.render_config.scale); - let Some(mut result) = self.evaluate(request) else { return }; + let result = match self.output.clone() { + Some(output) => self.evaluate(&output, request), + None => Some(ExecutionResult::Uncompiled), + }; + let Some(mut result) = result else { return }; let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); if let Some(RenderOutput { data, metadata }) = result.render_output() { @@ -378,24 +382,20 @@ impl NodeRuntime { Some(frame) } - async fn run_export(&mut self, request: ExecutionRequest) { - let result = self.evaluate(request); - if matches!(result, Some(ExecutionResult::Pending)) { + async fn run_export(&mut self, id: u64, render_config: RenderConfig, output: OutputHandle) { + let mut result = self.execute(&output, render_config); + if matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) { + self.exports.push((id, render_config, output)); return; } - self.pending_export = None; - let Some(mut result) = result else { return }; - self.dirty.store(true, Ordering::Release); - if let Some(RenderOutput { data, .. }) = result.render_output() && let RenderOutputType::Texture(texture) = data { let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8(); *data = RenderOutputType::Buffer { data: buffer, width, height }; } - let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); - self.respond(request, result, observations).await; + self.send_export(id, result); } async fn run_eyedropper(&mut self, mut request: ExecutionRequest) { @@ -405,7 +405,8 @@ impl NodeRuntime { request.render_config.pointer = viewport.render_config.pointer; } - if let Some(mut result) = self.evaluate(request) + if let Some(output) = self.output.clone() + && let Some(mut result) = self.evaluate(&output, request) && let Some(RenderOutput { data: RenderOutputType::Texture(texture), .. @@ -416,11 +417,7 @@ impl NodeRuntime { } } - fn evaluate(&mut self, request: ExecutionRequest) -> Option { - if self.compile_failed { - return Some(ExecutionResult::Uncompiled); - } - + fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option { let ExecutionRequest { execution_id, mut render_config } = request; // Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active @@ -428,40 +425,53 @@ impl NodeRuntime { render_config.export_format = ExportFormat::Svg; } + match self.execute(output, render_config) { + ExecutionResult::Panic(payload) => { + self.send_result(execution_id, ExecutionResult::Panic(payload)); + None + } + result => Some(result), + } + } + + fn execute(&mut self, output: &OutputHandle, render_config: RenderConfig) -> ExecutionResult { let context = render_config.into_context_with_generations(self.async_runtime().snapshot()); - let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(output, context))) { Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, - Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending, Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value), Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value), Ok(Ok(Poll::Fallback(boxed))) => { let (value, error) = *boxed; - ExecutionResult::Fallback(value, self.resolve_errors(&error)) + ExecutionResult::Fallback(value, self.resolve_errors(output, &error)) } - Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)), + Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(output, &error)), Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))), - Err(payload) => { - let response = ExecutionResponse { - execution_id, - result: ExecutionResult::Panic(payload), - responses: VecDeque::new(), - dropped_thumbnails: Vec::new(), - observations: HashMap::new(), - #[cfg(all(target_family = "wasm", feature = "wasm"))] - viewport_canvas_info: None, - }; - self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); - return None; - } + Err(payload) => ExecutionResult::Panic(payload), + } + } + + fn send_result(&self, execution_id: u64, result: ExecutionResult) { + let response = ExecutionResponse { + execution_id, + result, + responses: VecDeque::new(), + dropped_thumbnails: Vec::new(), + observations: HashMap::new(), + #[cfg(all(target_family = "wasm", feature = "wasm"))] + viewport_canvas_info: None, }; - Some(result) + self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); + } + + fn send_export(&self, id: u64, result: ExecutionResult) { + self.sender.send(NodeGraphUpdate::Export { id, result: Box::new(result) }).expect("Failed to send response"); } async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap) { let mut responses = VecDeque::new(); // While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did - let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await }; + let dropped_thumbnails = if self.output.is_none() { Vec::new() } else { self.update_thumbnails(&mut responses).await }; #[cfg(all(target_family = "wasm", feature = "wasm"))] let mut result = result; @@ -506,11 +516,15 @@ impl NodeRuntime { Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await } - fn update_network(&mut self, graph: NodeNetwork) -> Result { + fn update_network(&mut self, graph: NodeNetwork) -> Result<(), String> { + if let Some(output) = self.output.take() { + self.previous = Some(output); + } + let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle()); if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { - return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string())); + return Err(e.to_string()); } // We assume only one output @@ -522,26 +536,25 @@ impl NodeRuntime { Err(CompileError::Graph(errors)) => { let message = format!("{errors:?}"); self.node_graph_errors = errors; - return Err((ResolvedDocumentNodeTypesDelta::default(), message)); + return Err(message); } - Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)), + Err(CompileError::Message(message)) => return Err(message), }; self.node_graph_warnings = warnings; assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); - let updated = self.executor.update(proto_network).map(|(output, types)| { - self.output = output; - types + let updated = self.executor.insert(proto_network).map(|output| { + self.output = Some(output); }); - let result = updated.map_err(|(types, e)| { + let result = updated.map_err(|e| { self.node_graph_errors.clone_from(&e); - (types, format!("{e:?}")) + format!("{e:?}") }); self.async_runtime().update_sources(self.executor.sources()); result } - fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors { + fn resolve_errors(&self, output: &OutputHandle, error: &NodeError) -> EvaluationErrors { let source_map = self.executor.tree().source_map(); let paths = |node: NodeId| -> NodePaths { let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect(); @@ -549,7 +562,7 @@ impl NodeRuntime { paths.into() }; let mut errors = Vec::new(); - let output = self.output.node(); + let output = output.node(); let mut pending = vec![(vec![paths(output)], output, error)]; while let Some((mut trace, node, error)) = pending.pop() { let passed = self.executor.trace_error(node, error); @@ -673,7 +686,7 @@ mod tests { .unwrap(); } - /// Sends a network update and a request to export it, as the editor does for an export. + /// Sends a request to export the document, as the editor does for an export. fn send_export(editor: &mut EditorTestUtils, file_type: FileType) { let portfolio = editor.portfolio_message_handler_mut(); let document_id = portfolio.active_document_id.unwrap(); @@ -686,7 +699,7 @@ mod tests { bounds: ExportBounds::AllArtwork, ..Default::default() }; - executor.submit_document_export(document, document_id, export_config).unwrap(); + executor.submit_document_export(document, export_config).unwrap(); } /// Whether the runtime evaluated the graph since this was last called. @@ -744,11 +757,60 @@ mod tests { }); } + fn send_request(editor: &mut EditorTestUtils) { + let portfolio = editor.portfolio_message_handler_mut(); + let document_id = portfolio.active_document_id.unwrap(); + 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) + .unwrap(); + } + + async fn run(editor: &mut EditorTestUtils) -> Option { + editor.runtime.update(); + editor.runtime.run().await + } + /// 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) } + fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec { + let response = ExecutionResponse { + execution_id: last_request(editor).unwrap(), + result, + responses: VecDeque::new(), + dropped_thumbnails: Vec::new(), + observations: HashMap::new(), + }; + editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).unwrap(); + editor.dispatch(Message::Wake) + } + + fn failed(messages: &[FrontendMessage]) -> bool { + messages.iter().any(|message| matches!(message, FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error })) + } + + fn drawn_in(messages: &[FrontendMessage]) -> Option<&str> { + messages.iter().find_map(|message| match message { + FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg.as_str()), + _ => None, + }) + } + + fn empty_svg() -> RenderOutputType { + RenderOutputType::Svg { + svg: String::new(), + image_data: Vec::new(), + } + } + + fn rendered(data: RenderOutputType) -> TaggedValue { + TaggedValue::RenderOutput(RenderOutput { data, metadata: Default::default() }) + } + #[tokio::test] async fn only_update_reads_the_channel() { let mut editor = editor().await; @@ -1032,28 +1094,167 @@ mod tests { assert!(shows_dialog, "the export should show why it saved nothing"); } - #[tokio::test] - async fn an_export_goes_ahead_of_what_was_sent_after_it() { - let mut editor = editor().await; - let last = last_request(&editor); - send_export(&mut editor, FileType::Svg); - send_update(&mut editor); + fn rectangle_node(editor: &EditorTestUtils) -> NodeId { + use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; + use graphene_std::vector::generator_nodes::rectangle; - editor.runtime.update(); - assert!(editor.runtime.pending_export.is_some()); - assert_eq!(last_request(&editor), last, "the request sent after the export was read ahead of it"); + let interface = &editor.active_document().network_interface; + let nodes = interface.document_network().nodes.keys().copied(); + let reference = Some(DefinitionIdentifier::ProtoNode(rectangle::IDENTIFIER)); + nodes.into_iter().find(|node_id| interface.reference(node_id, &[]) == reference).unwrap() + } - editor.runtime.run().await; - assert!(exported(&mut editor)); + fn set_layer_visible(editor: &mut EditorTestUtils, visible: bool) { + let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node(); + editor.active_document_mut().network_interface.set_visibility(&layer, &[], visible); + } - editor.runtime.update(); - assert_ne!(last_request(&editor), last); - editor.runtime.run().await; - assert!(evaluated(&mut editor), "the request sent after the export was lost"); + fn compiled_nodes(editor: &EditorTestUtils) -> HashMap, NodeId> { + let document = &editor.active_document().network_interface.document_network().nodes; + let source_map = editor.runtime.executor.tree().source_map(); + let of_the_document = source_map.iter().filter(|(path, _)| path.first().is_some_and(|node| document.contains_key(node))); + of_the_document.map(|(path, (node, _))| (path.to_vec(), *node)).collect() } #[tokio::test] - async fn a_parked_export_holds_back_everything_sent_after_it() { + async fn an_export_shows_the_network_it_was_sent_with_whatever_was_sent_after_it() { + let mut editor = editor().await; + + set_layer_visible(&mut editor, false); + send_export(&mut editor, FileType::Svg); + set_layer_visible(&mut editor, true); + send_update(&mut editor); + + editor.runtime.update(); + editor.runtime.run().await; + let messages = editor.dispatch(Message::Wake); + let exported = messages.iter().find_map(|message| match message { + FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()), + _ => None, + }); + assert!(exported.is_some_and(|svg| !svg.contains("