mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Render a copy's SVG as an export of the copied layers' own network
This commit is contained in:
1 parent
deaee8aa80
commit
06285430f0
5 files changed
+341
-139
No files matched your search
@@ -665,6 +665,18 @@ mod test {
|
||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
|
||||
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
|
||||
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
|
||||
}
|
||||
|
||||
/// - paste
|
||||
/// - assert that ellipse was copied
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1124,18 +1124,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitClipboardSvg { id } => {
|
||||
let layers = self.active_document().map(|document| {
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|layer| selected.contains(layer))
|
||||
.map(|layer| layer.to_node())
|
||||
.collect::<Vec<_>>();
|
||||
layers.reverse();
|
||||
layers
|
||||
});
|
||||
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
|
||||
let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
|
||||
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||
return;
|
||||
};
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
|
||||
layers.reverse();
|
||||
responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::list;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
|
||||
use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
@@ -33,12 +37,6 @@ pub struct ExecutionRequest {
|
||||
render_config: RenderConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExportRequest {
|
||||
export_id: u64,
|
||||
render_config: RenderConfig,
|
||||
}
|
||||
|
||||
pub struct ExecutionResponse {
|
||||
execution_id: u64,
|
||||
result: ExecutionResult,
|
||||
@@ -118,10 +116,6 @@ pub enum NodeGraphUpdate {
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
svg: Option<String>,
|
||||
},
|
||||
Export {
|
||||
id: u64,
|
||||
result: Box<ExecutionResult>,
|
||||
@@ -138,7 +132,7 @@ pub struct NodeGraphExecutor {
|
||||
pending: Option<(u64, ExecutionContext)>,
|
||||
|
||||
current_export_id: u64,
|
||||
exports: HashMap<u64, ExportConfig>,
|
||||
exports: HashMap<u64, ExportTarget>,
|
||||
|
||||
node_graph_hash: u64,
|
||||
/// The document whose network the graph runtime was last sent.
|
||||
@@ -161,6 +155,12 @@ pub struct NodeGraphExecutor {
|
||||
gradient_migration_attempted: HashSet<DocumentId>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ExportTarget {
|
||||
File(ExportConfig),
|
||||
Clipboard(u64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ExecutionContext {
|
||||
document_id: DocumentId,
|
||||
@@ -227,6 +227,22 @@ impl NodeGraphExecutor {
|
||||
execution_id
|
||||
}
|
||||
|
||||
fn queue_export(&mut self, document: &DocumentMessageHandler, network: NodeNetwork, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
|
||||
let id = self.current_export_id;
|
||||
self.current_export_id += 1;
|
||||
let resources = document.resources.registry.clone();
|
||||
let request = GraphRuntimeRequest::Export {
|
||||
id,
|
||||
render_config,
|
||||
network,
|
||||
resources,
|
||||
};
|
||||
self.sender.send(request).map_err(|e| e.to_string())?;
|
||||
self.exports.insert(id, target);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
|
||||
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
|
||||
log::error!("Failed to send the overlays: {error}");
|
||||
@@ -245,13 +261,27 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the context overrides");
|
||||
}
|
||||
|
||||
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
||||
if document_id.is_none() || self.node_graph_document != document_id {
|
||||
return ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
}
|
||||
pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
|
||||
let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
let Some((network, [min, max])) = copied_layers(document, layers) else { return no_svg };
|
||||
|
||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
||||
Message::NoOp
|
||||
let viewport = Footprint {
|
||||
resolution: (max - min).round().as_uvec2(),
|
||||
transform: DAffine2::from_translation(-min),
|
||||
..Default::default()
|
||||
};
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: 1.,
|
||||
export_format: ExportFormat::Svg,
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match self.queue_export(document, network, render_config, ExportTarget::Clipboard(id)) {
|
||||
Ok(()) => Message::NoOp,
|
||||
Err(_) => no_svg,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||
@@ -430,9 +460,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
/// Evaluates a node graph for export
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let resources = document.resources.registry.clone();
|
||||
let network = network_as_compiled(&document.network_interface);
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
@@ -466,28 +494,12 @@ impl NodeGraphExecutor {
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed,
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let export_id = self.current_export_id;
|
||||
self.current_export_id += 1;
|
||||
self.sender.send(GraphRuntimeRequest::Export(ExportRequest { export_id, render_config })).map_err(|e| e.to_string())?;
|
||||
self.exports.insert(export_id, export_config);
|
||||
|
||||
Ok(())
|
||||
self.queue_export(document, network, render_config, ExportTarget::File(export_config))
|
||||
}
|
||||
|
||||
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
|
||||
@@ -759,7 +771,6 @@ impl NodeGraphExecutor {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
|
||||
}
|
||||
}
|
||||
@@ -1049,24 +1060,48 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(export_config) = self.exports.remove(&export_id) else { return };
|
||||
let Some(target) = self.exports.remove(&export_id) else { return };
|
||||
|
||||
let failure = match result {
|
||||
ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => return self.process_export(value, export_config, document, responses),
|
||||
ExecutionResult::Error(errors) => Some(errors.to_string()),
|
||||
ExecutionResult::Panic(payload) => {
|
||||
let failure = match (result, &target) {
|
||||
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
|
||||
return match target {
|
||||
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
|
||||
ExportTarget::Clipboard(id) => {
|
||||
let svg = match value {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => Some(svg),
|
||||
_ => None,
|
||||
};
|
||||
responses.add(ClipboardMessage::Rendered { id, svg });
|
||||
}
|
||||
};
|
||||
}
|
||||
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
|
||||
(ExecutionResult::Panic(payload), _) => {
|
||||
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
||||
Some(format!("Panicked: {}", message.unwrap_or("no message")))
|
||||
}
|
||||
ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled => None,
|
||||
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
|
||||
};
|
||||
if let Some(message) = &failure {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||
});
|
||||
|
||||
match target {
|
||||
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||
}),
|
||||
ExportTarget::Clipboard(id) => {
|
||||
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||
if let Some(description) = failure {
|
||||
let title = "Unable to copy as SVG".to_string();
|
||||
responses.add(DialogMessage::DisplayDialogError { title, description });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
@@ -1168,6 +1203,46 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
|
||||
}
|
||||
}
|
||||
|
||||
fn network_as_compiled(interface: &NodeNetworkInterface) -> NodeNetwork {
|
||||
let mut network = interface.document_network().clone();
|
||||
apply_previews(&mut network, &interface.previewed_nodes());
|
||||
write_layer_paths(&mut network, &interface.layer_paths());
|
||||
|
||||
network
|
||||
}
|
||||
|
||||
fn copied_layers(document: &DocumentMessageHandler, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
|
||||
let (interface, metadata) = (&document.network_interface, document.metadata());
|
||||
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
|
||||
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
|
||||
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
|
||||
artboards if artboards == layers.len() => list!(Artboard),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let mut network = network_as_compiled(interface);
|
||||
let mut below = NodeInput::type_default(stack, true);
|
||||
let mut bounds = None;
|
||||
for &layer in layers {
|
||||
let mut node = network.nodes.get(&layer.to_node())?.clone();
|
||||
*node.inputs.first_mut()? = below;
|
||||
let copy = NodeId::new();
|
||||
network.nodes.insert(copy, node);
|
||||
below = NodeInput::node(copy, 0);
|
||||
|
||||
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
|
||||
true => metadata.downstream_transform_to_document(layer).inverse(),
|
||||
false => DAffine2::IDENTITY,
|
||||
};
|
||||
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
|
||||
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
|
||||
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
|
||||
}
|
||||
network.exports = vec![below];
|
||||
|
||||
Some((network, bounds?))
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
|
||||
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
||||
|
||||
@@ -54,12 +54,13 @@ pub struct NodeRuntime {
|
||||
previous: Option<OutputHandle>,
|
||||
|
||||
pending: Option<ExecutionRequest>,
|
||||
pending_exports: Vec<(ExportRequest, OutputHandle)>,
|
||||
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>,
|
||||
|
||||
@@ -106,11 +107,21 @@ enum ViewportArtwork {
|
||||
pub enum GraphRuntimeRequest {
|
||||
GraphUpdate(GraphUpdate),
|
||||
ExecutionRequest(ExecutionRequest),
|
||||
ThumbnailsInView { layers: HashSet<NodeId>, document_id: DocumentId },
|
||||
Export(ExportRequest),
|
||||
ClipboardSvg { id: u64, layers: Vec<NodeId> },
|
||||
Export {
|
||||
id: u64,
|
||||
render_config: RenderConfig,
|
||||
network: NodeNetwork,
|
||||
resources: ResourceRegistry,
|
||||
},
|
||||
ThumbnailsInView {
|
||||
layers: HashSet<NodeId>,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
RenderOverlays(OverlayContext),
|
||||
Observe { key: ObservationKey, observation: Option<Observation> },
|
||||
Observe {
|
||||
key: ObservationKey,
|
||||
observation: Option<Observation>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -159,12 +170,13 @@ impl NodeRuntime {
|
||||
previous: None,
|
||||
|
||||
pending: None,
|
||||
pending_exports: Vec::new(),
|
||||
pending_eyedropper: None,
|
||||
pending_thumbnails: None,
|
||||
|
||||
viewport_artwork: None,
|
||||
|
||||
exports: Vec::new(),
|
||||
|
||||
old_graph: None,
|
||||
|
||||
async_runtime: None,
|
||||
@@ -238,13 +250,25 @@ impl NodeRuntime {
|
||||
self.pending = Some(request);
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
}
|
||||
GraphRuntimeRequest::Export(request) => match self.output.clone() {
|
||||
Some(output) => {
|
||||
self.pending_exports.push((request, output));
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
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.update_without_freeing(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),
|
||||
}
|
||||
None => self.send_export(request.export_id, ExecutionResult::Uncompiled),
|
||||
},
|
||||
}
|
||||
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => {
|
||||
self.thumbnails.set_in_view(layers);
|
||||
self.pending_thumbnails = Some(document_id);
|
||||
@@ -253,10 +277,6 @@ impl NodeRuntime {
|
||||
self.observer.set(key, observation);
|
||||
self.observations_changed = true;
|
||||
}
|
||||
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
|
||||
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
|
||||
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
||||
}
|
||||
GraphRuntimeRequest::RenderOverlays(context) => {
|
||||
self.overlays = Some(context);
|
||||
self.overlays_stale = true;
|
||||
@@ -270,8 +290,8 @@ impl NodeRuntime {
|
||||
let mut texture = None;
|
||||
|
||||
if dirty {
|
||||
for (request, output) in std::mem::take(&mut self.pending_exports) {
|
||||
self.run_export(request, output).await;
|
||||
for (id, render_config, output) in std::mem::take(&mut self.exports) {
|
||||
self.run_export(id, render_config, output).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,10 +397,10 @@ impl NodeRuntime {
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
async fn run_export(&mut self, request: ExportRequest, output: OutputHandle) {
|
||||
let mut result = self.execute(&output, request.render_config);
|
||||
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.pending_exports.push((request, output));
|
||||
self.exports.push((id, render_config, output));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -390,7 +410,7 @@ impl NodeRuntime {
|
||||
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
self.send_export(request.export_id, result);
|
||||
self.send_export(id, result);
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
@@ -682,7 +702,7 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Sends a network update and a request to export it, as the editor does for an export.
|
||||
/// Sends a request to export the document, as the editor does for an export.
|
||||
fn send_export(editor: &mut EditorTestUtils, file_type: FileType) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
@@ -753,6 +773,16 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
fn send_request(editor: &mut EditorTestUtils) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
portfolio
|
||||
.executor
|
||||
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn run(editor: &mut EditorTestUtils) -> Option<Texture> {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await
|
||||
@@ -1095,6 +1125,13 @@ mod tests {
|
||||
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;
|
||||
@@ -1115,6 +1152,77 @@ mod tests {
|
||||
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_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();
|
||||
@@ -1125,7 +1233,7 @@ mod tests {
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
assert!(!editor.runtime.pending_exports.is_empty(), "the export took a single evaluation");
|
||||
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
|
||||
|
||||
let last = last_request(&editor);
|
||||
set_layer_visible(&mut editor, false);
|
||||
@@ -1145,12 +1253,12 @@ mod tests {
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
assert!(!editor.runtime.pending_exports.is_empty(), "the export took a single evaluation");
|
||||
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.pending_exports.is_empty() {
|
||||
while !editor.runtime.exports.is_empty() {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
saved |= exported(&mut editor);
|
||||
@@ -1217,25 +1325,68 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_nodes_only_a_finished_export_kept_lose_their_types_at_the_next_network_update() {
|
||||
let mut editor = editor().await;
|
||||
let rectangle = rectangle_node(&editor);
|
||||
let typed = |editor: &EditorTestUtils| editor.active_document().network_interface.resolved_types.types.contains_key(&vec![rectangle]);
|
||||
async fn cutting_a_layer_still_being_traced_writes_its_svg_once_the_trace_is_done() {
|
||||
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
||||
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
set_layer_visible(&mut editor, false);
|
||||
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);
|
||||
editor.runtime.update();
|
||||
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");
|
||||
}
|
||||
|
||||
send_update(&mut editor);
|
||||
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!(exported(&mut editor));
|
||||
assert!(typed(&editor), "the rectangle's nodes should outlive the export until the network is updated");
|
||||
assert!(!editor.runtime.exports.is_empty(), "the copy took a single evaluation");
|
||||
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
assert!(!typed(&editor), "the hidden rectangle kept the type of the network the export held on to");
|
||||
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, &[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.
|
||||
|
||||
@@ -12,8 +12,8 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
use graphene_std::renderer::Render;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -276,11 +276,11 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images.
|
||||
fn content_bounds(&self) -> RenderBoundingBox {
|
||||
match self {
|
||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
|
||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||
@@ -289,7 +289,7 @@ impl ThumbnailContent {
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self) -> [DVec2; 2] {
|
||||
let bounds = match self.content_bounds(true) {
|
||||
let bounds = match self.content_bounds() {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||
_ => [DVec2::ZERO, DVec2::ONE],
|
||||
};
|
||||
@@ -297,38 +297,6 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
|
||||
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
||||
let contents: Vec<ThumbnailContent> = layers
|
||||
.iter()
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||
.collect();
|
||||
|
||||
let bounds = contents
|
||||
.iter()
|
||||
.filter_map(|content| match content.content_bounds(false) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
})
|
||||
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
||||
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
for content in &contents {
|
||||
content.graphic().render_svg(&mut render, &render_params);
|
||||
}
|
||||
if render.svg.is_empty() {
|
||||
return None;
|
||||
}
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
|
||||
Some(render.svg.to_svg_string())
|
||||
}
|
||||
|
||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
Reference in new issue
Block a user