mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a42db391e6 | ||
|
|
4e3dfcd7e0 | ||
|
|
ceeb8ed909 | ||
|
|
b3823aa4e6 | ||
|
|
5779dca840 |
No files matched your search
Generated
+2
-2
@@ -4842,9 +4842,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ollev"
|
||||
version = "0.1.2"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d77164e6c8fb386ee064104ab480578451b0fd106ca4c0a6988eb7ca4ed9ec4b"
|
||||
checksum = "9e858a872f7e5f74992f283fe52d9c184234e8505f316e6aa7822fa394b39d0a"
|
||||
dependencies = [
|
||||
"glam",
|
||||
]
|
||||
|
||||
+1
-1
@@ -271,7 +271,7 @@ tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.8", features = ["html_reports"] }
|
||||
gungraun = { version = "0.20" }
|
||||
ndarray = "0.17"
|
||||
ollev = "0.1.2"
|
||||
ollev = "0.2.0"
|
||||
dirs = "7.0"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
|
||||
@@ -6,7 +6,8 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeProgress, FrontendNodeType, FrontendRemoteCursor,
|
||||
NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -199,18 +200,6 @@ pub enum FrontendMessage {
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
/// A History panel step's captured image as an SVG, sent when the GPU is unavailable, which the panel shows wherever a row names `id`.
|
||||
UpdateHistoryThumbnail {
|
||||
id: String,
|
||||
svg: String,
|
||||
},
|
||||
/// A History panel step's captured image as straight RGBA pixels.
|
||||
UpdateHistoryThumbnailPixels {
|
||||
id: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: serde_bytes::ByteBuf,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
@@ -338,6 +327,9 @@ pub enum FrontendMessage {
|
||||
UpdateNodeGraphErrorDiagnostics {
|
||||
errors: Vec<NodeGraphErrorDiagnostic>,
|
||||
},
|
||||
UpdateNodeGraphProgress {
|
||||
progress: Vec<FrontendNodeProgress>,
|
||||
},
|
||||
UpdateVisibleNodes {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
|
||||
@@ -58,6 +58,10 @@ pub enum MouseCursorIcon {
|
||||
pub enum RenderStatus {
|
||||
#[default]
|
||||
Rendering,
|
||||
/// Rendering a frame computed from provisional data, while async work is in progress.
|
||||
Partial,
|
||||
/// Rendering a frame computed from substitute data, because part of the graph failed.
|
||||
Fallback,
|
||||
Error,
|
||||
Panic,
|
||||
}
|
||||
|
||||
@@ -461,6 +461,8 @@ pub struct NodeSection {
|
||||
/// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom.
|
||||
#[serde(rename = "contentWireContinues")]
|
||||
pub content_wire_continues: bool,
|
||||
/// How far the work in progress of the node has come from 0 to 1, shown in the section header with a button to cancel it (none when it has no work in progress).
|
||||
pub progress: Option<f64>,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose Inspector section this is.
|
||||
@@ -533,6 +535,7 @@ impl LayoutGroup {
|
||||
node_reference: false,
|
||||
content_wire: None,
|
||||
content_wire_continues: false,
|
||||
progress: None,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -647,6 +650,7 @@ impl Diffable for LayoutGroup {
|
||||
node_reference: current_node_reference,
|
||||
content_wire: current_content_wire,
|
||||
content_wire_continues: current_content_wire_continues,
|
||||
progress: current_progress,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
@@ -663,6 +667,7 @@ impl Diffable for LayoutGroup {
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
progress: new_progress,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -682,6 +687,7 @@ impl Diffable for LayoutGroup {
|
||||
|| *current_node_reference != new_node_reference
|
||||
|| *current_content_wire != new_content_wire
|
||||
|| *current_content_wire_continues != new_content_wire_continues
|
||||
|| *current_progress != new_progress
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
@@ -697,6 +703,7 @@ impl Diffable for LayoutGroup {
|
||||
*current_node_reference = new_node_reference;
|
||||
*current_content_wire = new_content_wire;
|
||||
*current_content_wire_continues = new_content_wire_continues;
|
||||
*current_progress = new_progress;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
@@ -714,6 +721,7 @@ impl Diffable for LayoutGroup {
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
progress: new_progress,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
|
||||
@@ -224,6 +224,9 @@ pub enum DocumentMessage {
|
||||
layers: Vec<NodeId>,
|
||||
layers_missing_details: Vec<NodeId>,
|
||||
},
|
||||
CancelNodeWork {
|
||||
node_id: NodeId,
|
||||
},
|
||||
SetNodePinned {
|
||||
node_id: NodeId,
|
||||
pinned: bool,
|
||||
|
||||
@@ -1577,6 +1577,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::SendLayerPanelDetails { layers: layers_missing_details });
|
||||
}
|
||||
}
|
||||
DocumentMessage::CancelNodeWork { node_id } => {
|
||||
let node_path = [self.selection_network_path.as_slice(), &[node_id]].concat();
|
||||
responses.add(PortfolioMessage::CancelNodeWork { node_path });
|
||||
}
|
||||
DocumentMessage::SetNodePinned { node_id, pinned } => {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
|
||||
|
||||
@@ -345,6 +345,10 @@ pub enum NodeGraphMessage {
|
||||
UpdateEvaluationErrors {
|
||||
errors: Vec<NodeEvaluationError>,
|
||||
},
|
||||
/// The progress of the nodes with work in progress, by their full path from the root network.
|
||||
UpdateNodeProgress {
|
||||
progress: Vec<(Vec<NodeId>, f64)>,
|
||||
},
|
||||
UpdateActionButtons,
|
||||
UpdateGraphBarRight,
|
||||
UpdateInSelectedNetwork,
|
||||
@@ -457,6 +461,7 @@ impl NodeGraphMessage {
|
||||
| Self::UpdateNewNodeGraph
|
||||
| Self::UpdateTypes { .. }
|
||||
| Self::UpdateEvaluationErrors { .. }
|
||||
| Self::UpdateNodeProgress { .. }
|
||||
| Self::UpdateActionButtons
|
||||
| Self::UpdateGraphBarRight
|
||||
| Self::UpdateInSelectedNetwork
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, FrontendNodeProgress, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
@@ -136,6 +136,8 @@ pub struct NodeGraphMessageHandler {
|
||||
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
|
||||
frontend_wires: HashSet<(NodeId, usize)>,
|
||||
evaluation_errors: Vec<NodeEvaluationError>,
|
||||
/// The progress of the nodes with work in progress, by their full path from the root network.
|
||||
node_progress: Vec<(Vec<NodeId>, f64)>,
|
||||
}
|
||||
|
||||
/// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network.
|
||||
@@ -2074,6 +2076,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(FrontendMessage::UpdateNetworkReadOnly {
|
||||
read_only: network_interface.is_read_only(breadcrumb_network_path),
|
||||
});
|
||||
let progress = self.node_graph_progress(breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
|
||||
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
@@ -2680,6 +2684,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::UpdateNodeProgress { progress } => {
|
||||
if self.node_progress != progress {
|
||||
self.node_progress = progress;
|
||||
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
|
||||
let progress = self.node_graph_progress(breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::UpdateActionButtons => {
|
||||
if selection_network_path == breadcrumb_network_path {
|
||||
self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses);
|
||||
@@ -3900,6 +3913,22 @@ impl NodeGraphMessageHandler {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The progress of the nodes in the network at `breadcrumb_network_path`, where a node shows the first work in progress within it.
|
||||
fn node_graph_progress(&self, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNodeProgress> {
|
||||
let depth = breadcrumb_network_path.len();
|
||||
|
||||
let mut shown = HashSet::new();
|
||||
self.node_progress
|
||||
.iter()
|
||||
.filter(|(path, _)| path.starts_with(breadcrumb_network_path) && path.len() > depth)
|
||||
.filter(|(path, _)| shown.insert(path[depth]))
|
||||
.map(|(path, progress)| FrontendNodeProgress {
|
||||
node_id: path[depth],
|
||||
progress: *progress,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view.
|
||||
// O(given layers × nesting depth), apart from what the active tool would edit in the selected layers
|
||||
fn update_layer_panel(
|
||||
@@ -4109,6 +4138,7 @@ impl Default for NodeGraphMessageHandler {
|
||||
frontend_nodes: Vec::new(),
|
||||
frontend_wires: HashSet::new(),
|
||||
evaluation_errors: Vec::new(),
|
||||
node_progress: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3316,6 +3316,7 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let mut section = LayoutGroup::section(name, icon, description, visible, pinned, expanded, node_id.0, Layout(layout));
|
||||
if let LayoutGroup::NodeSection(node_section) = &mut section {
|
||||
node_section.chain_wire = chain_wire;
|
||||
node_section.progress = context.executor.node_progress(&[network_path, &[node_id]].concat());
|
||||
}
|
||||
section
|
||||
}
|
||||
|
||||
@@ -202,6 +202,15 @@ pub struct NodeGraphErrorDiagnostic {
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendNodeProgress {
|
||||
#[serde(rename = "nodeId")]
|
||||
pub node_id: NodeId,
|
||||
/// How much of the work within the node is done, from 0 to 1.
|
||||
pub progress: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeEvaluationError {
|
||||
pub node_path: Vec<NodeId>,
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
//! Tints what a step changed onto a close-up of the document, colored by how the layer under each changed pixel changed.
|
||||
|
||||
use super::utility_types::Pixels;
|
||||
use glam::{DVec2, UVec2};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
Added,
|
||||
Removed,
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// Where a layer's change shows, in document coordinates.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ChangedArea {
|
||||
pub change: Change,
|
||||
pub bounds: [DVec2; 2],
|
||||
}
|
||||
|
||||
/// How far apart two premultiplied channels must be for a pixel to count as changed, out of 255.
|
||||
const THRESHOLD: u8 = 16;
|
||||
/// How much of a tint's color covers a changed pixel.
|
||||
const TINT_STRENGTH: f32 = 0.6;
|
||||
/// How opaque unchanged pixels stay, so the tints stand out.
|
||||
const UNCHANGED_OPACITY: f32 = 0.35;
|
||||
|
||||
fn tint_color(change: Change) -> [u8; 3] {
|
||||
match change {
|
||||
Change::Added => [64, 200, 96],
|
||||
Change::Removed => [232, 64, 64],
|
||||
Change::Changed => [240, 176, 32],
|
||||
}
|
||||
}
|
||||
|
||||
/// The close-up `after` of `frame` with each pixel that differs from `before`, the whole document before the step
|
||||
/// showing `before_frame`, tinted by the change of the area it falls in. A pixel that lost coverage shows as it was.
|
||||
pub fn tint_changes(after: &Pixels, frame: [DVec2; 2], before: &Pixels, before_frame: [DVec2; 2], areas: &[ChangedArea]) -> Pixels {
|
||||
let size = after.size;
|
||||
let mut rgba = Vec::with_capacity(after.rgba.len());
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let point = frame[0] + (DVec2::new(x as f64, y as f64) + 0.5) / size.as_dvec2() * (frame[1] - frame[0]);
|
||||
let now = pixel(after, UVec2::new(x, y));
|
||||
let then = sample(before, before_frame, point);
|
||||
let shown = if differs(now, then) {
|
||||
let lost = now[3] < then[3];
|
||||
tint(if lost { then } else { now }, change_at(areas, point, lost))
|
||||
} else {
|
||||
[now[0], now[1], now[2], (now[3] as f32 * UNCHANGED_OPACITY) as u8]
|
||||
};
|
||||
rgba.extend_from_slice(&shown);
|
||||
}
|
||||
}
|
||||
Pixels { size, rgba }
|
||||
}
|
||||
|
||||
/// The area around every change, with a margin, at the thumbnails' aspect ratio. None when nothing changed.
|
||||
pub fn close_up(areas: &[ChangedArea]) -> Option<[DVec2; 2]> {
|
||||
/// The thumbnails' width over their height.
|
||||
const ASPECT_RATIO: f64 = 1.5;
|
||||
|
||||
let [min, max] = areas.iter().map(|area| area.bounds).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])?;
|
||||
let margin = ((max - min) * 0.15).max(DVec2::splat(4.));
|
||||
let (min, max) = (min - margin, max + margin);
|
||||
|
||||
let size = max - min;
|
||||
let size = if size.x >= size.y * ASPECT_RATIO {
|
||||
DVec2::new(size.x, size.x / ASPECT_RATIO)
|
||||
} else {
|
||||
DVec2::new(size.y * ASPECT_RATIO, size.y)
|
||||
};
|
||||
let center = (min + max) / 2.;
|
||||
Some([center - size / 2., center + size / 2.])
|
||||
}
|
||||
|
||||
/// The change of the areas holding `point`, preferring a removal where the pixel lost coverage and an addition elsewhere.
|
||||
fn change_at(areas: &[ChangedArea], point: DVec2, lost: bool) -> Change {
|
||||
let holding = |change: Change| areas.iter().any(|area| area.change == change && contains(area.bounds, point));
|
||||
let order = match lost {
|
||||
true => [Change::Removed, Change::Changed, Change::Added],
|
||||
false => [Change::Added, Change::Changed, Change::Removed],
|
||||
};
|
||||
order.into_iter().find(|&change| holding(change)).unwrap_or(Change::Changed)
|
||||
}
|
||||
|
||||
fn contains(bounds: [DVec2; 2], point: DVec2) -> bool {
|
||||
point.cmpge(bounds[0]).all() && point.cmple(bounds[1]).all()
|
||||
}
|
||||
|
||||
fn pixel(pixels: &Pixels, at: UVec2) -> [u8; 4] {
|
||||
let index = (at.y * pixels.size.x + at.x) as usize * 4;
|
||||
pixels.rgba.get(index..index + 4).and_then(|pixel| pixel.try_into().ok()).unwrap_or([0; 4])
|
||||
}
|
||||
|
||||
/// The pixel of `pixels`, which shows `frame`, at a document point, transparent outside it.
|
||||
fn sample(pixels: &Pixels, frame: [DVec2; 2], point: DVec2) -> [u8; 4] {
|
||||
let at = (point - frame[0]) / (frame[1] - frame[0]) * pixels.size.as_dvec2();
|
||||
if at.cmplt(DVec2::ZERO).any() || at.cmpge(pixels.size.as_dvec2()).any() {
|
||||
return [0; 4];
|
||||
}
|
||||
pixel(pixels, at.as_uvec2())
|
||||
}
|
||||
|
||||
fn differs(a: [u8; 4], b: [u8; 4]) -> bool {
|
||||
let premultiplied = |pixel: [u8; 4]| pixel.map(|channel| (channel as u16 * pixel[3] as u16 / 255) as u8);
|
||||
let (a, b) = (premultiplied(a), premultiplied(b));
|
||||
a.iter().zip(&b).any(|(a, b)| a.abs_diff(*b) > THRESHOLD) || a[3].abs_diff(b[3]) > THRESHOLD
|
||||
}
|
||||
|
||||
fn tint(pixel: [u8; 4], change: Change) -> [u8; 4] {
|
||||
let color = tint_color(change);
|
||||
let mix = |channel: u8, tint: u8| (channel as f32 + (tint as f32 - channel as f32) * TINT_STRENGTH) as u8;
|
||||
[mix(pixel[0], color[0]), mix(pixel[1], color[1]), mix(pixel[2], color[2]), pixel[3]]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FRAME: [DVec2; 2] = [DVec2::ZERO, DVec2::new(4., 2.)];
|
||||
const CLEAR: [u8; 4] = [0; 4];
|
||||
const WHITE: [u8; 4] = [255; 4];
|
||||
|
||||
/// A 4×2 image of the given pixels, row by row.
|
||||
fn image(pixels: [[u8; 4]; 8]) -> Pixels {
|
||||
Pixels {
|
||||
size: UVec2::new(4, 2),
|
||||
rgba: pixels.concat(),
|
||||
}
|
||||
}
|
||||
|
||||
fn left_half(change: Change) -> ChangedArea {
|
||||
ChangedArea {
|
||||
change,
|
||||
bounds: [DVec2::ZERO, DVec2::new(2., 2.)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_stayed_fades_and_what_came_is_tinted_as_added() {
|
||||
let before = image([CLEAR; 8]);
|
||||
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Added)]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Added));
|
||||
assert_eq!(pixel(&tinted, UVec2::new(3, 1))[3], 0, "transparent pixels that stayed stay transparent");
|
||||
|
||||
let unchanged = tint_changes(&after, FRAME, &after, FRAME, &[]);
|
||||
assert_eq!(pixel(&unchanged, UVec2::new(0, 0))[3], (255. * UNCHANGED_OPACITY) as u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_went_shows_as_it_was_tinted_as_removed() {
|
||||
let before = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let after = image([CLEAR; 8]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Removed)]);
|
||||
|
||||
let removed = pixel(&tinted, UVec2::new(1, 1));
|
||||
assert_eq!(removed, tint(WHITE, Change::Removed));
|
||||
assert_eq!(removed[3], 255, "a removed pixel keeps the coverage it had");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_layer_is_tinted_as_changed_where_it_was_and_where_it_is() {
|
||||
let before = image([WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
|
||||
let after = image([CLEAR, WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Changed)]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Changed), "where it was");
|
||||
assert_eq!(pixel(&tinted, UVec2::new(1, 0)), tint(WHITE, Change::Changed), "where it is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_close_up_samples_the_whole_document_before_at_its_own_scale() {
|
||||
// The before image shows twice the area, so its left pixel column covers the close-up's left two
|
||||
let before = image([WHITE, CLEAR, CLEAR, CLEAR, WHITE, CLEAR, CLEAR, CLEAR]);
|
||||
let before_frame = [DVec2::ZERO, DVec2::new(8., 4.)];
|
||||
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, before_frame, &[]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(1, 0))[3], (255. * UNCHANGED_OPACITY) as u8, "still covered, so unchanged");
|
||||
assert_eq!(pixel(&tinted, UVec2::new(2, 0))[3], 0);
|
||||
}
|
||||
}
|
||||
@@ -5,39 +5,14 @@ use crate::messages::prelude::*;
|
||||
pub enum HistoryMessage {
|
||||
Refresh,
|
||||
Tick,
|
||||
Expand {
|
||||
id: String,
|
||||
expanded: bool,
|
||||
},
|
||||
Expand { id: String, expanded: bool },
|
||||
LoadMore,
|
||||
GoBack {
|
||||
id: String,
|
||||
},
|
||||
RemoveStep {
|
||||
id: String,
|
||||
},
|
||||
BringBack {
|
||||
id: String,
|
||||
},
|
||||
Follow {
|
||||
id: Option<String>,
|
||||
},
|
||||
Preview {
|
||||
id: Option<String>,
|
||||
},
|
||||
GoBack { id: String },
|
||||
RemoveStep { id: String },
|
||||
BringBack { id: String },
|
||||
Follow { id: Option<String> },
|
||||
Preview { id: Option<String> },
|
||||
RetirePending,
|
||||
Rename {
|
||||
id: String,
|
||||
label: String,
|
||||
},
|
||||
Tag {
|
||||
id: String,
|
||||
tag: String,
|
||||
on: bool,
|
||||
},
|
||||
Captured {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
capture: Option<Box<super::utility_types::DocumentCapture>>,
|
||||
},
|
||||
Rename { id: String, label: String },
|
||||
Tag { id: String, tag: String, on: bool },
|
||||
}
|
||||
@@ -1,22 +1,19 @@
|
||||
use super::changes::{Change, ChangedArea, close_up, tint_changes};
|
||||
use super::utility_types::{CaptureImage, DocumentCapture, HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow, HistoryThumbnail, LineChange, Pixels};
|
||||
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow, LineChange};
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_proto_node_definition};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
|
||||
use crate::messages::portfolio::sync::now_ms;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use document_format::GddV1;
|
||||
use document_graph_storage::attr::{delta as delta_attr, network as network_attr, node as node_attr, session as session_attr};
|
||||
use document_graph_storage::{
|
||||
AttributeDelta, Declarations, Delta, HistoryMetadata, HotOp, HotOpId, Implementation, InputMetadataEntry, Node, NodeId, PeerId, Registry, RegistryDelta, Rev, Session, Subject, TimeStamp, UserId,
|
||||
Value, coarsen, rev_attr,
|
||||
AttributeDelta, Declarations, Delta, HistoryMetadata, HotOp, HotOpId, Implementation, InputMetadataEntry, Node, NodeId, PeerId, Registry, RegistryDelta, Rev, Session, Subject, UserId, Value,
|
||||
coarsen, rev_attr,
|
||||
};
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use peer_transport::RemotePeer;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
@@ -24,7 +21,6 @@ pub struct HistoryMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
pub panel_open: bool,
|
||||
pub executor: &'a NodeGraphExecutor,
|
||||
}
|
||||
|
||||
/// Sends the History panel the active document's history and turns its actions into head moves.
|
||||
@@ -37,61 +33,10 @@ pub struct HistoryMessageHandler {
|
||||
/// The head last sent, to stop following a branch once the head moves.
|
||||
seen_head: Option<Rev>,
|
||||
last_sent: Option<u64>,
|
||||
/// Each document's steps as they looked once done, captured while the panel was open, by the stamp of their newest change.
|
||||
captures: HashMap<DocumentId, HashMap<TimeStamp, Capture>>,
|
||||
/// The one capture asked for and not yet back.
|
||||
requested: Option<(DocumentId, TimeStamp)>,
|
||||
/// The past state asked for, kept to ask for its close-up.
|
||||
past: Option<PastState>,
|
||||
/// The steps whose past state didn't render, which aren't asked for again.
|
||||
failed: HashSet<(DocumentId, TimeStamp)>,
|
||||
/// Counts the images the frontend got, so the panel is sent again once a step's capture or its close-up arrives.
|
||||
images_sent: u64,
|
||||
}
|
||||
|
||||
/// A step's document as history folds it, for rendering a step captured neither live nor before.
|
||||
#[derive(Debug)]
|
||||
struct PastState {
|
||||
step: TimeStamp,
|
||||
network: graph_craft::document::NodeNetwork,
|
||||
/// Full path from the root network to every layer.
|
||||
layers: Vec<Vec<graph_craft::document::NodeId>>,
|
||||
/// The layers holding other layers, as groups and artboards do.
|
||||
containers: HashSet<graph_craft::document::NodeId>,
|
||||
}
|
||||
|
||||
/// What a captured step showed. The frontend keeps its images.
|
||||
#[derive(Debug)]
|
||||
struct Capture {
|
||||
frame: [DVec2; 2],
|
||||
layers: BTreeMap<graph_craft::document::NodeId, LayerShot>,
|
||||
/// The whole document's pixels, kept by the newest few captures for the steps after them to compare with.
|
||||
pixels: Option<Pixels>,
|
||||
/// The frontend got a close-up of what the step changed.
|
||||
detailed: bool,
|
||||
/// The area to render close up once the document shows this step and no tool is mid-gesture.
|
||||
close_up: Option<[DVec2; 2]>,
|
||||
/// Orders the captures so the oldest is dropped first.
|
||||
taken: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct LayerShot {
|
||||
bounds: Option<[DVec2; 2]>,
|
||||
/// Changes with what the layer itself shows.
|
||||
source: Option<graph_craft::document::NodeId>,
|
||||
/// A group or artboard, which changes with its children and is only shown coming and going.
|
||||
container: bool,
|
||||
}
|
||||
|
||||
/// How many interactions each request adds.
|
||||
const PAGE: usize = 100;
|
||||
/// The most recent captures kept for each document, as many as the frontend keeps images.
|
||||
const MAX_CAPTURES: usize = 300;
|
||||
/// How many of the newest captures keep their pixels.
|
||||
const PIXELS_KEPT: usize = 16;
|
||||
/// How many of the newest steps are rendered from their past state when they weren't captured.
|
||||
const PAST_STEPS: usize = 24;
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
|
||||
@@ -110,23 +55,9 @@ impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessag
|
||||
}
|
||||
HistoryMessage::Tick => {
|
||||
if context.panel_open {
|
||||
self.request_capture(&context);
|
||||
self.send(&context, responses);
|
||||
}
|
||||
}
|
||||
HistoryMessage::Captured { document_id, step, capture } => {
|
||||
if self.requested == Some((document_id, step)) {
|
||||
self.requested = None;
|
||||
}
|
||||
match capture {
|
||||
Some(capture) => self.receive_capture(document_id, step, *capture, &context, responses),
|
||||
None if self.past.as_ref().is_some_and(|past| past.step == step) => {
|
||||
self.past = None;
|
||||
self.failed.insert((document_id, step));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
HistoryMessage::Expand { id, expanded } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
match expanded {
|
||||
@@ -195,155 +126,6 @@ impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessag
|
||||
}
|
||||
|
||||
impl HistoryMessageHandler {
|
||||
/// Asks for the newest step to be captured once no tool is mid-gesture and no past step is previewed, since a capture
|
||||
/// shows the document as it renders now, and once it is, for the steps before it that weren't. One capture is asked for
|
||||
/// at a time.
|
||||
fn request_capture(&mut self, context: &HistoryMessageContext) {
|
||||
self.captures.retain(|id, _| context.documents.contains_key(id));
|
||||
let Some(document_id) = context.active_document_id else { return };
|
||||
let Some(document) = context.documents.get(&document_id) else { return };
|
||||
if self.requested.is_some() || document.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
let Some(step) = document.storage().and_then(|gdd| current_stamp(gdd.session())) else { return };
|
||||
// The whole document until the step is captured, then its close-up, with `None` asking for the whole document
|
||||
let live_render = match self.captures.get(&document_id).and_then(|captures| captures.get(&step)) {
|
||||
None => Some(None),
|
||||
Some(own) if !own.detailed => own.close_up.map(Some),
|
||||
Some(_) => None,
|
||||
};
|
||||
let shows_current_step = document.previewed_history_step().is_none();
|
||||
if shows_current_step && let Some(close_up) = live_render {
|
||||
if context.executor.submit_document_capture(document, document_id, step, close_up) {
|
||||
self.requested = Some((document_id, step));
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.request_past_capture(document_id, document, context.executor);
|
||||
}
|
||||
|
||||
/// Asks for the newest step in history without a capture to be rendered from its past state, starting with the oldest
|
||||
/// of them, so each close-up can compare with the step before it.
|
||||
fn request_past_capture(&mut self, document_id: DocumentId, document: &DocumentMessageHandler, executor: &NodeGraphExecutor) {
|
||||
let Some(gdd) = document.storage() else { return };
|
||||
let captures = self.captures.get(&document_id);
|
||||
let missing = recent_steps(gdd.session(), PAST_STEPS)
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|&(_, step)| captures.is_none_or(|captures| !captures.contains_key(&step)) && !self.failed.contains(&(document_id, step)));
|
||||
let Some((rev, step)) = missing else { return };
|
||||
let Some(past) = past_state(gdd, document.declarations(), rev, step) else {
|
||||
self.failed.insert((document_id, step));
|
||||
return;
|
||||
};
|
||||
if executor.submit_past_capture(document_id, step, past.network.clone(), past.layers.clone(), None) {
|
||||
self.requested = Some((document_id, step));
|
||||
self.past = Some(past);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a capture that still shows its step, with where each layer was, and gives the frontend its image. When the
|
||||
/// step before kept its pixels, notes the area that changed to be rendered close up, which comes back to be tinted by
|
||||
/// how it changed. A past state asks for it at once, while the document waits until it shows the step with no tool
|
||||
/// mid-gesture.
|
||||
fn receive_capture(&mut self, document_id: DocumentId, step: TimeStamp, capture: DocumentCapture, context: &HistoryMessageContext, responses: &mut VecDeque<Message>) {
|
||||
let Some(document) = context.documents.get(&document_id) else { return };
|
||||
let Some(session) = document.storage().map(GddV1::session) else { return };
|
||||
let past = self.past.take_if(|past| past.step == step);
|
||||
if past.is_none() && current_stamp(session) != Some(step) {
|
||||
return;
|
||||
}
|
||||
let captures = self.captures.entry(document_id).or_default();
|
||||
let before = parent_stamp(session, step)
|
||||
.and_then(|parent| captures.get(&parent))
|
||||
.and_then(|before| Some((before, before.pixels.as_ref()?)));
|
||||
|
||||
if let Some(own) = captures.get(&step) {
|
||||
let tinted = before.zip(capture.detail).and_then(|((before, before_pixels), (frame, image))| match image {
|
||||
CaptureImage::Pixels(close_up) => Some(tint_changes(&close_up, frame, before_pixels, before.frame, &changed_areas(&before.layers, &own.layers))),
|
||||
CaptureImage::Svg(_) => None,
|
||||
});
|
||||
if let Some(own) = captures.get_mut(&step) {
|
||||
own.close_up = None;
|
||||
own.detailed = tinted.is_some();
|
||||
}
|
||||
let Some(tinted) = tinted else { return };
|
||||
responses.add(image_message(detail_id(step), CaptureImage::Pixels(tinted)));
|
||||
self.images_sent += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
// The runtime measures layers alike for every state, and a past one has no metadata to measure them from
|
||||
let bounds = |node: &graph_craft::document::NodeId, metadata: Option<[DVec2; 2]>| match &capture.layer_bounds {
|
||||
Some(layer_bounds) => layer_bounds.get(node).copied(),
|
||||
None => metadata,
|
||||
};
|
||||
let layers: BTreeMap<_, _> = match &past {
|
||||
Some(past) => past
|
||||
.layers
|
||||
.iter()
|
||||
.filter_map(|path| path.last())
|
||||
.map(|node| {
|
||||
let shot = LayerShot {
|
||||
bounds: bounds(node, None),
|
||||
source: capture.layer_sources.get(node).copied(),
|
||||
container: past.containers.contains(node),
|
||||
};
|
||||
(*node, shot)
|
||||
})
|
||||
.collect(),
|
||||
None => {
|
||||
let metadata = document.metadata();
|
||||
metadata
|
||||
.all_layers()
|
||||
.map(|layer| {
|
||||
let node = layer.to_node();
|
||||
let shot = LayerShot {
|
||||
bounds: bounds(&node, metadata.bounding_box_document(layer)),
|
||||
source: capture.layer_sources.get(&node).copied(),
|
||||
container: layer.has_children(metadata) || document.network_interface.is_artboard(&node, &[]),
|
||||
};
|
||||
(node, shot)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let pixels = match &capture.image {
|
||||
CaptureImage::Pixels(pixels) => Some(pixels.clone()),
|
||||
CaptureImage::Svg(_) => None,
|
||||
};
|
||||
let detail = before.filter(|_| pixels.is_some()).and_then(|(before, _)| close_up(&changed_areas(&before.layers, &layers)));
|
||||
|
||||
let taken = captures.values().map(|capture| capture.taken + 1).max().unwrap_or(0);
|
||||
if captures.len() >= MAX_CAPTURES
|
||||
&& let Some(&oldest) = captures.iter().min_by_key(|(_, capture)| capture.taken).map(|(stamp, _)| stamp)
|
||||
{
|
||||
captures.remove(&oldest);
|
||||
}
|
||||
if let Some(oldest_kept) = taken.checked_sub(PIXELS_KEPT as u64) {
|
||||
captures.values_mut().filter(|capture| capture.taken <= oldest_kept).for_each(|capture| capture.pixels = None);
|
||||
}
|
||||
let own = Capture {
|
||||
frame: capture.frame,
|
||||
layers,
|
||||
pixels,
|
||||
detailed: false,
|
||||
close_up: detail.filter(|_| past.is_none()),
|
||||
taken,
|
||||
};
|
||||
captures.insert(step, own);
|
||||
responses.add(image_message(shot_id(step), capture.image));
|
||||
self.images_sent += 1;
|
||||
|
||||
if let Some(past) = past
|
||||
&& let Some(detail) = detail
|
||||
&& context.executor.submit_past_capture(document_id, step, past.network.clone(), past.layers.clone(), Some(detail))
|
||||
{
|
||||
self.past = Some(past);
|
||||
self.requested = Some((document_id, step));
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>) {
|
||||
let document = context.active_document_id.and_then(|id| context.documents.get(&id));
|
||||
let gdd = document.and_then(|document| document.storage());
|
||||
@@ -356,8 +138,7 @@ impl HistoryMessageHandler {
|
||||
|
||||
let previewing = document.and_then(|document| document.previewed_history_step());
|
||||
let limit = self.limit.max(PAGE);
|
||||
let captures = context.active_document_id.and_then(|id| self.captures.get(&id));
|
||||
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following, previewing, self.images_sent);
|
||||
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following, previewing);
|
||||
if self.last_sent == Some(fingerprint) {
|
||||
return;
|
||||
}
|
||||
@@ -366,7 +147,7 @@ impl HistoryMessageHandler {
|
||||
.zip(gdd)
|
||||
.map(|(document, gdd)| HistoryPanelState {
|
||||
previewing: previewing.map(|rev| rev.to_string()),
|
||||
..panel_state(gdd, document.declarations(), captures, limit, &self.expanded, self.following)
|
||||
..panel_state(gdd, document.declarations(), limit, &self.expanded, self.following)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state });
|
||||
@@ -409,9 +190,9 @@ pub(crate) fn place(session: &Session, rev: Rev) -> Option<Place> {
|
||||
}
|
||||
|
||||
/// A hash of the panel's inputs, cheap enough for every frame.
|
||||
fn fingerprint(document_id: Option<DocumentId>, gdd: Option<&GddV1>, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>, previewing: Option<Rev>, images_sent: u64) -> u64 {
|
||||
fn fingerprint(document_id: Option<DocumentId>, gdd: Option<&GddV1>, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>, previewing: Option<Rev>) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
(document_id, limit, expanded, following, previewing, images_sent).hash(&mut hasher);
|
||||
(document_id, limit, expanded, following, previewing).hash(&mut hasher);
|
||||
if let Some(gdd) = gdd {
|
||||
let session = gdd.session();
|
||||
(session.history_len(), session.head_rev(), session.redo_stack(), session.hot_log().len(), session.pending_action()).hash(&mut hasher);
|
||||
@@ -425,7 +206,7 @@ fn fingerprint(document_id: Option<DocumentId>, gdd: Option<&GddV1>, limit: usiz
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn panel_state(gdd: &GddV1, declarations: &Declarations, captures: Option<&HashMap<TimeStamp, Capture>>, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
fn panel_state(gdd: &GddV1, declarations: &Declarations, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
let session = gdd.session();
|
||||
let names = Names {
|
||||
registry: gdd.registry(),
|
||||
@@ -462,7 +243,6 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, captures: Option<&HashM
|
||||
head,
|
||||
people: &people,
|
||||
names: &names,
|
||||
captures,
|
||||
expanded,
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
@@ -474,7 +254,7 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, captures: Option<&HashM
|
||||
let collaborating = gdd.peers().next().is_some();
|
||||
HistoryPanelState {
|
||||
rows,
|
||||
progress: progress_rows(session, &people, &names, captures),
|
||||
progress: progress_rows(session, &people, &names),
|
||||
more,
|
||||
following: following.map(|tip| tip.to_string()),
|
||||
previewing: None,
|
||||
@@ -483,27 +263,7 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, captures: Option<&HashM
|
||||
}
|
||||
|
||||
/// Open interactions first, then closed ones waiting to retire, newest first.
|
||||
fn progress_rows(session: &Session, people: &People, names: &Names, captures: Option<&HashMap<TimeStamp, Capture>>) -> Vec<HistoryProgressRow> {
|
||||
hot_steps(session)
|
||||
.into_iter()
|
||||
.map(|step| {
|
||||
let thumbnail = newest_change(step.ops.iter().copied()).and_then(|stamp| thumbnail(captures?, stamp));
|
||||
progress_row(people, names, step.author, &retired_kinds(step.ops), step.open, step.action, thumbnail)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A step still in the hot log.
|
||||
struct HotStep<'a> {
|
||||
author: PeerId,
|
||||
ops: Vec<&'a HotOp>,
|
||||
/// Still being made, not closed and waiting.
|
||||
open: bool,
|
||||
action: Option<String>,
|
||||
}
|
||||
|
||||
/// Each author's open interaction first, then the closed ones waiting to retire, newest first.
|
||||
fn hot_steps(session: &Session) -> Vec<HotStep<'_>> {
|
||||
fn progress_rows(session: &Session, people: &People, names: &Names) -> Vec<HistoryProgressRow> {
|
||||
let hot_log = session.hot_log();
|
||||
let closed = session.closed_interactions();
|
||||
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|interaction| interaction.ops.iter().copied()).collect();
|
||||
@@ -514,100 +274,20 @@ fn hot_steps(session: &Session) -> Vec<HotStep<'_>> {
|
||||
None => open_by_peer.push((hot_op.timestamp.peer, vec![hot_op])),
|
||||
}
|
||||
}
|
||||
let mut steps: Vec<HotStep> = open_by_peer
|
||||
let mut progress: Vec<HistoryProgressRow> = open_by_peer
|
||||
.into_iter()
|
||||
.map(|(author, ops)| {
|
||||
let action = session.pending_action().filter(|_| author == session.peer()).map(str::to_string);
|
||||
HotStep { author, ops, open: true, action }
|
||||
.map(|(peer, ops)| {
|
||||
let action = session.pending_action().filter(|_| peer == session.peer()).map(str::to_string);
|
||||
progress_row(people, names, peer, &retired_kinds(ops), true, action)
|
||||
})
|
||||
.collect();
|
||||
for interaction in closed.iter().rev() {
|
||||
let ids: HashSet<HotOpId> = interaction.ops.iter().copied().collect();
|
||||
let ops: Vec<&HotOp> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).collect();
|
||||
let action = ops.iter().find_map(|hot_op| hot_op.attributes.get_typed::<String>(delta_attr::ACTION));
|
||||
steps.push(HotStep {
|
||||
author: interaction.author,
|
||||
ops,
|
||||
open: false,
|
||||
action,
|
||||
});
|
||||
progress.push(progress_row(people, names, interaction.author, &retired_kinds(ops), false, action));
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The stamp of the newest change among `ops`, which keys a step's capture. Retiring keeps each op's stamp and merging
|
||||
/// keeps a step's newest op, so a step keeps its key from the hot log into history.
|
||||
fn newest_change<'a>(ops: impl IntoIterator<Item = &'a HotOp>) -> Option<TimeStamp> {
|
||||
ops.into_iter().filter(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)).map(|hot_op| hot_op.timestamp).max()
|
||||
}
|
||||
|
||||
fn head_stamp(session: &Session) -> Option<TimeStamp> {
|
||||
session.head_rev().and_then(|rev| session.delta(rev)).map(|delta| delta.timestamp)
|
||||
}
|
||||
|
||||
/// The key of the step the document shows now: the newest change still hot, else the head.
|
||||
fn current_stamp(session: &Session) -> Option<TimeStamp> {
|
||||
newest_change(session.hot_log()).or_else(|| head_stamp(session))
|
||||
}
|
||||
|
||||
/// The key of the step before `step`: for a hot step, the one whose newest change came last before its own, else the
|
||||
/// head; for a step in history, the one before its interaction.
|
||||
fn parent_stamp(session: &Session, step: TimeStamp) -> Option<TimeStamp> {
|
||||
let hot: Vec<TimeStamp> = hot_steps(session).iter().filter_map(|hot_step| newest_change(hot_step.ops.iter().copied())).collect();
|
||||
if hot.contains(&step) {
|
||||
return hot.into_iter().filter(|&other| other < step).max().or_else(|| head_stamp(session));
|
||||
}
|
||||
let (deltas, _) = line(session, session.head_rev(), None, usize::MAX);
|
||||
let groups = interactions(&deltas);
|
||||
let group = groups.iter().find(|group| group[0].timestamp == step)?;
|
||||
group.last()?.parent.and_then(|rev| session.delta(rev)).map(|delta| delta.timestamp)
|
||||
}
|
||||
|
||||
/// The closing rev and capture key of the newest `count` steps in history the panel shows, undone ones first, newest first.
|
||||
fn recent_steps(session: &Session, count: usize) -> Vec<(Rev, TimeStamp)> {
|
||||
let head = session.head_rev();
|
||||
let undone = match session.redo_stack().first() {
|
||||
Some(&checkpoint) => line(session, Some(checkpoint), head, usize::MAX).0,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let (shown, _) = line(session, head, None, count);
|
||||
interactions(&undone)
|
||||
.into_iter()
|
||||
.chain(interactions(&shown))
|
||||
.take(count)
|
||||
.map(|group| (group[0].id, group[0].timestamp))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The document as history folds it once `rev` was done, as the network the runtime compiles.
|
||||
fn past_state(gdd: &GddV1, declarations: &Declarations, rev: Rev, step: TimeStamp) -> Option<PastState> {
|
||||
let registry = gdd.session().registry_at(rev).ok()?;
|
||||
let (network, entries) = registry.to_runtime_with_metadata(declarations, gdd.blobs()).ok()?;
|
||||
// A layer in a shared network has a path per use, so only the root network's are shown
|
||||
let layers: HashSet<graph_craft::document::NodeId> = entries.iter().filter(|entry| entry.is_layer && entry.network.is_none()).map(|entry| entry.local_id).collect();
|
||||
let containers = layers.iter().copied().filter(|&layer| holds_layers(&network, layer, &layers)).collect();
|
||||
let mut layers: Vec<_> = layers.into_iter().map(|layer| vec![layer]).collect();
|
||||
layers.sort();
|
||||
Some(PastState { step, network, layers, containers })
|
||||
}
|
||||
|
||||
/// Whether what feeds a layer, besides the stack below it, holds other layers.
|
||||
fn holds_layers(network: &graph_craft::document::NodeNetwork, layer: graph_craft::document::NodeId, layers: &HashSet<graph_craft::document::NodeId>) -> bool {
|
||||
let upstream = |node: &graph_craft::document::DocumentNode| node.inputs.iter().filter_map(|input| input.as_node()).collect::<Vec<_>>();
|
||||
let Some(node) = network.nodes.get(&layer) else { return false };
|
||||
let mut pending: Vec<_> = upstream(node).into_iter().skip(1).collect();
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(id) = pending.pop() {
|
||||
if layers.contains(&id) {
|
||||
return true;
|
||||
}
|
||||
if seen.insert(id)
|
||||
&& let Some(node) = network.nodes.get(&id)
|
||||
{
|
||||
pending.extend(upstream(node));
|
||||
}
|
||||
}
|
||||
false
|
||||
progress
|
||||
}
|
||||
|
||||
/// The deltas from `from` back along first parents to `until` (exclusive) or the root, newest first. Stops after
|
||||
@@ -651,7 +331,6 @@ struct View<'a> {
|
||||
head: Option<Rev>,
|
||||
people: &'a People<'a>,
|
||||
names: &'a Names<'a>,
|
||||
captures: Option<&'a HashMap<TimeStamp, Capture>>,
|
||||
expanded: &'a BTreeSet<Rev>,
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
@@ -703,7 +382,6 @@ impl View<'_> {
|
||||
head: Some(closing.id) == self.head,
|
||||
expanded: is_expanded,
|
||||
details,
|
||||
thumbnail: self.captures.and_then(|captures| thumbnail(captures, closing.timestamp)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -731,57 +409,7 @@ fn retired_kinds(ops: Vec<&HotOp>) -> Vec<&RegistryDelta> {
|
||||
coarsen(ops).into_iter().map(|hot_op| &hot_op.op).collect()
|
||||
}
|
||||
|
||||
/// The images captured for `step`.
|
||||
fn thumbnail(captures: &HashMap<TimeStamp, Capture>, step: TimeStamp) -> Option<HistoryThumbnail> {
|
||||
let capture = captures.get(&step)?;
|
||||
Some(HistoryThumbnail {
|
||||
whole: shot_id(step),
|
||||
detail: capture.detailed.then(|| detail_id(step)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The ID the frontend keeps a capture's image by.
|
||||
fn shot_id(stamp: TimeStamp) -> String {
|
||||
format!("{}-{}", stamp.counter, stamp.peer.0)
|
||||
}
|
||||
|
||||
fn detail_id(stamp: TimeStamp) -> String {
|
||||
format!("{}-detail", shot_id(stamp))
|
||||
}
|
||||
|
||||
fn image_message(id: String, image: CaptureImage) -> FrontendMessage {
|
||||
match image {
|
||||
CaptureImage::Pixels(pixels) => FrontendMessage::UpdateHistoryThumbnailPixels {
|
||||
id,
|
||||
width: pixels.size.x,
|
||||
height: pixels.size.y,
|
||||
pixels: serde_bytes::ByteBuf::from(pixels.rgba),
|
||||
},
|
||||
CaptureImage::Svg(svg) => FrontendMessage::UpdateHistoryThumbnail { id, svg },
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each layer came, went or changed between two captures. A container counts only coming or going, since its
|
||||
/// children show what changed within it.
|
||||
fn changed_areas(before: &BTreeMap<graph_craft::document::NodeId, LayerShot>, after: &BTreeMap<graph_craft::document::NodeId, LayerShot>) -> Vec<ChangedArea> {
|
||||
let area = |change, bounds: Option<[DVec2; 2]>| bounds.map(|bounds| ChangedArea { change, bounds });
|
||||
let mut areas = Vec::new();
|
||||
for (layer, now) in after {
|
||||
match before.get(layer) {
|
||||
None => areas.extend(area(Change::Added, now.bounds)),
|
||||
Some(then) if !now.container && then != now => areas.extend([area(Change::Changed, then.bounds), area(Change::Changed, now.bounds)].into_iter().flatten()),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
for (layer, then) in before {
|
||||
if !after.contains_key(layer) {
|
||||
areas.extend(area(Change::Removed, then.bounds));
|
||||
}
|
||||
}
|
||||
areas
|
||||
}
|
||||
|
||||
fn progress_row(people: &People, names: &Names, peer: PeerId, ops: &[&RegistryDelta], open: bool, action: Option<String>, thumbnail: Option<HistoryThumbnail>) -> HistoryProgressRow {
|
||||
fn progress_row(people: &People, names: &Names, peer: PeerId, ops: &[&RegistryDelta], open: bool, action: Option<String>) -> HistoryProgressRow {
|
||||
let person = people.person(peer);
|
||||
HistoryProgressRow {
|
||||
label: action.unwrap_or_else(|| names.summarize(ops.iter().copied())),
|
||||
@@ -791,7 +419,6 @@ fn progress_row(people: &People, names: &Names, peer: PeerId, ops: &[&RegistryDe
|
||||
color: person.color,
|
||||
ops: foreground(ops, |kind| kind).len() as u32,
|
||||
open,
|
||||
thumbnail,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1042,7 +669,7 @@ mod tests {
|
||||
gdd.undo().expect("undo");
|
||||
gdd.undo().expect("undo");
|
||||
|
||||
assert_eq!(panel_state(&gdd, &Declarations::new(), None, PAGE, &BTreeSet::new(), None).rows.len(), 3);
|
||||
assert_eq!(panel_state(&gdd, &Declarations::new(), PAGE, &BTreeSet::new(), None).rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1088,255 +715,6 @@ mod tests {
|
||||
assert_eq!(names.summarize([&import_type, &reflection_metadata, &import_type, &moved]), "Moved a Node in the Graph");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_that_came_went_and_changed_mark_their_areas() {
|
||||
use graph_craft::document::NodeId as LayerId;
|
||||
|
||||
let layer = |x: f64, source: u64, container: bool| LayerShot {
|
||||
bounds: Some([DVec2::splat(x), DVec2::splat(x + 1.)]),
|
||||
source: Some(LayerId(source)),
|
||||
container,
|
||||
};
|
||||
let layers = |layers: Vec<(u64, LayerShot)>| layers.into_iter().map(|(id, shot)| (LayerId(id), shot)).collect::<BTreeMap<_, _>>();
|
||||
let before = layers(vec![(1, layer(0., 1, false)), (2, layer(5., 2, false)), (3, layer(9., 3, false)), (4, layer(0., 4, true))]);
|
||||
let after = layers(vec![(1, layer(0., 1, false)), (2, layer(6., 2, false)), (4, layer(0., 5, true)), (5, layer(3., 6, false))]);
|
||||
|
||||
let areas: Vec<(Change, f64)> = changed_areas(&before, &after).into_iter().map(|area| (area.change, area.bounds[0].x)).collect();
|
||||
assert_eq!(
|
||||
areas,
|
||||
[(Change::Changed, 5.), (Change::Changed, 6.), (Change::Added, 3.), (Change::Removed, 9.)],
|
||||
"a moved layer marks where it was and where it is, and a container changing with its children marks nothing"
|
||||
);
|
||||
}
|
||||
|
||||
/// Runs the graph and captures the current step, then lets the editor take in what comes back, a close-up included.
|
||||
async fn capture_now(editor: &mut crate::test_utils::EditorTestUtils) -> (TimeStamp, Vec<FrontendMessage>) {
|
||||
let (step, mut responses) = capture_whole_now(editor).await;
|
||||
|
||||
// The panel asks for the close-up on a later tick, once the document is idle
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let close_up = portfolio
|
||||
.history
|
||||
.captures
|
||||
.get(&document_id)
|
||||
.and_then(|captures| captures.get(&step))
|
||||
.and_then(|capture| capture.close_up);
|
||||
if let Some(close_up) = close_up {
|
||||
let document = &portfolio.documents[&document_id];
|
||||
assert!(portfolio.executor.submit_document_capture(document, document_id, step, Some(close_up)));
|
||||
responses.extend(take_in_capture(editor).await);
|
||||
}
|
||||
(step, responses)
|
||||
}
|
||||
|
||||
/// Runs the graph and captures the whole document at the current step, leaving its close-up to be asked for.
|
||||
async fn capture_whole_now(editor: &mut crate::test_utils::EditorTestUtils) -> (TimeStamp, Vec<FrontendMessage>) {
|
||||
let gdd = editor.active_document().storage().expect("every document has a working copy");
|
||||
let step = current_stamp(gdd.session()).expect("the document has a step");
|
||||
evaluate_graph(editor);
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = &portfolio.documents[&document_id];
|
||||
assert!(portfolio.executor.submit_document_capture(document, document_id, step, None), "the runtime holds this document's graph");
|
||||
(step, take_in_capture(editor).await)
|
||||
}
|
||||
|
||||
/// Hands the runtime the active document's graph to run, as the viewport does before the panel captures it.
|
||||
fn evaluate_graph(editor: &mut crate::test_utils::EditorTestUtils) {
|
||||
use glam::UVec2;
|
||||
use graphene_std::application_io::TimingInformation;
|
||||
|
||||
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_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn take_in_capture(editor: &mut crate::test_utils::EditorTestUtils) -> Vec<FrontendMessage> {
|
||||
let mut responses = Vec::new();
|
||||
for _ in 0..2 {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
responses.extend(editor.dispatch(Message::Wake));
|
||||
}
|
||||
responses
|
||||
}
|
||||
|
||||
/// The pixels, or else the SVG, the frontend got under `id`.
|
||||
fn image(responses: &[FrontendMessage], id: &str) -> Option<Result<Vec<u8>, String>> {
|
||||
responses.iter().find_map(|message| match message {
|
||||
FrontendMessage::UpdateHistoryThumbnailPixels { id: sent, pixels, .. } if sent == id => Some(Ok(pixels.to_vec())),
|
||||
FrontendMessage::UpdateHistoryThumbnail { id: sent, svg } if sent == id => Some(Err(svg.clone())),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A step made before the panel captured anything is rendered from its past state, compiled next to the document's
|
||||
/// current graph, and shows only what was there then.
|
||||
#[tokio::test]
|
||||
async fn a_step_never_captured_is_rendered_from_its_past_state() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let retire = |editor: &mut EditorTestUtils| {
|
||||
editor
|
||||
.active_document_mut()
|
||||
.storage_mut()
|
||||
.expect("every document has a working copy")
|
||||
.retire_pending_interaction()
|
||||
.expect("retire")
|
||||
};
|
||||
retire(&mut editor);
|
||||
editor.draw_rect(200., 0., 300., 100.).await;
|
||||
editor.handle_message(DocumentMessage::StartTransaction).await;
|
||||
retire(&mut editor);
|
||||
let (now, responses) = capture_now(&mut editor).await;
|
||||
let current = image(&responses, &shot_id(now)).expect("the current step is captured live");
|
||||
|
||||
let gdd = editor.active_document().storage().expect("every document has a working copy");
|
||||
let (_, first) = recent_steps(gdd.session(), PAST_STEPS)[1];
|
||||
let mut responses = Vec::new();
|
||||
for _ in 0..PAST_STEPS {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
if portfolio.history.requested.is_none() {
|
||||
portfolio.history.request_past_capture(document_id, &portfolio.documents[&document_id], &portfolio.executor);
|
||||
}
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
responses.extend(editor.dispatch(Message::Wake));
|
||||
}
|
||||
|
||||
let past = image(&responses, &shot_id(first)).expect("the first rectangle's step is rendered from its past state");
|
||||
assert_ne!(past, current, "the past state shows one rectangle and the current one two");
|
||||
match past {
|
||||
Ok(pixels) => {
|
||||
assert!(pixels.chunks(4).any(|pixel| pixel[3] > 0), "the first rectangle should be drawn");
|
||||
assert!(image(&responses, &detail_id(first)).is_some(), "the step before it was rendered first, so it has a close-up");
|
||||
}
|
||||
Err(svg) => assert!(svg.contains("<path"), "the first rectangle should be drawn: {svg}"),
|
||||
}
|
||||
|
||||
// Captured again from scratch
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
portfolio.history.captures.get_mut(&document_id).map(|captures| captures.remove(&now));
|
||||
let (_, responses) = capture_now(&mut editor).await;
|
||||
assert_eq!(image(&responses, &shot_id(now)), Some(current), "the document renders as before once its past was compiled next to it");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_step_still_hot_is_captured_once_the_runtime_has_run() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let (step, responses) = capture_now(&mut editor).await;
|
||||
|
||||
match image(&responses, &shot_id(step)).expect("the step's capture should reach the frontend") {
|
||||
Ok(pixels) => assert!(pixels.chunks(4).any(|pixel| pixel[3] > 0), "the rectangle should be drawn"),
|
||||
Err(svg) => assert!(svg.contains("<path"), "the rectangle should be drawn: {svg}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_a_layer_shows_it_close_up_tinted_as_removed() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
capture_now(&mut editor).await;
|
||||
editor.handle_message(DocumentMessage::DeleteSelectedLayers).await;
|
||||
editor.handle_message(DocumentMessage::StartTransaction).await;
|
||||
let (step, responses) = capture_now(&mut editor).await;
|
||||
|
||||
let Some(whole) = image(&responses, &shot_id(step)) else {
|
||||
panic!("an empty document is captured too")
|
||||
};
|
||||
// Without a GPU, captures are SVGs, which aren't compared
|
||||
if whole.is_err() {
|
||||
return;
|
||||
}
|
||||
let detail = image(&responses, &detail_id(step)).expect("the deletion should be shown close up").unwrap();
|
||||
let reddened = detail.chunks(4).any(|pixel| pixel[3] > 0 && pixel[0] > pixel[1] + 40);
|
||||
assert!(reddened, "the rectangle should show where it was, tinted as removed");
|
||||
}
|
||||
|
||||
/// A close-up renders the document as it is, so it waits for a gesture underway to end rather than show it half done
|
||||
/// in the area measured before it.
|
||||
#[tokio::test]
|
||||
async fn a_close_up_waits_for_the_gesture_underway_to_end() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
fn asks_for_a_capture(editor: &mut EditorTestUtils) -> bool {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let context = HistoryMessageContext {
|
||||
documents: &mut portfolio.documents,
|
||||
active_document_id: portfolio.active_document_id,
|
||||
panel_open: true,
|
||||
executor: &portfolio.executor,
|
||||
};
|
||||
portfolio.history.request_capture(&context);
|
||||
portfolio.history.requested.is_some()
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
capture_now(&mut editor).await;
|
||||
editor.drag_tool(ToolType::Ellipse, 150., 0., 250., 100., ModifierKeys::empty()).await;
|
||||
editor.handle_message(DocumentMessage::StartTransaction).await;
|
||||
capture_whole_now(&mut editor).await;
|
||||
|
||||
assert!(!asks_for_a_capture(&mut editor), "the close-up waits while a transaction is open");
|
||||
editor.handle_message(DocumentMessage::EndTransaction).await;
|
||||
evaluate_graph(&mut editor);
|
||||
assert!(asks_for_a_capture(&mut editor), "and is asked for once it ends");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_capture_taken_while_hot_stays_with_its_step_in_history() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
let step = current_stamp(gdd.session()).expect("the rectangle is a step");
|
||||
let capture = Capture {
|
||||
frame: [DVec2::ZERO, DVec2::ONE],
|
||||
layers: BTreeMap::new(),
|
||||
pixels: None,
|
||||
detailed: false,
|
||||
close_up: None,
|
||||
taken: 0,
|
||||
};
|
||||
let captures = HashMap::from([(step, capture)]);
|
||||
let state = panel_state(gdd, document.declarations(), Some(&captures), PAGE, &BTreeSet::new(), None);
|
||||
assert!(state.progress[0].thumbnail.is_some(), "the step shows its capture before it enters history");
|
||||
|
||||
let gdd = editor.active_document_mut().storage_mut().expect("every document has a working copy");
|
||||
gdd.retire_pending_interaction().expect("retire");
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
let state = panel_state(gdd, document.declarations(), Some(&captures), PAGE, &BTreeSet::new(), None);
|
||||
assert!(state.progress.is_empty());
|
||||
assert_eq!(
|
||||
state.rows[0].thumbnail.as_ref().map(|thumbnail| thumbnail.whole.clone()),
|
||||
Some(shot_id(step)),
|
||||
"and keeps it once it has"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tool_names_its_step() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
@@ -1363,7 +741,7 @@ mod tests {
|
||||
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
let state = panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None);
|
||||
let state = panel_state(gdd, document.declarations(), PAGE, &BTreeSet::new(), None);
|
||||
let labels: Vec<&str> = state.progress.iter().map(|row| row.label.as_str()).collect();
|
||||
assert_eq!(labels, ["Drew a Rectangle", "Drew a Rectangle"], "the open draw and the closed one waiting to retire");
|
||||
}
|
||||
@@ -1382,7 +760,7 @@ mod tests {
|
||||
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
let pending = panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None).progress[0].ops;
|
||||
let pending = panel_state(gdd, document.declarations(), PAGE, &BTreeSet::new(), None).progress[0].ops;
|
||||
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
assert_eq!(rows(&editor)[0].deltas, pending);
|
||||
@@ -1400,7 +778,7 @@ mod tests {
|
||||
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
let state = panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None);
|
||||
let state = panel_state(gdd, document.declarations(), PAGE, &BTreeSet::new(), None);
|
||||
let labels: Vec<&str> = state.progress.iter().map(|row| row.label.as_str()).collect();
|
||||
assert_eq!(labels, ["Deleted a Layer", "Drew a Rectangle"]);
|
||||
}
|
||||
@@ -1429,7 +807,7 @@ mod tests {
|
||||
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
let state = panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None);
|
||||
let state = panel_state(gdd, document.declarations(), PAGE, &BTreeSet::new(), None);
|
||||
let labels: Vec<&str> = state.progress.iter().map(|row| row.label.as_str()).collect();
|
||||
assert!(labels.contains(&"Added an Image"), "{labels:?}");
|
||||
}
|
||||
@@ -1451,7 +829,7 @@ mod tests {
|
||||
fn rows(editor: &crate::test_utils::EditorTestUtils) -> Vec<HistoryRow> {
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None).rows
|
||||
panel_state(gdd, document.declarations(), PAGE, &BTreeSet::new(), None).rows
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1482,7 +860,7 @@ mod tests {
|
||||
fn panel_rows(editor: &EditorTestUtils, following: Option<Rev>) -> Vec<HistoryRow> {
|
||||
let document = editor.active_document();
|
||||
let gdd = document.storage().expect("every document has a working copy");
|
||||
panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), following).rows
|
||||
panel_state(gdd, document.declarations(), PAGE, &BTreeSet::new(), following).rows
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
mod changes;
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
@@ -1,39 +1,5 @@
|
||||
//! What the History panel shows, as the frontend receives it, and the changes it asks of the head's line.
|
||||
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The document as rendered once a step is done, for the History panel to show and compare.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DocumentCapture {
|
||||
/// The whole document.
|
||||
pub image: CaptureImage,
|
||||
/// The document area `image` shows.
|
||||
pub frame: [DVec2; 2],
|
||||
/// The area asked for in detail, and its image.
|
||||
pub detail: Option<([DVec2; 2], CaptureImage)>,
|
||||
/// The proto node giving each layer's own content, whose ID changes with that content.
|
||||
pub layer_sources: HashMap<NodeId, NodeId>,
|
||||
/// Where each layer's own content lies, measured alike for the current state and past ones, which the editor holds no
|
||||
/// layer metadata for.
|
||||
pub layer_bounds: Option<HashMap<NodeId, [DVec2; 2]>>,
|
||||
}
|
||||
|
||||
/// A capture rendered like the layer thumbnails: pixels from Vello, or an SVG for the frontend to draw when the GPU is unavailable.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum CaptureImage {
|
||||
Pixels(Pixels),
|
||||
Svg(String),
|
||||
}
|
||||
|
||||
/// Straight RGBA pixels, row by row.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Pixels {
|
||||
pub size: glam::UVec2,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum LineChange {
|
||||
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
|
||||
@@ -84,17 +50,6 @@ pub struct HistoryRow {
|
||||
pub head: bool,
|
||||
pub expanded: bool,
|
||||
pub details: Vec<HistoryDeltaRow>,
|
||||
/// How the document looked once this step was done, if the panel was open to capture it.
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryThumbnail {
|
||||
/// The ID the frontend received the whole document's image under.
|
||||
pub whole: String,
|
||||
/// The ID of a close-up of what the step changed, tinted by how, when the step before was captured too.
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -126,5 +81,4 @@ pub struct HistoryProgressRow {
|
||||
pub ops: u32,
|
||||
/// Still being made, not closed and waiting.
|
||||
pub open: bool,
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
@@ -41,6 +41,10 @@ pub enum PortfolioMessage {
|
||||
AutoSaveDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Cancels the work in progress of the active document's node at this full path from the root network.
|
||||
CancelNodeWork {
|
||||
node_path: Vec<graphene_std::uuid::NodeId>,
|
||||
},
|
||||
CloseActiveDocumentWithConfirmation,
|
||||
CloseAllDocuments,
|
||||
CloseAllDocumentsWithConfirmation,
|
||||
|
||||
@@ -60,7 +60,7 @@ pub struct PortfolioMessageHandler {
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
ingest: IngestMessageHandler,
|
||||
pub(crate) history: HistoryMessageHandler,
|
||||
history: HistoryMessageHandler,
|
||||
sync: SyncMessageHandler,
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
@@ -144,7 +144,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
|
||||
executor: &self.executor,
|
||||
};
|
||||
self.history.process_message(message, responses, context);
|
||||
}
|
||||
@@ -286,6 +285,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
responses.add(PersistentStateMessage::WriteState);
|
||||
}
|
||||
PortfolioMessage::CancelNodeWork { node_path } => {
|
||||
self.executor.cancel_node_work(node_path);
|
||||
}
|
||||
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
|
||||
if let Some(document_id) = self.active_document_id {
|
||||
responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id });
|
||||
|
||||
@@ -41,6 +41,8 @@ pub struct ExecutionResponse {
|
||||
dropped_thumbnails: Vec<NodeId>,
|
||||
/// The latest result of each observation.
|
||||
observations: HashMap<ObservationKey, InspectResult>,
|
||||
/// The progress of each source with work in progress, by the path of the value node injecting the source.
|
||||
progress: Vec<(Vec<NodeId>, f64)>,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
@@ -59,6 +61,8 @@ pub enum ObservationKey {
|
||||
pub enum ExecutionResult {
|
||||
Pending,
|
||||
Value(TaggedValue),
|
||||
/// A value computed from provisional data, which is evaluated again once that data is final.
|
||||
Partial(TaggedValue),
|
||||
Fallback(TaggedValue, EvaluationErrors),
|
||||
Error(EvaluationErrors),
|
||||
Panic(Box<dyn Any + Send>),
|
||||
@@ -99,12 +103,6 @@ pub enum NodeGraphUpdate {
|
||||
responses: VecDeque<FrontendMessage>,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
DocumentCapture {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
/// `None` when a newer graph replaced the one the request was for, so it can be asked again.
|
||||
capture: Option<Box<crate::messages::portfolio::history::utility_types::DocumentCapture>>,
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
@@ -129,6 +127,8 @@ pub struct NodeGraphExecutor {
|
||||
inspect_context_overrides: ContextOverrides,
|
||||
/// The canvas images the frontend holds, so a render sends only those it lacks.
|
||||
canvas_images_sent: HashSet<u64>,
|
||||
/// The progress of the active document's nodes with work in progress, by their full path from the root network.
|
||||
node_progress: Vec<(Vec<NodeId>, f64)>,
|
||||
/// Evaluation errors of the last evaluation, used in tests
|
||||
#[cfg(test)]
|
||||
evaluation_errors: Option<EvaluationErrors>,
|
||||
@@ -183,6 +183,7 @@ impl NodeGraphExecutor {
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
inspect_context_overrides: ContextOverrides::default(),
|
||||
canvas_images_sent: HashSet::new(),
|
||||
node_progress: Vec::new(),
|
||||
#[cfg(test)]
|
||||
evaluation_errors: None,
|
||||
gradient_migration: None,
|
||||
@@ -218,6 +219,16 @@ impl NodeGraphExecutor {
|
||||
execution_id
|
||||
}
|
||||
|
||||
/// The progress of the work of the node at this full path from the root network, if it has work in progress.
|
||||
pub fn node_progress(&self, node_path: &[NodeId]) -> Option<f64> {
|
||||
self.node_progress.iter().find(|(path, _)| path == node_path).map(|(_, progress)| *progress)
|
||||
}
|
||||
|
||||
/// Cancels the work in progress of the node at this full path from the root network.
|
||||
pub fn cancel_node_work(&self, node_path: Vec<NodeId>) {
|
||||
self.sender.send(GraphRuntimeRequest::Cancel(node_path)).expect("Failed to send the cancellation");
|
||||
}
|
||||
|
||||
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
|
||||
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
|
||||
log::error!("Failed to send the overlays: {error}");
|
||||
@@ -257,36 +268,6 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the thumbnails in view");
|
||||
}
|
||||
|
||||
/// Asks for the document as rendered once what was submitted before has run, for the History panel's `step`, with the area `detail` close up.
|
||||
/// Returns false when the runtime doesn't hold the document's graph as it is now, so nothing was asked.
|
||||
pub fn submit_document_capture(&self, document: &DocumentMessageHandler, document_id: DocumentId, step: document_graph_storage::TimeStamp, detail: Option<[DVec2; 2]>) -> bool {
|
||||
if self.node_graph_document != Some(document_id) || self.node_graph_hash != document.network_interface.network_hash() {
|
||||
return false;
|
||||
}
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::CaptureDocument { document_id, step, detail })
|
||||
.expect("Failed to send the capture request");
|
||||
true
|
||||
}
|
||||
|
||||
/// Asks for a past state of the document, `network` with its `layers`, rendered for the History panel's `step` like
|
||||
/// [`submit_document_capture`](Self::submit_document_capture) renders the current one. Returns false when the runtime
|
||||
/// holds another document's graph, which the past state wouldn't share any nodes with.
|
||||
pub fn submit_past_capture(&self, document_id: DocumentId, step: document_graph_storage::TimeStamp, network: NodeNetwork, layers: Vec<Vec<NodeId>>, detail: Option<[DVec2; 2]>) -> bool {
|
||||
if self.node_graph_document != Some(document_id) {
|
||||
return false;
|
||||
}
|
||||
let past = runtime::PastCapture {
|
||||
document_id,
|
||||
step,
|
||||
network,
|
||||
layers,
|
||||
detail,
|
||||
};
|
||||
self.sender.send(GraphRuntimeRequest::CapturePast(past)).expect("Failed to send the capture request");
|
||||
true
|
||||
}
|
||||
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
@@ -567,6 +548,7 @@ impl NodeGraphExecutor {
|
||||
responses: existing_responses,
|
||||
dropped_thumbnails,
|
||||
mut observations,
|
||||
progress,
|
||||
} = *execution_response;
|
||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||
|
||||
@@ -611,14 +593,24 @@ impl NodeGraphExecutor {
|
||||
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// The deepest document node containing each source shows its progress
|
||||
if execution_context.document_id == document_id {
|
||||
let node_progress: Vec<_> = progress
|
||||
.into_iter()
|
||||
.filter_map(|(path, progress)| {
|
||||
let node_path = (1..=path.len()).rev().map(|length| &path[..length]).find(|path| is_document_node(document, path))?;
|
||||
Some((node_path.to_vec(), progress))
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.update_node_progress(node_progress, responses);
|
||||
}
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
||||
let errors = match &result {
|
||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||
let in_document = |path: &&[NodeId]| {
|
||||
path.split_last()
|
||||
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
|
||||
};
|
||||
let in_document = |path: &&[NodeId]| is_document_node(document, path);
|
||||
errors
|
||||
.iter()
|
||||
.flat_map(|(error, trace)| {
|
||||
@@ -635,7 +627,7 @@ impl NodeGraphExecutor {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => Vec::new(),
|
||||
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => Vec::new(),
|
||||
};
|
||||
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
|
||||
}
|
||||
@@ -644,9 +636,14 @@ impl NodeGraphExecutor {
|
||||
{
|
||||
self.evaluation_errors = None;
|
||||
}
|
||||
let render_status = match result {
|
||||
ExecutionResult::Partial(_) => RenderStatus::Partial,
|
||||
ExecutionResult::Fallback(..) => RenderStatus::Fallback,
|
||||
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Error(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => RenderStatus::Rendering,
|
||||
};
|
||||
let node_graph_output = match result {
|
||||
ExecutionResult::Pending => Ok(None),
|
||||
ExecutionResult::Value(value) => Ok(Some(value)),
|
||||
ExecutionResult::Value(value) | ExecutionResult::Partial(value) => Ok(Some(value)),
|
||||
ExecutionResult::Fallback(value, _errors) => {
|
||||
#[cfg(test)]
|
||||
{
|
||||
@@ -700,7 +697,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
match (node_graph_output, execution_context.export_config) {
|
||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
|
||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, responses),
|
||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
|
||||
(None, _) => {}
|
||||
}
|
||||
responses.add(DeferMessage::TriggerGraphRun {
|
||||
@@ -748,6 +745,7 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
self.update_node_progress(Vec::new(), responses);
|
||||
|
||||
// The graph only shows errors tied to nodes, so the console gets the others
|
||||
if node_graph_errors.is_empty() {
|
||||
@@ -796,7 +794,6 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -816,7 +813,6 @@ impl NodeGraphExecutor {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -824,6 +820,16 @@ impl NodeGraphExecutor {
|
||||
all_dropped_thumbnails
|
||||
}
|
||||
|
||||
/// Sends the active document's node progress to its graph, which keeps its own copy, and refreshes the Properties panel when it changed.
|
||||
fn update_node_progress(&mut self, node_progress: Vec<(Vec<NodeId>, f64)>, responses: &mut VecDeque<Message>) {
|
||||
responses.add(NodeGraphMessage::UpdateNodeProgress { progress: node_progress.clone() });
|
||||
|
||||
if self.node_progress != node_progress {
|
||||
self.node_progress = node_progress;
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
}
|
||||
}
|
||||
|
||||
fn receive_thumbnails(document: &mut DocumentMessageHandler, thumbnails: VecDeque<FrontendMessage>, responses: &mut VecDeque<Message>) {
|
||||
for thumbnail in thumbnails {
|
||||
match LayersInView::thumbnail_layer(&thumbnail) {
|
||||
@@ -1037,7 +1043,7 @@ impl NodeGraphExecutor {
|
||||
self.node_graph_hash = 0;
|
||||
}
|
||||
|
||||
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque<Message>) {
|
||||
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, render_status: RenderStatus, responses: &mut VecDeque<Message>) {
|
||||
let TaggedValue::RenderOutput(render_output) = node_graph_output else {
|
||||
log::error!("Invalid node graph output type: {node_graph_output:#?}");
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
@@ -1119,7 +1125,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Rendering });
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
@@ -1177,6 +1183,12 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the node at this full path from the root network exists in the document.
|
||||
fn is_document_node(document: &DocumentMessageHandler, path: &[NodeId]) -> bool {
|
||||
path.split_last()
|
||||
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
|
||||
/// (or set by the user), so a measured bake may safely be written.
|
||||
|
||||
@@ -2,7 +2,6 @@ use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
||||
use crate::messages::portfolio::history::utility_types::DocumentCapture;
|
||||
use crate::task::{Spawn, Spawner, Task};
|
||||
use glam::UVec2;
|
||||
use graph_craft::application_io::resource::{Resource, ResourceRegistry};
|
||||
@@ -10,8 +9,9 @@ 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::{GraphError, GraphErrorType, GraphErrors, ProtoNetwork};
|
||||
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
@@ -53,22 +53,18 @@ pub struct NodeRuntime {
|
||||
pending_export: Option<ExecutionRequest>,
|
||||
pending_eyedropper: Option<ExecutionRequest>,
|
||||
pending_thumbnails: Option<DocumentId>,
|
||||
/// The step the History panel wants the document captured for, once what is pending has run.
|
||||
pending_capture: Option<(DocumentId, document_graph_storage::TimeStamp, Option<[DVec2; 2]>)>,
|
||||
/// A past state the History panel wants captured, once nothing else is waiting to run.
|
||||
pending_past: Option<PastCapture>,
|
||||
/// The network the executor last compiled successfully, with previews applied.
|
||||
old_graph: Option<NodeNetwork>,
|
||||
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
||||
compile_failed: bool,
|
||||
/// What `old_graph` compiled to, which a past state is compiled alongside.
|
||||
compiled: Option<ProtoNetwork>,
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
/// Each source of the compiled network, with the path of the value node injecting it.
|
||||
source_paths: Vec<(SourceId, Vec<NodeId>)>,
|
||||
thumbnails: Thumbnails,
|
||||
observer: Observer<ObservationKey>,
|
||||
/// Whether an observation changed since its results were last sent.
|
||||
@@ -111,13 +107,8 @@ pub enum GraphRuntimeRequest {
|
||||
layers: Vec<NodeId>,
|
||||
},
|
||||
RenderOverlays(OverlayContext),
|
||||
CaptureDocument {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
/// The area to render close up as well.
|
||||
detail: Option<[DVec2; 2]>,
|
||||
},
|
||||
CapturePast(PastCapture),
|
||||
/// Cancels the work in progress of the sources within the node at this full path from the root network.
|
||||
Cancel(Vec<NodeId>),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -132,18 +123,6 @@ pub struct GraphUpdate {
|
||||
pub(super) observations: HashMap<ObservationKey, Observation>,
|
||||
}
|
||||
|
||||
/// A past state of a document to render like [`GraphRuntimeRequest::CaptureDocument`] renders the current one.
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PastCapture {
|
||||
pub(super) document_id: DocumentId,
|
||||
pub(super) step: document_graph_storage::TimeStamp,
|
||||
pub(super) network: NodeNetwork,
|
||||
/// Full path from the root network to every layer of the past state.
|
||||
pub(super) layers: Vec<Vec<NodeId>>,
|
||||
/// The area to render close up as well.
|
||||
pub(super) detail: Option<[DVec2; 2]>,
|
||||
}
|
||||
|
||||
/// Replaces each network's primary export with its previewed node.
|
||||
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
|
||||
for (network_path, previewed) in previewed {
|
||||
@@ -198,11 +177,8 @@ impl NodeRuntime {
|
||||
pending_export: None,
|
||||
pending_eyedropper: None,
|
||||
pending_thumbnails: None,
|
||||
pending_capture: None,
|
||||
pending_past: None,
|
||||
old_graph: None,
|
||||
compile_failed: false,
|
||||
compiled: None,
|
||||
resources: ResourceRegistry::default(),
|
||||
async_runtime: None,
|
||||
|
||||
@@ -217,6 +193,7 @@ impl NodeRuntime {
|
||||
|
||||
node_graph_errors: Vec::new(),
|
||||
node_graph_warnings: Vec::new(),
|
||||
source_paths: Vec::new(),
|
||||
thumbnails: Thumbnails::new(),
|
||||
observer: Observer::default(),
|
||||
observations_changed: false,
|
||||
@@ -242,15 +219,7 @@ impl NodeRuntime {
|
||||
let mut graph = None;
|
||||
for request in self.receiver.try_iter() {
|
||||
match request {
|
||||
GraphRuntimeRequest::GraphUpdate(update) => {
|
||||
graph = Some(update);
|
||||
// The graph may be another document's, or show a later step than the one asked for
|
||||
if let Some((document_id, step, _)) = self.pending_capture.take() {
|
||||
self.sender
|
||||
.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture: None })
|
||||
.expect("Failed to send response");
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
|
||||
self.pending_export = Some(request);
|
||||
@@ -265,8 +234,6 @@ impl NodeRuntime {
|
||||
self.thumbnails.set_in_view(layers);
|
||||
self.pending_thumbnails = Some(document_id);
|
||||
}
|
||||
GraphRuntimeRequest::CaptureDocument { document_id, step, detail } => self.pending_capture = Some((document_id, step, detail)),
|
||||
GraphRuntimeRequest::CapturePast(past) => self.pending_past = Some(past),
|
||||
// A graph update applied after this loop would otherwise replace this with what it observed before
|
||||
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
|
||||
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
|
||||
@@ -284,6 +251,15 @@ impl NodeRuntime {
|
||||
self.overlays = Some(context);
|
||||
self.overlays_stale = true;
|
||||
}
|
||||
GraphRuntimeRequest::Cancel(node_path) => {
|
||||
let mut canceled = false;
|
||||
for (source, _) in self.source_paths.iter().filter(|(_, path)| path.starts_with(&node_path)) {
|
||||
canceled |= self.async_runtime().cancel(*source);
|
||||
}
|
||||
if canceled {
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,7 +284,7 @@ impl NodeRuntime {
|
||||
let result = self.update_network(&network);
|
||||
self.compile_failed = result.is_err();
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &thumbnails::compiled_sources(&self.executor));
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
self.old_graph = Some(network);
|
||||
}
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
@@ -362,30 +338,6 @@ impl NodeRuntime {
|
||||
if self.overlays_stale {
|
||||
texture = self.composite_viewport_frame();
|
||||
}
|
||||
|
||||
if let Some((document_id, step, detail)) = self.pending_capture.take() {
|
||||
let capture = match &self.old_graph {
|
||||
Some(network) => {
|
||||
self.thumbnails
|
||||
.capture_document(network, &self.executor, &thumbnails::compiled_sources(&self.executor), &self.editor_api, detail)
|
||||
.await
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let capture = capture.map(|mut capture| {
|
||||
capture.layer_bounds = Some(self.thumbnails.layer_bounds(&self.executor));
|
||||
Box::new(capture)
|
||||
});
|
||||
self.sender.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture }).expect("Failed to send response");
|
||||
}
|
||||
|
||||
if viewport.is_none()
|
||||
&& let Some(past) = self.pending_past.take()
|
||||
{
|
||||
let capture = self.capture_past(&past).await.map(Box::new);
|
||||
let (document_id, step) = (past.document_id, past.step);
|
||||
self.sender.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture }).expect("Failed to send response");
|
||||
}
|
||||
}
|
||||
|
||||
(self.editor_wake)();
|
||||
@@ -521,7 +473,8 @@ impl NodeRuntime {
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value),
|
||||
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(&error))
|
||||
@@ -535,6 +488,7 @@ impl NodeRuntime {
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
progress: Vec::new(),
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
return None;
|
||||
@@ -549,12 +503,23 @@ impl NodeRuntime {
|
||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||
|
||||
let progress = self
|
||||
.async_runtime()
|
||||
.progress()
|
||||
.into_iter()
|
||||
.filter_map(|(source, progress)| {
|
||||
let (_, path) = self.source_paths.iter().find(|(candidate, _)| *candidate == source)?;
|
||||
Some((path.clone(), progress))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
result,
|
||||
responses,
|
||||
dropped_thumbnails,
|
||||
observations,
|
||||
progress,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
@@ -592,8 +557,7 @@ impl NodeRuntime {
|
||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||
}
|
||||
|
||||
/// Compiles a document network to the proto network the executor runs.
|
||||
fn compile(&mut self, graph: &NodeNetwork) -> Result<CompiledNetwork, CompileError> {
|
||||
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph.clone(), self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
// A missing resource compiles as the empty one, which its consumers draw with a fallback, and warns on the nodes using it
|
||||
@@ -605,21 +569,17 @@ impl NodeRuntime {
|
||||
})
|
||||
};
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &resolve_resource) {
|
||||
return Err(CompileError::Message(e.to_string()));
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
}
|
||||
if resource_missing.get() {
|
||||
self.node_graph_warnings = missing_resource_warnings(graph, &self.resources);
|
||||
}
|
||||
|
||||
// We assume only one output
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
let mut compiled_network = Compiler {}.compile_single(scoped_network)?;
|
||||
if resource_missing.get() {
|
||||
compiled_network.warnings.splice(0..0, missing_resource_warnings(graph, &self.resources));
|
||||
}
|
||||
Ok(compiled_network)
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let CompiledNetwork { network: proto_network, warnings } = match self.compile(graph) {
|
||||
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:?}");
|
||||
@@ -628,61 +588,18 @@ impl NodeRuntime {
|
||||
}
|
||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
||||
};
|
||||
self.node_graph_warnings = warnings;
|
||||
self.node_graph_warnings.extend(warnings);
|
||||
self.source_paths = proto_network.source_paths().map(|(source, path)| (*source, path.to_vec())).collect();
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
let compiled = proto_network.clone();
|
||||
let result = self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
self.node_graph_errors.clone_from(&e);
|
||||
(types, format!("{e:?}"))
|
||||
});
|
||||
self.compiled = result.is_ok().then_some(compiled);
|
||||
self.async_runtime().update_sources(self.executor.sources());
|
||||
result
|
||||
}
|
||||
|
||||
/// Renders a past state of the document, compiled alongside the current graph as a second output. A proto node's ID
|
||||
/// hashes everything upstream of it, so what the two states share is one node, which keeps its cache. The current
|
||||
/// nodes go in last, so the executor still names them for their document paths, and the past state's own nodes are
|
||||
/// freed once a later graph update leaves them out.
|
||||
async fn capture_past(&mut self, past: &PastCapture) -> Option<DocumentCapture> {
|
||||
let current = self.compiled.clone()?;
|
||||
let CompiledNetwork { network: past_network, .. } = self
|
||||
.compile(&past.network)
|
||||
.inspect_err(|error| log::warn!("The History panel's past state didn't compile: {error:?}"))
|
||||
.ok()?;
|
||||
|
||||
let past_output = past_network.output;
|
||||
let past_sources: HashMap<Vec<NodeId>, NodeId> = past_network.nodes.iter().filter_map(|(id, node)| Some((node.original_location.path.clone()?, *id))).collect();
|
||||
let current_ids: HashSet<NodeId> = current.nodes.iter().map(|(id, _)| *id).collect();
|
||||
let mut merged = current.clone();
|
||||
merged.nodes = past_network.nodes.into_iter().filter(|(id, _)| !current_ids.contains(id)).chain(current.nodes).collect();
|
||||
if let Err((_, error)) = self.executor.update(merged) {
|
||||
log::warn!("The History panel's past state didn't compile alongside the document: {error:?}");
|
||||
return None;
|
||||
}
|
||||
self.async_runtime().update_sources(self.executor.sources());
|
||||
|
||||
// Thumbnail content evaluates from the context it last ran in, so the past state runs once as the viewport does
|
||||
let mut render_config = self.pending?.render_config;
|
||||
if render_config.export_format == ExportFormat::Raster && self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_none() {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let evaluated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(past_output, &context)));
|
||||
if !matches!(evaluated, Ok(Ok(_))) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let source_of = |path: &[NodeId]| past_sources.get(path).copied();
|
||||
let mut thumbnails = Thumbnails::new();
|
||||
thumbnails.set_scale(self.thumbnails.scale());
|
||||
thumbnails.update_sources(&past.layers, &past.network, &source_of);
|
||||
let mut capture = thumbnails.capture_document(&past.network, &self.executor, &source_of, &self.editor_api, past.detail).await?;
|
||||
capture.layer_bounds = Some(thumbnails.layer_bounds(&self.executor));
|
||||
Some(capture)
|
||||
}
|
||||
|
||||
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
||||
let source_map = self.executor.tree().source_map();
|
||||
let paths = |node: NodeId| -> NodePaths {
|
||||
@@ -714,7 +631,9 @@ impl NodeRuntime {
|
||||
|
||||
impl ExecutionResult {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
let (Self::Value(value) | Self::Fallback(value, _)) = self else { return None };
|
||||
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
||||
return None;
|
||||
};
|
||||
let TaggedValue::RenderOutput(output) = value else { return None };
|
||||
Some(output)
|
||||
}
|
||||
@@ -777,6 +696,7 @@ impl Spawn for NodeTaskExecutor {
|
||||
#[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;
|
||||
@@ -798,12 +718,17 @@ mod tests {
|
||||
|
||||
/// 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) {
|
||||
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, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -833,8 +758,8 @@ mod tests {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
|
||||
}
|
||||
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) {
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations. Returns the Vectorize node.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) -> NodeId {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
|
||||
@@ -859,6 +784,7 @@ mod tests {
|
||||
output_connector: OutputConnector::primary_output(vectorize),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
});
|
||||
vectorize
|
||||
}
|
||||
|
||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||
@@ -1219,6 +1145,39 @@ mod tests {
|
||||
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
|
||||
}
|
||||
|
||||
/// A trace renders partial frames and shows its progress on its node until it is canceled, which keeps the shapes traced so far.
|
||||
#[tokio::test]
|
||||
async fn a_trace_shows_its_progress_until_it_is_canceled() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 512., 512.).await;
|
||||
let vectorize = vectorize_layer(&mut editor);
|
||||
|
||||
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"
|
||||
);
|
||||
assert!(editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_some(), "the trace shows no progress");
|
||||
|
||||
editor.dispatch(PortfolioMessage::CancelNodeWork { node_path: vec![vectorize] });
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
assert!(
|
||||
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Fallback }),
|
||||
"the canceled trace's frame isn't a fallback"
|
||||
);
|
||||
assert!(
|
||||
editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_none(),
|
||||
"the canceled trace still shows progress"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
|
||||
let previewed_node = NodeId(1);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::evaluated_output;
|
||||
use crate::messages::frontend::FrontendMessage;
|
||||
use crate::messages::portfolio::history::utility_types::{CaptureImage, DocumentCapture, Pixels};
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
@@ -27,14 +26,6 @@ mod atlas;
|
||||
/// The time thumbnails are evaluated at, so they don't depend on the playhead.
|
||||
const THUMBNAIL_TIME: f64 = 0.;
|
||||
|
||||
/// Finds the proto node compiled from the document node at a path.
|
||||
pub type SourceLookup<'a> = &'a dyn Fn(&[NodeId]) -> Option<NodeId>;
|
||||
|
||||
/// Looks paths up in what `executor` last compiled.
|
||||
pub fn compiled_sources(executor: &DynamicExecutor) -> impl Fn(&[NodeId]) -> Option<NodeId> + '_ {
|
||||
|path| executor.tree().source_map().get(path).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
/// The size in pixels of a thumbnail rendered at this device pixel ratio.
|
||||
fn cell_size(scale: f64) -> UVec2 {
|
||||
/// The size thumbnails are shown at in the node graph, in CSS pixels.
|
||||
@@ -92,11 +83,11 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
|
||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, source_of: SourceLookup) {
|
||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
|
||||
// O(layers * depth)
|
||||
let sources: HashMap<NodeId, NodeId> = layer_paths
|
||||
.iter()
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, source_of)?)))
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
|
||||
.collect();
|
||||
|
||||
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
|
||||
@@ -225,71 +216,22 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
|
||||
self.show_svg(layer, content.svg(), responses).await;
|
||||
}
|
||||
|
||||
/// Renders the whole document as the network's export gives it, and the area `detail` close up, the way layer
|
||||
/// thumbnails are rendered, along with what each layer currently shows.
|
||||
pub async fn capture_document(
|
||||
&self,
|
||||
network: &NodeNetwork,
|
||||
executor: &DynamicExecutor,
|
||||
source_of: SourceLookup<'_>,
|
||||
editor_api: &PlatformEditorApi,
|
||||
detail: Option<[DVec2; 2]>,
|
||||
) -> Option<DocumentCapture> {
|
||||
let content = match network.exports.first().and_then(|export| network.input_source(&[], export)) {
|
||||
Some(source) => {
|
||||
let content_node = source_of(source.as_slice())?;
|
||||
ThumbnailContent::evaluate(executor, content_node)?
|
||||
}
|
||||
// Nothing reaches the export, so the document shows nothing
|
||||
None => ThumbnailContent::Graphics(List::default()),
|
||||
let bounds = content.bounds(false);
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_translation(bounds[0]),
|
||||
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
|
||||
quality: RenderQuality::Full,
|
||||
};
|
||||
|
||||
let maps_resolved = editor_api.application_io.as_ref().and_then(|io| io.gpu_executor()).is_some();
|
||||
let frame = content.bounds(maps_resolved);
|
||||
let frames: Vec<[DVec2; 2]> = std::iter::once(frame).chain(detail).collect();
|
||||
let mut images: Vec<CaptureImage> = match self.render_frames_with_vello(&content, &frames, editor_api).await {
|
||||
Some(pixels) => pixels.into_iter().map(CaptureImage::Pixels).collect(),
|
||||
None => frames.iter().map(|&frame| CaptureImage::Svg(content.svg_of(frame))).collect(),
|
||||
let render_params = RenderParams {
|
||||
footprint,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let detail_image = (images.len() > 1).then(|| images.pop()).flatten();
|
||||
Some(DocumentCapture {
|
||||
image: images.pop()?,
|
||||
frame,
|
||||
detail: detail.zip(detail_image),
|
||||
layer_sources: self.sources.clone(),
|
||||
layer_bounds: None,
|
||||
})
|
||||
}
|
||||
let mut render = SvgRender::new();
|
||||
content.graphic().render_svg(&mut render, &render_params);
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
|
||||
pub fn scale(&self) -> f64 {
|
||||
self.scale
|
||||
}
|
||||
|
||||
/// Where each layer's own content lies, from the content its thumbnail shows.
|
||||
pub fn layer_bounds(&self, executor: &DynamicExecutor) -> HashMap<NodeId, [DVec2; 2]> {
|
||||
let bounds = |source: NodeId| ThumbnailContent::evaluate(executor, source)?.content_bounds(true);
|
||||
self.sources.iter().filter_map(|(&layer, &source)| Some((layer, bounds(source)?))).collect()
|
||||
}
|
||||
|
||||
/// Renders each frame of the content into a cell the size of a layer thumbnail, giving none if Vello is unavailable.
|
||||
async fn render_frames_with_vello(&self, content: &ThumbnailContent, frames: &[[DVec2; 2]], editor_api: &PlatformEditorApi) -> Option<Vec<Pixels>> {
|
||||
let executor = editor_api.application_io.as_ref()?.gpu_executor()?;
|
||||
let cell_size = cell_size(self.scale);
|
||||
let size = UVec2::new(cell_size.x * frames.len() as u32, cell_size.y);
|
||||
|
||||
let texture = executor.render_vello(size, DAffine2::IDENTITY, &mut |scene| atlas::draw_frames(scene, cell_size, content, frames));
|
||||
let texture = texture.inspect_err(|error| log::error!("Failed to render the document capture: {error}")).ok()?;
|
||||
let raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await;
|
||||
let (pixels, _, _) = raster.to_flat_u8();
|
||||
|
||||
let cell = |index: usize| Pixels {
|
||||
size: cell_size,
|
||||
rgba: atlas::cell_pixels(&pixels, size.x, cell_size, UVec2::new(index as u32 * cell_size.x, 0)),
|
||||
};
|
||||
Some((0..frames.len()).map(cell).collect())
|
||||
self.show_svg(layer, render.svg.to_svg_string(), responses).await;
|
||||
}
|
||||
|
||||
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
|
||||
@@ -394,59 +336,40 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
fn svg(&self) -> String {
|
||||
self.svg_of(self.bounds(false))
|
||||
}
|
||||
|
||||
/// The SVG of the area `bounds`.
|
||||
fn svg_of(&self, bounds: [DVec2; 2]) -> String {
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_translation(bounds[0]),
|
||||
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
|
||||
quality: RenderQuality::Full,
|
||||
};
|
||||
let render_params = RenderParams {
|
||||
footprint,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
self.graphic().render_svg(&mut render, &render_params);
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
render.svg.to_svg_string()
|
||||
}
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self, maps_resolved: bool) -> [DVec2; 2] {
|
||||
expand_to_thumbnail_aspect(self.content_bounds(maps_resolved).unwrap_or([DVec2::ZERO, DVec2::ONE]))
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered, if it has any extent, counting the effects drawn through maps and images only if they're `maps_resolved`, which an SVG without a GPU leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> Option<[DVec2; 2]> {
|
||||
let bounds = match self {
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which an SVG without a GPU leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> 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),
|
||||
// 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),
|
||||
};
|
||||
match bounds {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self, maps_resolved: bool) -> [DVec2; 2] {
|
||||
let bounds = match self.content_bounds(maps_resolved) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||
_ => [DVec2::ZERO, DVec2::ONE],
|
||||
};
|
||||
expand_to_thumbnail_aspect(bounds)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, &compiled_sources(executor))?))
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||
.collect();
|
||||
|
||||
let bounds = contents
|
||||
.iter()
|
||||
.filter_map(|content| content.content_bounds(false))
|
||||
.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 {
|
||||
@@ -467,10 +390,10 @@ pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicEx
|
||||
}
|
||||
|
||||
/// 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, source_of: SourceLookup) -> Option<NodeId> {
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
source_of(source.as_slice())
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
/// Converts the other kinds of graphical content into a graphic.
|
||||
@@ -536,7 +459,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::messages::portfolio::history::utility_types::CaptureImage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -560,30 +482,6 @@ mod tests {
|
||||
editor.runtime.executor.tree().source_map().get(path).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_document_capture_shows_the_document_and_what_each_layer_shows() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let runtime = &editor.runtime;
|
||||
let network = runtime.old_graph.as_ref().expect("The document should have compiled");
|
||||
let capture = runtime
|
||||
.thumbnails
|
||||
.capture_document(network, &runtime.executor, &super::compiled_sources(&runtime.executor), &runtime.editor_api, None)
|
||||
.await;
|
||||
let capture = capture.expect("The document should render");
|
||||
match &capture.image {
|
||||
CaptureImage::Pixels(pixels) => assert!(pixels.rgba.chunks(4).any(|pixel| pixel[3] > 0), "The rectangle should be drawn"),
|
||||
CaptureImage::Svg(svg) => assert!(svg.contains("<path"), "The rectangle should be drawn: {svg}"),
|
||||
}
|
||||
assert!(capture.layer_sources.contains_key(&layer), "The rectangle's layer should have its content");
|
||||
let [min, max] = capture.frame;
|
||||
assert!(min.cmple(DVec2::ZERO).all() && max.cmpge(DVec2::splat(10.)).all(), "The frame {min} to {max} should hold the rectangle");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_merge_layer_shows_its_content_and_another_layer_its_output() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{ThumbnailContent, cell_size};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||
use graphene_std::renderer::{RenderOutputType, RenderParams};
|
||||
@@ -43,59 +43,46 @@ impl ThumbnailAtlasLayout {
|
||||
}
|
||||
|
||||
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
|
||||
cell_pixels(atlas_pixels, self.size().x, self.cell_size, self.cell_origin(index))
|
||||
let atlas_row_length = self.size().x as usize * 4;
|
||||
let row_length = self.cell_size.x as usize * 4;
|
||||
let origin = self.cell_origin(index).as_usizevec2();
|
||||
|
||||
(origin.y..origin.y + self.cell_size.y as usize)
|
||||
.filter_map(|row| {
|
||||
let start = row * atlas_row_length + origin.x * 4;
|
||||
atlas_pixels.get(start..start + row_length)
|
||||
})
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels of the cell at `origin` in an atlas `atlas_width` pixels wide, row by row.
|
||||
pub fn cell_pixels(atlas_pixels: &[u8], atlas_width: u32, cell_size: UVec2, origin: UVec2) -> Vec<u8> {
|
||||
let atlas_row_length = atlas_width as usize * 4;
|
||||
let row_length = cell_size.x as usize * 4;
|
||||
let origin = origin.as_usizevec2();
|
||||
|
||||
(origin.y..origin.y + cell_size.y as usize)
|
||||
.filter_map(|row| {
|
||||
let start = row * atlas_row_length + origin.x * 4;
|
||||
atlas_pixels.get(start..start + row_length)
|
||||
})
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Draws the content of each layer in the layout centered within its cell.
|
||||
pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout, contents: &HashMap<NodeId, ThumbnailContent>) {
|
||||
for (index, layer) in layout.layers.iter().enumerate() {
|
||||
let Some(content) = contents.get(layer) else { continue };
|
||||
draw_cell(scene, layout.cell_origin(index), layout.cell_size, content, content.bounds(true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the area `frame` of the content into each cell of a row of them, one per frame.
|
||||
pub fn draw_frames(scene: &mut VelloSceneBuilder, cell_size: UVec2, content: &ThumbnailContent, frames: &[[DVec2; 2]]) {
|
||||
for (index, &frame) in frames.iter().enumerate() {
|
||||
draw_cell(scene, UVec2::new(index as u32 * cell_size.x, 0), cell_size, content, frame);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_cell(scene: &mut VelloSceneBuilder, origin: UVec2, cell_size: UVec2, content: &ThumbnailContent, frame: [DVec2; 2]) {
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::BOUNDLESS,
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (origin, cell_size) = (origin.as_dvec2(), cell_size.as_dvec2());
|
||||
let [min, max] = frame;
|
||||
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
|
||||
let cell_size = layout.cell_size.as_dvec2();
|
||||
|
||||
// The clip also limits content filling the whole scene, like a background, to the cell
|
||||
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
|
||||
scene.draw_placed(Affine::new(transform.to_cols_array()), |scene| {
|
||||
content.graphic().render_to_vello(scene, DAffine2::IDENTITY, &render_params)
|
||||
});
|
||||
scene.pop_layer();
|
||||
for (index, layer) in layout.layers.iter().enumerate() {
|
||||
let Some(content) = contents.get(layer) else { continue };
|
||||
|
||||
let origin = layout.cell_origin(index).as_dvec2();
|
||||
let [min, max] = content.bounds(true);
|
||||
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
|
||||
|
||||
// The clip also limits content filling the whole scene, like a background, to the cell
|
||||
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
|
||||
scene.draw_placed(Affine::new(transform.to_cols_array()), |scene| {
|
||||
content.graphic().render_to_vello(scene, DAffine2::IDENTITY, &render_params)
|
||||
});
|
||||
scene.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGBA pixels with runs of fully transparent ones left out, which most of a thumbnail's margins are.
|
||||
|
||||
@@ -718,9 +718,14 @@
|
||||
<div bind:this={textInput} style:transform="matrix({textInputMatrix})" on:scroll={preventTextEditingScroll}></div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if isWeb && $document.renderStatus === "Rendering"}
|
||||
{#if isWeb && !["Error", "Panic"].includes($document.renderStatus)}
|
||||
<TextLabel class="shader-compiling-overlay" italic={true} classes={{ show: !firstArtworkReceived }}>Initializing Renderer…</TextLabel>
|
||||
{/if}
|
||||
{#if $document.renderStatus === "Partial"}
|
||||
<div class="render-status-outline"></div>
|
||||
{:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
|
||||
<div class="render-status-outline failed"></div>
|
||||
{/if}
|
||||
{#if $document.renderStatus === "Error"}
|
||||
<LayoutCol class="render-status-overlay">
|
||||
<TextLabel>
|
||||
@@ -983,6 +988,19 @@
|
||||
}
|
||||
}
|
||||
|
||||
.render-status-outline {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
// Above the error overlays so the outline frames them too
|
||||
z-index: 1;
|
||||
box-shadow: inset 0 0 0 1px var(--color-warning-yellow);
|
||||
pointer-events: none;
|
||||
|
||||
&.failed {
|
||||
box-shadow: inset 0 0 0 1px var(--color-error-red);
|
||||
}
|
||||
}
|
||||
|
||||
.render-status-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { getContext, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import HistoryShot from "/src/components/views/HistoryShot.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
|
||||
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
|
||||
@@ -14,7 +13,6 @@
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const history = getContext<HistoryStore>("history");
|
||||
const portfolio = getContext<PortfolioStore>("portfolio");
|
||||
const thumbnails = history.thumbnails;
|
||||
|
||||
// Relative times age while the panel stays open
|
||||
let now = Date.now();
|
||||
@@ -98,7 +96,6 @@
|
||||
<span class="rail"
|
||||
>{#if $history.collaborating}<span class="dot hollow" style:border-color={row.color}></span>{/if}</span
|
||||
>
|
||||
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />
|
||||
<div class="text">
|
||||
<span class="label">{row.label || (row.open ? "In Progress" : "Waiting to Enter History")}</span>
|
||||
<span class="meta">
|
||||
@@ -123,7 +120,7 @@
|
||||
on:click={(e) => preview(e, row)}
|
||||
on:dblclick={(e) => goBackTo(e, row)}
|
||||
>
|
||||
{#if row.deltas > 1 || row.thumbnail?.detail}
|
||||
{#if row.deltas > 1}
|
||||
<button
|
||||
class="expand"
|
||||
data-row-control
|
||||
@@ -137,7 +134,6 @@
|
||||
<span class="rail"
|
||||
>{#if $history.collaborating || !row.mine}<span class="dot" style:background={row.color}></span>{/if}</span
|
||||
>
|
||||
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />
|
||||
<div class="text">
|
||||
{#if renamingId === row.id}
|
||||
<span class="editing" data-row-control use:focusInput on:focusout={() => (renamingId = undefined)}>
|
||||
@@ -208,13 +204,6 @@
|
||||
</span>
|
||||
</div>
|
||||
{#if row.expanded}
|
||||
{#if row.thumbnail?.detail}
|
||||
<div class="row comparison" class:undone={row.undone}>
|
||||
<span class="gutter"></span>
|
||||
<span class="rail"></span>
|
||||
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} large={true} />
|
||||
</div>
|
||||
{/if}
|
||||
{#each row.details as delta (delta.id)}
|
||||
<div class="row delta" class:undone={row.undone}>
|
||||
<span class="gutter"></span>
|
||||
@@ -322,16 +311,6 @@
|
||||
&.delta {
|
||||
min-height: 24px;
|
||||
font-size: 11px;
|
||||
|
||||
// Lines up with the step's label, past its thumbnail and the gap after it
|
||||
.text {
|
||||
padding-left: 42px;
|
||||
}
|
||||
}
|
||||
|
||||
&.comparison {
|
||||
padding-top: 4px;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
|
||||
@@ -973,10 +973,12 @@
|
||||
{@const clipPathId = String(Math.random()).substring(2)}
|
||||
{@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined}
|
||||
{@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"}
|
||||
{@const progress = $nodeGraph.progress.get(node.id)}
|
||||
<div
|
||||
class="node"
|
||||
class:selected={$nodeGraph.selected.includes(node.id)}
|
||||
class:previewed={node.previewed}
|
||||
class:in-progress={progress !== undefined}
|
||||
class:disabled={!node.visible}
|
||||
style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)}
|
||||
style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)}
|
||||
@@ -992,6 +994,9 @@
|
||||
<IconLabel {icon} />
|
||||
<!-- TODO: Allow the user to edit the name, just like in the Layers panel -->
|
||||
<TextLabel>{node.displayName}</TextLabel>
|
||||
{#if progress !== undefined}
|
||||
<div class="progress" style:width={`${Math.min(Math.max(progress, 0), 1) * 100}%`}></div>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Secondary rows -->
|
||||
{#if exposedInputsOutputs.length > 0}
|
||||
@@ -1515,6 +1520,10 @@
|
||||
border: 1px dashed var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
&.in-progress::after {
|
||||
border-color: var(--color-warning-yellow);
|
||||
}
|
||||
|
||||
.connectors {
|
||||
position: absolute;
|
||||
// Keeps the connectors above the wires
|
||||
@@ -1900,6 +1909,15 @@
|
||||
margin-left: 0;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.progress {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background: var(--color-e-nearwhite);
|
||||
transition: width 0.1s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.secondary {
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { HistoryThumbnail } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// An empty slot until the step is captured, so every row keeps one
|
||||
export let thumbnail: HistoryThumbnail | undefined;
|
||||
// The images the frontend received, by ID
|
||||
export let images: Record<string, string>;
|
||||
export let large = false;
|
||||
</script>
|
||||
|
||||
<span class="history-shot" class:large>
|
||||
<span class="image" data-tooltip-label="The document once this step was done">
|
||||
{#if thumbnail && images[thumbnail.whole]}<img src={images[thumbnail.whole]} alt="" />{/if}
|
||||
</span>
|
||||
<!-- The close-up is shown large only, beside the whole document, so a row never has two -->
|
||||
{#if large && thumbnail?.detail}
|
||||
<span class="image" data-tooltip-label="What this step changed, close up" data-tooltip-description="Green was added, red removed, and yellow changed.">
|
||||
{#if images[thumbnail.detail]}<img src={images[thumbnail.detail]} alt="" />{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
|
||||
<style lang="scss">
|
||||
.history-shot {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
|
||||
.image {
|
||||
width: 36px;
|
||||
height: 24px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
background-image: var(--color-transparent-checkered-background);
|
||||
background-size: var(--color-transparent-checkered-background-size-mini);
|
||||
background-position: var(--color-transparent-checkered-background-position-mini);
|
||||
background-repeat: var(--color-transparent-checkered-background-repeat);
|
||||
}
|
||||
|
||||
&.large {
|
||||
gap: 4px;
|
||||
|
||||
.image {
|
||||
// The size captures are rendered at, like layer thumbnails
|
||||
width: 72px;
|
||||
height: 48px;
|
||||
background-size: var(--color-transparent-checkered-background-size);
|
||||
background-position: var(--color-transparent-checkered-background-position);
|
||||
}
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -3,6 +3,7 @@
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import ProgressBar from "/src/components/widgets/labels/ProgressBar.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import NodeSection from "/src/components/widgets/NodeSection.svelte";
|
||||
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
|
||||
@@ -93,6 +94,18 @@
|
||||
<div class="expand-arrow"></div>
|
||||
</div>
|
||||
<TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description}>{widgetData.name}</TextLabel>
|
||||
{#if typeof widgetData.progress === "number"}
|
||||
<ProgressBar fraction={widgetData.progress} label={`${Math.floor(Math.min(Math.max(widgetData.progress, 0), 1) * 100)}%`} />
|
||||
<IconButton
|
||||
icon="CloseX"
|
||||
tooltipDescription="Stop the work in progress, keeping its result so far."
|
||||
size={24}
|
||||
action={(e) => {
|
||||
editor.cancelNodeWork(widgetData.id);
|
||||
e?.stopPropagation();
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
<IconButton
|
||||
icon={widgetData.visible ? "EyeVisible" : "EyeHidden"}
|
||||
hoverIcon={widgetData.visible ? "EyeHide" : "EyeShow"}
|
||||
@@ -461,6 +474,12 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
margin-left: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
// Hovering the chain sections within doesn't count
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<script lang="ts">
|
||||
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
let className = "";
|
||||
export { className as class };
|
||||
export let classes: Record<string, boolean> = {};
|
||||
|
||||
// Content
|
||||
export let fraction: number;
|
||||
export let label = "";
|
||||
// Tooltips
|
||||
export let tooltipLabel: string | undefined = undefined;
|
||||
export let tooltipDescription: string | undefined = undefined;
|
||||
export let tooltipShortcut: ActionShortcut | undefined = undefined;
|
||||
|
||||
$: extraClasses = Object.entries(classes)
|
||||
.flatMap(([className, stateName]) => (stateName ? [className] : []))
|
||||
.join(" ");
|
||||
$: percent = `${Math.min(Math.max(fraction, 0), 1) * 100}%`;
|
||||
</script>
|
||||
|
||||
<div
|
||||
class={`progress-bar ${className} ${extraClasses}`.trim()}
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={1}
|
||||
aria-valuenow={Math.min(Math.max(fraction, 0), 1)}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
data-tooltip-description={tooltipDescription}
|
||||
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
|
||||
>
|
||||
<div class="track">
|
||||
<div class="fill" style:width={percent}></div>
|
||||
</div>
|
||||
{#if label}
|
||||
<span class="label">{label}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.progress-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: 1 1 100%;
|
||||
height: 24px;
|
||||
|
||||
.track {
|
||||
position: relative;
|
||||
flex: 1 1 100%;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
background: var(--color-1-nearblack);
|
||||
}
|
||||
|
||||
.fill {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: var(--color-e-nearwhite);
|
||||
transition: width 0.1s linear;
|
||||
}
|
||||
|
||||
.label {
|
||||
flex: 0 0 auto;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
color: var(--color-a-softgray);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -9,57 +9,10 @@ const initialState: HistoryPanelState = { rows: [], progress: [], more: false, f
|
||||
|
||||
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
|
||||
const store: Writable<HistoryPanelState> = import.meta.hot?.data?.store || writable<HistoryPanelState>(initialState);
|
||||
// The captured images by the ID rows name them with, sent once each
|
||||
const thumbnails: Writable<Record<string, string>> = import.meta.hot?.data?.thumbnails || writable<Record<string, string>>({});
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.store = store;
|
||||
import.meta.hot.data.thumbnails = thumbnails;
|
||||
}
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
|
||||
const { subscribe, set } = store;
|
||||
|
||||
// The most recent images kept, oldest dropped first. Each step has a whole image and maybe a close-up, so twice as many as the editor keeps captures
|
||||
const MAX_THUMBNAILS = 600;
|
||||
// The size an SVG capture is drawn at, twice the largest a capture is shown
|
||||
const RASTER_WIDTH = 144;
|
||||
const RASTER_HEIGHT = 96;
|
||||
|
||||
// Kept as a small PNG rather than the pixels themselves
|
||||
function encodePixels(pixels: Uint8Array, width: number, height: number): string {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
canvas.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(pixels), width, height), 0, 0);
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
// Without the GPU a capture comes as an SVG, which can embed whole images, so it is kept as a small PNG, or as the SVG when the browser can't draw it
|
||||
async function rasterize(svg: string): Promise<string> {
|
||||
// An SVG drawn as an image needs an intrinsic size, which the capture's only gives as a view box
|
||||
const sized = svg.replace("<svg ", `<svg width="${RASTER_WIDTH}" height="${RASTER_HEIGHT}" `);
|
||||
const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(sized)}`;
|
||||
try {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = RASTER_WIDTH;
|
||||
canvas.height = RASTER_HEIGHT;
|
||||
canvas.getContext("2d")?.drawImage(image, 0, 0, RASTER_WIDTH, RASTER_HEIGHT);
|
||||
return canvas.toDataURL("image/png");
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function keepThumbnail(id: string, url: string) {
|
||||
thumbnails.update((images) => {
|
||||
const ids = Object.keys(images);
|
||||
const kept = ids.length < MAX_THUMBNAILS ? images : Object.fromEntries(ids.slice(ids.length - MAX_THUMBNAILS + 1).map((id) => [id, images[id]]));
|
||||
return { ...kept, [id]: url };
|
||||
});
|
||||
}
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
|
||||
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
@@ -70,16 +23,7 @@ export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
set(data.state);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnail", async (data) => {
|
||||
const url = await rasterize(data.svg);
|
||||
keepThumbnail(data.id, url);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnailPixels", (data) => {
|
||||
keepThumbnail(data.id, encodePixels(data.pixels, data.width, data.height));
|
||||
});
|
||||
|
||||
return { subscribe, thumbnails: { subscribe: thumbnails.subscribe } };
|
||||
return { subscribe };
|
||||
}
|
||||
|
||||
export function destroyHistoryStore() {
|
||||
@@ -87,7 +31,5 @@ export function destroyHistoryStore() {
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnail");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnailPixels");
|
||||
subscriptionsRouter = undefined;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ type NodeGraphStoreState = {
|
||||
clickTargets: FrontendClickTargets | undefined;
|
||||
contextMenuInformation: ContextMenuInformation | undefined;
|
||||
errors: NodeGraphErrorDiagnostic[];
|
||||
progress: Map<bigint, number>;
|
||||
layerWidths: Map<bigint, number>;
|
||||
chainWidths: Map<bigint, number>;
|
||||
hasLeftInputWire: Map<bigint, boolean>;
|
||||
@@ -48,6 +49,7 @@ const initialState: NodeGraphStoreState = {
|
||||
clickTargets: undefined,
|
||||
contextMenuInformation: undefined,
|
||||
errors: [],
|
||||
progress: new Map(),
|
||||
layerWidths: new Map(),
|
||||
chainWidths: new Map(),
|
||||
hasLeftInputWire: new Map(),
|
||||
@@ -236,6 +238,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphProgress", (data) => {
|
||||
update((state) => {
|
||||
state.progress = new Map(data.progress.map(({ nodeId, progress }) => [nodeId, progress]));
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
|
||||
const newNodes = new Set<bigint>(data.nodes);
|
||||
|
||||
@@ -360,6 +369,7 @@ export function destroyNodeGraphStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphProgress");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
|
||||
|
||||
@@ -750,6 +750,11 @@ mod editor_commands {
|
||||
DocumentMessage::ToggleNodeVisibility { node_id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Stop the work in progress of a node shown in the Inspector, which may be in a subgraph
|
||||
fn cancel_node_work(id: u64) -> Message {
|
||||
DocumentMessage::CancelNodeWork { node_id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Pin or unpin a node given its node ID
|
||||
fn set_node_pinned(id: u64, pinned: bool) -> Message {
|
||||
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
|
||||
|
||||
@@ -385,9 +385,14 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
pub fn source_ids(&self) -> impl Iterator<Item = &SourceId> {
|
||||
self.source_paths().map(|(source, _)| source)
|
||||
}
|
||||
|
||||
/// Each source with the path of the value node that injects it, which lies within the node that owns the source.
|
||||
pub fn source_paths(&self) -> impl Iterator<Item = (&SourceId, &[NodeId])> {
|
||||
self.nodes.iter().filter_map(|(_, node)| match &node.construction_args {
|
||||
ConstructionArgs::Value(value) => match &**value {
|
||||
TaggedValue::SourceId(source) => Some(source),
|
||||
TaggedValue::SourceId(source) => Some((source, node.original_location.path.as_deref().unwrap_or_default())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
|
||||
@@ -2,11 +2,11 @@ use crate::poll::Poll;
|
||||
use crate::uuid::NodeId;
|
||||
use dyn_any::WasmNotSend;
|
||||
use futures::future::{AbortHandle, Abortable};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::task::{Context, Waker};
|
||||
pub use web_time::Instant;
|
||||
|
||||
@@ -34,7 +34,12 @@ impl SourceId {
|
||||
pub type Generations = Arc<[(SourceId, u64)]>;
|
||||
|
||||
pub trait Runtime {
|
||||
/// Runs `task` outside of the graph, bumping the generation of `source` once it finishes.
|
||||
fn spawn(&self, source: SourceId, task: Task);
|
||||
/// Sets how far the work of `source` has come from 0 to 1, or with `None` clears it along with any cancellation request.
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>);
|
||||
/// Whether cancellation of the work of `source` was requested since this was last called.
|
||||
fn take_cancellation(&self, source: SourceId) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
@@ -44,6 +49,14 @@ impl Runtime for RuntimeHandle {
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
}
|
||||
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
|
||||
self.0.report_progress(source, progress);
|
||||
}
|
||||
|
||||
fn take_cancellation(&self, source: SourceId) -> bool {
|
||||
self.0.take_cancellation(source)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
@@ -68,16 +81,42 @@ impl AsyncRuntime {
|
||||
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
|
||||
Self(Arc::new(RuntimeInner {
|
||||
generations: Mutex::default(),
|
||||
progress: Mutex::default(),
|
||||
cancellations: Mutex::default(),
|
||||
spawner,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn update_sources(&self, live: &[SourceId]) {
|
||||
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut generations = lock(&self.0.generations);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
for source in live {
|
||||
generations.entry(*source).or_insert(0);
|
||||
}
|
||||
|
||||
lock(&self.0.progress).retain(|source, _| live.contains(source));
|
||||
lock(&self.0.cancellations).retain(|source| live.contains(source));
|
||||
}
|
||||
|
||||
/// The progress of every source that reported some and has not cleared it, sorted by source.
|
||||
pub fn progress(&self) -> Vec<(SourceId, f64)> {
|
||||
let mut progress: Vec<_> = lock(&self.0.progress).iter().map(|(source, progress)| (*source, *progress)).collect();
|
||||
progress.sort_unstable_by_key(|(source, _)| *source);
|
||||
progress
|
||||
}
|
||||
|
||||
/// Requests cancellation of the work of `source` and bumps its generation, so the node is evaluated again to see the request.
|
||||
/// Only work that reports progress can be canceled, so a request can't outlive the work it was meant for. Returns whether there was any.
|
||||
pub fn cancel(&self, source: SourceId) -> bool {
|
||||
if !lock(&self.0.progress).contains_key(&source) {
|
||||
return false;
|
||||
}
|
||||
lock(&self.0.cancellations).insert(source);
|
||||
|
||||
if let Some(generation) = lock(&self.0.generations).get_mut(&source) {
|
||||
*generation += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Generations {
|
||||
@@ -97,10 +136,20 @@ impl Runtime for AsyncRuntime {
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
}
|
||||
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
|
||||
self.0.report_progress(source, progress);
|
||||
}
|
||||
|
||||
fn take_cancellation(&self, source: SourceId) -> bool {
|
||||
self.0.take_cancellation(source)
|
||||
}
|
||||
}
|
||||
|
||||
struct RuntimeInner {
|
||||
generations: Mutex<HashMap<SourceId, u64>>,
|
||||
progress: Mutex<HashMap<SourceId, f64>>,
|
||||
cancellations: Mutex<HashSet<SourceId>>,
|
||||
spawner: Arc<dyn Spawn + Send + Sync>,
|
||||
}
|
||||
|
||||
@@ -109,11 +158,31 @@ impl RuntimeInner {
|
||||
let inner = Arc::clone(self);
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
task.await;
|
||||
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
|
||||
if let Some(generation) = lock(&inner.generations).get_mut(&source) {
|
||||
*generation += 1;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
|
||||
match progress {
|
||||
Some(progress) => {
|
||||
lock(&self.progress).insert(source, progress);
|
||||
}
|
||||
None => {
|
||||
lock(&self.progress).remove(&source);
|
||||
lock(&self.cancellations).remove(&source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_cancellation(&self, source: SourceId) -> bool {
|
||||
lock(&self.cancellations).remove(&source)
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
|
||||
@@ -289,6 +358,24 @@ mod tests {
|
||||
assert!(runtime.snapshot().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_work_in_progress_can_be_canceled() {
|
||||
let runtime = AsyncRuntime::new(Arc::new(CollectSpawner::default()));
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
assert!(!runtime.cancel(SOURCE));
|
||||
|
||||
runtime.report_progress(SOURCE, Some(0.5));
|
||||
assert!(runtime.cancel(SOURCE));
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)], "a cancellation bumps the generation");
|
||||
assert!(runtime.take_cancellation(SOURCE));
|
||||
assert!(!runtime.take_cancellation(SOURCE));
|
||||
|
||||
runtime.cancel(SOURCE);
|
||||
runtime.report_progress(SOURCE, None);
|
||||
assert!(!runtime.take_cancellation(SOURCE), "clearing the progress drops the request");
|
||||
assert!(runtime.progress().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_serves_the_placeholder_until_the_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
|
||||
@@ -89,19 +89,32 @@ fn vectorize(
|
||||
instancing: *instancing.element(),
|
||||
path_gradients: *path_gradients.element(),
|
||||
};
|
||||
let runtime = runtime.element();
|
||||
let source = *source.element();
|
||||
|
||||
let max_megabytes = Some(*max_memory.element()).filter(|&megabytes| megabytes > 0.);
|
||||
if cfg!(target_family = "wasm") && !*exceed_browser_limit.element() && max_megabytes.is_none_or(|megabytes| megabytes > BROWSER_MAX_MEGABYTES) {
|
||||
trace.clear();
|
||||
runtime.report_progress(source, None);
|
||||
return Poll::error(format!(
|
||||
"A memory limit above {BROWSER_MAX_MEGABYTES} MB, or none, can crash the editor in the browser. Lower the limit or turn on \"Exceed Browser Limit\"."
|
||||
));
|
||||
}
|
||||
let max_pixels = max_megabytes.map(|megabytes| (megabytes * 1e6 / BYTES_PER_PIXEL) as usize);
|
||||
let runtime = runtime.element();
|
||||
|
||||
if runtime.take_cancellation(source) {
|
||||
trace.cancel();
|
||||
}
|
||||
|
||||
let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE);
|
||||
if let Poll::Partial(_) = state {
|
||||
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
|
||||
runtime.spawn(*source.element(), Box::pin(async {}));
|
||||
match state {
|
||||
Poll::Partial(_) => {
|
||||
runtime.report_progress(source, trace.progress());
|
||||
|
||||
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
|
||||
runtime.spawn(source, Box::pin(async {}));
|
||||
}
|
||||
_ => runtime.report_progress(source, None),
|
||||
}
|
||||
state
|
||||
}
|
||||
@@ -135,14 +148,13 @@ fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: o
|
||||
width,
|
||||
height,
|
||||
};
|
||||
let options = ollev::TraceOptions {
|
||||
tolerance,
|
||||
detail: ollev::Detail::Scaled(detail),
|
||||
max_pixels,
|
||||
host: CAPABILITIES,
|
||||
stages,
|
||||
..Default::default()
|
||||
};
|
||||
let mut options = ollev::TraceOptions::default();
|
||||
options.tolerance = tolerance;
|
||||
options.detail = ollev::Detail::Scaled(detail);
|
||||
options.max_pixels = max_pixels;
|
||||
options.host = CAPABILITIES;
|
||||
options.stages = stages;
|
||||
|
||||
ollev::Tracing::new(&source, &options).map(|tracing| (tracing, pixels_to_document))
|
||||
};
|
||||
|
||||
@@ -404,4 +416,50 @@ mod test {
|
||||
assert_eq!(spawner.drain(), 2);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 2)]);
|
||||
}
|
||||
|
||||
/// A running trace reports progress that never goes down until it is done.
|
||||
#[test]
|
||||
fn a_trace_reports_progress_until_it_is_done() {
|
||||
let (spawner, runtime) = collecting_runtime();
|
||||
let (image, slot) = (busy(96), TraceSlot::default());
|
||||
|
||||
let mut previous = 0.;
|
||||
while matches!(evaluate(&slot, &image, &runtime), Poll::Partial(_)) {
|
||||
let progress = runtime.progress();
|
||||
let [(source, fraction)] = progress.as_slice() else { panic!("the trace reported {progress:?}") };
|
||||
assert_eq!(*source, SOURCE);
|
||||
assert!((previous..=1.).contains(fraction), "progress went from {previous} to {fraction}");
|
||||
|
||||
previous = *fraction;
|
||||
spawner.drain();
|
||||
}
|
||||
assert!(previous > 0., "the trace never reported any progress");
|
||||
assert!(runtime.progress().is_empty(), "a finished trace still reports progress");
|
||||
}
|
||||
|
||||
/// A canceled trace keeps its shapes so far, with an error, until its inputs change.
|
||||
#[test]
|
||||
fn a_canceled_trace_keeps_its_shapes_until_the_inputs_change() {
|
||||
let (_spawner, runtime) = collecting_runtime();
|
||||
let slot = TraceSlot::default();
|
||||
let image = busy(96);
|
||||
let shown = loop {
|
||||
match evaluate(&slot, &image, &runtime) {
|
||||
Poll::Partial(shown) if !shown.is_empty() => break shown,
|
||||
Poll::Partial(_) => {}
|
||||
state => panic!("the trace ended in {state:?} before showing shapes"),
|
||||
}
|
||||
};
|
||||
|
||||
assert!(runtime.cancel(SOURCE));
|
||||
let Poll::Fallback(boxed) = evaluate(&slot, &image, &runtime) else {
|
||||
panic!("the canceled trace went on")
|
||||
};
|
||||
assert!(boxed.0.len() >= shown.len(), "the canceled trace dropped its shapes");
|
||||
assert!(runtime.progress().is_empty());
|
||||
assert!(!runtime.cancel(SOURCE), "a canceled trace can be canceled again");
|
||||
|
||||
assert!(matches!(evaluate(&slot, &image, &runtime), Poll::Fallback(_)), "the canceled trace was started again");
|
||||
assert!(matches!(evaluate(&slot, &busy(128), &runtime), Poll::Partial(_)), "new inputs were not traced");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use core_types::Poll;
|
||||
use core_types::list::List;
|
||||
use core_types::runtime::Instant;
|
||||
use core_types::{NodeError, Poll};
|
||||
use glam::DAffine2;
|
||||
use graphic_types::Graphic;
|
||||
use ollev::model::Model;
|
||||
@@ -23,13 +23,15 @@ struct Trace {
|
||||
inputs: u64,
|
||||
/// `None` once the trace is done and `shown` is its result, or once it failed.
|
||||
tracing: Option<ollev::Tracing>,
|
||||
/// Why the trace failed, kept so the same inputs are not traced again.
|
||||
failed: Option<ollev::TraceError>,
|
||||
/// Why the trace failed or was canceled, kept so the same inputs are not traced again.
|
||||
failed: Option<NodeError>,
|
||||
/// Places the traced image's pixels in the document.
|
||||
pixels_to_document: DAffine2,
|
||||
shown: List<Graphic>,
|
||||
/// The revision of the scene in `shown`.
|
||||
revision: Option<u64>,
|
||||
/// How much of the trace is done from 0 to 1, as ollev last reported it.
|
||||
progress: f64,
|
||||
}
|
||||
|
||||
impl TraceSlot {
|
||||
@@ -54,6 +56,7 @@ impl TraceSlot {
|
||||
pixels_to_document,
|
||||
shown: List::new(),
|
||||
revision: None,
|
||||
progress: 0.,
|
||||
},
|
||||
Err(error) => return Poll::fallback(List::new(), error),
|
||||
},
|
||||
@@ -61,7 +64,11 @@ impl TraceSlot {
|
||||
|
||||
if let Some(tracing) = &mut trace.tracing {
|
||||
let deadline = Instant::now() + slice;
|
||||
let step = tracing.step(|_| if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) });
|
||||
let progress = &mut trace.progress;
|
||||
let step = tracing.step(|checkpoint| {
|
||||
*progress = checkpoint.overall;
|
||||
if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
});
|
||||
match step {
|
||||
Ok(ollev::Step::Done(model)) => {
|
||||
trace.shown = convert(&model, trace.pixels_to_document);
|
||||
@@ -69,7 +76,7 @@ impl TraceSlot {
|
||||
}
|
||||
Err(error) => {
|
||||
trace.tracing = None;
|
||||
trace.failed = Some(error);
|
||||
trace.failed = Some(error.into());
|
||||
}
|
||||
Ok(ollev::Step::Paused(progress)) => {
|
||||
if progress.showable()
|
||||
@@ -84,8 +91,8 @@ impl TraceSlot {
|
||||
}
|
||||
|
||||
let shown = trace.shown.clone();
|
||||
let state = match trace.failed {
|
||||
Some(error) => Poll::fallback(shown, error),
|
||||
let state = match &trace.failed {
|
||||
Some(error) => Poll::Fallback(Box::new((shown, error.clone()))),
|
||||
None if trace.tracing.is_some() => Poll::Partial(shown),
|
||||
None => Poll::Final(shown),
|
||||
};
|
||||
@@ -93,6 +100,21 @@ impl TraceSlot {
|
||||
state
|
||||
}
|
||||
|
||||
/// How much of the slot's trace is done from 0 to 1, while it is not yet done.
|
||||
pub fn progress(&self) -> Option<f64> {
|
||||
let held = self.lock();
|
||||
held.as_ref().filter(|trace| trace.tracing.is_some()).map(|trace| trace.progress)
|
||||
}
|
||||
|
||||
/// Stops the slot's trace, keeping the scene traced so far as the result for its inputs.
|
||||
pub fn cancel(&self) {
|
||||
let mut held = self.lock();
|
||||
let Some(trace) = held.as_mut().filter(|trace| trace.tracing.is_some()) else { return };
|
||||
|
||||
trace.tracing = None;
|
||||
trace.failed = Some(NodeError::new("The trace was canceled"));
|
||||
}
|
||||
|
||||
/// Drops the slot's trace.
|
||||
pub fn clear(&self) {
|
||||
self.lock().take();
|
||||
|
||||
Reference in new issue
Block a user