Files
Graphite/editor/src/node_graph_executor/runtime.rs
T

1642 lines
64 KiB
Rust

use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
use crate::task::{Spawn, Spawner, Task};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::GraphErrors;
use graph_ui::scene::{GraphUiScene, GraphUiSceneDelta};
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
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};
use interpreted_executor::util::{wrap_network_in_scope, wrap_network_with_render_node_in_scope};
use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use thumbnails::Thumbnails;
use vello_gpu::peniko::ImageSampler;
use wgpu_executor::{VelloCanvas, VelloSceneBuilder};
#[cfg(test)]
mod layer_path_tests;
mod observer;
mod thumbnails;
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
/// Some of these fields are put into a [`PlatformEditorApi`] which is passed to the final compiled graph network upon each execution.
/// Once the implementation is finished, this will live in a separate thread. Right now it's part of the main JS thread, but its own separate JS stack frame independent from the editor.
pub struct NodeRuntime {
#[cfg(test)]
pub(super) executor: DynamicExecutor,
#[cfg(not(test))]
executor: DynamicExecutor,
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
dirty: Arc<AtomicBool>,
output: Option<OutputHandle>,
previous: Option<OutputHandle>,
pending: Option<ExecutionRequest>,
pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>,
viewport_artwork: Option<ViewportArtwork>,
exports: Vec<(u64, RenderConfig, OutputHandle)>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
observations_changed: bool,
preprocessor: preprocessor::Preprocessor,
/// 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<OverlayContext>,
/// Whether the overlays or the artwork changed since the overlays were last rendered.
overlays_stale: bool,
overlays_canvas: VelloCanvas,
overlays_texture: Option<Texture>,
overlays_redrawn: bool,
graph_ui_scene: GraphUiScene,
graph_ui_stale: bool,
graph_ui_output: OutputHandle,
graph_ui_network_hash: Option<u64>,
graph_ui_texture: Option<Texture>,
graph_ui_redrawn: bool,
/// 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.
enum ViewportArtwork {
/// Rendered by Vello, with the overlays drawn over it.
Texture(Texture),
/// An SVG the frontend draws, with the overlays shown alone above it.
Svg,
}
/// Messages passed from the editor thread to the node runtime thread.
#[derive(Debug)]
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
Export {
id: u64,
render_config: RenderConfig,
network: NodeNetwork,
resources: ResourceRegistry,
},
ThumbnailsInView {
layers: HashSet<NodeId>,
layers_panel: HashSet<NodeId>,
document_id: DocumentId,
},
RenderOverlays(OverlayContext),
Observe {
key: ObservationKey,
observation: Option<Observation>,
},
GraphUi(GraphUiSceneDelta),
}
#[derive(Debug)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
pub(super) thumbnails: Vec<(NodeId, Vec<NodeId>)>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportConfig {
pub name: String,
pub file_type: FileType,
pub scale_factor: f64,
pub bounds: ExportBounds,
pub artboard_name: Option<String>,
pub artboard_count: usize,
}
impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
Self {
executor: DynamicExecutor::default(),
receiver,
sender,
editor_wake,
dirty: Default::default(),
output: None,
previous: None,
pending: None,
pending_eyedropper: None,
pending_thumbnails: None,
viewport_artwork: None,
exports: Vec::new(),
old_graph: None,
async_runtime: None,
editor_api: PlatformEditorApi {
#[cfg(not(test))]
application_io: None,
#[cfg(test)]
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(),
rendered_layers: RenderedLayers::default(),
overlays: None,
overlays_stale: false,
overlays_canvas: VelloCanvas::default(),
overlays_texture: None,
overlays_redrawn: false,
graph_ui_scene: GraphUiScene::default(),
graph_ui_stale: false,
graph_ui_output: OutputHandle::default(),
graph_ui_network_hash: None,
graph_ui_texture: None,
graph_ui_redrawn: false,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
}
}
pub fn update(&mut self) {
while let Ok(request) = self.receiver.try_recv() {
match request {
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, layers_panel, document_id } => {
self.thumbnails.set_in_view(layers, layers_panel);
self.pending_thumbnails = Some(document_id);
}
GraphRuntimeRequest::Observe { key, observation } => {
self.observer.set(key, observation);
self.observations_changed = true;
}
GraphRuntimeRequest::RenderOverlays(context) => {
self.overlays = Some(context);
self.overlays_stale = true;
}
GraphRuntimeRequest::GraphUi(delta) => self.graph_ui_scene.apply(delta),
}
}
}
pub async fn run(&mut self) -> Option<Texture> {
let dirty = self.dirty.swap(false, Ordering::Acquire);
if dirty {
for (id, render_config, output) in std::mem::take(&mut self.exports) {
self.run_export(id, render_config, output).await;
}
}
let viewport = if dirty { self.pending } else { None };
if let Some(document_id) = self.pending_thumbnails.take()
&& viewport.is_none()
&& self.output.is_some()
{
let mut responses = VecDeque::new();
let rendered = self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
self.graph_ui_stale |= rendered;
if !responses.is_empty() {
self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response");
}
}
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(eyedropper) = self.pending_eyedropper.take() {
self.run_eyedropper(eyedropper).await;
}
if let Some(viewport) = viewport {
self.run_viewport(viewport).await;
}
if let Some(request) = self.pending {
self.draw_overlays(&request);
self.draw_graph_ui(&request);
}
let texture = self.composite_viewport_frame();
(self.editor_wake)();
texture
}
async fn run_viewport(&mut self, request: ExecutionRequest) {
self.thumbnails.set_scale(request.render_config.scale);
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() {
let content = match data {
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
_ => None,
};
if content.is_some() {
self.viewport_artwork = content;
let path_contents = path_contents(&observations);
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
}
}
self.respond(request, result, observations).await;
self.overlays_stale = true;
self.graph_ui_stale = true;
}
fn draw_overlays(&mut self, request: &ExecutionRequest) {
if !std::mem::take(&mut self.overlays_stale) {
return;
}
self.overlays_redrawn = true;
if request.graph_ui_config.is_some() {
self.overlays_texture = None;
return;
}
let Some(overlays) = &self.overlays else { return };
let executor = self.editor_api.application_io.as_ref().and_then(|application_io| application_io.gpu_executor());
if let Some(executor) = executor {
self.overlays_texture = executor
.render_vello_scene_on_canvas(&mut self.overlays_canvas, overlays.render(&self.rendered_layers))
.inspect_err(|error| log::error!("Failed to render the overlays: {error:?}"))
.ok();
}
}
fn draw_graph_ui(&mut self, request: &ExecutionRequest) {
if !std::mem::take(&mut self.graph_ui_stale) {
return;
}
self.graph_ui_redrawn = true;
let Some(mut config) = request.graph_ui_config else {
self.graph_ui_texture = None;
self.graph_ui_network_hash = None;
self.graph_ui_output = OutputHandle::default();
return;
};
if !matches!(self.viewport_artwork, Some(ViewportArtwork::Texture(_))) {
config.fade_artwork = 1.;
}
let scene = self.graph_ui_scene.clone();
let thumbnails = self.thumbnails.graphics();
let graph_ui_network = graph_ui::network(&scene, &config, &thumbnails);
let hash = graph_ui_network.current_hash();
if self.graph_ui_network_hash != Some(hash) {
let mut graph_ui_network = wrap_network_in_scope(graph_ui_network, self.editor_api.clone(), self.async_runtime().handle());
self.preprocessor.preprocess(&mut graph_ui_network, &|_| None).expect("The network of the node graph preprocesses");
let graph_ui_network = Compiler {}.compile_single(graph_ui_network).expect("The network of the node graph compiles").network;
let replaced = std::mem::take(&mut self.graph_ui_output);
self.graph_ui_output = self.executor.replace(replaced, graph_ui_network).expect("The network of the node graph is typed");
self.graph_ui_network_hash = Some(hash);
self.async_runtime().update_sources(self.executor.sources());
}
let context = graph_ui::render_config(config.view, request.render_config).into_context();
self.graph_ui_texture = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.graph_ui_output, context))) {
Ok(Ok(Poll::Final(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(frame),
..
})))) => Some(frame),
Ok(Ok(Poll::Error(error))) => {
log::error!("Failed to draw the node graph: {}", error.error());
None
}
Ok(Ok(_)) => None,
Ok(Err(error)) => {
log::error!("Failed to draw the node graph: {error}");
None
}
Err(payload) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
log::error!("Panicked while drawing the node graph: {}", message.unwrap_or("no message"));
None
}
};
}
fn composite_viewport_frame(&mut self) -> Option<Texture> {
let graph_ui_redrawn = std::mem::take(&mut self.graph_ui_redrawn);
let overlays_redrawn = std::mem::take(&mut self.overlays_redrawn);
if !graph_ui_redrawn && !overlays_redrawn {
return None;
}
if self.viewport_artwork.is_none() && self.graph_ui_texture.is_none() {
return None;
}
let executor = self.editor_api.application_io.as_ref().and_then(|application_io| application_io.gpu_executor())?;
let artwork = match &self.viewport_artwork {
Some(ViewportArtwork::Texture(artwork)) => Some(artwork),
Some(ViewportArtwork::Svg) | None => None,
};
let frame = match (artwork, &self.graph_ui_texture, &self.overlays_texture) {
(None, None, None) => return None,
(Some(frame), None, None) | (None, Some(frame), None) | (None, None, Some(frame)) => frame.clone(),
(artwork, graph_ui, overlays) => {
// The node graph is drawn at the viewport's size, which artwork from before a resize doesn't have
let base = graph_ui.as_ref().or(artwork).or(overlays.as_ref())?;
let (width, height) = (base.width(), base.height());
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
let mut scene = VelloSceneBuilder::new(width as u16, height as u16, kurbo::Affine::IDENTITY, max_texture_size);
for layer in [artwork, graph_ui.as_ref()].into_iter().flatten() {
scene.draw_texture(layer.clone(), ImageSampler::new(), kurbo::Affine::IDENTITY);
}
if let Some(overlays) = overlays {
let overlays_to_frame = kurbo::Affine::scale_non_uniform(width as f64 / overlays.width() as f64, height as f64 / overlays.height() as f64);
scene.draw_texture(overlays.clone(), ImageSampler::new(), overlays_to_frame);
}
executor
.render_vello_scene_on_canvas(&mut self.overlays_canvas, scene)
.inspect_err(|error| log::error!("Failed to draw the viewport's frame: {error:?}"))
.unwrap_or_else(|_| base.clone())
}
};
#[cfg(all(target_family = "wasm", feature = "wasm"))]
self.wasm_canvas_cache.present(&frame, executor);
Some(frame)
}
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;
}
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 };
}
self.send_export(id, result);
}
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
// Eyedropper should use the same time and pointer to not invalidate the cache
if let Some(viewport) = self.pending {
request.render_config.time = viewport.render_config.time;
request.render_config.pointer = viewport.render_config.pointer;
}
if let Some(output) = self.output.clone()
&& let Some(mut result) = self.evaluate(&output, request)
&& let Some(RenderOutput {
data: RenderOutputType::Texture(texture),
..
}) = result.render_output()
{
let raster = self.read_back(texture.clone()).await;
self.sender.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response");
}
}
fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option<ExecutionResult> {
let ExecutionRequest {
execution_id,
mut render_config,
graph_ui_config,
} = request;
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active and the graph, isn't open
if render_config.export_format == ExportFormat::Raster && render_config.render_mode == RenderMode::SvgPreview && graph_ui_config.is_none() {
render_config.export_format = ExportFormat::Svg;
}
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());
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),
Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(output, &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) => 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,
};
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<ObservationKey, InspectResult>) {
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() { Vec::new() } else { self.update_thumbnails(&mut responses).await };
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let mut result = result;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let viewport_canvas_info = (!request.render_config.for_export
&& match result.render_output() {
Some(RenderOutput { data, .. }) => match data {
RenderOutputType::Texture(_) => true,
RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster,
RenderOutputType::Buffer { .. } => false,
},
None => request.graph_ui_config.is_some(),
})
.then(|| ViewportCanvasInfo {
id: self.wasm_canvas_cache.id(),
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
});
let response = ExecutionResponse {
execution_id: request.execution_id,
result,
responses,
dropped_thumbnails,
observations,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
async fn read_back(&self, texture: Texture) -> Raster<CPU> {
let application_io = self.editor_api.application_io.as_ref().unwrap();
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
}
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(e.to_string());
}
// We assume only one output
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {};
let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
Ok(compiled_network) => compiled_network,
Err(CompileError::Graph(errors)) => {
let message = format!("{errors:?}");
self.node_graph_errors = errors;
return Err(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.insert(proto_network).map(|output| {
self.output = Some(output);
});
let result = updated.map_err(|e| {
self.node_graph_errors.clone_from(&e);
format!("{e:?}")
});
self.async_runtime().update_sources(self.executor.sources());
result
}
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();
paths.sort_unstable();
paths.into()
};
let mut errors = Vec::new();
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);
let origin = passed.last().copied().unwrap_or(node);
trace.extend(passed.into_iter().map(&paths));
pending.extend(error.upstream().iter().rev().map(|upstream| (trace.clone(), origin, upstream)));
errors.push((Arc::clone(error.error()), trace.into()));
}
EvaluationErrors(errors.into())
}
/// Renders the stale thumbnails, giving back the layers whose thumbnails were dropped because they no longer have content to show.
async fn update_thumbnails(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
let dropped_thumbnails = self.thumbnails.drop_sourceless();
self.thumbnails.render_stale(&self.executor, &self.editor_api, responses).await;
dropped_thumbnails
}
/// Reads one observation from the last evaluation, apart from the observations the runtime keeps.
#[cfg(test)]
pub(crate) fn observe(&self, observation: Observation) -> Option<ObservedValue> {
let mut observer = Observer::default();
observer.set((), Some(observation));
observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data
}
}
impl ExecutionResult {
pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> {
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
return None;
};
let TaggedValue::RenderOutput(output) = value else { return None };
Some(output)
}
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
Poll::Fallback(boxed) => Some(boxed.0),
Poll::Pending | Poll::Error(_) => None,
}
}
fn context_hash(context: &Context) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
context.cache_hash(&mut hasher);
std::hash::Hasher::finish(&hasher)
}
impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi {
application_io: Some(application_io.into()),
}
.into();
}
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) {
let spawn = NodeTaskExecutor {
spawner,
dirty: self.dirty.clone(),
wake,
};
self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn)));
}
fn async_runtime(&self) -> &AsyncRuntime {
self.async_runtime.as_ref().expect("the task executor is installed before the first graph update")
}
}
struct NodeTaskExecutor {
spawner: Spawner,
dirty: Arc<AtomicBool>,
wake: Wake,
}
impl Spawn for NodeTaskExecutor {
fn spawn(&self, task: Task) {
let dirty = self.dirty.clone();
let wake = self.wake.clone();
self.spawner.spawn(Box::pin(async move {
task.await;
dirty.store(true, Ordering::Release);
wake();
}));
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::frontend::utility_types::RenderStatus;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::test_utils::EditorTestUtils;
use glam::{DVec2, UVec2};
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
const SOURCE: SourceId = SourceId(1);
async fn editor() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// We use the svg pipeline for these tests since we don't read back the result for editor tests anyway
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().update_sources(&[SOURCE]);
editor
}
/// Sends a network update and a request to evaluate it, as the editor does for a change to the graph.
fn send_update(editor: &mut EditorTestUtils) {
send_update_at(editor, UVec2::ONE);
}
/// Sends a network update and a request to evaluate it at a viewport of `resolution` pixels.
fn send_update_at(editor: &mut EditorTestUtils, resolution: UVec2) {
send_update_with_graph_ui(editor, resolution, None);
}
fn send_update_with_graph_ui(editor: &mut EditorTestUtils, resolution: UVec2, graph_ui_config: Option<GraphUiConfig>) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
executor
.submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO, graph_ui_config)
.unwrap();
}
/// 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();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let export_config = ExportConfig {
name: "export".to_string(),
file_type,
scale_factor: 1.,
bounds: ExportBounds::AllArtwork,
..Default::default()
};
executor.submit_document_export(document, export_config).unwrap();
}
/// Whether the runtime evaluated the graph since this was last called.
fn evaluated(editor: &mut EditorTestUtils) -> bool {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
}
/// Whether the runtime finished an export since this was last called.
fn exported(editor: &mut EditorTestUtils) -> bool {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
}
/// Adds a layer tracing an image of noise, which an export has to wait on over several evaluations.
async fn add_traced_noise_layer(editor: &mut EditorTestUtils) {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use graphene_std::raster::Image;
use graphene_std::raster::color::Color;
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
let mut noise = Image::new(64, 64, Color::BLACK);
let mut state = 0x2545_f491_u32;
for pixel in &mut noise.data {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
let gray = (state % 256) as f32 / 255.;
*pixel = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
}
editor.create_raster_image(noise, None).await;
// Trace the image between the layer and the nodes feeding it
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let content = InputConnector::node_at_index(layer.to_node(), 1);
let image = editor
.active_document()
.network_interface
.upstream_output_connector(&content, &[])
.expect("the image layer has content");
let vectorize = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(vectorize),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER),
xy: None,
add_transaction: true,
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: image,
input_connector: InputConnector::node_at_index(vectorize, 0),
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(vectorize),
input_connector: content,
});
}
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, None)
.unwrap();
}
async fn run(editor: &mut EditorTestUtils) -> Option<Texture> {
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<u64> {
editor.runtime.pending.as_ref().map(|request| request.execution_id)
}
fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec<FrontendMessage> {
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;
send_update(&mut editor);
editor.runtime.run().await;
assert!(!evaluated(&mut editor), "run read the request");
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
}
/// Asks for a render of the unchanged graph at this device pixel ratio, as a pan or zoom does.
fn send_render(editor: &mut EditorTestUtils, scale: f64) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let message = executor
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, scale, Default::default(), DVec2::ZERO, None)
.unwrap();
editor.dispatch(message);
}
/// Wires the rectangle into a 'Read Attribute' node's name, which must be a fixed value, so the graph fails to compile.
/// Gives back the layer's content input and the value that restores it.
fn break_compile(editor: &mut EditorTestUtils) -> (InputConnector, NodeInput) {
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_proto_node_type};
use graphene_std::graphic::read_attribute_number;
use graphene_std::vector::generator_nodes::rectangle;
let rectangle_reference = DefinitionIdentifier::ProtoNode(rectangle::IDENTIFIER);
let interface = &editor.active_document().network_interface;
let rectangle_node = interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| interface.reference(node_id, &[]) == Some(rectangle_reference.clone()))
.unwrap();
let layer_content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
let original_content = editor.active_document().network_interface.input_from_connector(&layer_content, &[]).unwrap().clone();
let read_node = NodeId::new();
let template = resolve_proto_node_type(read_attribute_number::IDENTIFIER).unwrap().default_node_template();
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.insert_node(read_node, template, &[]);
network_interface.set_input(&InputConnector::node(read_node, read_attribute_number::NameInput), NodeInput::node(rectangle_node, 0), &[]);
network_interface.set_input(&layer_content, NodeInput::node(read_node, 0), &[]);
(layer_content, original_content)
}
#[tokio::test]
async fn a_graph_that_fails_to_compile_keeps_its_error_up_until_it_compiles() {
use crate::messages::frontend::utility_types::RenderStatus;
/// Lets the runtime handle what was sent and gives back whether the editor drew artwork and whether it shows the error.
async fn drawn_and_errored(editor: &mut EditorTestUtils) -> (bool, bool) {
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
let drawn = messages.iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }));
let errored = messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
(drawn, errored)
}
let mut editor = editor().await;
send_update(&mut editor);
assert_eq!(drawn_and_errored(&mut editor).await, (true, false));
let (layer_content, original_content) = break_compile(&mut editor);
send_update(&mut editor);
assert_eq!(drawn_and_errored(&mut editor).await, (false, true));
send_render(&mut editor, 1.);
assert_eq!(
drawn_and_errored(&mut editor).await,
(false, true),
"the last graph that compiled shouldn't be drawn in place of the error"
);
editor.active_document_mut().network_interface.set_input(&layer_content, original_content, &[]);
send_update(&mut editor);
assert_eq!(drawn_and_errored(&mut editor).await, (true, false));
}
#[tokio::test]
async fn thumbnails_wait_for_a_graph_that_fails_to_compile() {
/// Lets the runtime handle what was sent and gives back whether the layer's thumbnail is left to render.
async fn thumbnail_stale(editor: &mut EditorTestUtils, layer: NodeId) -> bool {
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
editor.runtime.thumbnails.is_stale(layer)
}
let mut editor = editor().await;
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
editor.runtime.thumbnails.set_in_view(HashSet::from([layer]), HashSet::from([layer]));
send_update(&mut editor);
assert!(!thumbnail_stale(&mut editor, layer).await);
// A new device pixel ratio makes the thumbnail stale, but the network to render it from has yet to compile
let (layer_content, original_content) = break_compile(&mut editor);
send_update(&mut editor);
thumbnail_stale(&mut editor, layer).await;
send_render(&mut editor, 2.);
assert!(thumbnail_stale(&mut editor, layer).await, "the thumbnail shouldn't render from the last network that compiled");
editor.active_document_mut().network_interface.set_input(&layer_content, original_content, &[]);
send_update(&mut editor);
assert!(!thumbnail_stale(&mut editor, layer).await, "the thumbnail should render once the graph compiles");
}
#[tokio::test]
async fn a_resource_that_loads_recompiles_the_unchanged_network() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use crate::test_utils::test_prelude::{Color, Image};
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
use graphene_std::raster_nodes::std_nodes::image;
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back whether it drew an image.
async fn image_drawn_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> bool {
editor.dispatch(message);
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
messages
.iter()
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()))
}
let mut editor = editor().await;
let document_id = editor.portfolio_message_handler().active_document_id.unwrap();
editor.dispatch(ViewportMessage::Update {
x: 0.,
y: 0.,
width: 100.,
height: 100.,
scale: 1.,
});
// The layer shows an 'Image' node whose image is known only by where to load it from
let resource_id = ResourceId::new();
let source = DataSource::Url("https://example.com/image.png".parse().unwrap());
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source.clone());
let image_node = NodeId::new();
let input = NodeInput::value(TaggedValue::Resource(resource_id), false);
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(input)]);
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(image_node),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
// Failing to load sends the network while the image has no data
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
let hash = ResourceHash::from(data.as_ref());
editor.dispatch(ResourceStorageMessage::Store { data });
let resolved = ResourceMessage::Resolved { resource_id, source, hash }.into();
assert!(image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await);
}
#[tokio::test]
async fn a_missing_resource_renders_with_an_error_traced_through_its_node() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use graph_craft::application_io::resource::ResourceId;
use graphene_std::platform_application_io::MissingResourceError;
use graphene_std::raster_nodes::std_nodes::image;
let mut editor = editor().await;
// The layer shows an 'Image' node holding an image the document has no record of
let image_node = NodeId::new();
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(image_node),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
let errors = editor.portfolio_message_handler_mut().executor.take_evaluation_errors().unwrap();
assert!(
errors
.iter()
.any(|(error, trace)| error.is::<MissingResourceError>() && trace.iter().flatten().any(|path| **path == [image_node])),
"{errors:?}"
);
}
#[tokio::test]
async fn a_raster_export_shows_the_artwork_whatever_the_render_mode() {
use crate::test_utils::test_prelude::{Color, Image};
for render_mode in [RenderMode::Normal, RenderMode::Outline, RenderMode::SvgPreview] {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
editor.draw_rect(0., 0., 100., 100.).await;
send_export(&mut editor, FileType::Png);
editor.runtime.update();
editor.runtime.run().await;
let png = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
_ => None,
});
let Some(png) = png else { panic!("the export in {render_mode:?} should save a PNG") };
let image = Image::from_encoded(&png).expect("the export should be a valid PNG");
let center = image.data[(image.height / 2 * image.width + image.width / 2) as usize];
assert_eq!(center, Color::WHITE, "the export in {render_mode:?} should show the rectangle's fill");
}
}
#[tokio::test]
async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use graphene_std::blending_nodes::effects::drop_shadow;
use graphene_std::raster_nodes::adjustments::black_and_white;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
// Following a shadow, Black & White can't fold into the paints, and no SVG filter mixes the channels as it does, so the rectangle is drawn as an image the GPU renders of it
let layer = editor.active_document().metadata().all_layers().next().unwrap();
for node in [drop_shadow::IDENTIFIER, black_and_white::IDENTIFIER] {
let node_type = DefinitionIdentifier::ProtoNode(node);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
}
// The export waits for the render node to read the image back into the SVG
send_export(&mut editor, FileType::Svg);
let mut saved = None;
for _ in 0..100 {
editor.runtime.update();
editor.runtime.run().await;
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
_ => None,
});
if saved.is_some() {
break;
}
}
let Some(saved) = saved else { panic!("the export never finished") };
let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text");
assert!(svg.contains("data:image/png;base64,"), "the image should be embedded: {svg}");
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
}
#[tokio::test]
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
let mut editor = editor().await;
break_compile(&mut editor);
send_export(&mut editor, FileType::Png);
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
let shows_dialog = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
assert!(shows_dialog, "the export should show why it saved nothing");
}
fn rectangle_node(editor: &EditorTestUtils) -> NodeId {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use graphene_std::vector::generator_nodes::rectangle;
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()
}
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);
}
fn compiled_nodes(editor: &EditorTestUtils) -> HashMap<Vec<NodeId>, 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 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("<path")), "the export should leave out the rectangle hidden when it was sent");
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the update sent after the export should be drawn");
}
#[tokio::test]
async fn an_export_leaves_what_the_viewport_shows_as_it_is() {
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
set_layer_visible(&mut editor, false);
send_export(&mut editor, FileType::Svg);
send_request(&mut editor);
run(&mut editor).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("<path")), "the export should show the document as the editor has it");
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the export changed the network the viewport shows");
}
#[tokio::test]
async fn an_export_shows_the_node_previewed_in_the_document() {
let mut editor = editor().await;
let below = editor.active_document().metadata().all_layers().next().unwrap().to_node();
editor.draw_ellipse(0., 0., 100., 100.).await;
editor.active_document_mut().network_interface.toggle_preview(below, &[]);
send_export(&mut editor, FileType::Svg);
run(&mut editor).await;
let exported = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.into_vec()).unwrap()),
_ => None,
});
assert!(
exported.is_some_and(|svg| svg.matches("<path").count() == 1),
"the export should show the previewed layer without the one above it"
);
}
#[tokio::test]
async fn an_export_runs_the_nodes_the_viewport_runs_for_the_same_document() {
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
let compiled = compiled_nodes(&editor);
send_export(&mut editor, FileType::Svg);
editor.runtime.update();
assert!(!editor.runtime.exports.is_empty(), "the export's network should be inserted");
assert_eq!(compiled_nodes(&editor), compiled, "the export compiled a node of the document anew");
}
#[tokio::test]
async fn a_node_an_export_inserted_before_its_network_update_still_gets_its_types() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use graphene_std::vector::bounding_box;
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
let rectangle = rectangle_node(&editor);
let content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
let node = NodeId::new();
let template = resolve_proto_node_type(bounding_box::IDENTIFIER).unwrap().default_node_template();
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.insert_node(node, template, &[]);
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(rectangle, 0), &[]);
network_interface.set_input(&content, NodeInput::node(node, 0), &[]);
send_export(&mut editor, FileType::Svg);
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
assert!(editor.active_document().network_interface.resolved_types.types.contains_key([node].as_slice()));
}
#[tokio::test]
async fn a_copied_group_runs_the_nodes_the_viewport_runs_for_the_layers_in_it() {
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
let mut editor = editor().await;
let group_folder_type = GroupFolderType::Layer;
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
let compiled = compiled_nodes(&editor);
editor.dispatch(ClipboardMessage::CopyLayers);
editor.runtime.update();
assert!(!editor.runtime.exports.is_empty(), "the group's network should be inserted");
let copied = compiled_nodes(&editor);
assert!(compiled.iter().all(|(path, node)| copied.get(path) == Some(node)), "the copy compiled a node of the document anew");
}
#[tokio::test]
async fn a_parked_export_holds_back_nothing_sent_after_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
add_traced_noise_layer(&mut editor).await;
send_export(&mut editor, FileType::Svg);
run(&mut editor).await;
editor.dispatch(Message::Wake);
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
let last = last_request(&editor);
set_layer_visible(&mut editor, false);
send_update(&mut editor);
run(&mut editor).await;
assert_ne!(last_request(&editor), last, "the parked export held back the request sent after it");
assert!(evaluated(&mut editor), "the request sent after the parked export was not evaluated");
}
#[tokio::test]
async fn an_export_that_finishes_after_what_was_sent_after_it_is_still_saved() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
add_traced_noise_layer(&mut editor).await;
send_export(&mut editor, FileType::Svg);
editor.runtime.update();
editor.runtime.run().await;
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
send_update(&mut editor);
let mut saved = false;
let mut runs = 0;
while !editor.runtime.exports.is_empty() {
editor.runtime.update();
editor.runtime.run().await;
saved |= exported(&mut editor);
runs += 1;
assert!(runs < 100_000, "the export never finished");
}
assert!(saved, "the export was lost");
}
#[tokio::test]
async fn two_exports_sent_together_are_both_saved() {
let mut editor = editor().await;
send_export(&mut editor, FileType::Svg);
send_export(&mut editor, FileType::Svg);
run(&mut editor).await;
let messages = editor.dispatch(Message::Wake);
let saved = messages.iter().filter(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }));
assert_eq!(saved.count(), 2);
}
#[tokio::test]
async fn a_failed_export_leaves_the_frame_that_follows_it_shown() {
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
send_export(&mut editor, FileType::Svg);
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");
assert!(!failed(&messages), "the failed export marked the viewport's render as failed");
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 cutting_a_layer_still_being_traced_writes_its_svg_once_the_trace_is_done() {
use crate::messages::portfolio::ingest::utility_types::TransferData;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
add_traced_noise_layer(&mut editor).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
send_update(&mut editor);
let mut runs = 0;
while editor.active_document().metadata().bounding_box_document(layer).is_none() {
run(&mut editor).await;
editor.dispatch(Message::Wake);
runs += 1;
assert!(runs < 100_000, "the trace never drew a shape");
}
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
editor.dispatch(ClipboardMessage::CutLayers);
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
run(&mut editor).await;
assert!(!editor.runtime.exports.is_empty(), "the copy took a single evaluation");
let mut written = None;
runs = 0;
while written.is_none() {
run(&mut editor).await;
written = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
});
runs += 1;
assert!(runs < 100_000, "the cut layer never reached the clipboard");
}
let svg = written.iter().flat_map(|content| &content.0).find_map(|item| match &item.data {
TransferData::Svg(svg) => Some(svg.as_str()),
_ => None,
});
assert!(svg.is_some_and(|svg| svg.contains("<path")), "the SVG should hold the shapes traced from the cut layer");
}
#[tokio::test]
async fn a_layer_copied_out_of_an_artboard_is_framed_in_the_space_the_artboard_gives_it() {
use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys;
use crate::messages::tool::utility_types::ToolType;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Artboard, 100., 50., 300., 250., ModifierKeys::empty()).await;
editor.draw_rect(120., 80., 160., 130.).await;
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected");
let document = editor.active_document();
let metadata = document.metadata();
let artboard = layer.parent(metadata).expect("the rectangle should be in the artboard");
assert!(document.network_interface.is_artboard(&artboard.to_node(), &[]));
let [artboard_min, _] = metadata.bounding_box_document(artboard).expect("the artboard has bounds");
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).expect("the rectangle has bounds");
assert!(artboard_min.length() > 1., "the artboard should be away from the origin");
let (_, [framed_min, framed_max]) = copied_layers(&document.network_interface, &[layer]).expect("the rectangle should be copied");
assert!(framed_min.abs_diff_eq(min - artboard_min, 1e-6), "{framed_min} should leave out where the artboard is");
assert!(framed_max.abs_diff_eq(max - artboard_min, 1e-6), "{framed_max} should leave out where the artboard is");
}
/// Feeds the rectangle into an 'Add' node, which takes numbers, so the graph compiles but fails to type check.
fn break_type_check(editor: &mut EditorTestUtils) {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use graphene_std::math_nodes::add;
let rectangle = rectangle_node(editor);
let content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
let add_node = NodeId::new();
let template = resolve_proto_node_type(add::IDENTIFIER).unwrap().default_node_template();
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.insert_node(add_node, template, &[]);
network_interface.set_input(&InputConnector::node_at_index(add_node, 0), NodeInput::node(rectangle, 0), &[]);
network_interface.set_input(&content, NodeInput::node(add_node, 0), &[]);
}
#[tokio::test]
async fn a_network_that_fails_to_type_check_leaves_no_output_and_keeps_the_last_one_that_did() {
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
let output = editor.runtime.output.as_ref().expect("the network should compile").node();
break_type_check(&mut editor);
send_update(&mut editor);
run(&mut editor).await;
assert!(editor.runtime.output.is_none(), "a rectangle should not type check as a number");
assert_eq!(editor.runtime.previous.as_ref().map(OutputHandle::node), Some(output));
}
#[tokio::test]
async fn a_layer_hidden_and_shown_again_finds_its_nodes_again() {
let mut editor = editor().await;
let rectangle = rectangle_node(&editor);
let compiled = |editor: &EditorTestUtils| {
let tree = editor.runtime.executor.tree();
tree.source_map().get([rectangle].as_slice()).and_then(|(node, _)| tree.get(*node))
};
send_update(&mut editor);
run(&mut editor).await;
let before = compiled(&editor).expect("the rectangle should be compiled");
for visible in [false, true] {
set_layer_visible(&mut editor, visible);
send_update(&mut editor);
run(&mut editor).await;
}
let after = compiled(&editor).expect("the rectangle should be compiled again");
assert!(Arc::ptr_eq(&before, &after), "the rectangle was built again");
}
#[tokio::test]
async fn a_graph_settles_while_network_updates_keep_arriving() {
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
let last = last_request(&editor);
for _ in 0..3 {
send_update(&mut editor);
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the finished task didn't evaluate the graph again");
assert_eq!(last_request(&editor), last, "run read the request");
}
editor.runtime.update();
assert_ne!(last_request(&editor), last);
assert!(editor.runtime.receiver.try_recv().is_err(), "update left a request in the channel");
editor.runtime.run().await;
assert!(evaluated(&mut editor));
}
#[tokio::test]
async fn several_network_updates_evaluate_once() {
let mut editor = editor().await;
for _ in 0..3 {
send_update(&mut editor);
}
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
editor.runtime.run().await;
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
}
/// A trace renders partial frames until it is done.
#[tokio::test]
async fn a_trace_renders_partial_frames() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
add_traced_noise_layer(&mut editor).await;
send_update_at(&mut editor, UVec2::splat(512));
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
assert!(
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Partial }),
"the trace's frame isn't partial"
);
}
#[test]
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
let previewed_node = NodeId(1);
let exported_node = NodeId(2);
let mut network = NodeNetwork {
exports: vec![NodeInput::node(exported_node, 0)],
nodes: [(previewed_node, DocumentNode::default()), (exported_node, DocumentNode::default())].into_iter().collect(),
..Default::default()
};
apply_previews(
&mut network,
&[(
Vec::new(),
RootNode {
node_id: previewed_node,
output_index: 0,
},
)],
);
assert_eq!(network.exports.first().and_then(|export| export.as_node()), Some(previewed_node));
}
}