Track graph execution id to associate messages with their corresponding execution id

This commit is contained in:
Dennis Kobert
2025-07-28 15:48:26 +02:00
parent 0c913277d5
commit 35ce634571
12 changed files with 47 additions and 41 deletions
+4 -1
View File
@@ -51,7 +51,10 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateDocumentLayerStructure), MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateDocumentLayerStructure),
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontLoad), MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontLoad),
]; ];
const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[MessageDiscriminant::Broadcast(BroadcastMessageDiscriminant::TriggerEvent(BroadcastEventDiscriminant::AnimationFrame))]; const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
MessageDiscriminant::Broadcast(BroadcastMessageDiscriminant::TriggerEvent(BroadcastEventDiscriminant::AnimationFrame)),
MessageDiscriminant::Animation(AnimationMessageDiscriminant::IncrementFrameCounter),
];
// TODO: Find a way to combine these with the list above. We use strings for now since these are the standard variant names used by multiple messages. But having these also type-checked would be best. // TODO: Find a way to combine these with the list above. We use strings for now since these are the standard variant names used by multiple messages. But having these also type-checked would be best.
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"]; const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
+3 -3
View File
@@ -3,8 +3,8 @@ use crate::messages::prelude::*;
#[impl_message(Message, Defer)] #[impl_message(Message, Defer)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DeferMessage { pub enum DeferMessage {
TriggerGraphRun, TriggerGraphRun(u64),
AfterGraphRun { messages: Vec<Message> }, AfterGraphRun { messages: Vec<Message> },
TriggerViewportResize, TriggerViewportReady,
AfterViewportResize { messages: Vec<Message> }, AfterViewportReady { messages: Vec<Message> },
} }
@@ -2,26 +2,28 @@ use crate::messages::prelude::*;
#[derive(Debug, Default, ExtractField)] #[derive(Debug, Default, ExtractField)]
pub struct DeferMessageHandler { pub struct DeferMessageHandler {
after_graph_run: Vec<Message>, after_graph_run: Vec<(u64, Message)>,
after_viewport_resize: Vec<Message>, after_viewport_resize: Vec<Message>,
current_graph_submission_id: u64,
} }
#[message_handler_data] #[message_handler_data]
impl MessageHandler<DeferMessage, ()> for DeferMessageHandler { impl MessageHandler<DeferMessage, ()> for DeferMessageHandler {
fn process_message(&mut self, message: DeferMessage, responses: &mut VecDeque<Message>, _: ()) { fn process_message(&mut self, message: DeferMessage, responses: &mut VecDeque<Message>, _: ()) {
match message { match message {
DeferMessage::AfterGraphRun { messages } => { DeferMessage::AfterGraphRun { mut messages } => {
self.after_graph_run.extend_from_slice(&messages); self.after_graph_run.extend(messages.drain(..).map(|m| (self.current_graph_submission_id, m)));
} }
DeferMessage::AfterViewportResize { messages } => { DeferMessage::AfterViewportReady { messages } => {
self.after_viewport_resize.extend_from_slice(&messages); self.after_viewport_resize.extend_from_slice(&messages);
} }
DeferMessage::TriggerGraphRun => { DeferMessage::TriggerGraphRun(execution_id) => {
for message in self.after_graph_run.drain(..) { self.current_graph_submission_id = execution_id;
responses.push_front(message); for message in self.after_graph_run.extract_if(.., |x| x.0 < self.current_graph_submission_id) {
responses.push_front(message.1);
} }
} }
DeferMessage::TriggerViewportResize => { DeferMessage::TriggerViewportReady => {
for message in self.after_viewport_resize.drain(..) { for message in self.after_viewport_resize.drain(..) {
responses.push_front(message); responses.push_front(message);
} }
@@ -36,9 +36,7 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
}); });
} }
// TODO: Figure out how to get StartBuffer to work here so we can delete this and use `DocumentMessage::ZoomCanvasToFitAll` instead responses.add(DeferMessage::AfterViewportReady {
// Currently, it is necessary to use `FrontendMessage::TriggerDelayedZoomCanvasToFitAll` rather than `DocumentMessage::ZoomCanvasToFitAll` because the size of the viewport is not yet populated
responses.add(DeferMessage::AfterViewportResize {
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()], messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
}); });
responses.add(DocumentMessage::DeselectAllLayers); responses.add(DocumentMessage::DeselectAllLayers);
@@ -59,7 +59,6 @@ pub enum FrontendMessage {
#[serde(rename = "commitDate")] #[serde(rename = "commitDate")]
commit_date: String, commit_date: String,
}, },
TriggerDelayedZoomCanvasToFitAll,
TriggerDownloadImage { TriggerDownloadImage {
svg: String, svg: String,
name: String, name: String,
@@ -34,7 +34,6 @@ impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> f
self.viewport_bounds = bounds; self.viewport_bounds = bounds;
responses.add(NavigationMessage::CanvasPan { delta: DVec2::ZERO }); responses.add(NavigationMessage::CanvasPan { delta: DVec2::ZERO });
responses.add(DeferMessage::TriggerGraphRun);
responses.add(NodeGraphMessage::SetGridAlignedEdges); responses.add(NodeGraphMessage::SetGridAlignedEdges);
} }
} }
@@ -1435,6 +1435,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}, },
}) })
} }
// Some parts of the editior depend on these bounds to be present
let bounds = if self.graph_view_overlay_open {
self.network_interface.all_nodes_bounding_box(&self.breadcrumb_network_path).cloned()
} else {
self.network_interface.document_bounds_document_space(true)
};
if bounds.is_some() {
responses.add(DeferMessage::TriggerViewportReady);
} else {
// If we don't have bounds yet, we need wait until the node graph has run once more
responses.add(DeferMessage::AfterGraphRun {
messages: vec![DocumentMessage::PTZUpdate.into()],
});
}
} }
DocumentMessage::SelectionStepBack => { DocumentMessage::SelectionStepBack => {
self.network_interface.selection_step_back(&self.selection_network_path); self.network_interface.selection_step_back(&self.selection_network_path);
@@ -702,13 +702,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
if create_document { if create_document {
// Wait for the document to be rendered so the click targets can be calculated in order to determine the artboard size that will encompass the pasted image // Wait for the document to be rendered so the click targets can be calculated in order to determine the artboard size that will encompass the pasted image
responses.add(DeferMessage::AfterViewportReady {
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
});
responses.add(DeferMessage::AfterGraphRun { responses.add(DeferMessage::AfterGraphRun {
messages: vec![DocumentMessage::WrapContentInArtboard { place_artboard_at_origin: true }.into()], messages: vec![DocumentMessage::WrapContentInArtboard { place_artboard_at_origin: true }.into()],
}); });
responses.add(DeferMessage::AfterViewportResize {
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
});
} }
} }
PortfolioMessage::PasteSvg { PortfolioMessage::PasteSvg {
@@ -738,7 +737,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
messages: vec![DocumentMessage::WrapContentInArtboard { place_artboard_at_origin: true }.into()], messages: vec![DocumentMessage::WrapContentInArtboard { place_artboard_at_origin: true }.into()],
}); });
responses.add(DeferMessage::AfterViewportResize { responses.add(DeferMessage::AfterViewportReady {
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()], messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
}); });
} }
@@ -1020,7 +1019,6 @@ impl PortfolioMessageHandler {
/text>"# /text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed. // It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string(); .to_string();
responses.add(DeferMessage::TriggerGraphRun);
responses.add(FrontendMessage::UpdateDocumentArtwork { svg: error }); responses.add(FrontendMessage::UpdateDocumentArtwork { svg: error });
} }
result result
@@ -1721,9 +1721,9 @@ impl Fsm for PenToolFsmState {
let next_point = tool_data.next_point; let next_point = tool_data.next_point;
let start = latest_point.id; let start = latest_point.id;
if let Some(layer) = layer { if let Some(layer) = layer
let mut vector_data = document.network_interface.compute_modified_vector(layer).unwrap(); && let Some(mut vector_data) = document.network_interface.compute_modified_vector(layer)
{
let closest_point = vector_data.extendable_points(preferences.vector_meshes).filter(|&id| id != start).find(|&id| { let closest_point = vector_data.extendable_points(preferences.vector_meshes).filter(|&id| id != start).find(|&id| {
vector_data.point_domain.position_from_id(id).map_or(false, |pos| { vector_data.point_domain.position_from_id(id).map_or(false, |pos| {
let dist_sq = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point)); let dist_sq = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point));
+8 -5
View File
@@ -3,7 +3,7 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, TaggedValue}; use graph_craft::document::value::{RenderOutput, TaggedValue};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, generate_uuid}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::proto::GraphErrors; use graph_craft::proto::GraphErrors;
use graph_craft::wasm_application_io::EditorPreferences; use graph_craft::wasm_application_io::EditorPreferences;
use graphene_std::application_io::TimingInformation; use graphene_std::application_io::TimingInformation;
@@ -56,6 +56,7 @@ pub enum NodeGraphUpdate {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct NodeGraphExecutor { pub struct NodeGraphExecutor {
runtime_io: NodeRuntimeIO, runtime_io: NodeRuntimeIO,
current_execution_id: u64,
futures: HashMap<u64, ExecutionContext>, futures: HashMap<u64, ExecutionContext>,
node_graph_hash: u64, node_graph_hash: u64,
old_inspect_node: Option<NodeId>, old_inspect_node: Option<NodeId>,
@@ -78,13 +79,15 @@ impl NodeGraphExecutor {
futures: Default::default(), futures: Default::default(),
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver), runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
node_graph_hash: 0, node_graph_hash: 0,
current_execution_id: 0,
old_inspect_node: None, old_inspect_node: None,
}; };
(node_runtime, node_executor) (node_runtime, node_executor)
} }
/// Execute the network by flattening it and creating a borrow stack. /// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&self, render_config: RenderConfig) -> u64 { fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
let execution_id = generate_uuid(); 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 };
self.runtime_io.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); self.runtime_io.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request");
@@ -105,7 +108,7 @@ impl NodeGraphExecutor {
#[cfg(test)] #[cfg(test)]
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> { pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache. // We should always invalidate the cache.
self.node_graph_hash = generate_uuid(); self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let instrumented = Instrumented::new(&mut network); let instrumented = Instrumented::new(&mut network);
@@ -280,6 +283,7 @@ impl NodeGraphExecutor {
} else { } else {
self.process_node_graph_output(node_graph_output, transform, responses)? self.process_node_graph_output(node_graph_output, transform, responses)?
} }
responses.add(DeferMessage::TriggerGraphRun(execution_id));
// Update the spreadsheet on the frontend using the value of the inspect result. // Update the spreadsheet on the frontend using the value of the inspect result.
if self.old_inspect_node.is_some() { if self.old_inspect_node.is_some() {
@@ -384,7 +388,6 @@ impl NodeGraphExecutor {
return Err(format!("Invalid node graph output type: {node_graph_output:#?}")); return Err(format!("Invalid node graph output type: {node_graph_output:#?}"));
} }
}; };
responses.add(DeferMessage::TriggerGraphRun);
let graphene_std::renderer::RenderMetadata { let graphene_std::renderer::RenderMetadata {
upstream_footprints: footprints, upstream_footprints: footprints,
local_transforms, local_transforms,
-3
View File
@@ -791,8 +791,6 @@ export class TriggerImport extends JsMessage {}
export class TriggerPaste extends JsMessage {} export class TriggerPaste extends JsMessage {}
export class TriggerDelayedZoomCanvasToFitAll extends JsMessage {}
export class TriggerDownloadImage extends JsMessage { export class TriggerDownloadImage extends JsMessage {
readonly svg!: string; readonly svg!: string;
@@ -1649,7 +1647,6 @@ export const messageMakers: Record<string, MessageMaker> = {
DisplayRemoveEditableTextbox, DisplayRemoveEditableTextbox,
SendUIMetadata, SendUIMetadata,
TriggerAboutGraphiteLocalizedCommitDate, TriggerAboutGraphiteLocalizedCommitDate,
TriggerDelayedZoomCanvasToFitAll,
TriggerDownloadImage, TriggerDownloadImage,
TriggerDownloadTextFile, TriggerDownloadTextFile,
TriggerFetchAndOpenDocument, TriggerFetchAndOpenDocument,
-7
View File
@@ -13,7 +13,6 @@ import {
UpdateWorkingColorsLayout, UpdateWorkingColorsLayout,
UpdateNodeGraphControlBarLayout, UpdateNodeGraphControlBarLayout,
UpdateGraphViewOverlay, UpdateGraphViewOverlay,
TriggerDelayedZoomCanvasToFitAll,
UpdateGraphFadeArtwork, UpdateGraphFadeArtwork,
} from "@graphite/messages"; } from "@graphite/messages";
@@ -94,12 +93,6 @@ export function createDocumentState(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeJsMessage(TriggerDelayedZoomCanvasToFitAll, () => {
// TODO: This is horribly hacky
[0, 1, 10, 50, 100, 200, 300, 400, 500].forEach((delay) => {
setTimeout(() => editor.handle.zoomCanvasToFitAll(), delay);
});
});
return { return {
subscribe, subscribe,