Report Vectorize progress in the graph view and the Properties panel with a cancel button

This commit is contained in:
Dennis Kobert committed 2026-11-21 23:12:00 +01:00
1 parent b3823aa4e6
commit ceeb8ed909
21 files changed
+634 -30

No files matched your search

@@ -6,7 +6,8 @@ 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, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeProgress, FrontendNodeType, FrontendRemoteCursor,
NodeGraphErrorDiagnostic,
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -326,6 +327,9 @@ pub enum FrontendMessage {
UpdateNodeGraphErrorDiagnostics {
errors: Vec<NodeGraphErrorDiagnostic>,
},
UpdateNodeGraphProgress {
progress: Vec<FrontendNodeProgress>,
},
UpdateVisibleNodes {
nodes: Vec<NodeId>,
},
@@ -360,7 +360,7 @@ impl LayoutMessageHandler {
responses.add(callback_message);
}
Widget::ImageLabel(_) => {}
Widget::ImageLabel(_) | Widget::ProgressBar(_) => {}
Widget::MathExpressionInput(math_expression_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (math_expression_input.on_commit.callback)(&()),
@@ -560,6 +560,7 @@ impl LayoutGroup {
Widget::NumberInput(x) => &mut x.tooltip_description,
Widget::ParameterChainToggle(x) => &mut x.tooltip_description,
Widget::PopoverButton(x) => &mut x.tooltip_description,
Widget::ProgressBar(x) => &mut x.tooltip_description,
Widget::TextAreaInput(x) => &mut x.tooltip_description,
Widget::TextButton(x) => &mut x.tooltip_description,
Widget::TextInput(x) => &mut x.tooltip_description,
@@ -964,6 +965,7 @@ pub enum Widget {
ParameterExposeButton(ParameterExposeButton),
ReferencePointInput(ReferencePointInput),
PopoverButton(PopoverButton),
ProgressBar(ProgressBar),
RadioInput(RadioInput),
Separator(Separator),
SliderInput(SliderInput),
@@ -1001,7 +1003,7 @@ impl Widget {
Self::TextInput(widget) => &mut widget.disabled,
Self::TextLabel(widget) => &mut widget.disabled,
Self::VisualColorPickersInput(widget) => &mut widget.disabled,
Self::ImageButton(_) | Self::ImageLabel(_) | Self::ShortcutLabel(_) | Self::ParameterChainToggle(_) | Self::Separator(_) | Self::WorkingColorsInput(_) => {
Self::ImageButton(_) | Self::ImageLabel(_) | Self::ProgressBar(_) | Self::ShortcutLabel(_) | Self::ParameterChainToggle(_) | Self::Separator(_) | Self::WorkingColorsInput(_) => {
return;
}
};
@@ -1122,6 +1124,7 @@ impl DiffUpdate {
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
Widget::IconLabel(_)
| Widget::ImageLabel(_)
| Widget::ProgressBar(_)
| Widget::MathExpressionInput(_)
| Widget::NodeCatalog(_)
| Widget::ReferencePointInput(_)
@@ -103,6 +103,26 @@ pub struct ImageLabel {
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
#[derivative(Debug, PartialEq)]
pub struct ProgressBar {
// Content
/// How much of the bar is filled, from 0 to 1.
#[widget_builder(constructor)]
pub fraction: f64,
/// Text shown over the bar.
pub label: String,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
#[derivative(Debug, PartialEq)]
@@ -345,6 +345,10 @@ pub enum NodeGraphMessage {
UpdateEvaluationErrors {
errors: Vec<NodeEvaluationError>,
},
/// The progress of the nodes with work in progress, by their full path from the root network.
UpdateNodeProgress {
progress: Vec<(Vec<NodeId>, f64)>,
},
UpdateActionButtons,
UpdateGraphBarRight,
UpdateInSelectedNetwork,
@@ -457,6 +461,7 @@ impl NodeGraphMessage {
| Self::UpdateNewNodeGraph
| Self::UpdateTypes { .. }
| Self::UpdateEvaluationErrors { .. }
| Self::UpdateNodeProgress { .. }
| Self::UpdateActionButtons
| Self::UpdateGraphBarRight
| Self::UpdateInSelectedNetwork
@@ -6,7 +6,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, FrontendNodeProgress, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
@@ -136,6 +136,8 @@ pub struct NodeGraphMessageHandler {
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
frontend_wires: HashSet<(NodeId, usize)>,
evaluation_errors: Vec<NodeEvaluationError>,
/// The progress of the nodes with work in progress, by their full path from the root network.
node_progress: Vec<(Vec<NodeId>, f64)>,
}
/// 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.
@@ -2074,6 +2076,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(FrontendMessage::UpdateNetworkReadOnly {
read_only: network_interface.is_read_only(breadcrumb_network_path),
});
let progress = self.node_graph_progress(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
responses.add(NodeGraphMessage::UpdateImportsExports);
@@ -2680,6 +2684,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
NodeGraphMessage::UpdateNodeProgress { progress } => {
if self.node_progress != progress {
self.node_progress = progress;
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let progress = self.node_graph_progress(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
}
}
}
NodeGraphMessage::UpdateActionButtons => {
if selection_network_path == breadcrumb_network_path {
self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses);
@@ -3900,6 +3913,22 @@ impl NodeGraphMessageHandler {
.collect()
}
/// The progress of the nodes in the network at `breadcrumb_network_path`, where a node shows the first work in progress within it.
fn node_graph_progress(&self, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNodeProgress> {
let depth = breadcrumb_network_path.len();
let mut shown = HashSet::new();
self.node_progress
.iter()
.filter(|(path, _)| path.starts_with(breadcrumb_network_path) && path.len() > depth)
.filter(|(path, _)| shown.insert(path[depth]))
.map(|(path, progress)| FrontendNodeProgress {
node_id: path[depth],
progress: *progress,
})
.collect()
}
/// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view.
// O(given layers × nesting depth), apart from what the active tool would edit in the selected layers
fn update_layer_panel(
@@ -4109,6 +4138,7 @@ impl Default for NodeGraphMessageHandler {
frontend_nodes: Vec::new(),
frontend_wires: HashSet::new(),
evaluation_errors: Vec::new(),
node_progress: Vec::new(),
}
}
}
@@ -3162,6 +3162,24 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo
]
}
/// The progress of the work in progress of the node at `node_path`, with a button to cancel it.
fn progress_row(progress: f64, node_path: Vec<NodeId>) -> LayoutGroup {
let percent = (progress.clamp(0., 1.) * 100.).floor();
let mut widgets = Vec::new();
add_blank_assist(&mut widgets);
widgets.extend([
ProgressBar::new(progress).label(format!("{percent}%")).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("Cancel")
.tooltip_description("Stop the work in progress, keeping its result so far.")
.on_update(move |_| PortfolioMessage::CancelNodeWork { node_path: node_path.clone() }.into())
.widget_instance(),
]);
LayoutGroup::row(widgets)
}
pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> LayoutGroup {
let mut layout = Vec::new();
@@ -3250,6 +3268,11 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
}
}
let node_path = [context.selection_network_path, &[node_id]].concat();
if let Some(progress) = context.executor.node_progress(&node_path) {
layout.insert(0, progress_row(progress, node_path));
}
let display_name = context
.network_interface
.node_metadata(&node_id, context.selection_network_path)
@@ -202,6 +202,15 @@ pub struct NodeGraphErrorDiagnostic {
pub error: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendNodeProgress {
#[serde(rename = "nodeId")]
pub node_id: NodeId,
/// How much of the work within the node is done, from 0 to 1.
pub progress: f64,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeEvaluationError {
pub node_path: Vec<NodeId>,
@@ -41,6 +41,10 @@ pub enum PortfolioMessage {
AutoSaveDocument {
document_id: DocumentId,
},
/// Cancels the work in progress of the active document's node at this full path from the root network.
CancelNodeWork {
node_path: Vec<graphene_std::uuid::NodeId>,
},
CloseActiveDocumentWithConfirmation,
CloseAllDocuments,
CloseAllDocumentsWithConfirmation,
@@ -285,6 +285,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
});
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::CancelNodeWork { node_path } => {
self.executor.cancel_node_work(node_path);
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id });
+47 -4
View File
@@ -41,6 +41,8 @@ pub struct ExecutionResponse {
dropped_thumbnails: Vec<NodeId>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>,
/// The progress of each source with work in progress, by the path of the value node injecting the source.
progress: Vec<(Vec<NodeId>, f64)>,
}
/// Names an observation so it can be changed or stopped without touching the others.
@@ -125,6 +127,8 @@ pub struct NodeGraphExecutor {
inspect_context_overrides: ContextOverrides,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
/// The progress of the active document's nodes with work in progress, by their full path from the root network.
node_progress: Vec<(Vec<NodeId>, f64)>,
/// Evaluation errors of the last evaluation, used in tests
#[cfg(test)]
evaluation_errors: Option<EvaluationErrors>,
@@ -179,6 +183,7 @@ impl NodeGraphExecutor {
previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(),
canvas_images_sent: HashSet::new(),
node_progress: Vec::new(),
#[cfg(test)]
evaluation_errors: None,
gradient_migration: None,
@@ -214,6 +219,16 @@ impl NodeGraphExecutor {
execution_id
}
/// The progress of the work of the node at this full path from the root network, if it has work in progress.
pub fn node_progress(&self, node_path: &[NodeId]) -> Option<f64> {
self.node_progress.iter().find(|(path, _)| path == node_path).map(|(_, progress)| *progress)
}
/// Cancels the work in progress of the node at this full path from the root network.
pub fn cancel_node_work(&self, node_path: Vec<NodeId>) {
self.sender.send(GraphRuntimeRequest::Cancel(node_path)).expect("Failed to send the cancellation");
}
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}");
@@ -533,6 +548,7 @@ impl NodeGraphExecutor {
responses: existing_responses,
dropped_thumbnails,
mut observations,
progress,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -577,14 +593,24 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw);
// The deepest document node containing each source shows its progress
if execution_context.document_id == document_id {
let node_progress: Vec<_> = progress
.into_iter()
.filter_map(|(path, progress)| {
let node_path = (1..=path.len()).rev().map(|length| &path[..length]).find(|path| is_document_node(document, path))?;
Some((node_path.to_vec(), progress))
})
.collect();
self.update_node_progress(node_progress, responses);
}
// A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
};
let in_document = |path: &&[NodeId]| is_document_node(document, path);
errors
.iter()
.flat_map(|(error, trace)| {
@@ -719,6 +745,7 @@ impl NodeGraphExecutor {
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());
self.update_node_progress(Vec::new(), responses);
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
@@ -793,6 +820,16 @@ impl NodeGraphExecutor {
all_dropped_thumbnails
}
/// Sends the active document's node progress to its graph, which keeps its own copy, and refreshes the Properties panel when it changed.
fn update_node_progress(&mut self, node_progress: Vec<(Vec<NodeId>, f64)>, responses: &mut VecDeque<Message>) {
responses.add(NodeGraphMessage::UpdateNodeProgress { progress: node_progress.clone() });
if self.node_progress != node_progress {
self.node_progress = node_progress;
responses.add(InspectorMessage::Refresh);
}
}
fn receive_thumbnails(document: &mut DocumentMessageHandler, thumbnails: VecDeque<FrontendMessage>, responses: &mut VecDeque<Message>) {
for thumbnail in thumbnails {
match LayersInView::thumbnail_layer(&thumbnail) {
@@ -1146,6 +1183,12 @@ impl NodeGraphExecutor {
}
}
/// Whether the node at this full path from the root network exists in the document.
fn is_document_node(document: &DocumentMessageHandler, path: &[NodeId]) -> bool {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
}
// TODO: Eventually remove this document upgrade code
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
/// (or set by the user), so a measured bake may safely be written.
+48 -5
View File
@@ -11,6 +11,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
use graphene_hash::CacheHash;
use graphene_std::SourceId;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
@@ -62,6 +63,8 @@ pub struct NodeRuntime {
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
/// Each source of the compiled network, with the path of the value node injecting it.
source_paths: Vec<(SourceId, Vec<NodeId>)>,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
@@ -104,6 +107,8 @@ pub enum GraphRuntimeRequest {
layers: Vec<NodeId>,
},
RenderOverlays(OverlayContext),
/// Cancels the work in progress of the sources within the node at this full path from the root network.
Cancel(Vec<NodeId>),
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
@@ -188,6 +193,7 @@ impl NodeRuntime {
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
source_paths: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
@@ -245,6 +251,15 @@ impl NodeRuntime {
self.overlays = Some(context);
self.overlays_stale = true;
}
GraphRuntimeRequest::Cancel(node_path) => {
let mut canceled = false;
for (source, _) in self.source_paths.iter().filter(|(_, path)| path.starts_with(&node_path)) {
canceled |= self.async_runtime().cancel(*source);
}
if canceled {
self.dirty.store(true, Ordering::Release);
}
}
}
}
@@ -473,6 +488,7 @@ impl NodeRuntime {
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
progress: Vec::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -487,12 +503,23 @@ impl NodeRuntime {
// 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 progress = self
.async_runtime()
.progress()
.into_iter()
.filter_map(|(source, progress)| {
let (_, path) = self.source_paths.iter().find(|(candidate, _)| *candidate == source)?;
Some((path.clone(), progress))
})
.collect();
let response = ExecutionResponse {
execution_id,
result,
responses,
dropped_thumbnails,
observations,
progress,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
@@ -562,6 +589,7 @@ impl NodeRuntime {
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings.extend(warnings);
self.source_paths = proto_network.source_paths().map(|(source, path)| (*source, path.to_vec())).collect();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -730,8 +758,8 @@ mod tests {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
}
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
fn vectorize_layer(editor: &mut EditorTestUtils) {
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations. Returns the Vectorize node.
fn vectorize_layer(editor: &mut EditorTestUtils) -> NodeId {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
@@ -756,6 +784,7 @@ mod tests {
output_connector: OutputConnector::primary_output(vectorize),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
vectorize
}
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
@@ -1116,14 +1145,14 @@ mod tests {
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
}
/// A trace renders partial frames until it is done.
/// A trace renders partial frames and shows its progress on its node until it is canceled, which keeps the shapes traced so far.
#[tokio::test]
async fn a_trace_renders_partial_frames() {
async fn a_trace_shows_its_progress_until_it_is_canceled() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 512., 512.).await;
vectorize_layer(&mut editor);
let vectorize = vectorize_layer(&mut editor);
send_update_at(&mut editor, UVec2::splat(512));
editor.runtime.update();
@@ -1133,6 +1162,20 @@ mod tests {
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Partial }),
"the trace's frame isn't partial"
);
assert!(editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_some(), "the trace shows no progress");
editor.dispatch(PortfolioMessage::CancelNodeWork { node_path: vec![vectorize] });
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
assert!(
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Fallback }),
"the canceled trace's frame isn't a fallback"
);
assert!(
editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_none(),
"the canceled trace still shows progress"
);
}
#[test]
@@ -973,10 +973,12 @@
{@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"}
{@const progress = $nodeGraph.progress.get(node.id)}
<div
class="node"
class:selected={$nodeGraph.selected.includes(node.id)}
class:previewed={node.previewed}
class:in-progress={progress !== undefined}
class:disabled={!node.visible}
style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)}
style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)}
@@ -992,6 +994,9 @@
<IconLabel {icon} />
<!-- TODO: Allow the user to edit the name, just like in the Layers panel -->
<TextLabel>{node.displayName}</TextLabel>
{#if progress !== undefined}
<div class="progress" style:width={`${Math.min(Math.max(progress, 0), 1) * 100}%`}></div>
{/if}
</div>
<!-- Secondary rows -->
{#if exposedInputsOutputs.length > 0}
@@ -1515,6 +1520,10 @@
border: 1px dashed var(--color-e-nearwhite);
}
&.in-progress::after {
border-color: var(--color-warning-yellow);
}
.connectors {
position: absolute;
// Keeps the connectors above the wires
@@ -1900,6 +1909,15 @@
margin-left: 0;
margin-right: 4px;
}
.progress {
position: absolute;
left: 0;
bottom: 0;
height: 2px;
background: var(--color-e-nearwhite);
transition: width 0.1s linear;
}
}
.secondary {
@@ -25,6 +25,7 @@
import WorkingColorsInput from "/src/components/widgets/inputs/WorkingColorsInput.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import ImageLabel from "/src/components/widgets/labels/ImageLabel.svelte";
import ProgressBar from "/src/components/widgets/labels/ProgressBar.svelte";
import Separator from "/src/components/widgets/labels/Separator.svelte";
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
@@ -308,6 +309,10 @@
layoutTarget,
}),
},
ProgressBar: {
component: ProgressBar,
getProps: (props) => ({ ...props }),
},
RadioInput: {
component: RadioInput,
getProps: (props, index) => ({
@@ -0,0 +1,71 @@
<script lang="ts">
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
export let classes: Record<string, boolean> = {};
// Content
export let fraction: number;
export let label = "";
// Tooltips
export let tooltipLabel: string | undefined = undefined;
export let tooltipDescription: string | undefined = undefined;
export let tooltipShortcut: ActionShortcut | undefined = undefined;
$: extraClasses = Object.entries(classes)
.flatMap(([className, stateName]) => (stateName ? [className] : []))
.join(" ");
$: percent = `${Math.min(Math.max(fraction, 0), 1) * 100}%`;
</script>
<div
class={`progress-bar ${className} ${extraClasses}`.trim()}
role="progressbar"
aria-valuemin={0}
aria-valuemax={1}
aria-valuenow={Math.min(Math.max(fraction, 0), 1)}
data-tooltip-label={tooltipLabel}
data-tooltip-description={tooltipDescription}
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
>
<div class="track">
<div class="fill" style:width={percent}></div>
</div>
{#if label}
<span class="label">{label}</span>
{/if}
</div>
<style lang="scss">
.progress-bar {
display: flex;
align-items: center;
gap: 8px;
flex: 1 1 100%;
height: 24px;
.track {
position: relative;
flex: 1 1 100%;
height: 4px;
border-radius: 2px;
overflow: hidden;
background: var(--color-1-nearblack);
}
.fill {
position: absolute;
inset: 0 auto 0 0;
background: var(--color-e-nearwhite);
transition: width 0.1s linear;
}
.label {
flex: 0 0 auto;
font-size: 12px;
white-space: nowrap;
color: var(--color-a-softgray);
}
}
</style>
+10
View File
@@ -25,6 +25,7 @@ type NodeGraphStoreState = {
clickTargets: FrontendClickTargets | undefined;
contextMenuInformation: ContextMenuInformation | undefined;
errors: NodeGraphErrorDiagnostic[];
progress: Map<bigint, number>;
layerWidths: Map<bigint, number>;
chainWidths: Map<bigint, number>;
hasLeftInputWire: Map<bigint, boolean>;
@@ -48,6 +49,7 @@ const initialState: NodeGraphStoreState = {
clickTargets: undefined,
contextMenuInformation: undefined,
errors: [],
progress: new Map(),
layerWidths: new Map(),
chainWidths: new Map(),
hasLeftInputWire: new Map(),
@@ -236,6 +238,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
});
});
subscriptions.subscribeFrontendMessage("UpdateNodeGraphProgress", (data) => {
update((state) => {
state.progress = new Map(data.progress.map(({ nodeId, progress }) => [nodeId, progress]));
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
const newNodes = new Set<bigint>(data.nodes);
@@ -360,6 +369,7 @@ export function destroyNodeGraphStore() {
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphProgress");
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
+6 -1
View File
@@ -385,9 +385,14 @@ impl ProtoNetwork {
}
pub fn source_ids(&self) -> impl Iterator<Item = &SourceId> {
self.source_paths().map(|(source, _)| source)
}
/// Each source with the path of the value node that injects it, which lies within the node that owns the source.
pub fn source_paths(&self) -> impl Iterator<Item = (&SourceId, &[NodeId])> {
self.nodes.iter().filter_map(|(_, node)| match &node.construction_args {
ConstructionArgs::Value(value) => match &**value {
TaggedValue::SourceId(source) => Some(source),
TaggedValue::SourceId(source) => Some((source, node.original_location.path.as_deref().unwrap_or_default())),
_ => None,
},
_ => None,
+91 -4
View File
@@ -2,11 +2,11 @@ use crate::poll::Poll;
use crate::uuid::NodeId;
use dyn_any::WasmNotSend;
use futures::future::{AbortHandle, Abortable};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Waker};
pub use web_time::Instant;
@@ -34,7 +34,12 @@ impl SourceId {
pub type Generations = Arc<[(SourceId, u64)]>;
pub trait Runtime {
/// Runs `task` outside of the graph, bumping the generation of `source` once it finishes.
fn spawn(&self, source: SourceId, task: Task);
/// Sets how far the work of `source` has come from 0 to 1, or with `None` clears it along with any cancellation request.
fn report_progress(&self, source: SourceId, progress: Option<f64>);
/// Whether cancellation of the work of `source` was requested since this was last called.
fn take_cancellation(&self, source: SourceId) -> bool;
}
#[derive(Clone, dyn_any::DynAny)]
@@ -44,6 +49,14 @@ impl Runtime for RuntimeHandle {
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
}
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
self.0.report_progress(source, progress);
}
fn take_cancellation(&self, source: SourceId) -> bool {
self.0.take_cancellation(source)
}
}
impl std::fmt::Debug for RuntimeHandle {
@@ -68,16 +81,42 @@ impl AsyncRuntime {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
Self(Arc::new(RuntimeInner {
generations: Mutex::default(),
progress: Mutex::default(),
cancellations: Mutex::default(),
spawner,
}))
}
pub fn update_sources(&self, live: &[SourceId]) {
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut generations = lock(&self.0.generations);
generations.retain(|source, _| live.contains(source));
for source in live {
generations.entry(*source).or_insert(0);
}
lock(&self.0.progress).retain(|source, _| live.contains(source));
lock(&self.0.cancellations).retain(|source| live.contains(source));
}
/// The progress of every source that reported some and has not cleared it, sorted by source.
pub fn progress(&self) -> Vec<(SourceId, f64)> {
let mut progress: Vec<_> = lock(&self.0.progress).iter().map(|(source, progress)| (*source, *progress)).collect();
progress.sort_unstable_by_key(|(source, _)| *source);
progress
}
/// Requests cancellation of the work of `source` and bumps its generation, so the node is evaluated again to see the request.
/// Only work that reports progress can be canceled, so a request can't outlive the work it was meant for. Returns whether there was any.
pub fn cancel(&self, source: SourceId) -> bool {
if !lock(&self.0.progress).contains_key(&source) {
return false;
}
lock(&self.0.cancellations).insert(source);
if let Some(generation) = lock(&self.0.generations).get_mut(&source) {
*generation += 1;
}
true
}
pub fn snapshot(&self) -> Generations {
@@ -97,10 +136,20 @@ impl Runtime for AsyncRuntime {
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
}
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
self.0.report_progress(source, progress);
}
fn take_cancellation(&self, source: SourceId) -> bool {
self.0.take_cancellation(source)
}
}
struct RuntimeInner {
generations: Mutex<HashMap<SourceId, u64>>,
progress: Mutex<HashMap<SourceId, f64>>,
cancellations: Mutex<HashSet<SourceId>>,
spawner: Arc<dyn Spawn + Send + Sync>,
}
@@ -109,11 +158,31 @@ impl RuntimeInner {
let inner = Arc::clone(self);
self.spawner.spawn(Box::pin(async move {
task.await;
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
if let Some(generation) = lock(&inner.generations).get_mut(&source) {
*generation += 1;
}
}));
}
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
match progress {
Some(progress) => {
lock(&self.progress).insert(source, progress);
}
None => {
lock(&self.progress).remove(&source);
lock(&self.cancellations).remove(&source);
}
}
}
fn take_cancellation(&self, source: SourceId) -> bool {
lock(&self.cancellations).remove(&source)
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
@@ -289,6 +358,24 @@ mod tests {
assert!(runtime.snapshot().is_empty());
}
#[test]
fn only_work_in_progress_can_be_canceled() {
let runtime = AsyncRuntime::new(Arc::new(CollectSpawner::default()));
runtime.update_sources(&[SOURCE]);
assert!(!runtime.cancel(SOURCE));
runtime.report_progress(SOURCE, Some(0.5));
assert!(runtime.cancel(SOURCE));
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)], "a cancellation bumps the generation");
assert!(runtime.take_cancellation(SOURCE));
assert!(!runtime.take_cancellation(SOURCE));
runtime.cancel(SOURCE);
runtime.report_progress(SOURCE, None);
assert!(!runtime.take_cancellation(SOURCE), "clearing the progress drops the request");
assert!(runtime.progress().is_empty());
}
#[test]
fn a_slot_serves_the_placeholder_until_the_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
+65 -5
View File
@@ -1,4 +1,5 @@
mod convert;
mod progress;
mod slices;
pub use convert::{ATTR_OLLEV_REPEAT, RepeatStructure};
@@ -89,19 +90,32 @@ fn vectorize(
instancing: *instancing.element(),
path_gradients: *path_gradients.element(),
};
let runtime = runtime.element();
let source = *source.element();
let max_megabytes = Some(*max_memory.element()).filter(|&megabytes| megabytes > 0.);
if cfg!(target_family = "wasm") && !*exceed_browser_limit.element() && max_megabytes.is_none_or(|megabytes| megabytes > BROWSER_MAX_MEGABYTES) {
trace.clear();
runtime.report_progress(source, None);
return Poll::error(format!(
"A memory limit above {BROWSER_MAX_MEGABYTES} MB, or none, can crash the editor in the browser. Lower the limit or turn on \"Exceed Browser Limit\"."
));
}
let max_pixels = max_megabytes.map(|megabytes| (megabytes * 1e6 / BYTES_PER_PIXEL) as usize);
let runtime = runtime.element();
if runtime.take_cancellation(source) {
trace.cancel();
}
let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE);
if let Poll::Partial(_) = state {
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
runtime.spawn(*source.element(), Box::pin(async {}));
match state {
Poll::Partial(_) => {
runtime.report_progress(source, trace.progress());
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
runtime.spawn(source, Box::pin(async {}));
}
_ => runtime.report_progress(source, None),
}
state
}
@@ -146,7 +160,7 @@ fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: o
ollev::Tracing::new(&source, &options).map(|tracing| (tracing, pixels_to_document))
};
slot.poll(hasher.finish(), slice, start, convert::model_to_graphic)
slot.poll(hasher.finish(), slice, stages.translucency, start, convert::model_to_graphic)
}
#[cfg(test)]
@@ -404,4 +418,50 @@ mod test {
assert_eq!(spawner.drain(), 2);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 2)]);
}
/// A running trace reports progress that never goes down until it is done.
#[test]
fn a_trace_reports_progress_until_it_is_done() {
let (spawner, runtime) = collecting_runtime();
let (image, slot) = (busy(96), TraceSlot::default());
let mut previous = 0.;
while matches!(evaluate(&slot, &image, &runtime), Poll::Partial(_)) {
let progress = runtime.progress();
let [(source, fraction)] = progress.as_slice() else { panic!("the trace reported {progress:?}") };
assert_eq!(*source, SOURCE);
assert!((previous..=1.).contains(fraction), "progress went from {previous} to {fraction}");
previous = *fraction;
spawner.drain();
}
assert!(previous > 0., "the trace never reported any progress");
assert!(runtime.progress().is_empty(), "a finished trace still reports progress");
}
/// A canceled trace keeps its shapes so far, with an error, until its inputs change.
#[test]
fn a_canceled_trace_keeps_its_shapes_until_the_inputs_change() {
let (_spawner, runtime) = collecting_runtime();
let slot = TraceSlot::default();
let image = busy(96);
let shown = loop {
match evaluate(&slot, &image, &runtime) {
Poll::Partial(shown) if !shown.is_empty() => break shown,
Poll::Partial(_) => {}
state => panic!("the trace ended in {state:?} before showing shapes"),
}
};
assert!(runtime.cancel(SOURCE));
let Poll::Fallback(boxed) = evaluate(&slot, &image, &runtime) else {
panic!("the canceled trace went on")
};
assert!(boxed.0.len() >= shown.len(), "the canceled trace dropped its shapes");
assert!(runtime.progress().is_empty());
assert!(!runtime.cancel(SOURCE), "a canceled trace can be canceled again");
assert!(matches!(evaluate(&slot, &image, &runtime), Poll::Fallback(_)), "the canceled trace was started again");
assert!(matches!(evaluate(&slot, &busy(128), &runtime), Poll::Partial(_)), "new inputs were not traced");
}
}
+137
View File
@@ -0,0 +1,137 @@
/// The top-level stages of a trace in the order ollev runs them, each with its share of the trace's time.
/// Measured with ollev 0.1.2 on 1024 by 1024 pixel renders of the demo artwork with the node's default stages, averaged over the images.
/// The unnamed stage is the setup before the first checkpoint names one.
const STAGES: [(&str, f64); 8] = [
("", 0.03),
("analyze", 0.21),
("plan", 0.09),
("draw", 0.18),
("redraw", 0.09),
("shapes", 0.16),
("families", 0.),
("passes", 0.24),
];
const FAMILIES: usize = 6;
/// The share of the trace's time the translucent families take with translucency on, which ranged from 6 to 93% on the same images.
/// The other stages split the rest in proportion to their shares.
const FAMILIES_SHARE: f64 = 0.35;
/// How many nested traces of the families stage fill half of its share, since how many there will be isn't known up front.
const HALF_FILLING_NESTED_TRACES: f64 = 4.;
/// Folds the stages ollev reports into one fraction of the whole trace that never goes down.
#[derive(Clone, Debug)]
pub struct TraceProgress {
translucency: bool,
stage: usize,
/// The fraction of the current stage, or for the families stage how many traces beneath its layers have started.
within_stage: f64,
previous_stage: &'static str,
fraction: f64,
}
impl TraceProgress {
pub fn new(translucency: bool) -> Self {
Self {
translucency,
stage: 0,
within_stage: 0.,
previous_stage: "",
fraction: 0.,
}
}
/// Takes in a checkpoint of the trace, where it is in `stage` with `fraction` of the stage done.
pub fn observe(&mut self, stage: &'static str, fraction: f64) {
let entered = stage != self.previous_stage;
self.previous_stage = stage;
// The traces beneath translucent layers repeat the stages before the families stage, so they count as part of it
if self.stage == FAMILIES && stage != "passes" {
if entered && stage == "analyze" {
self.within_stage += 1.;
}
} else if let Some(index) = STAGES.iter().position(|(name, _)| *name == stage)
&& index >= self.stage
{
if index > self.stage {
self.stage = index;
self.within_stage = 0.;
}
if index != FAMILIES {
self.within_stage = fraction.clamp(0., 1.);
}
}
let within_share = match self.stage {
FAMILIES => self.within_stage / (self.within_stage + HALF_FILLING_NESTED_TRACES),
_ => self.within_stage,
};
let before: f64 = (0..self.stage).map(|index| self.share(index)).sum();
self.fraction = self.fraction.max(before + self.share(self.stage) * within_share);
}
/// How much of the trace is done, from 0 to 1.
pub fn fraction(&self) -> f64 {
self.fraction.min(1.)
}
fn share(&self, index: usize) -> f64 {
match (self.translucency, index) {
(false, _) => STAGES[index].1,
(true, FAMILIES) => FAMILIES_SHARE,
(true, _) => STAGES[index].1 * (1. - FAMILIES_SHARE),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn the_stages_fill_the_whole_trace() {
for translucency in [false, true] {
let progress = TraceProgress::new(translucency);
let total: f64 = (0..STAGES.len()).map(|index| progress.share(index)).sum();
assert!((total - 1.).abs() < 1e-9, "the shares add up to {total}");
}
}
#[test]
fn progress_moves_through_the_stages_and_within_them() {
let mut progress = TraceProgress::new(false);
progress.observe("analyze", 0.);
assert!((progress.fraction() - 0.03).abs() < 1e-9);
progress.observe("draw", 0.5);
assert!((progress.fraction() - (0.03 + 0.21 + 0.09 + 0.09)).abs() < 1e-9);
progress.observe("passes", 0.);
assert!((progress.fraction() - 0.76).abs() < 1e-9);
}
#[test]
fn the_traces_beneath_translucent_layers_never_move_progress_back() {
let mut progress = TraceProgress::new(true);
progress.observe("shapes", 0.);
progress.observe("families", 0.);
let families_start = progress.fraction();
let mut previous = families_start;
for _ in 0..3 {
for stage in ["analyze", "plan", "draw", "redraw", "shapes"] {
progress.observe(stage, 0.5);
assert!(progress.fraction() >= previous, "{stage} moved progress back");
previous = progress.fraction();
}
}
assert!(previous > families_start, "the nested traces didn't move progress");
assert!(previous < families_start + FAMILIES_SHARE, "the nested traces filled the families stage");
progress.observe("passes", 0.);
assert!((progress.fraction() - (1. - 0.24 * (1. - FAMILIES_SHARE))).abs() < 1e-9);
}
}
+31 -7
View File
@@ -1,6 +1,7 @@
use core_types::Poll;
use crate::progress::TraceProgress;
use core_types::list::List;
use core_types::runtime::Instant;
use core_types::{NodeError, Poll};
use glam::DAffine2;
use graphic_types::Graphic;
use ollev::model::Model;
@@ -23,22 +24,25 @@ struct Trace {
inputs: u64,
/// `None` once the trace is done and `shown` is its result, or once it failed.
tracing: Option<ollev::Tracing>,
/// Why the trace failed, kept so the same inputs are not traced again.
failed: Option<ollev::TraceError>,
/// Why the trace failed or was canceled, kept so the same inputs are not traced again.
failed: Option<NodeError>,
/// Places the traced image's pixels in the document.
pixels_to_document: DAffine2,
shown: List<Graphic>,
/// The revision of the scene in `shown`.
revision: Option<u64>,
progress: TraceProgress,
}
impl TraceSlot {
/// Advances the trace of `inputs` by `slice`, replacing any trace of other inputs with one from `start`, which also gives where the traced pixels lie.
/// Traces translucent layers if `translucency`.
/// Returns the latest showable scene, partial until the trace is done.
pub fn poll(
&self,
inputs: u64,
slice: Duration,
translucency: bool,
start: impl FnOnce() -> Result<(ollev::Tracing, DAffine2), ollev::TraceError>,
convert: impl Fn(&Model, DAffine2) -> List<Graphic>,
) -> Poll<List<Graphic>> {
@@ -54,6 +58,7 @@ impl TraceSlot {
pixels_to_document,
shown: List::new(),
revision: None,
progress: TraceProgress::new(translucency),
},
Err(error) => return Poll::fallback(List::new(), error),
},
@@ -61,7 +66,11 @@ impl TraceSlot {
if let Some(tracing) = &mut trace.tracing {
let deadline = Instant::now() + slice;
let step = tracing.step(|_| if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) });
let progress = &mut trace.progress;
let step = tracing.step(|checkpoint| {
progress.observe(checkpoint.stage, checkpoint.fraction);
if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
});
match step {
Ok(ollev::Step::Done(model)) => {
trace.shown = convert(&model, trace.pixels_to_document);
@@ -69,7 +78,7 @@ impl TraceSlot {
}
Err(error) => {
trace.tracing = None;
trace.failed = Some(error);
trace.failed = Some(error.into());
}
Ok(ollev::Step::Paused(progress)) => {
if progress.showable()
@@ -84,8 +93,8 @@ impl TraceSlot {
}
let shown = trace.shown.clone();
let state = match trace.failed {
Some(error) => Poll::fallback(shown, error),
let state = match &trace.failed {
Some(error) => Poll::Fallback(Box::new((shown, error.clone()))),
None if trace.tracing.is_some() => Poll::Partial(shown),
None => Poll::Final(shown),
};
@@ -93,6 +102,21 @@ impl TraceSlot {
state
}
/// How much of the slot's trace is done from 0 to 1, while it is not yet done.
pub fn progress(&self) -> Option<f64> {
let held = self.lock();
held.as_ref().filter(|trace| trace.tracing.is_some()).map(|trace| trace.progress.fraction())
}
/// Stops the slot's trace, keeping the scene traced so far as the result for its inputs.
pub fn cancel(&self) {
let mut held = self.lock();
let Some(trace) = held.as_mut().filter(|trace| trace.tracing.is_some()) else { return };
trace.tracing = None;
trace.failed = Some(NodeError::new("The trace was canceled"));
}
/// Drops the slot's trace.
pub fn clear(&self) {
self.lock().take();