mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4be20d6df2 |
No files matched your search
@@ -199,6 +199,18 @@ 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>,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! 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,14 +5,39 @@ 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 },
|
||||
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>>,
|
||||
},
|
||||
}
|
||||
@@ -1,19 +1,22 @@
|
||||
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow, LineChange};
|
||||
use super::changes::{Change, ChangedArea, close_up, tint_changes};
|
||||
use super::utility_types::{CaptureImage, DocumentCapture, HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow, HistoryThumbnail, LineChange, Pixels};
|
||||
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, UserId, Value,
|
||||
coarsen, rev_attr,
|
||||
AttributeDelta, Declarations, Delta, HistoryMetadata, HotOp, HotOpId, Implementation, InputMetadataEntry, Node, NodeId, PeerId, Registry, RegistryDelta, Rev, Session, Subject, TimeStamp, UserId,
|
||||
Value, coarsen, rev_attr,
|
||||
};
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use peer_transport::RemotePeer;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
@@ -21,6 +24,7 @@ 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.
|
||||
@@ -33,10 +37,61 @@ 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 {
|
||||
@@ -55,9 +110,23 @@ 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 {
|
||||
@@ -126,6 +195,155 @@ 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());
|
||||
@@ -138,7 +356,8 @@ impl HistoryMessageHandler {
|
||||
|
||||
let previewing = document.and_then(|document| document.previewed_history_step());
|
||||
let limit = self.limit.max(PAGE);
|
||||
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following, previewing);
|
||||
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);
|
||||
if self.last_sent == Some(fingerprint) {
|
||||
return;
|
||||
}
|
||||
@@ -147,7 +366,7 @@ impl HistoryMessageHandler {
|
||||
.zip(gdd)
|
||||
.map(|(document, gdd)| HistoryPanelState {
|
||||
previewing: previewing.map(|rev| rev.to_string()),
|
||||
..panel_state(gdd, document.declarations(), limit, &self.expanded, self.following)
|
||||
..panel_state(gdd, document.declarations(), captures, limit, &self.expanded, self.following)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state });
|
||||
@@ -190,9 +409,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>) -> u64 {
|
||||
fn fingerprint(document_id: Option<DocumentId>, gdd: Option<&GddV1>, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>, previewing: Option<Rev>, images_sent: u64) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
(document_id, limit, expanded, following, previewing).hash(&mut hasher);
|
||||
(document_id, limit, expanded, following, previewing, images_sent).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);
|
||||
@@ -206,7 +425,7 @@ fn fingerprint(document_id: Option<DocumentId>, gdd: Option<&GddV1>, limit: usiz
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn panel_state(gdd: &GddV1, declarations: &Declarations, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
fn panel_state(gdd: &GddV1, declarations: &Declarations, captures: Option<&HashMap<TimeStamp, Capture>>, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
let session = gdd.session();
|
||||
let names = Names {
|
||||
registry: gdd.registry(),
|
||||
@@ -243,6 +462,7 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, limit: usize, expanded:
|
||||
head,
|
||||
people: &people,
|
||||
names: &names,
|
||||
captures,
|
||||
expanded,
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
@@ -254,7 +474,7 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, limit: usize, expanded:
|
||||
let collaborating = gdd.peers().next().is_some();
|
||||
HistoryPanelState {
|
||||
rows,
|
||||
progress: progress_rows(session, &people, &names),
|
||||
progress: progress_rows(session, &people, &names, captures),
|
||||
more,
|
||||
following: following.map(|tip| tip.to_string()),
|
||||
previewing: None,
|
||||
@@ -263,7 +483,27 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, limit: usize, expanded:
|
||||
}
|
||||
|
||||
/// Open interactions first, then closed ones waiting to retire, newest first.
|
||||
fn progress_rows(session: &Session, people: &People, names: &Names) -> Vec<HistoryProgressRow> {
|
||||
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<'_>> {
|
||||
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();
|
||||
@@ -274,20 +514,100 @@ fn progress_rows(session: &Session, people: &People, names: &Names) -> Vec<Histo
|
||||
None => open_by_peer.push((hot_op.timestamp.peer, vec![hot_op])),
|
||||
}
|
||||
}
|
||||
let mut progress: Vec<HistoryProgressRow> = open_by_peer
|
||||
let mut steps: Vec<HotStep> = open_by_peer
|
||||
.into_iter()
|
||||
.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)
|
||||
.map(|(author, ops)| {
|
||||
let action = session.pending_action().filter(|_| author == session.peer()).map(str::to_string);
|
||||
HotStep { author, ops, open: 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));
|
||||
progress.push(progress_row(people, names, interaction.author, &retired_kinds(ops), false, action));
|
||||
steps.push(HotStep {
|
||||
author: interaction.author,
|
||||
ops,
|
||||
open: false,
|
||||
action,
|
||||
});
|
||||
}
|
||||
progress
|
||||
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
|
||||
}
|
||||
|
||||
/// The deltas from `from` back along first parents to `until` (exclusive) or the root, newest first. Stops after
|
||||
@@ -331,6 +651,7 @@ 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,
|
||||
@@ -382,6 +703,7 @@ impl View<'_> {
|
||||
head: Some(closing.id) == self.head,
|
||||
expanded: is_expanded,
|
||||
details,
|
||||
thumbnail: self.captures.and_then(|captures| thumbnail(captures, closing.timestamp)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -409,7 +731,57 @@ fn retired_kinds(ops: Vec<&HotOp>) -> Vec<&RegistryDelta> {
|
||||
coarsen(ops).into_iter().map(|hot_op| &hot_op.op).collect()
|
||||
}
|
||||
|
||||
fn progress_row(people: &People, names: &Names, peer: PeerId, ops: &[&RegistryDelta], open: bool, action: Option<String>) -> HistoryProgressRow {
|
||||
/// 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 {
|
||||
let person = people.person(peer);
|
||||
HistoryProgressRow {
|
||||
label: action.unwrap_or_else(|| names.summarize(ops.iter().copied())),
|
||||
@@ -419,6 +791,7 @@ fn progress_row(people: &People, names: &Names, peer: PeerId, ops: &[&RegistryDe
|
||||
color: person.color,
|
||||
ops: foreground(ops, |kind| kind).len() as u32,
|
||||
open,
|
||||
thumbnail,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,7 +1042,7 @@ mod tests {
|
||||
gdd.undo().expect("undo");
|
||||
gdd.undo().expect("undo");
|
||||
|
||||
assert_eq!(panel_state(&gdd, &Declarations::new(), PAGE, &BTreeSet::new(), None).rows.len(), 3);
|
||||
assert_eq!(panel_state(&gdd, &Declarations::new(), None, PAGE, &BTreeSet::new(), None).rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -715,6 +1088,255 @@ 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::*;
|
||||
@@ -741,7 +1363,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(), PAGE, &BTreeSet::new(), None);
|
||||
let state = panel_state(gdd, document.declarations(), None, 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");
|
||||
}
|
||||
@@ -760,7 +1382,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(), PAGE, &BTreeSet::new(), None).progress[0].ops;
|
||||
let pending = panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None).progress[0].ops;
|
||||
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
assert_eq!(rows(&editor)[0].deltas, pending);
|
||||
@@ -778,7 +1400,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(), PAGE, &BTreeSet::new(), None);
|
||||
let state = panel_state(gdd, document.declarations(), None, 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"]);
|
||||
}
|
||||
@@ -807,7 +1429,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(), PAGE, &BTreeSet::new(), None);
|
||||
let state = panel_state(gdd, document.declarations(), None, 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:?}");
|
||||
}
|
||||
@@ -829,7 +1451,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(), PAGE, &BTreeSet::new(), None).rows
|
||||
panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), None).rows
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -860,7 +1482,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(), PAGE, &BTreeSet::new(), following).rows
|
||||
panel_state(gdd, document.declarations(), None, PAGE, &BTreeSet::new(), following).rows
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod changes;
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
@@ -1,5 +1,39 @@
|
||||
//! 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.
|
||||
@@ -50,6 +84,17 @@ 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))]
|
||||
@@ -81,4 +126,5 @@ pub struct HistoryProgressRow {
|
||||
pub ops: u32,
|
||||
/// Still being made, not closed and waiting.
|
||||
pub open: bool,
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
@@ -60,7 +60,7 @@ pub struct PortfolioMessageHandler {
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
ingest: IngestMessageHandler,
|
||||
history: HistoryMessageHandler,
|
||||
pub(crate) history: HistoryMessageHandler,
|
||||
sync: SyncMessageHandler,
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
@@ -144,6 +144,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -99,6 +99,12 @@ 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 {
|
||||
@@ -251,6 +257,36 @@ 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> {
|
||||
@@ -760,6 +796,7 @@ 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 }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -779,6 +816,7 @@ 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 }),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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};
|
||||
@@ -9,7 +10,7 @@ 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};
|
||||
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors, ProtoNetwork};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
@@ -52,10 +53,16 @@ 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>,
|
||||
@@ -104,6 +111,13 @@ 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),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -118,6 +132,18 @@ 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 {
|
||||
@@ -172,8 +198,11 @@ 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,
|
||||
|
||||
@@ -213,7 +242,15 @@ impl NodeRuntime {
|
||||
let mut graph = None;
|
||||
for request in self.receiver.try_iter() {
|
||||
match request {
|
||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||
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::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);
|
||||
@@ -228,6 +265,8 @@ 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),
|
||||
@@ -269,7 +308,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, &self.executor);
|
||||
self.thumbnails.update_sources(&layers, &network, &thumbnails::compiled_sources(&self.executor));
|
||||
self.old_graph = Some(network);
|
||||
}
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
@@ -323,6 +362,30 @@ 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)();
|
||||
@@ -529,7 +592,8 @@ impl NodeRuntime {
|
||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
/// Compiles a document network to the proto network the executor runs.
|
||||
fn compile(&mut self, graph: &NodeNetwork) -> Result<CompiledNetwork, CompileError> {
|
||||
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
|
||||
@@ -541,17 +605,21 @@ impl NodeRuntime {
|
||||
})
|
||||
};
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &resolve_resource) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
}
|
||||
if resource_missing.get() {
|
||||
self.node_graph_warnings = missing_resource_warnings(graph, &self.resources);
|
||||
return Err(CompileError::Message(e.to_string()));
|
||||
}
|
||||
|
||||
// We assume only one output
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
let c = Compiler {};
|
||||
let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
|
||||
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) {
|
||||
Ok(compiled_network) => compiled_network,
|
||||
Err(CompileError::Graph(errors)) => {
|
||||
let message = format!("{errors:?}");
|
||||
@@ -560,17 +628,61 @@ impl NodeRuntime {
|
||||
}
|
||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
||||
};
|
||||
self.node_graph_warnings.extend(warnings);
|
||||
self.node_graph_warnings = warnings;
|
||||
|
||||
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 {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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;
|
||||
@@ -26,6 +27,14 @@ 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.
|
||||
@@ -83,11 +92,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, executor: &DynamicExecutor) {
|
||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, source_of: SourceLookup) {
|
||||
// O(layers * depth)
|
||||
let sources: HashMap<NodeId, NodeId> = layer_paths
|
||||
.iter()
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, source_of)?)))
|
||||
.collect();
|
||||
|
||||
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
|
||||
@@ -216,22 +225,71 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
|
||||
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 render_params = RenderParams {
|
||||
footprint,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
content.graphic().render_svg(&mut render, &render_params);
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
self.show_svg(layer, content.svg(), responses).await;
|
||||
}
|
||||
|
||||
self.show_svg(layer, render.svg.to_svg_string(), 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 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 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,
|
||||
})
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
|
||||
@@ -336,24 +394,46 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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 {
|
||||
// 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),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
match bounds {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,15 +441,12 @@ impl ThumbnailContent {
|
||||
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
||||
let contents: Vec<ThumbnailContent> = layers
|
||||
.iter()
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, &compiled_sources(executor))?))
|
||||
.collect();
|
||||
|
||||
let bounds = contents
|
||||
.iter()
|
||||
.filter_map(|content| match content.content_bounds(false) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
})
|
||||
.filter_map(|content| content.content_bounds(false))
|
||||
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
||||
|
||||
let render_params = RenderParams {
|
||||
@@ -390,10 +467,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, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, source_of: SourceLookup) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
source_of(source.as_slice())
|
||||
}
|
||||
|
||||
/// Converts the other kinds of graphical content into a graphic.
|
||||
@@ -459,6 +536,7 @@ 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;
|
||||
@@ -482,6 +560,30 @@ 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, UVec2};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||
use graphene_std::renderer::{RenderOutputType, RenderParams};
|
||||
@@ -43,46 +43,59 @@ impl ThumbnailAtlasLayout {
|
||||
}
|
||||
|
||||
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
|
||||
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()
|
||||
cell_pixels(atlas_pixels, self.size().x, self.cell_size, self.cell_origin(index))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 cell_size = layout.cell_size.as_dvec2();
|
||||
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);
|
||||
|
||||
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 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.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
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";
|
||||
@@ -13,6 +14,7 @@
|
||||
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();
|
||||
@@ -96,6 +98,7 @@
|
||||
<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">
|
||||
@@ -120,7 +123,7 @@
|
||||
on:click={(e) => preview(e, row)}
|
||||
on:dblclick={(e) => goBackTo(e, row)}
|
||||
>
|
||||
{#if row.deltas > 1}
|
||||
{#if row.deltas > 1 || row.thumbnail?.detail}
|
||||
<button
|
||||
class="expand"
|
||||
data-row-control
|
||||
@@ -134,6 +137,7 @@
|
||||
<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)}>
|
||||
@@ -204,6 +208,13 @@
|
||||
</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>
|
||||
@@ -311,6 +322,16 @@
|
||||
&.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 {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<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>
|
||||
@@ -9,10 +9,57 @@ 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);
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
// 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;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -23,7 +70,16 @@ export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
set(data.state);
|
||||
});
|
||||
|
||||
return { subscribe };
|
||||
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 } };
|
||||
}
|
||||
|
||||
export function destroyHistoryStore() {
|
||||
@@ -31,5 +87,7 @@ export function destroyHistoryStore() {
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnail");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnailPixels");
|
||||
subscriptionsRouter = undefined;
|
||||
}
|
||||
Reference in new issue
Block a user