diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index 9e1874ef63..2383b6d1de 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -997,7 +997,7 @@ impl MessageHandler> 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 { diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 318e753e98..80d7d78910 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -33,6 +33,12 @@ pub struct ExecutionRequest { render_config: RenderConfig, } +#[derive(Debug, Clone)] +pub struct ExportRequest { + export_id: u64, + render_config: RenderConfig, +} + pub struct ExecutionResponse { execution_id: u64, result: ExecutionResult, @@ -116,15 +122,24 @@ pub enum NodeGraphUpdate { id: u64, svg: Option, }, + Export { + id: u64, + 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, @@ -148,7 +163,6 @@ pub struct NodeGraphExecutor { #[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 +197,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(), @@ -337,7 +353,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 +419,6 @@ impl NodeGraphExecutor { self.futures.push_back(( execution_id, ExecutionContext { - export_config: None, document_id, document_to_viewport: viewport.transform, measure_fill: None, @@ -415,7 +429,7 @@ 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> { + pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, 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(); @@ -468,16 +482,10 @@ impl NodeGraphExecutor { 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, - }, - )); + let export_id = self.current_export_id; + self.current_export_id += 1; + self.sender.send(GraphRuntimeRequest::Export(ExportRequest { export_id, render_config })).map_err(|e| e.to_string())?; + self.exports.insert(export_id, export_config); Ok(()) } @@ -491,8 +499,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 { @@ -506,12 +514,17 @@ impl NodeGraphExecutor { } = *execution_response; all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); - self.futures - .retain(|(queued_execution_id, execution_context)| *queued_execution_id >= execution_id || execution_context.export_config.is_some()); + while let Some(&(queued_execution_id, _)) = self.futures.front() { + if queued_execution_id < execution_id { + self.futures.pop_front(); + } else { + break; + } + } - let execution_context = if let Some(index) = self.futures.iter().position(|&(queued_execution_id, _)| queued_execution_id == execution_id) { - let (_, execution_context) = self.futures.remove(index).expect("the index was just found"); - if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { + 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.measure_fill.is_none() { self.pending = Some((execution_id, execution_context.clone())); } execution_context @@ -566,7 +579,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]| { @@ -631,20 +644,16 @@ impl NodeGraphExecutor { let node_graph_output = match node_graph_output { Ok(output) => output, Err(message) => { - if let Some(message) = &message { - log::error!("Node graph evaluation failed:\n{message}"); - } - if execution_context.export_config.is_some() { - responses.add(export_failure_dialog(message)); - continue; - } - // 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()); + if let Some(message) = &message { + log::error!("Node graph evaluation failed:\n{message}"); + } + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); - break; + continue; } }; @@ -662,10 +671,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, @@ -720,7 +727,7 @@ impl NodeGraphExecutor { }); responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); - break; + continue; } Ok(result) => result, }; @@ -753,34 +760,7 @@ impl NodeGraphExecutor { } } 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)); - } - self.futures - .retain(|(execution_id, execution_context)| *execution_id != execution_response.execution_id || execution_context.export_config.is_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), } } @@ -796,15 +776,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 @@ -918,7 +889,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)), @@ -1078,6 +1048,27 @@ 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(export_config) = self.exports.remove(&export_id) else { return }; + + let failure = match result { + ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => return self.process_export(value, export_config, document, responses), + 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}"); + } + 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()), + }); + } + fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque) { let ExportConfig { file_type, @@ -1198,14 +1189,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)); diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index a058c089b0..825a7ca102 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -54,7 +54,7 @@ pub struct NodeRuntime { previous: Option, pending: Option, - pending_exports: Vec<(ExecutionRequest, OutputHandle)>, + pending_exports: Vec<(ExportRequest, OutputHandle)>, pending_eyedropper: Option, pending_thumbnails: Option, @@ -106,20 +106,11 @@ enum ViewportArtwork { pub enum GraphRuntimeRequest { GraphUpdate(GraphUpdate), ExecutionRequest(ExecutionRequest), - ThumbnailsInView { - layers: HashSet, - document_id: DocumentId, - }, - /// Starts, changes, or with `None` stops one observation without a graph update. - Observe { - key: ObservationKey, - observation: Option, - }, - ClipboardSvg { - id: u64, - layers: Vec, - }, + ThumbnailsInView { layers: HashSet, document_id: DocumentId }, + Export(ExportRequest), + ClipboardSvg { id: u64, layers: Vec }, RenderOverlays(OverlayContext), + Observe { key: ObservationKey, observation: Option }, } #[derive(Debug)] @@ -243,17 +234,17 @@ impl NodeRuntime { .expect("Failed to send response"); } GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request), - GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => match self.output.clone() { - Some(output) => { - self.pending_exports.push((request, output)); - self.dirty.store(true, Ordering::Release); - } - None => self.send_result(request.execution_id, ExecutionResult::Uncompiled), - }, GraphRuntimeRequest::ExecutionRequest(request) => { self.pending = Some(request); self.dirty.store(true, Ordering::Release); } + GraphRuntimeRequest::Export(request) => match self.output.clone() { + Some(output) => { + self.pending_exports.push((request, output)); + self.dirty.store(true, Ordering::Release); + } + None => self.send_export(request.export_id, ExecutionResult::Uncompiled), + }, GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => { self.thumbnails.set_in_view(layers); self.pending_thumbnails = Some(document_id); @@ -386,23 +377,20 @@ impl NodeRuntime { Some(frame) } - async fn run_export(&mut self, request: ExecutionRequest, output: OutputHandle) { - let result = self.evaluate(&output, request); - if matches!(result, Some(ExecutionResult::Pending | ExecutionResult::Partial(_))) { + async fn run_export(&mut self, request: ExportRequest, output: OutputHandle) { + let mut result = self.execute(&output, request.render_config); + if matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) { self.pending_exports.push((request, output)); return; } - let Some(mut result) = result else { return }; - 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(request.export_id, result); } async fn run_eyedropper(&mut self, mut request: ExecutionRequest) { @@ -432,8 +420,18 @@ 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(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(value))) => ExecutionResult::Partial(value), Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value), @@ -443,12 +441,8 @@ impl NodeRuntime { } 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) => { - self.send_result(execution_id, ExecutionResult::Panic(payload)); - return None; - } - }; - Some(result) + Err(payload) => ExecutionResult::Panic(payload), + } } fn send_result(&self, execution_id: u64, result: ExecutionResult) { @@ -464,15 +458,15 @@ impl NodeRuntime { 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.output.is_none() || request.render_config.for_export { - 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; @@ -701,7 +695,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. @@ -1186,14 +1180,9 @@ mod tests { editor.dispatch(Message::Wake); send_export(&mut editor, FileType::Svg); - let failed_export = ExecutionResponse { - execution_id: editor.portfolio_message_handler().executor.futures.back().unwrap().0, - result: ExecutionResult::Error(EvaluationErrors(Box::new([]))), - responses: VecDeque::new(), - dropped_thumbnails: Vec::new(), - observations: HashMap::new(), - }; - editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(failed_export))).unwrap(); + let id = *editor.portfolio_message_handler().executor.exports.keys().next().unwrap(); + let result = Box::new(ExecutionResult::Error(EvaluationErrors(Box::new([])))); + editor.runtime.sender.send(NodeGraphUpdate::Export { id, result }).unwrap(); let messages = respond_to_last_request(&mut editor, ExecutionResult::Value(rendered(empty_svg()))); let shows_dialog = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. })); assert!(shows_dialog, "the export should say it failed"); @@ -1201,6 +1190,32 @@ mod tests { assert!(drawn_in(&messages).is_some(), "the frame that followed the failed export was dropped"); } + #[tokio::test] + async fn an_export_answered_behind_a_failed_frame_is_still_saved() { + let mut editor = editor().await; + send_update(&mut editor); + run(&mut editor).await; + editor.dispatch(Message::Wake); + + send_export(&mut editor, FileType::Svg); + let failed_frame = ExecutionResponse { + execution_id: last_request(&editor).unwrap(), + result: ExecutionResult::Error(EvaluationErrors(Box::new([]))), + responses: VecDeque::new(), + dropped_thumbnails: Vec::new(), + observations: HashMap::new(), + }; + editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(failed_frame))).unwrap(); + let id = *editor.portfolio_message_handler().executor.exports.keys().next().unwrap(); + let result = Box::new(ExecutionResult::Value(rendered(empty_svg()))); + editor.runtime.sender.send(NodeGraphUpdate::Export { id, result }).unwrap(); + + let messages = editor.dispatch(Message::Wake); + let saved = messages.iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. })); + assert!(failed(&messages), "the frame should be reported as failed"); + assert!(saved, "the export answered behind the failed frame was dropped"); + } + #[tokio::test] async fn the_nodes_only_a_finished_export_kept_lose_their_types_at_the_next_network_update() { let mut editor = editor().await;