Compare commits

...
Author SHA1 Message Date
Dennis Kobert a42db391e6 Report Vectorize progress from ollev's own estimate of the whole trace 2026-11-21 23:12:25 +01:00
Dennis Kobert 4e3dfcd7e0 Move the Properties panel progress bar into the node section header and thicken the node progress bar 2026-11-21 23:12:18 +01:00
Dennis Kobert ceeb8ed909 Report Vectorize progress in the graph view and the Properties panel with a cancel button 2026-11-21 23:12:00 +01:00
Dennis Kobert b3823aa4e6 Outline the viewport in yellow while it shows a partial render and in red for fallbacks and errors 2026-11-21 19:30:12 +01:00
Dennis Kobert 5779dca840 Report partial and fallback renders as their own render status 2026-11-21 19:30:10 +01:00
Dennis Kobert 126e0c2fe7 Preview History panel steps and go back to one on double click (#4985)
* Preview History panel steps and go back to one on double click

* Autosave the current state while previewing a History panel step, and key its banners on the previewed step
2026-11-21 19:10:33 +01:00
Dennis Kobert 9ec601a069 Undo and redo History panel head moves and move the head onto branches (#4983)
* Undo and redo History panel head moves and move the head onto branches

* Persist the publish frontier with History panel head moves, refuse copies off the line, and warn on going back to an unknown step
2026-11-21 18:57:37 +01:00
Dennis Kobert b610d4cbf5 Repair the graph when the History panel removes a step or brings one back (#4982)
* Repair the graph when the History panel removes a step or brings one back

* Keep output indices and newer chain bottoms in the History panel's repair, and give an input naming a removed node its earlier value
2026-11-21 18:51:48 +01:00
Dennis Kobert d1969ce0b4 Move overlay computation into the runtime to reduce desync (#4956)
* Resolve layer outlines and path overlays against the render they're drawn over, so they stay on the artwork

* Trigger CI

* Make the Select tool's cage, pivot, compass rose, origin markers, and Path node outlines follow the render they're drawn over

* Tidy overlay comments and remove the local transform log, the magic Path input index, and duplicate transform lookups

* Follow rendered rotation and anchors in overlays, evaluate observer once
2026-11-21 18:50:54 +01:00
Timon 53a02c9c64 Store resources only in the resource storage instead of in the working copy (#4971)
* Unpack an opened file's resources straight into the resource storage

* Keep resources out of a document's container in the editor
2026-11-21 17:08:34 +00:00
Dennis Kobert 948ec7ba4e New node: 'Tile', which repeats content to fill the viewport (#4991)
Add Tile node repeating content over the viewport
2026-11-21 17:02:42 +00:00
Dennis Kobert f20eea64a9 Mark whole-input nodes as footprint invariant (#4990)
* Mark whole-input nodes as footprint invariant

* Mark Sort as footprint invariant

* Bump Area and Centroid versions for InjectFootprint
2026-11-21 17:01:46 +00:00
66 changed files with 3188 additions and 444 deletions

No files matched your search

Generated
+2 -2
View File
@@ -4842,9 +4842,9 @@ dependencies = [
[[package]] [[package]]
name = "ollev" name = "ollev"
version = "0.1.2" version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d77164e6c8fb386ee064104ab480578451b0fd106ca4c0a6988eb7ca4ed9ec4b" checksum = "9e858a872f7e5f74992f283fe52d9c184234e8505f316e6aa7822fa394b39d0a"
dependencies = [ dependencies = [
"glam", "glam",
] ]
+1 -1
View File
@@ -271,7 +271,7 @@ tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.8", features = ["html_reports"] } criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" } gungraun = { version = "0.20" }
ndarray = "0.17" ndarray = "0.17"
ollev = "0.1.2" ollev = "0.2.0"
dirs = "7.0" dirs = "7.0"
cef = "156" cef = "156"
cef-dll-sys = "156" cef-dll-sys = "156"
+16 -3
View File
@@ -54,11 +54,18 @@ pub trait Archive {
fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>>; fn writer<W: Write + Seek>(output: W) -> Result<Self::Writer<W>>;
fn unpack<R: Read + Seek>(source: R, sink: &mut UnpackEntry) -> Result<()>;
/// Read entries from `source` and write each into `dest`, streaming so neither the full /// Read entries from `source` and write each into `dest`, streaming so neither the full
/// archive nor the full container ever sits in memory at once. /// archive nor the full container ever sits in memory at once.
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()>; fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
Self::unpack(source, &mut |path, size, fill| dest.write_sized_non_blocking(path, size, fill))
}
} }
/// See [`Archive::unpack`].
pub type UnpackEntry<'a> = dyn FnMut(&str, usize, &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> + 'a;
pub trait ArchiveWriter: Sized { pub trait ArchiveWriter: Sized {
type Sink; type Sink;
@@ -100,12 +107,18 @@ impl ArchiveFormat {
/// Errors if the bytes are neither a recognized xz nor zip archive. /// Errors if the bytes are neither a recognized xz nor zip archive.
#[cfg(any(feature = "xz", feature = "zip"))] #[cfg(any(feature = "xz", feature = "zip"))]
pub fn open_auto<C: AsyncContainer>(bytes: &[u8], dest: &mut C) -> Result<()> { pub fn open_auto<C: AsyncContainer>(bytes: &[u8], dest: &mut C) -> Result<()> {
unpack_auto(bytes, &mut |path, size, fill| dest.write_sized_non_blocking(path, size, fill))
}
/// Like [`open_auto`], but hands each entry to `sink` instead of writing it into a container.
#[cfg(any(feature = "xz", feature = "zip"))]
pub fn unpack_auto(bytes: &[u8], sink: &mut UnpackEntry) -> Result<()> {
let source = std::io::Cursor::new(bytes); let source = std::io::Cursor::new(bytes);
match ArchiveFormat::detect(bytes) { match ArchiveFormat::detect(bytes) {
#[cfg(feature = "xz")] #[cfg(feature = "xz")]
Some(ArchiveFormat::Xz) => Xz::open(source, dest), Some(ArchiveFormat::Xz) => Xz::unpack(source, sink),
#[cfg(feature = "zip")] #[cfg(feature = "zip")]
Some(ArchiveFormat::Zip) => Zip::open(source, dest), Some(ArchiveFormat::Zip) => Zip::unpack(source, sink),
#[allow(unreachable_patterns)] #[allow(unreachable_patterns)]
Some(format) => Err(ContainerError::Codec(format!("tried to open {format:?}, but the binary was compiled without the feature enabled "))), Some(format) => Err(ContainerError::Codec(format!("tried to open {format:?}, but the binary was compiled without the feature enabled "))),
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip) ".into())), None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip) ".into())),
+4 -4
View File
@@ -1,7 +1,7 @@
//! Xz-compressed tarball archive codec. //! Xz-compressed tarball archive codec.
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size}; use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, UnpackEntry, checked_entry_size};
use crate::{AsyncContainer, ContainerError, Result, validate_path}; use crate::{ContainerError, Result, validate_path};
use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter}; use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter};
use std::io::{Read, Seek, Write}; use std::io::{Read, Seek, Write};
@@ -23,7 +23,7 @@ impl Archive for Xz {
}) })
} }
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> { fn unpack<R: Read + Seek>(source: R, sink: &mut UnpackEntry) -> Result<()> {
// `take` bounds how many bytes we decompress from the xz stream, but each tar entry's declared // `take` bounds how many bytes we decompress from the xz stream, but each tar entry's declared
// size is fed to `write_sized`, which pre-allocates from it before reading. Cap the cumulative // size is fed to `write_sized`, which pre-allocates from it before reading. Cap the cumulative
// declared size too so a header claiming a huge size can't trigger a giant allocation up front. // declared size too so a header claiming a huge size can't trigger a giant allocation up front.
@@ -46,7 +46,7 @@ impl Archive for Xz {
let size = checked_entry_size(&mut total_size, entry.size())?; let size = checked_entry_size(&mut total_size, entry.size())?;
dest.write_sized_non_blocking(&path, size, &mut |buffer| { sink(&path, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?; entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(()) Ok(())
})?; })?;
+4 -4
View File
@@ -1,7 +1,7 @@
//! Zip archive codec. //! Zip archive codec.
use crate::archive::{Archive, ArchiveWriter, checked_entry_size}; use crate::archive::{Archive, ArchiveWriter, UnpackEntry, checked_entry_size};
use crate::{AsyncContainer, ContainerError, Result, validate_path}; use crate::{ContainerError, Result, validate_path};
use std::io::{Read, Seek, Write}; use std::io::{Read, Seek, Write};
use zip::ZipArchive; use zip::ZipArchive;
@@ -24,7 +24,7 @@ impl Archive for Zip {
}) })
} }
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> { fn unpack<R: Read + Seek>(source: R, sink: &mut UnpackEntry) -> Result<()> {
let mut archive = ZipArchive::new(source).map_err(zip_err)?; let mut archive = ZipArchive::new(source).map_err(zip_err)?;
// Zip headers declare each entry's uncompressed size up front; `checked_entry_size` caps the running // Zip headers declare each entry's uncompressed size up front; `checked_entry_size` caps the running
@@ -41,7 +41,7 @@ impl Archive for Zip {
let size = checked_entry_size(&mut total_size, entry.size())?; let size = checked_entry_size(&mut total_size, entry.size())?;
dest.write_sized_non_blocking(&name, size, &mut |buffer| { sink(&name, size, &mut |buffer| {
entry.read_exact(buffer).map_err(ContainerError::Io)?; entry.read_exact(buffer).map_err(ContainerError::Io)?;
Ok(()) Ok(())
})?; })?;
+5 -4
View File
@@ -160,7 +160,7 @@ pub(crate) struct PendingPersist {
#[derive(Default)] #[derive(Default)]
struct MigrationInputs<'a> { struct MigrationInputs<'a> {
#[cfg(feature = "migrations")] #[cfg(feature = "migrations")]
byte_store: Option<&'a dyn graphene_resource::LoadResource>, byte_store: Option<&'a dyn ResourceStorage>,
#[cfg(feature = "migrations")] #[cfg(feature = "migrations")]
host: Option<&'a dyn migration_core::MigrationHost>, host: Option<&'a dyn migration_core::MigrationHost>,
#[cfg(not(feature = "migrations"))] #[cfg(not(feature = "migrations"))]
@@ -255,7 +255,7 @@ impl<L: Layout> Gdd<L> {
bytes: &[u8], bytes: &[u8],
mut working: AnyContainer, mut working: AnyContainer,
layout: L, layout: L,
byte_store: Option<&dyn graphene_resource::LoadResource>, byte_store: Option<&dyn ResourceStorage>,
host: Option<&dyn migration_core::MigrationHost>, host: Option<&dyn migration_core::MigrationHost>,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
document_container::archive::open_auto(bytes, &mut working)?; document_container::archive::open_auto(bytes, &mut working)?;
@@ -278,9 +278,10 @@ impl<L: Layout> Gdd<L> {
} }
/// [`open_in`](Self::open_in), offering migrations what only the caller has. `host` gives them the compiler, and without one, those asking for it /// [`open_in`](Self::open_in), offering migrations what only the caller has. `host` gives them the compiler, and without one, those asking for it
/// settle on their fallback for good. `byte_store` holds declarations the container doesn't, such as the editor's global cache. /// settle on their fallback for good. `byte_store` holds declarations the container doesn't, such as the editor's global cache,
/// and takes the ones migrations introduce in the container's place.
#[cfg(feature = "migrations")] #[cfg(feature = "migrations")]
pub async fn open_in_with(working: AnyContainer, layout: L, byte_store: Option<&dyn graphene_resource::LoadResource>, host: Option<&dyn migration_core::MigrationHost>) -> Result<Self, Error> { pub async fn open_in_with(working: AnyContainer, layout: L, byte_store: Option<&dyn ResourceStorage>, host: Option<&dyn migration_core::MigrationHost>) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs { byte_store, host }).await Self::open_stored(working, layout, MigrationInputs { byte_store, host }).await
} }
+7 -3
View File
@@ -7,7 +7,7 @@ use document_container::AsyncContainer;
use document_graph_storage::BlobHash; use document_graph_storage::BlobHash;
use document_graph_storage::blob::NewBlobs; use document_graph_storage::blob::NewBlobs;
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp}; use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
use graphene_resource::LoadResource; use graphene_resource::ResourceStorage;
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, Payload, PayloadCodec}; use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, Payload, PayloadCodec};
use migration_runner::{DocumentPayloads, HistoryOutcome, MigrationBlobs, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations}; use migration_runner::{DocumentPayloads, HistoryOutcome, MigrationBlobs, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
@@ -70,7 +70,7 @@ fn payload_codec(codec: Codec) -> PayloadCodec {
impl<L: Layout> Gdd<L> { impl<L: Layout> Gdd<L> {
/// Rewrite history through every registered node migration whose source declaration it references, in dependency order. Returns whether any ran. /// Rewrite history through every registered node migration whose source declaration it references, in dependency order. Returns whether any ran.
pub(crate) async fn migrate_nodes(&mut self, byte_store: Option<&dyn LoadResource>, host: Option<&dyn MigrationHost>) -> Result<bool, Error> { pub(crate) async fn migrate_nodes(&mut self, byte_store: Option<&dyn ResourceStorage>, host: Option<&dyn MigrationHost>) -> Result<bool, Error> {
let migrations = migration_core::registered_migrations(); let migrations = migration_core::registered_migrations();
if migrations.is_empty() { if migrations.is_empty() {
return Ok(false); return Ok(false);
@@ -112,6 +112,10 @@ impl<L: Layout> Gdd<L> {
// Declarations the migrations introduced need their bytes next to the other resources // Declarations the migrations introduced need their bytes next to the other resources
let referenced = self.session.all_declaration_resources(); let referenced = self.session.all_declaration_resources();
for declaration in resolver.encoded.values().filter(|declaration| referenced.contains_key(&declaration.id)) { for declaration in resolver.encoded.values().filter(|declaration| referenced.contains_key(&declaration.id)) {
if let Some(byte_store) = byte_store {
byte_store.store(&declaration.bytes);
continue;
}
let path = self.layout.resource_path(&declaration.hash); let path = self.layout.resource_path(&declaration.hash);
if !self.working.exists(&path).await { if !self.working.exists(&path).await {
self.working.write_non_blocking(&path, &declaration.bytes)?; self.working.write_non_blocking(&path, &declaration.bytes)?;
@@ -124,7 +128,7 @@ impl<L: Layout> Gdd<L> {
} }
/// Every declaration this document's nodes and history reference, from `byte_store` where it has them and otherwise from the container. /// Every declaration this document's nodes and history reference, from `byte_store` where it has them and otherwise from the container.
async fn load_stored_declarations(&self, byte_store: Option<&dyn LoadResource>) -> Declarations { async fn load_stored_declarations(&self, byte_store: Option<&dyn ResourceStorage>) -> Declarations {
let mut declarations = Declarations::new(); let mut declarations = Declarations::new();
for (id, hash) in self.session.all_declaration_resources() { for (id, hash) in self.session.all_declaration_resources() {
+6
View File
@@ -286,6 +286,9 @@ impl<L: Layout> SyncTarget for Gdd<L> {
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> { fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, touched) = self.session.drop_interaction(rev)?; let (moved, touched) = self.session.drop_interaction(rev)?;
if let Some(head) = moved.head {
self.session.publish_up_to(head);
}
self.remote_changes.touched.extend(touched); self.remote_changes.touched.extend(touched);
self.pending_persist.history = true; self.pending_persist.history = true;
self.pending_persist.hot_log = true; self.pending_persist.hot_log = true;
@@ -311,6 +314,9 @@ impl<L: Layout> SyncTarget for Gdd<L> {
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> { fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, touched) = self.session.move_head_to(rev)?; let (moved, touched) = self.session.move_head_to(rev)?;
if let Some(head) = moved.head {
self.session.publish_up_to(head);
}
self.remote_changes.touched.extend(touched); self.remote_changes.touched.extend(touched);
self.pending_persist.snapshot = true; self.pending_persist.snapshot = true;
Ok(moved) Ok(moved)
+14 -1
View File
@@ -504,6 +504,8 @@ impl<L: Layout> Gdd<L> {
let (moved, touched) = self.session.drop_interaction(rev)?; let (moved, touched) = self.session.drop_interaction(rev)?;
self.remote_changes.touched.extend(touched); self.remote_changes.touched.extend(touched);
#[cfg(feature = "network")]
self.publish_head_move(&moved);
self.persist_rewritten_line()?; self.persist_rewritten_line()?;
#[cfg(feature = "network")] #[cfg(feature = "network")]
if let Some(replica) = &mut self.network { if let Some(replica) = &mut self.network {
@@ -514,12 +516,13 @@ impl<L: Layout> Gdd<L> {
Ok(()) Ok(())
} }
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer asks the retirer. /// Move the head to an ancestor or a branch, keeping the line it was on as a branch. A non-retiring peer asks the retirer.
#[cfg(feature = "network")] #[cfg(feature = "network")]
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> { pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() { if self.retires_locally() {
let (moved, touched) = self.session.move_head_to(rev)?; let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched); self.remote_changes.touched.extend(touched);
self.publish_head_move(&moved);
self.persist_registry_snapshot()?; self.persist_registry_snapshot()?;
self.persist_session_state()?; self.persist_session_state()?;
if let Some(replica) = &mut self.network { if let Some(replica) = &mut self.network {
@@ -531,6 +534,16 @@ impl<L: Layout> Gdd<L> {
Ok(()) Ok(())
} }
/// Counts a head move the room is about to be sent as published, so the session state persisted with it keeps the frontier.
#[cfg(feature = "network")]
fn publish_head_move(&mut self, moved: &document_graph_storage::HeadMove) {
if self.network.is_some()
&& let Some(head) = moved.head
{
self.session.publish_up_to(head);
}
}
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer. /// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> { pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
if !self.retires_locally() { if !self.retires_locally() {
+12
View File
@@ -73,6 +73,18 @@ impl LoadResource for EmptyStore {
} }
} }
impl ResourceStorage for EmptyStore {
fn store(&self, data: &[u8]) -> ResourceHash {
ResourceHash::from(data)
}
fn contains(&self, _hash: &ResourceHash) -> bool {
false
}
fn garbage_collect(&self, _used: &[ResourceHash]) {}
}
fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork { fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
let node = |identifier: &'static str| DocumentNode { let node = |identifier: &'static str| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)), implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
+2
View File
@@ -12,6 +12,7 @@ pub mod model;
mod network_reference; mod network_reference;
mod prior; mod prior;
pub mod registry; pub mod registry;
mod repair;
pub mod resources; pub mod resources;
mod schema; mod schema;
pub mod session; pub mod session;
@@ -52,6 +53,7 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
mod tests { mod tests {
mod bookkeeping; mod bookkeeping;
mod crdt; mod crdt;
mod history_simulation;
mod projection; mod projection;
mod round_trip; mod round_trip;
mod sessions; mod sessions;
+420
View File
@@ -0,0 +1,420 @@
//! Repairs the graph after steps are replayed onto a line that changed since they were made, as bringing a step back
//! or removing one does. Replayed writes keep their stamps, so a slot written since keeps the newer value, which can
//! leave an input naming a removed node, two nodes on one, or a node nothing reaches any more.
//!
//! Nodes connected through their primary inputs form chains, like a stack of layers or a node feeding the next. Each
//! chain hangs off a head slot: an export, or an input past the primary one. The repair rebuilds every chain from the
//! order the line had before the replay and the order the replayed step left it in when it was made, so the step's
//! own changes land on the chains as they are now.
use crate::{NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta};
use std::collections::{BTreeSet, HashMap, HashSet};
/// What history holds of inputs the line no longer has.
#[derive(Default)]
pub(crate) struct KnownInputs {
/// Each node's network and newest primary input, for nodes this line no longer or never had.
pub primary: HashMap<NodeId, (NetworkId, NodeInput)>,
/// Each input's newest value not naming a node, for an input left naming a removed node that leads nowhere.
pub values: HashMap<(NodeId, u32), NodeInput>,
}
impl KnownInputs {
fn value(&self, slot: Slot) -> Option<NodeInput> {
match slot {
Slot::Input(id, index) => self.values.get(&(id, index)).cloned(),
Slot::Export(..) => None,
}
}
}
/// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Slot {
Input(NodeId, u32),
Export(NetworkId, u32),
}
/// A chain's nodes from its head down, and what the last one rests on.
struct Chain {
head: Slot,
nodes: Vec<NodeId>,
bottom: Option<NodeInput>,
}
/// Which of a dropped step's ops the line still needs, and the nodes they add. `registry` is the line with the step.
/// Kept are subgraphs the step added that a later node is built from, with their contents, resources, and the
/// registrations of peers in `later_authors`.
pub(crate) fn still_needed(registry: &Registry, dropped: &[RegistryDelta], later_authors: &HashSet<PeerId>) -> (Vec<usize>, HashSet<NodeId>) {
let added_networks: HashSet<NetworkId> = dropped
.iter()
.filter_map(|op| match op {
RegistryDelta::AddNetwork { id, .. } => Some(*id),
_ => None,
})
.collect();
let added_nodes: HashSet<NodeId> = dropped
.iter()
.filter_map(|op| match op {
RegistryDelta::AddNode { id, .. } => Some(*id),
_ => None,
})
.collect();
let built_from = |node: &crate::Node| match node.implementation() {
crate::Implementation::Network(network) if added_networks.contains(network) => Some(*network),
_ => None,
};
let mut needed: HashSet<NetworkId> = registry
.node_instances
.iter()
.filter(|(id, _)| !added_nodes.contains(id))
.filter_map(|(_, node)| built_from(node))
.collect();
// A needed subgraph's own nodes need the subgraphs they are built from
loop {
let nested: Vec<NetworkId> = registry
.node_instances
.values()
.filter(|node| needed.contains(&node.network()))
.filter_map(built_from)
.filter(|network| !needed.contains(network))
.collect();
if nested.is_empty() {
break;
}
needed.extend(nested);
}
let kept_nodes: HashSet<NodeId> = registry.node_instances.iter().filter(|(_, node)| needed.contains(&node.network())).map(|(&id, _)| id).collect();
let kept = dropped
.iter()
.enumerate()
.filter(|(_, op)| match op {
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::SetNetworkExport { id, .. } | RegistryDelta::ChangeNetworkAttribute { id, .. } => needed.contains(id),
RegistryDelta::AddNode { id, .. }
| RegistryDelta::ChangeNodeInput { id, .. }
| RegistryDelta::SetNodeInputs { id, .. }
| RegistryDelta::SetNodeImplementation { id, .. }
| RegistryDelta::ChangeNodeAttribute { id, .. }
| RegistryDelta::ChangeNodeInputAttribute { id, .. } => kept_nodes.contains(id),
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::AddSource { .. } => true,
RegistryDelta::RegisterPeer { peer, .. } => later_authors.contains(peer),
_ => false,
})
.map(|(index, _)| index)
.collect();
(kept, kept_nodes)
}
/// The ops that repair `registry`, which is `before` with `replayed` folded in. `intended` is the document as the
/// replayed step left it when it was made, and `gone` the nodes it must not have, as those the step deleted.
/// - A node in `gone`, or in neither `before` nor `intended`, is removed. A newer write to a node revives it over an
/// older removal, as one made on the line since does over a deletion brought back.
/// - Every chain keeps the nodes it had before, in their order, except those the replayed step moved, which take
/// their place from `intended`, after the node they followed there. A node the step added lands the same way.
/// - A node on no chain any more, which was on one, goes back where it was.
/// - An input naming a removed node takes that node's primary input instead, as deleting a node reconnects what it
/// sat between. A node this line never had counts as removed, with the primary input `known` gives it. Without
/// one, the input goes back to its newest value in `known`.
pub(crate) fn repair_ops(before: &Registry, registry: &Registry, intended: &Registry, replayed: &[RegistryDelta], gone: &HashSet<NodeId>, known: &KnownInputs) -> Vec<RegistryDelta> {
let mut registry = registry.clone();
let mut ops = Vec::new();
let mut unwanted: Vec<NodeId> = registry
.node_instances
.keys()
.filter(|id| gone.contains(id) || (!before.node_instances.contains_key(id) && !intended.node_instances.contains_key(id)))
.copied()
.collect();
unwanted.sort();
for id in unwanted {
if let Some(snapshot) = registry.node_instances.remove(&id) {
ops.push(RegistryDelta::RemoveNode { id, snapshot });
}
}
restore_subgraphs(&mut registry, intended, &mut ops);
let live = |id: &NodeId| registry.node_instances.contains_key(id);
let placed_by_step: HashSet<NodeId> = replayed.iter().flat_map(placed_nodes).filter(live).collect();
let heads: BTreeSet<Slot> = [before, &registry, intended].into_iter().flat_map(head_slots).filter(|&slot| owner_is_live(&registry, slot)).collect();
let was_in = |registry: &Registry| -> HashMap<NodeId, Slot> { heads.iter().flat_map(|&head| chain(registry, head).nodes.into_iter().map(move |id| (id, head))).collect() };
let (was_before, was_intended) = (was_in(before), was_in(intended));
// Where each node goes: where the step put it if it placed it, else where it was
let home = |id: &NodeId| match placed_by_step.contains(id) {
true => was_intended.get(id).or(was_before.get(id)),
false => was_before.get(id).or(was_intended.get(id)),
};
let mut chains = Vec::new();
let mut taken = HashSet::new();
for &head in &heads {
let owner = match head {
Slot::Input(owner, _) => Some(owner),
Slot::Export(..) => None,
};
let fits = |id: &NodeId| live(id) && Some(*id) != owner && home(id) == Some(&head);
let current = chain(&registry, head);
let earlier = chain(before, head);
let wanted = chain(intended, head);
// A node the step placed counts as moved when it sits on the other side of a node both orders have
let common: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| live(id) && wanted.nodes.contains(id)).collect();
let rank = |order: &[NodeId], id: &NodeId| order.iter().position(|node| node == id);
let moved = |id: &NodeId| {
placed_by_step.contains(id)
&& common.contains(id)
&& common
.iter()
.any(|other| other != id && (rank(&earlier.nodes, id) < rank(&earlier.nodes, other)) != (rank(&wanted.nodes, id) < rank(&wanted.nodes, other)))
};
let mut nodes: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| fits(id) && !moved(id)).collect();
for (position, id) in wanted.nodes.iter().enumerate() {
if nodes.contains(id) || !fits(id) {
continue;
}
let after = wanted.nodes[..position].iter().rev().find_map(|above| nodes.iter().position(|node| node == above));
nodes.insert(after.map_or(0, |index| index + 1), *id);
}
// What the chain rests on, as long as nothing else sits on it, preferring the replayed line's, which holds the newer
// of the step's write and the line's since. A chain of nodes rests on what the last node rested on in an order that
// had nodes too, since an empty one holds the head slot's own value, of another type.
let alike = |order: &Chain| order.nodes.is_empty() == nodes.is_empty();
let mut orders = [&current, &earlier, &wanted];
orders.sort_by_key(|order| !alike(order));
let bottom = orders.into_iter().filter_map(|order| order.bottom.clone()).find(|bottom| match bottom {
NodeInput::Node { id, .. } => live(id) && home(id).is_none(),
_ => true,
});
taken.extend(nodes.iter().copied());
chains.push(Chain { head, nodes, bottom });
}
// The output each node is taken from, where its order came from
let (outputs_before, outputs_now, outputs_intended) = (chain_outputs(before, &heads), chain_outputs(&registry, &heads), chain_outputs(intended, &heads));
let outputs: HashMap<NodeId, u32> = taken
.iter()
.map(|id| {
let orders = match placed_by_step.contains(id) {
true => [&outputs_intended, &outputs_now, &outputs_before],
false => [&outputs_before, &outputs_now, &outputs_intended],
};
(*id, orders.into_iter().find_map(|outputs| outputs.get(id).copied()).unwrap_or(0))
})
.collect();
for chain in &chains {
let mut slot = chain.head;
for &id in &chain.nodes {
set(&mut registry, &mut ops, slot, Some(NodeInput::Node { id, index: outputs[&id] }));
slot = Slot::Input(id, 0);
}
if let Some(bottom) = &chain.bottom {
set(&mut registry, &mut ops, slot, Some(bottom.clone()));
} else if let Some(NodeInput::Node { id, .. }) = slot_value(&registry, slot)
&& (taken.contains(&id) || !registry.node_instances.contains_key(&id))
{
// Resting on a node another chain holds, or one gone, it rests on nothing instead
let cleared = match slot {
Slot::Export(..) => None,
Slot::Input(..) => reconnect(&registry, id, slot_network(&registry, slot), known)
.filter(|input| !matches!(input, NodeInput::Node { .. }))
.or_else(|| known.value(slot)),
};
if cleared.is_some() || matches!(slot, Slot::Export(..)) {
set(&mut registry, &mut ops, slot, cleared);
}
}
}
// Inputs off every chain still naming a removed node
for (slot, named) in slots(&registry) {
if registry.node_instances.contains_key(&named) {
continue;
}
let reconnected = reconnect(&registry, named, slot_network(&registry, slot), known)
.or_else(|| slot_value(before, slot).filter(|earlier| !names_missing(&registry, earlier)))
.or_else(|| known.value(slot));
if reconnected.is_some() || matches!(slot, Slot::Export(..)) {
set(&mut registry, &mut ops, slot, reconnected);
}
}
ops
}
/// Adds back, as `intended` has them, the subgraphs the line lacks that its nodes are built from.
fn restore_subgraphs(registry: &mut Registry, intended: &Registry, ops: &mut Vec<RegistryDelta>) {
let lacking = |registry: &Registry, node: &crate::Node| match node.implementation() {
crate::Implementation::Network(network) if !registry.networks.contains_key(network) && intended.networks.contains_key(network) => Some(*network),
_ => None,
};
let mut missing: BTreeSet<NetworkId> = registry.node_instances.values().filter_map(|node| lacking(registry, node)).collect();
while let Some(network) = missing.pop_first() {
let content = intended.networks[&network].clone();
registry.networks.insert(network, content.clone());
ops.push(RegistryDelta::AddNetwork { id: network, network: content });
let mut inside: Vec<(&NodeId, &crate::Node)> = intended
.node_instances
.iter()
.filter(|(id, node)| node.network() == network && !registry.node_instances.contains_key(id))
.collect();
inside.sort_by_key(|(id, _)| **id);
for (&id, node) in inside {
missing.extend(lacking(registry, node));
registry.node_instances.insert(id, node.clone());
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
}
}
}
/// The output each node on the chains below `heads` is taken from.
fn chain_outputs(registry: &Registry, heads: &BTreeSet<Slot>) -> HashMap<NodeId, u32> {
let mut outputs = HashMap::new();
for &head in heads {
let mut below = slot_value(registry, head);
while let Some(NodeInput::Node { id, index }) = below
&& outputs.insert(id, index).is_none()
{
below = slot_value(registry, Slot::Input(id, 0));
}
}
outputs
}
fn names_missing(registry: &Registry, input: &NodeInput) -> bool {
matches!(input, NodeInput::Node { id, .. } if !registry.node_instances.contains_key(id))
}
/// The nodes a write places in a slot, or adds.
fn placed_nodes(op: &RegistryDelta) -> Vec<NodeId> {
match op {
RegistryDelta::AddNode { id, .. } => vec![*id],
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let placed = match new_input {
NodeInput::Node { id: placed, .. } => Some(*placed),
_ => None,
};
(*index == 0).then_some(*id).into_iter().chain(placed).collect()
}
RegistryDelta::SetNodeInputs { id, inputs } => {
let placed = inputs.iter().filter_map(|slot| match &slot.input {
NodeInput::Node { id: placed, .. } => Some(*placed),
_ => None,
});
std::iter::once(*id).chain(placed).collect()
}
RegistryDelta::SetNetworkExport {
export: Some(NodeInput::Node { id, .. }),
..
} => vec![*id],
_ => Vec::new(),
}
}
/// Every slot naming a node, in a fixed order.
fn slots(registry: &Registry) -> Vec<(Slot, NodeId)> {
let mut slots = Vec::new();
for (&id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = slot.input {
slots.push((Slot::Input(id, index as u32), named));
}
}
}
for (&id, network) in &registry.networks {
for (index, slot) in network.exports.iter().enumerate() {
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
slots.push((Slot::Export(id, index as u32), named));
}
}
}
slots.sort();
slots
}
/// The slots heading a chain: exports and inputs past the primary one, naming a node.
fn head_slots(registry: &Registry) -> impl Iterator<Item = Slot> + '_ {
slots(registry).into_iter().map(|(slot, _)| slot).filter(|slot| !matches!(slot, Slot::Input(_, 0)))
}
fn owner_is_live(registry: &Registry, slot: Slot) -> bool {
match slot {
Slot::Input(id, _) => registry.node_instances.contains_key(&id),
Slot::Export(id, _) => registry.networks.contains_key(&id),
}
}
/// The chain hanging off `head` in `registry`.
fn chain(registry: &Registry, head: Slot) -> Chain {
let mut nodes = Vec::new();
let mut below = slot_value(registry, head);
while let Some(NodeInput::Node { id, .. }) = below {
if nodes.contains(&id) || !registry.node_instances.contains_key(&id) {
return Chain { head, nodes, bottom: None };
}
nodes.push(id);
below = slot_value(registry, Slot::Input(id, 0));
}
Chain { head, nodes, bottom: below }
}
fn slot_network(registry: &Registry, slot: Slot) -> Option<NetworkId> {
match slot {
Slot::Input(id, _) => registry.node_instances.get(&id).map(|node| node.network),
Slot::Export(id, _) => Some(id),
}
}
fn slot_value(registry: &Registry, slot: Slot) -> Option<NodeInput> {
match slot {
Slot::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
Slot::Export(id, index) => registry.networks.get(&id)?.exports.get(index as usize)?.target.clone(),
}
}
/// What a removed node's primary input led to, through removed nodes, staying in `network`. None when the chain ends
/// at a node never seen or in another network.
fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, known: &KnownInputs) -> Option<NodeInput> {
let mut visited = HashSet::new();
let mut current = removed;
loop {
if !visited.insert(current) {
return None;
}
let (in_network, input) = match registry.removed_nodes.get(&current) {
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
None => known.primary.get(&current).cloned()?,
};
if Some(in_network) != network {
return None;
}
match input {
NodeInput::Node { id, .. } if !registry.node_instances.contains_key(&id) => current = id,
NodeInput::Node { id, .. } if Some(registry.node_instances[&id].network) != network => return None,
input => return Some(input),
}
}
}
/// Records and applies the op setting `slot` to `input`, unless the slot holds it already. `None` clears an export.
fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input: Option<NodeInput>) {
if slot_value(registry, slot) == input {
return;
}
match slot {
Slot::Input(id, index) => {
let Some(input) = input else { return };
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
slot.input = input.clone();
}
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
}
Slot::Export(id, index) => {
if let Some(slot) = registry.networks.get_mut(&id).and_then(|network| network.exports.get_mut(index as usize)) {
slot.target = input.clone();
}
ops.push(RegistryDelta::SetNetworkExport { id, index, export: input });
}
}
}
+186 -33
View File
@@ -446,23 +446,91 @@ impl Session {
} }
let position = newest_first.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?; let position = newest_first.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
// Minted on a scratch fold first, so a failing copy changes nothing. // Minted on a scratch fold first, so a failing copy changes nothing. Each copied interaction ends with the
// repairs it needs on the changed line.
let mut scratch = self.fold_scratch_at(Some(base))?; let mut scratch = self.fold_scratch_at(Some(base))?;
let mut copies = Vec::with_capacity(position); let mut copies = Vec::with_capacity(position);
// Per copy, the delta it carries attributes from, and the repair now closing that delta's interaction
let mut sources: Vec<(Option<&Delta>, Option<Rev>)> = Vec::with_capacity(position);
let mut parent = Some(base); let mut parent = Some(base);
let mut replayed = Vec::new();
let known = self.known_inputs();
// What the later steps build on stays, ahead of them
let dropped: Vec<&Delta> = newest_first[position..].iter().rev().collect();
let later_authors: HashSet<PeerId> = newest_first[..position].iter().map(|delta| delta.author).collect();
let (kept, kept_nodes) = match position {
0 => Default::default(),
_ => crate::repair::still_needed(&self.document.retired_snapshot, &dropped.iter().map(|delta| delta.kind.clone()).collect::<Vec<_>>(), &later_authors),
};
for original in kept.into_iter().map(|index| dropped[index]) {
let reverse = crate::prior::capture(&scratch.working_registry, &original.kind);
scratch.apply_op_with(RegistryTarget::Working, original.kind.clone(), original.timestamp, ApplyMode::Idempotent)?;
let copy = Delta::new(parent, original.timestamp.peer, original.timestamp, original.kind.clone(), reverse);
parent = Some(copy.id);
copies.push(copy);
sources.push((None, None));
}
let mut before = scratch.working_registry.clone();
// What the removed step added must not come back through a later step writing to it
let gone: HashSet<NodeId> = dropped
.iter()
.filter_map(|delta| match &delta.kind {
RegistryDelta::AddNode { id, .. } => Some(*id),
_ => None,
})
.filter(|id| !kept_nodes.contains(id))
.collect();
for original in newest_first[..position].iter().rev() { for original in newest_first[..position].iter().rev() {
let reverse = crate::prior::capture(&scratch.working_registry, &original.kind); let reverse = crate::prior::capture(&scratch.working_registry, &original.kind);
scratch.apply_op_with(RegistryTarget::Working, original.kind.clone(), original.timestamp, ApplyMode::Idempotent)?; scratch.apply_op_with(RegistryTarget::Working, original.kind.clone(), original.timestamp, ApplyMode::Idempotent)?;
let copy = Delta::new(parent, original.timestamp.peer, original.timestamp, original.kind.clone(), reverse); let copy = Delta::new(parent, original.timestamp.peer, original.timestamp, original.kind.clone(), reverse);
parent = Some(copy.id); parent = Some(copy.id);
copies.push(copy); copies.push(copy);
sources.push((Some(original), None));
replayed.push(original.kind.clone());
if !original.is_interaction_end() {
continue;
}
let closing_index = sources.len() - 1;
for op in crate::repair::repair_ops(
&before,
&scratch.working_registry,
&self.fold_scratch_at(Some(original.id))?.working_registry,
&std::mem::take(&mut replayed),
&gone,
&known,
) {
let reverse = crate::prior::capture(&scratch.working_registry, &op);
let timestamp = self.document.clock.tick();
scratch.apply_op_with(RegistryTarget::Working, op.clone(), timestamp, ApplyMode::Strict)?;
let repair = Delta::new(parent, original.author, timestamp, op, reverse);
parent = Some(repair.id);
sources[closing_index].1 = Some(repair.id);
copies.push(repair);
sources.push((None, None));
}
before = scratch.working_registry.clone();
} }
let mut touched = Touched::default(); let mut touched = Touched::default();
newest_first[position..].iter().for_each(|delta| touched.record(&delta.kind)); newest_first[position..].iter().for_each(|delta| touched.record(&delta.kind));
for (original, copy) in newest_first[..position].iter().rev().zip(&mut copies) { for (copy, _) in copies.iter().zip(&sources).filter(|(_, (original, _))| original.is_none()) {
self.document.history.push(copy.clone()); touched.record(&copy.kind);
self.carry_attributes(original, copy.id); }
// A kept op minted on its own parent is the original, attributes and all
for copy in &copies {
if !self.document.history.contains(copy.id) {
self.document.history.push(copy.clone());
}
}
for (&(original, closing), copy) in sources.iter().zip(&copies) {
if let Some(original) = original {
self.carry_attributes(original, copy.id, closing);
}
}
for copy in &mut copies {
if let Some(carried) = self.document.history.get(copy.id) { if let Some(carried) = self.document.history.get(copy.id) {
*copy = carried.clone(); *copy = carried.clone();
} }
@@ -474,9 +542,6 @@ impl Session {
self.document.redo_stack.clear(); self.document.redo_stack.clear();
self.document.rebuild_working(); self.document.rebuild_working();
self.runtime_base = None; self.runtime_base = None;
if let Some(head) = self.document.head {
self.publish_up_to(head);
}
Ok(( Ok((
HeadMove { HeadMove {
from, from,
@@ -487,14 +552,15 @@ impl Session {
)) ))
} }
/// Move the shared head back to its ancestor `target`, leaving the line since as a branch. Returns the move to /// Move the shared head to `target`, back to an ancestor or over to a branch, leaving the line it was on as a
/// broadcast and what the steps left behind named. Only the retirer does this; a guest asks it to. /// branch. Returns the move to broadcast and what the steps between the two lines named. Only the retirer does
/// this; a guest asks it to.
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> { pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
let from = self.document.head; let from = self.document.head;
if from == Some(target) { if from == Some(target) {
return Err(CrdtError::NothingToUndo); return Err(CrdtError::NothingToUndo);
} }
let touched = self.touched_since(Some(target))?; let touched = self.touched_between_lines(Some(target))?;
let snapshot = self.fold_at(Some(target))?; let snapshot = self.fold_at(Some(target))?;
self.document.head = Some(target); self.document.head = Some(target);
@@ -502,7 +568,6 @@ impl Session {
self.document.redo_stack.clear(); self.document.redo_stack.clear();
self.document.rebuild_working(); self.document.rebuild_working();
self.runtime_base = None; self.runtime_base = None;
self.publish_up_to(target);
Ok(( Ok((
HeadMove { HeadMove {
from, from,
@@ -514,8 +579,8 @@ impl Session {
} }
/// Follow a peer's [`HeadMove`], returning what the walked-over ops named. Changes nothing when the head is not /// Follow a peer's [`HeadMove`], returning what the walked-over ops named. Changes nothing when the head is not
/// where the move started, since this peer has then diverged, or when the copies don't chain from an ancestor of /// where the move started, since this peer has then diverged, or when the copies don't chain from a known rev to the
/// the head to the move's head. /// move's head.
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> { pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
if self.document.head != moved.from { if self.document.head != moved.from {
return Err(CrdtError::CursorMismatch { return Err(CrdtError::CursorMismatch {
@@ -524,7 +589,12 @@ impl Session {
}); });
} }
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent); let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
let touched = self.touched_since(base)?; // Copies are minted again on the line being left, so they start from one of its steps
let copies_off_the_line = !moved.copies.is_empty() && base.is_some_and(|base| !self.document.history.ancestors(moved.from).contains(&base));
if copies_off_the_line {
return Err(CrdtError::MalformedHeadMove);
}
let touched = self.touched_between_lines(base)?;
let mut tip = base; let mut tip = base;
for copy in &moved.copies { for copy in &moved.copies {
if copy.parent != tip || matches!(copy.kind, RegistryDelta::Merge { .. }) { if copy.parent != tip || matches!(copy.kind, RegistryDelta::Merge { .. }) {
@@ -568,26 +638,26 @@ impl Session {
touched touched
} }
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is /// What the deltas on just one of the head's and `other`'s lines named, merged branches included.
/// on the head's line. fn touched_between_lines(&self, other: Option<Rev>) -> Result<Touched, CrdtError> {
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
let history = &self.document.history; let history = &self.document.history;
let line = history.ancestors(self.document.head); if let Some(other) = other
if let Some(base) = base && !history.contains(other)
&& !line.contains(&base)
{ {
return Err(CrdtError::NotAncestor(base)); return Err(CrdtError::NotFoundInHistory(other));
} }
let kept = history.ancestors(base); let line = history.ancestors(self.document.head);
let other_line = history.ancestors(other);
let mut touched = Touched::default(); let mut touched = Touched::default();
for delta in history.iter().filter(|delta| line.contains(&delta.id) && !kept.contains(&delta.id)) { for delta in history.iter().filter(|delta| line.contains(&delta.id) != other_line.contains(&delta.id)) {
touched.record(&delta.kind); touched.record(&delta.kind);
} }
Ok(touched) Ok(touched)
} }
/// Mint a dropped interaction's deltas again on top of the line as one interaction. They keep their /// Mint a dropped interaction's deltas again on top of the line as one interaction. They keep their
/// original stamps, so a field someone wrote since keeps the newer value. Returns the new revs. /// original stamps, so a field someone wrote since keeps the newer value, and the graph is repaired where that
/// left it broken (see [`repair_ops`](crate::repair::repair_ops)). Returns the new revs.
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> { pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?; let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?;
let mut originals = Vec::new(); let mut originals = Vec::new();
@@ -599,10 +669,32 @@ impl Session {
originals.push(delta); originals.push(delta);
} }
originals.reverse(); originals.reverse();
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?; let before = self.document.retired_snapshot.clone();
let mut revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
let replayed: Vec<RegistryDelta> = originals.iter().map(|delta| delta.kind.clone()).collect();
let deleted: HashSet<NodeId> = replayed
.iter()
.filter_map(|op| match op {
RegistryDelta::RemoveNode { id, .. } => Some(*id),
_ => None,
})
.collect();
let repairs = crate::repair::repair_ops(
&before,
&self.document.retired_snapshot,
&self.fold_scratch_at(Some(dropped))?.working_registry,
&replayed,
&deleted,
&self.known_inputs(),
);
let author = originals.last().map_or(self.document.peer, |delta| delta.author);
let repaired = self.commit_repairs(repairs, author)?;
let closing = repaired.last().copied();
for (original, &rev) in originals.iter().zip(&revs) { for (original, &rev) in originals.iter().zip(&revs) {
self.carry_attributes(original, rev); let closes = original.id == dropped;
self.carry_attributes(original, rev, closing.filter(|_| closes));
} }
revs.extend(repaired);
if let Some(&last) = revs.last() { if let Some(&last) = revs.last() {
self.mark_interaction_end(last); self.mark_interaction_end(last);
} }
@@ -651,6 +743,11 @@ impl Session {
Ok(scratch) Ok(scratch)
} }
/// The document as it was once `rev` was done, folded from history.
pub fn registry_at(&self, rev: Rev) -> Result<Registry, CrdtError> {
Ok(self.fold_scratch_at(Some(rev))?.working_registry)
}
pub fn history_len(&self) -> usize { pub fn history_len(&self) -> usize {
self.document.history.len() self.document.history.len()
} }
@@ -942,16 +1039,74 @@ impl Session {
} }
} }
/// Give a minted copy the attributes and retirement time of the delta it stands for. /// Give a minted copy the attributes and retirement time of its original. The interaction end and action move to
fn carry_attributes(&mut self, original: &Delta, copy: Rev) { /// `closing` when repairs after the copy now end the interaction.
if let Some(wall_ms) = original.retired_at() { fn carry_attributes(&mut self, original: &Delta, copy: Rev, closing: Option<Rev>) {
self.document.history.set_retired_at(copy, wall_ms); use crate::attr::delta::{ACTION, INTERACTION_END};
for rev in std::iter::once(copy).chain(closing) {
if let Some(wall_ms) = original.retired_at() {
self.document.history.set_retired_at(rev, wall_ms);
}
} }
for (key, value) in original.attributes.live() { for (key, value) in original.attributes.live() {
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp); let moved = closing.filter(|_| key == INTERACTION_END || key == ACTION);
self.document.history.annotate(moved.unwrap_or(copy), key, value.value.clone(), value.timestamp);
} }
} }
/// Each node's network and newest primary input, and each input's newest value, anywhere in history, branches included.
fn known_inputs(&self) -> crate::repair::KnownInputs {
let mut networks: HashMap<NodeId, (TimeStamp, NetworkId)> = HashMap::new();
let mut primary: HashMap<NodeId, (TimeStamp, Option<crate::NodeInput>)> = HashMap::new();
let mut values: HashMap<(NodeId, u32), (TimeStamp, crate::NodeInput)> = HashMap::new();
for delta in self.document.history.iter() {
let whole_list = |slots: &[crate::InputSlot]| -> Vec<(u32, crate::NodeInput)> { slots.iter().enumerate().map(|(index, slot)| (index as u32, slot.input.clone())).collect() };
// The inputs the delta writes, and whether it writes the whole list, so an empty one ends the primary input
let (id, written, whole) = match &delta.kind {
RegistryDelta::AddNode { id, node } | RegistryDelta::RemoveNode { id, snapshot: node } => {
if networks.get(id).is_none_or(|(newest, _)| *newest < delta.timestamp) {
networks.insert(*id, (delta.timestamp, node.network));
}
(*id, whole_list(&node.inputs), true)
}
RegistryDelta::ChangeNodeInput { id, index, new_input } => (*id, vec![(*index, new_input.clone())], false),
RegistryDelta::SetNodeInputs { id, inputs } => (*id, whole_list(inputs), true),
_ => continue,
};
let newer = |newest: &TimeStamp| *newest < delta.timestamp;
let first = written.iter().find(|(index, _)| *index == 0).map(|(_, input)| input.clone());
if (whole || first.is_some()) && primary.get(&id).is_none_or(|(newest, _)| newer(newest)) {
primary.insert(id, (delta.timestamp, first));
}
for (index, input) in written {
if !matches!(input, crate::NodeInput::Node { .. }) && values.get(&(id, index)).is_none_or(|(newest, _)| newer(newest)) {
values.insert((id, index), (delta.timestamp, input));
}
}
}
crate::repair::KnownInputs {
primary: primary.into_iter().filter_map(|(id, (_, input))| Some((id, (networks.get(&id)?.1, input?)))).collect(),
values: values.into_iter().map(|(slot, (_, input))| (slot, input)).collect(),
}
}
/// Commit repair ops on top of the line, authored by whoever made the interaction they finish.
fn commit_repairs(&mut self, ops: Vec<RegistryDelta>, author: PeerId) -> Result<Vec<Rev>, CrdtError> {
let mut revs = Vec::with_capacity(ops.len());
for op in ops {
let reverse = crate::prior::capture(&self.document.retired_snapshot, &op);
let delta = Delta::new(self.document.head, author, self.document.clock.tick(), op, reverse);
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Strict)?;
self.document.head = Some(delta.id);
revs.push(delta.id);
self.document.history.push(delta);
}
Ok(revs)
}
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place. /// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the /// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this. /// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
@@ -1416,8 +1571,6 @@ pub enum CrdtError {
NotUndoable(Rev), NotUndoable(Rev),
#[error("Cursor is at {found:?}, the move expected {expected:?}")] #[error("Cursor is at {found:?}, the move expected {expected:?}")]
CursorMismatch { expected: Option<Rev>, found: Option<Rev> }, CursorMismatch { expected: Option<Rev>, found: Option<Rev> },
#[error("Delta {0} is not on the head's line")]
NotAncestor(Rev),
#[error("Head move copies do not chain from its base to its head")] #[error("Head move copies do not chain from its base to its head")]
MalformedHeadMove, MalformedHeadMove,
#[error("Node {0} already exists")] #[error("Node {0} already exists")]
@@ -0,0 +1,451 @@
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
//! head moves must hold the same document.
//!
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use std::collections::HashSet;
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// The layers from the top of the stack down, following each layer's first input.
fn stack(registry: &Registry) -> Vec<NodeId> {
let mut layers = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
break;
}
layers.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
layers
}
/// What feeds into `layer` from below.
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
registry.node_instances[&layer].inputs[0].input.clone()
}
/// Points what sits directly above `layer`, a layer or the export, at `input`.
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
let layers = stack(registry);
match layers.iter().position(|&id| id == layer) {
Some(0) | None => RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(input),
},
Some(position) => RegistryDelta::ChangeNodeInput {
id: layers[position - 1],
index: 0,
new_input: input,
},
}
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
ops
}
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
}
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = std::collections::HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The layers live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
fn assert_consistent(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
}
8 => {
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
continue;
};
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A layer the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A layer the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
}
#[test]
fn history_operations_keep_the_stack_whole_and_peers_converged() {
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
for seed in 0..seeds {
simulate(seed, steps, &mut Vec::new());
}
}
/// A seed fixes the run, so one that fails can be replayed.
#[test]
fn a_seed_fixes_the_history_run() {
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
for seed in 0..5 {
assert_eq!(histories(seed), histories(seed), "seed {seed}");
}
}
#[test]
#[ignore]
fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
let mut log = Vec::new();
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let host = simulate(seed, steps, &mut log);
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
}
+161 -4
View File
@@ -913,6 +913,126 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
assert_eq!(guest.retired_registry(), host.retired_registry()); assert_eq!(guest.retired_registry(), host.retired_registry());
} }
/// Dropping a peer's first step keeps the registration it carried while a later step of that peer is minted again, so
/// that step still names the person who made it.
#[test]
fn dropping_a_peers_first_step_keeps_the_registration_its_later_steps_need() {
fn retire_guest_step(guest: &mut Session, host: &mut Session, key: &str) -> Rev {
let hot = guest.stage_ops([set_attribute(key, 1)]).expect("stage");
for hot_op in &hot {
host.replay_hot_op(hot_op.clone()).expect("the guest's ops reach the host");
}
let ids: Vec<HotOpId> = hot.iter().map(HotOp::id).collect();
let closing = *host.retire_hot_ops(&ids).expect("retire").last().expect("the guest's step");
host.mark_interaction_end(closing);
let missing: Vec<Delta> = host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect();
guest.merge(missing).expect("merge");
guest.discard_hot_ops(&ids);
closing
}
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let first = retire_guest_step(&mut guest, &mut host, "first");
retire_guest_step(&mut guest, &mut host, "second");
assert_eq!(host.user_of(PeerId(2)), Some(UserId(2)));
host.drop_interaction(first).expect("drop");
assert_eq!(host.user_of(PeerId(2)), Some(UserId(2)), "the later step still names the guest's person");
}
/// Removing a step repairs the steps after it without changing which output of a node they take.
#[test]
fn removing_a_step_keeps_the_output_a_later_step_takes() {
let (taken, unrelated) = (NodeId(1), NodeId(2));
let node = || Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
let mut session = Session::with_peer(PeerId(1));
step(&mut session, add_network(5));
step(&mut session, RegistryDelta::AddNode { id: taken, node: node() });
let dropped = step(&mut session, RegistryDelta::AddNode { id: unrelated, node: node() });
let second_output = NodeInput::Node { id: taken, index: 1 };
let export = RegistryDelta::SetNetworkExport {
id: NetworkId(5),
index: 0,
export: Some(second_output.clone()),
};
step(&mut session, export);
session.drop_interaction(dropped).expect("drop");
let exports = &session.retired_registry().networks[&NetworkId(5)].exports;
assert_eq!(exports[0].target, Some(second_output));
}
/// Bringing back a step that set what a chain rests on keeps its value, rather than the one the line had before.
#[test]
fn bringing_back_a_step_keeps_the_value_it_gave_a_chain_bottom() {
let (layer, unrelated) = (NodeId(1), NodeId(2));
let value = |text: &str| NodeInput::Value {
value: Value::from(serde_json::json!(text)),
exposed: false,
};
let node = || Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
let mut session = Session::with_peer(PeerId(1));
step(&mut session, add_network(5));
step(&mut session, RegistryDelta::AddNode { id: layer, node: node() });
let export = RegistryDelta::SetNetworkExport {
id: NetworkId(5),
index: 0,
export: Some(NodeInput::Node { id: layer, index: 0 }),
};
let exported = step(&mut session, export);
let set_bottom = RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: value("set by the step"),
};
let changed = step(&mut session, set_bottom);
session.move_head_to(exported).expect("go back to before the change");
step(&mut session, RegistryDelta::AddNode { id: unrelated, node: node() });
session.restore_interaction(changed).expect("bring the change back");
assert_eq!(session.retired_registry().node_instances[&layer].inputs()[0].input, value("set by the step"));
}
/// Bringing back the deletion of a node without inputs, wired since into a node the deletion predates, gives that input
/// back its value from before, as there is nothing to reconnect it to.
#[test]
fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
let (source, consumer) = (NodeId(1), NodeId(2));
let source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 0);
let consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 2);
let earlier_value = consumer_node.inputs()[1].input.clone();
let mut session = Session::with_peer(PeerId(1));
step(&mut session, add_network(5));
let added = step(
&mut session,
RegistryDelta::AddNode {
id: source,
node: source_node.clone(),
},
);
let deleted = step(&mut session, RegistryDelta::RemoveNode { id: source, snapshot: source_node });
session.move_head_to(added).expect("go back to before the deletion");
step(&mut session, RegistryDelta::AddNode { id: consumer, node: consumer_node });
let wire = RegistryDelta::ChangeNodeInput {
id: consumer,
index: 1,
new_input: NodeInput::Node { id: source, index: 0 },
};
step(&mut session, wire);
session.restore_interaction(deleted).expect("bring the deletion back");
let registry = session.retired_registry();
assert!(!registry.node_instances.contains_key(&source));
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
}
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new /// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
/// peer id still undoes what its user did from the old one, and nobody else's. /// peer id still undoes what its user did from the old one, and nobody else's.
#[test] #[test]
@@ -1011,10 +1131,40 @@ fn a_head_move_back_across_a_merge_drops_both_branches() {
assert!(moved.retired_registry().networks.contains_key(&NetworkId(kept))); assert!(moved.retired_registry().networks.contains_key(&NetworkId(kept)));
assert!(!moved.retired_registry().networks.contains_key(&NetworkId(dropped))); assert!(!moved.retired_registry().networks.contains_key(&NetworkId(dropped)));
let sibling = if target == host_step { guest_step } else { host_step }; let sibling = if target == host_step { guest_step } else { host_step };
assert!(matches!(moved.move_head_to(sibling), Err(CrdtError::NotAncestor(rev)) if rev == sibling)); moved.move_head_to(sibling).expect("the other side of the merge is a branch to move over to");
assert!(moved.retired_registry().networks.contains_key(&NetworkId(dropped)));
assert!(!moved.retired_registry().networks.contains_key(&NetworkId(kept)));
} }
} }
/// Moving the head back onto the line a dropped step left behind takes the document back to before the drop, and a
/// follower takes the same move.
#[test]
fn a_head_move_returns_to_the_line_a_drop_left() {
let mut host = Session::with_peer(PeerId(1));
for id in 1..=3 {
host.commit_op_for_test(add_network(id)).expect("step");
host.mark_interaction_end(host.head_rev().expect("rev"));
}
let before = host.head_rev().expect("rev");
let mut follower = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let second = host
.history()
.find(|delta| matches!(delta.kind, RegistryDelta::AddNetwork { id: NetworkId(2), .. }))
.expect("second")
.id;
let (dropped, _) = host.drop_interaction(second).expect("drop");
follower.apply_head_move(&dropped).expect("follow the drop");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(2)));
let (back, touched) = host.move_head_to(before).expect("back to the line before the drop");
assert_eq!(host.head_rev(), Some(before));
assert!(host.retired_registry().networks.contains_key(&NetworkId(2)));
assert!(touched.networks.contains(&NetworkId(2)), "{touched:?}");
follower.apply_head_move(&back).expect("follow back");
assert_eq!(follower.retired_registry(), host.retired_registry());
}
/// A follower takes on the copies a move minted on top of its base and folds to the line they end. /// A follower takes on the copies a move minted on top of its base and folds to the line they end.
#[test] #[test]
fn a_head_move_with_copies_is_followed_onto_them() { fn a_head_move_with_copies_is_followed_onto_them() {
@@ -1057,7 +1207,14 @@ fn a_malformed_head_move_changes_nothing() {
let copy = |counter, parent| Delta::new(parent, PeerId(1), crate::TimeStamp { counter, peer: PeerId(1) }, set_attribute("c", counter as u32), Vec::new()); let copy = |counter, parent| Delta::new(parent, PeerId(1), crate::TimeStamp { counter, peer: PeerId(1) }, set_attribute("c", counter as u32), Vec::new());
let off_first = copy(50, Some(first)); let off_first = copy(50, Some(first));
let off_base_again = copy(51, Some(first)); let off_base_again = copy(51, Some(first));
let off_the_line = copy(52, Some(off_first.id));
for moved in [ for moved in [
// The copies start from a step not on the line being left.
crate::HeadMove {
from: Some(second),
head: Some(off_the_line.id),
copies: vec![off_the_line.clone()],
},
// The copies end somewhere other than the move's head. // The copies end somewhere other than the move's head.
crate::HeadMove { crate::HeadMove {
from: Some(second), from: Some(second),
@@ -1079,9 +1236,9 @@ fn a_malformed_head_move_changes_nothing() {
} }
} }
/// Peers hold the line up to where the head moved, so a silent undo must not reach behind it. /// The retirer publishes a head move only when it broadcasts it, while a follower holds the line it was sent.
#[test] #[test]
fn a_head_move_publishes_the_new_head() { fn a_followed_head_move_publishes_the_new_head() {
let mut host = Session::with_identity(PeerId(1), UserId(1)); let mut host = Session::with_identity(PeerId(1), UserId(1));
let [_, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| { let [_, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| {
host.commit_op_for_test(set_attribute(key, value)).expect("step"); host.commit_op_for_test(set_attribute(key, value)).expect("step");
@@ -1094,7 +1251,7 @@ fn a_head_move_publishes_the_new_head() {
guest.publish_up_to(third); guest.publish_up_to(third);
let (moved, _) = host.move_head_to(second).expect("move"); let (moved, _) = host.move_head_to(second).expect("move");
assert!(!host.can_undo(), "the step the room holds stays put"); assert!(host.can_undo(), "an unbroadcast move stays silently undoable");
guest.apply_head_move(&moved).expect("follow"); guest.apply_head_move(&moved).expect("follow");
assert!(!guest.can_undo(), "the follower holds the same line"); assert!(!guest.can_undo(), "the follower holds the same line");
} }
@@ -3,3 +3,6 @@
use migration_core::rename; use migration_core::rename;
rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2); rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2);
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
rename!("core_types::vector::AreaNode"@1 => @2);
rename!("core_types::vector::CentroidNode"@1 => @2);
+1 -1
View File
@@ -48,7 +48,7 @@ pub trait SyncTarget {
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError>; fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError>;
/// Host only. Mint a dropped interaction again on top of the line. See [`Session::restore_interaction`]. /// Host only. Mint a dropped interaction again on top of the line. See [`Session::restore_interaction`].
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>; fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>;
/// Host only. Move the shared head to an ancestor, leaving the line since as a branch. See [`Session::move_head_to`]. /// Host only. Move the shared head to an ancestor or a branch, leaving the line it was on as a branch. See [`Session::move_head_to`].
fn move_head_to(&mut self, _rev: Rev) -> Result<HeadMove, TargetError> { fn move_head_to(&mut self, _rev: Rev) -> Result<HeadMove, TargetError> {
Err("this target cannot move its head".into()) Err("this target cannot move its head".into())
} }
@@ -6,7 +6,8 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions; use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeProgress, FrontendNodeType, FrontendRemoteCursor,
NodeGraphErrorDiagnostic,
}; };
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry}; use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate}; use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -326,6 +327,9 @@ pub enum FrontendMessage {
UpdateNodeGraphErrorDiagnostics { UpdateNodeGraphErrorDiagnostics {
errors: Vec<NodeGraphErrorDiagnostic>, errors: Vec<NodeGraphErrorDiagnostic>,
}, },
UpdateNodeGraphProgress {
progress: Vec<FrontendNodeProgress>,
},
UpdateVisibleNodes { UpdateVisibleNodes {
nodes: Vec<NodeId>, nodes: Vec<NodeId>,
}, },
@@ -58,6 +58,10 @@ pub enum MouseCursorIcon {
pub enum RenderStatus { pub enum RenderStatus {
#[default] #[default]
Rendering, Rendering,
/// Rendering a frame computed from provisional data, while async work is in progress.
Partial,
/// Rendering a frame computed from substitute data, because part of the graph failed.
Fallback,
Error, Error,
Panic, Panic,
} }
@@ -44,6 +44,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
entry!(KeyUp(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: false }), entry!(KeyUp(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: false }),
entry!(KeyDown(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: true }), entry!(KeyDown(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: true }),
entry!(KeyDown(Escape); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: true }), entry!(KeyDown(Escape); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: true }),
entry!(KeyDown(Escape); action_dispatch=DocumentMessage::PreviewHistoryStep { rev: None }),
entry!(KeyDown(MouseLeft); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseLeft }), entry!(KeyDown(MouseLeft); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseLeft }),
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseMiddle }), entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseMiddle }),
entry!(KeyDown(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseRight }), entry!(KeyDown(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseRight }),
@@ -461,6 +461,8 @@ pub struct NodeSection {
/// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom. /// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom.
#[serde(rename = "contentWireContinues")] #[serde(rename = "contentWireContinues")]
pub content_wire_continues: bool, pub content_wire_continues: bool,
/// How far the work in progress of the node has come from 0 to 1, shown in the section header with a button to cancel it (none when it has no work in progress).
pub progress: Option<f64>,
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header. /// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
pub expanded: bool, pub expanded: bool,
/// The ID of the node whose Inspector section this is. /// The ID of the node whose Inspector section this is.
@@ -533,6 +535,7 @@ impl LayoutGroup {
node_reference: false, node_reference: false,
content_wire: None, content_wire: None,
content_wire_continues: false, content_wire_continues: false,
progress: None,
expanded, expanded,
id, id,
layout, layout,
@@ -647,6 +650,7 @@ impl Diffable for LayoutGroup {
node_reference: current_node_reference, node_reference: current_node_reference,
content_wire: current_content_wire, content_wire: current_content_wire,
content_wire_continues: current_content_wire_continues, content_wire_continues: current_content_wire_continues,
progress: current_progress,
expanded: current_expanded, expanded: current_expanded,
id: current_id, id: current_id,
layout: current_layout, layout: current_layout,
@@ -663,6 +667,7 @@ impl Diffable for LayoutGroup {
node_reference: new_node_reference, node_reference: new_node_reference,
content_wire: new_content_wire, content_wire: new_content_wire,
content_wire_continues: new_content_wire_continues, content_wire_continues: new_content_wire_continues,
progress: new_progress,
expanded: new_expanded, expanded: new_expanded,
id: new_id, id: new_id,
layout: new_layout, layout: new_layout,
@@ -682,6 +687,7 @@ impl Diffable for LayoutGroup {
|| *current_node_reference != new_node_reference || *current_node_reference != new_node_reference
|| *current_content_wire != new_content_wire || *current_content_wire != new_content_wire
|| *current_content_wire_continues != new_content_wire_continues || *current_content_wire_continues != new_content_wire_continues
|| *current_progress != new_progress
|| *current_expanded != new_expanded || *current_expanded != new_expanded
|| *current_id != new_id || *current_id != new_id
{ {
@@ -697,6 +703,7 @@ impl Diffable for LayoutGroup {
*current_node_reference = new_node_reference; *current_node_reference = new_node_reference;
*current_content_wire = new_content_wire; *current_content_wire = new_content_wire;
*current_content_wire_continues = new_content_wire_continues; *current_content_wire_continues = new_content_wire_continues;
*current_progress = new_progress;
*current_expanded = new_expanded; *current_expanded = new_expanded;
*current_id = new_id; *current_id = new_id;
current_layout.clone_from(&new_layout); current_layout.clone_from(&new_layout);
@@ -714,6 +721,7 @@ impl Diffable for LayoutGroup {
node_reference: new_node_reference, node_reference: new_node_reference,
content_wire: new_content_wire, content_wire: new_content_wire,
content_wire_continues: new_content_wire_continues, content_wire_continues: new_content_wire_continues,
progress: new_progress,
expanded: new_expanded, expanded: new_expanded,
id: new_id, id: new_id,
layout: new_layout, layout: new_layout,
@@ -31,6 +31,14 @@ pub struct DocumentHistory {
needs_whole_document_stage: bool, needs_whole_document_stage: bool,
/// How storage undid each step that redo can bring back, latest last. /// How storage undid each step that redo can bring back, latest last.
undo_notes: VecDeque<UndoNote>, undo_notes: VecDeque<UndoNote>,
/// The History panel's head moves, newest last, for undo to take back.
line_undo: Vec<LineMove>,
}
#[derive(Clone, Copy, Debug)]
struct LineMove {
from: document_graph_storage::Rev,
to: document_graph_storage::Rev,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -41,6 +49,8 @@ enum UndoNote {
Dropped(document_graph_storage::Rev), Dropped(document_graph_storage::Rev),
/// The storage cursor moved back over the step. /// The storage cursor moved back over the step.
Cursor, Cursor,
/// A History panel change was taken back.
LineMove(LineMove),
} }
impl DocumentHistory { impl DocumentHistory {
@@ -123,6 +133,9 @@ impl DocumentHistory {
if let Some(ops) = retracted { if let Some(ops) = retracted {
return Some(UndoNote::Retracted(ops)); return Some(UndoNote::Retracted(ops));
} }
if let Some(line_move) = self.undo_line_move() {
return Some(UndoNote::LineMove(line_move));
}
// A session's history is shared, so its cursor never moves // A session's history is shared, so its cursor never moves
if in_session { if in_session {
return self.undo_retired_step().map(UndoNote::Dropped); return self.undo_retired_step().map(UndoNote::Dropped);
@@ -139,6 +152,7 @@ impl DocumentHistory {
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()), UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
UndoNote::Dropped(rev) => line_reachable && self.redo_retired_step(*rev), UndoNote::Dropped(rev) => line_reachable && self.redo_retired_step(*rev),
UndoNote::Cursor => self.move_cursor(false), UndoNote::Cursor => self.move_cursor(false),
UndoNote::LineMove(line_move) => self.redo_line_move(*line_move),
}; };
if !redone { if !redone {
self.undo_notes.push_back(note); self.undo_notes.push_back(note);
@@ -198,12 +212,62 @@ impl DocumentHistory {
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else { let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
return false; return false;
}; };
let from = storage.session().head_rev();
let result = match change { let result = match change {
LineChange::MoveHead => storage.move_head(rev), LineChange::MoveHead => storage.move_head(rev),
LineChange::Remove => storage.drop_step(rev), LineChange::Remove => storage.drop_step(rev),
LineChange::Restore => storage.redo_retired_step(rev), LineChange::Restore => storage.redo_retired_step(rev),
}; };
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok() if result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_err() {
return false;
}
// A guest's change is made by the host, so its head has not moved yet
if let (Some(from), Some(to)) = (from, storage.session().head_rev())
&& from != to
{
self.line_undo.push(LineMove { from, to });
self.line_undo.drain(..self.line_undo.len().saturating_sub(crate::consts::MAX_UNDO_HISTORY_LEN));
}
true
}
/// Moves the head back over the newest History panel change, if the head is still where that change left it.
fn undo_line_move(&mut self) -> Option<LineMove> {
let storage = self.storage.as_mut().filter(|storage| storage.can_change_line())?;
let line_move = *self.line_undo.last()?;
if storage.session().head_rev() != Some(line_move.to) {
return None;
}
if let Err(error) = storage.move_head(line_move.from) {
log::error!("Taking the History panel change back failed: {error}");
return None;
}
self.line_undo.pop();
self.forget_unreachable_cursor_notes();
Some(line_move)
}
/// Makes a History panel change taken back by [`undo_line_move`](Self::undo_line_move) again. Returns whether the head moved.
fn redo_line_move(&mut self, line_move: LineMove) -> bool {
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
return false;
};
if storage.session().head_rev() != Some(line_move.from) {
return false;
}
if let Err(error) = storage.move_head(line_move.to) {
log::error!("Making the History panel change again failed: {error}");
return false;
}
self.line_undo.push(line_move);
true
}
/// Moving the head clears storage's redo stack, so cursor steps can no longer be redone.
fn forget_unreachable_cursor_notes(&mut self) {
self.undo_notes.retain(|note| !matches!(note, UndoNote::Cursor));
} }
pub fn retire_storage_interaction(&mut self) { pub fn retire_storage_interaction(&mut self) {
@@ -305,10 +369,25 @@ impl DocumentHistory {
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert. /// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> { pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
self.interface_from(self.storage.as_ref()?.registry())
}
/// Build an interface showing the document once `rev` was done, as history folds it. `None` when it doesn't convert.
pub fn interface_at(&self, rev: document_graph_storage::Rev) -> Option<NodeNetworkInterface> {
let registry = self
.storage
.as_ref()?
.session()
.registry_at(rev)
.inspect_err(|error| log::error!("Folding history at {rev:?} failed: {error}"))
.ok()?;
self.interface_from(&registry)
}
fn interface_from(&self, registry: &document_graph_storage::Registry) -> Option<NodeNetworkInterface> {
let storage = self.storage.as_ref()?; let storage = self.storage.as_ref()?;
storage registry
.registry()
.to_runtime_with_full_metadata(&self.declarations, storage.blobs()) .to_runtime_with_full_metadata(&self.declarations, storage.blobs())
.map_err(|error| error.to_string()) .map_err(|error| error.to_string())
.map(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries)) .map(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries))
@@ -60,6 +60,9 @@ pub enum DocumentMessage {
rev: document_graph_storage::Rev, rev: document_graph_storage::Rev,
change: crate::messages::portfolio::history::utility_types::LineChange, change: crate::messages::portfolio::history::utility_types::LineChange,
}, },
PreviewHistoryStep {
rev: Option<document_graph_storage::Rev>,
},
DocumentStructureChanged, DocumentStructureChanged,
DrawArtboardOverlays { DrawArtboardOverlays {
context: OverlayContext, context: OverlayContext,
@@ -221,6 +224,9 @@ pub enum DocumentMessage {
layers: Vec<NodeId>, layers: Vec<NodeId>,
layers_missing_details: Vec<NodeId>, layers_missing_details: Vec<NodeId>,
}, },
CancelNodeWork {
node_id: NodeId,
},
SetNodePinned { SetNodePinned {
node_id: NodeId, node_id: NodeId,
pinned: bool, pinned: bool,
@@ -24,6 +24,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::{Doc
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ}; use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled}; use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::history::utility_types::LineChange; use crate::messages::portfolio::history::utility_types::LineChange;
use crate::messages::portfolio::history::{Place, place};
use crate::messages::portfolio::utility_types::PanelType; use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::edit_target::EditTarget; use crate::messages::tool::common_functionality::edit_target::EditTarget;
@@ -169,9 +170,12 @@ pub struct DocumentMessageHandler {
/// Path to network that is currently selected. Updated based on the most recently clicked panel. /// Path to network that is currently selected. Updated based on the most recently clicked panel.
#[serde(skip)] #[serde(skip)]
selection_network_path: Vec<NodeId>, selection_network_path: Vec<NodeId>,
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor. /// Undo/redo state over the `Gdd` working copy.
#[serde(skip)] #[serde(skip)]
history: DocumentHistory, history: DocumentHistory,
/// A past step shown in place of the current state, which it keeps to return to.
#[serde(skip)]
history_preview: Option<HistoryPreview>,
/// The document's container in the document store. `None` for a document created this session until its store entry opens. /// The document's container in the document store. `None` for a document created this session until its store entry opens.
#[serde(skip)] #[serde(skip)]
#[derivative(Debug = "ignore")] #[derivative(Debug = "ignore")]
@@ -203,6 +207,12 @@ pub struct DocumentMessageHandler {
pub is_loaded: bool, pub is_loaded: bool,
} }
#[derive(Clone, Debug)]
struct HistoryPreview {
rev: Rev,
current: NodeNetworkInterface,
}
impl Default for DocumentMessageHandler { impl Default for DocumentMessageHandler {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -241,6 +251,7 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(), breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(), selection_network_path: Vec::new(),
history: DocumentHistory::default(), history: DocumentHistory::default(),
history_preview: None,
container: None, container: None,
pending_remote: Default::default(), pending_remote: Default::default(),
saved_hash: None, saved_hash: None,
@@ -478,9 +489,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.resolve_unresolved_resources(document_id, responses); self.resolve_unresolved_resources(document_id, responses);
} }
DocumentMessage::ChangeHistoryLine { rev, change } => { DocumentMessage::ChangeHistoryLine { rev, change } => {
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), responses); self.change_history_line(document_id, rev, change, viewport, &resource_storage.resources_mut(), responses);
self.resolve_unresolved_resources(document_id, responses); self.resolve_unresolved_resources(document_id, responses);
} }
DocumentMessage::PreviewHistoryStep { rev: Some(rev) } => self.preview_history_step(rev, viewport, &resource_storage.resources_mut(), responses),
DocumentMessage::PreviewHistoryStep { rev: None } => {
self.end_history_preview(viewport, responses);
}
DocumentMessage::NameInteraction { action } => { DocumentMessage::NameInteraction { action } => {
if let Some(storage) = self.history.storage_mut() { if let Some(storage) = self.history.storage_mut() {
storage.name_interaction(&action); storage.name_interaction(&action);
@@ -1142,7 +1157,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(ToolMessage::ActivateTool { tool_type: ToolType::Select }); responses.add(ToolMessage::ActivateTool { tool_type: ToolType::Select });
} }
DocumentMessage::Redo => { DocumentMessage::Redo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished { if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
return; return;
} }
responses.add(SelectToolMessage::Abort); responses.add(SelectToolMessage::Abort);
@@ -1267,6 +1282,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}); });
} }
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => { DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
self.end_history_preview(viewport, responses);
responses.add(PortfolioMessage::AutoSaveActiveDocument); responses.add(PortfolioMessage::AutoSaveActiveDocument);
let include_history = preferences.save_with_history; let include_history = preferences.save_with_history;
@@ -1561,6 +1577,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SendLayerPanelDetails { layers: layers_missing_details }); responses.add(NodeGraphMessage::SendLayerPanelDetails { layers: layers_missing_details });
} }
} }
DocumentMessage::CancelNodeWork { node_id } => {
let node_path = [self.selection_network_path.as_slice(), &[node_id]].concat();
responses.add(PortfolioMessage::CancelNodeWork { node_path });
}
DocumentMessage::SetNodePinned { node_id, pinned } => { DocumentMessage::SetNodePinned { node_id, pinned } => {
responses.add(DocumentMessage::AddTransaction); responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::SetPinned { node_id, pinned }); responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
@@ -1696,6 +1716,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
} }
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends. // Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
DocumentMessage::StartTransaction => { DocumentMessage::StartTransaction => {
self.continue_from_history_preview(document_id, viewport, &resource_storage.resources_mut(), responses);
self.stage_edits_outside_transaction(&resource_storage.resources_mut()); self.stage_edits_outside_transaction(&resource_storage.resources_mut());
self.end_storage_interaction(); self.end_storage_interaction();
@@ -1931,7 +1952,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.network_interface.update_effects_reach(layer_effects_reach); self.network_interface.update_effects_reach(layer_effects_reach);
} }
DocumentMessage::Undo => { DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished { if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
return; return;
} }
@@ -2169,6 +2190,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
ZoomCanvasToFitAll, ZoomCanvasToFitAll,
); );
if self.history_preview.is_some() {
common.extend(actions!(DocumentMessageDiscriminant::PreviewHistoryStep));
}
// Additional actions available on desktop // Additional actions available on desktop
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
common.extend(actions!(DocumentMessageDiscriminant::SaveDocumentAs)); common.extend(actions!(DocumentMessageDiscriminant::SaveDocumentAs));
@@ -2610,6 +2635,9 @@ impl DocumentMessageHandler {
/// Updates the interface with peer changes, in place unless a rebuild is needed. Returns false and keeps what it can't apply. /// Updates the interface with peer changes, in place unless a rebuild is needed. Returns false and keeps what it can't apply.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool { pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
if self.history_preview.is_some() {
return false;
}
let changes = std::mem::take(&mut self.pending_remote); let changes = std::mem::take(&mut self.pending_remote);
if changes.is_empty() { if changes.is_empty() {
return true; return true;
@@ -3078,12 +3106,87 @@ impl DocumentMessageHandler {
} }
/// Makes a History panel change in storage and drops the steps redo could bring back, which are off the head's line. /// Makes a History panel change in storage and drops the steps redo could bring back, which are off the head's line.
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) { fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, viewport: &ViewportMessageHandler, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
if self.network_interface.transaction_status() != TransactionStatus::Finished { if self.network_interface.transaction_status() != TransactionStatus::Finished {
return; return;
} }
self.end_history_preview(viewport, responses);
self.node_graph_handler.stop_gliding(&self.network_interface, responses); self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort); responses.add(EventMessage::ToolAbort);
self.apply_history_line_change(document_id, rev, change, byte_store, responses);
}
/// Shows the document as it was once `rev` was done, in place of the current state until the preview ends.
fn preview_history_step(&mut self, rev: Rev, viewport: &ViewportMessageHandler, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
if self.history_preview.is_none() {
self.stage_edits_outside_transaction(byte_store);
}
let Some(past) = self.history.interface_at(rev) else { return };
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort);
let replaced = self.install_history_snapshot(past, viewport);
let current = self.history_preview.take().map_or(replaced, |preview| preview.current);
self.history_preview = Some(HistoryPreview { rev, current });
self.show_installed_interface(responses);
}
/// Returns from a preview to the current state, and gives the step it showed.
fn end_history_preview(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<Rev> {
let preview = self.history_preview.take()?;
self.install_history_snapshot(preview.current, viewport);
self.show_installed_interface(responses);
self.apply_remote_changes(responses);
Some(preview.rev)
}
/// The step shown in place of the current state.
pub fn previewed_history_step(&self) -> Option<Rev> {
self.history_preview.as_ref().map(|preview| preview.rev)
}
/// Runs `action` with the current state installed in place of a previewed step.
pub fn with_current_state<T>(&mut self, action: impl FnOnce(&mut Self) -> T) -> T {
let Some(mut preview) = self.history_preview.take() else { return action(self) };
std::mem::swap(&mut self.network_interface, &mut preview.current);
let result = action(self);
std::mem::swap(&mut self.network_interface, &mut preview.current);
self.history_preview = Some(preview);
result
}
/// An edit while previewing continues from the previewed step, leaving the steps after it as a branch. In a session
/// it applies to the current state instead, since moving the head would move everyone's document.
fn continue_from_history_preview(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
let Some(rev) = self.end_history_preview(viewport, responses) else { return };
if self.is_in_session() {
return;
}
let place = self.storage().and_then(|gdd| place(gdd.session(), rev));
match place {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| self.redo_with_history(document_id, responses)),
Some(Place::Line(0)) => {}
Some(Place::Line(_)) | None => self.apply_history_line_change(document_id, rev, LineChange::MoveHead, byte_store, responses),
}
}
fn show_installed_interface(&self, responses: &mut VecDeque<Message>) {
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
fn apply_history_line_change(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
self.stage_edits_outside_transaction(byte_store); self.stage_edits_outside_transaction(byte_store);
self.history.retire_storage_interaction(); self.history.retire_storage_interaction();
let stored_name = self.stored_name().map(str::to_string); let stored_name = self.stored_name().map(str::to_string);
@@ -3097,6 +3200,20 @@ impl DocumentMessageHandler {
responses.add(EventMessage::SelectionChanged); responses.add(EventMessage::SelectionChanged);
} }
/// Swaps in `snapshot`, keeping the current view, and returns the interface it replaced.
fn install_history_snapshot(&mut self, mut snapshot: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
snapshot.copy_all_navigation_metadata(&self.network_interface);
std::mem::swap(&mut snapshot.resolved_types, &mut self.network_interface.resolved_types);
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
snapshot.set_document_to_viewport_transform(transform);
// Updating the selected nodes needs the structure's metadata
snapshot.load_structure();
std::mem::replace(&mut self.network_interface, snapshot)
}
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`. /// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) { fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
if let Some(gdd) = self.history.storage_mut() { if let Some(gdd) = self.history.storage_mut() {
@@ -345,6 +345,10 @@ pub enum NodeGraphMessage {
UpdateEvaluationErrors { UpdateEvaluationErrors {
errors: Vec<NodeEvaluationError>, errors: Vec<NodeEvaluationError>,
}, },
/// The progress of the nodes with work in progress, by their full path from the root network.
UpdateNodeProgress {
progress: Vec<(Vec<NodeId>, f64)>,
},
UpdateActionButtons, UpdateActionButtons,
UpdateGraphBarRight, UpdateGraphBarRight,
UpdateInSelectedNetwork, UpdateInSelectedNetwork,
@@ -457,6 +461,7 @@ impl NodeGraphMessage {
| Self::UpdateNewNodeGraph | Self::UpdateNewNodeGraph
| Self::UpdateTypes { .. } | Self::UpdateTypes { .. }
| Self::UpdateEvaluationErrors { .. } | Self::UpdateEvaluationErrors { .. }
| Self::UpdateNodeProgress { .. }
| Self::UpdateActionButtons | Self::UpdateActionButtons
| Self::UpdateGraphBarRight | Self::UpdateGraphBarRight
| Self::UpdateInSelectedNetwork | Self::UpdateInSelectedNetwork
@@ -6,7 +6,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls; use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext; use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic}; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, FrontendNodeProgress, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
@@ -136,6 +136,8 @@ pub struct NodeGraphMessageHandler {
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed /// Used to keep track of what wires are sent to the frontend so the old ones can be removed
frontend_wires: HashSet<(NodeId, usize)>, frontend_wires: HashSet<(NodeId, usize)>,
evaluation_errors: Vec<NodeEvaluationError>, evaluation_errors: Vec<NodeEvaluationError>,
/// The progress of the nodes with work in progress, by their full path from the root network.
node_progress: Vec<(Vec<NodeId>, f64)>,
} }
/// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network. /// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network.
@@ -2074,6 +2076,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(FrontendMessage::UpdateNetworkReadOnly { responses.add(FrontendMessage::UpdateNetworkReadOnly {
read_only: network_interface.is_read_only(breadcrumb_network_path), read_only: network_interface.is_read_only(breadcrumb_network_path),
}); });
let progress = self.node_graph_progress(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path); let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
responses.add(NodeGraphMessage::UpdateImportsExports); responses.add(NodeGraphMessage::UpdateImportsExports);
@@ -2680,6 +2684,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
} }
} }
} }
NodeGraphMessage::UpdateNodeProgress { progress } => {
if self.node_progress != progress {
self.node_progress = progress;
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let progress = self.node_graph_progress(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
}
}
}
NodeGraphMessage::UpdateActionButtons => { NodeGraphMessage::UpdateActionButtons => {
if selection_network_path == breadcrumb_network_path { if selection_network_path == breadcrumb_network_path {
self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses); self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses);
@@ -3900,6 +3913,22 @@ impl NodeGraphMessageHandler {
.collect() .collect()
} }
/// The progress of the nodes in the network at `breadcrumb_network_path`, where a node shows the first work in progress within it.
fn node_graph_progress(&self, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNodeProgress> {
let depth = breadcrumb_network_path.len();
let mut shown = HashSet::new();
self.node_progress
.iter()
.filter(|(path, _)| path.starts_with(breadcrumb_network_path) && path.len() > depth)
.filter(|(path, _)| shown.insert(path[depth]))
.map(|(path, progress)| FrontendNodeProgress {
node_id: path[depth],
progress: *progress,
})
.collect()
}
/// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view. /// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view.
// O(given layers × nesting depth), apart from what the active tool would edit in the selected layers // O(given layers × nesting depth), apart from what the active tool would edit in the selected layers
fn update_layer_panel( fn update_layer_panel(
@@ -4109,6 +4138,7 @@ impl Default for NodeGraphMessageHandler {
frontend_nodes: Vec::new(), frontend_nodes: Vec::new(),
frontend_wires: HashSet::new(), frontend_wires: HashSet::new(),
evaluation_errors: Vec::new(), evaluation_errors: Vec::new(),
node_progress: Vec::new(),
} }
} }
} }
@@ -3316,6 +3316,7 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
let mut section = LayoutGroup::section(name, icon, description, visible, pinned, expanded, node_id.0, Layout(layout)); let mut section = LayoutGroup::section(name, icon, description, visible, pinned, expanded, node_id.0, Layout(layout));
if let LayoutGroup::NodeSection(node_section) = &mut section { if let LayoutGroup::NodeSection(node_section) = &mut section {
node_section.chain_wire = chain_wire; node_section.chain_wire = chain_wire;
node_section.progress = context.executor.node_progress(&[network_path, &[node_id]].concat());
} }
section section
} }
@@ -202,6 +202,15 @@ pub struct NodeGraphErrorDiagnostic {
pub error: String, pub error: String,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendNodeProgress {
#[serde(rename = "nodeId")]
pub node_id: NodeId,
/// How much of the work within the node is done, from 0 to 1.
pub progress: f64,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeEvaluationError { pub struct NodeEvaluationError {
pub node_path: Vec<NodeId>, pub node_path: Vec<NodeId>,
@@ -15,7 +15,9 @@ use graphene_std::vector::algorithms::util::pathseg_tangent;
use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, PathSegPoints, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles}; use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, PathSegPoints, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles};
use graphene_std::vector::{PointId, SegmentId, VectorGeometry, curve_type_at, handle_point, segment_id_of, span_endpoints, spans}; use graphene_std::vector::{PointId, SegmentId, VectorGeometry, curve_type_at, handle_point, segment_id_of, span_endpoints, spans};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, PathSeg, Rect, Shape}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, PathSeg, Rect, Shape};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::sync::Arc;
pub fn selected_segments(network_interface: &NodeNetworkInterface, shape_editor: &ShapeState) -> HashMap<LayerNodeIdentifier, Vec<SegmentId>> { pub fn selected_segments(network_interface: &NodeNetworkInterface, shape_editor: &ShapeState) -> HashMap<LayerNodeIdentifier, Vec<SegmentId>> {
let mut map = HashMap::new(); let mut map = HashMap::new();
@@ -171,128 +173,159 @@ fn overlay_bezier_handle_specific_point(
} }
} }
/// Draws the path, handles, and anchors of each selected visible and unlocked layer, using its geometry from the render the overlays are shown over.
pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandles, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext) { pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandles, shape_editor: &mut ShapeState, overlay_context: &mut OverlayContext) {
let display_path = overlay_context.visibility_settings.path();
let display_handles = overlay_context.visibility_settings.handles();
let display_anchors = overlay_context.visibility_settings.anchors();
let document_zoom = document_zoom(document); let document_zoom = document_zoom(document);
let draw_handles = Arc::new(draw_handles);
// Locked layers can't be edited, so they get no points to grab // Locked layers can't be edited, so they get no points to grab
for layer in document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface) { for layer in document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface) {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); let source = document.network_interface.layer_vector_source(layer);
if display_path { let selected_shape_state = shape_editor.selected_shape_state.entry(layer).or_default().clone();
overlay_context.outline_vector(&vector, transform); let draw_handles = draw_handles.clone();
}
let selected_shape_state = shape_editor.selected_shape_state.entry(layer).or_default(); overlay_context.with_rendered_layers(move |overlay_context, rendered| {
// Get the selected segments and then add a bold line overlay on them let (vector, transform) = rendered.vector(source).unwrap_or((Cow::Borrowed(&vector), source.layer_to_viewport));
for (segment_id, bezier, _, _) in vector.segment_iter() { layer_path_overlays(layer, &vector, transform, &draw_handles, &selected_shape_state, document_zoom, overlay_context);
if selected_shape_state.is_segment_selected(segment_id) { });
overlay_context.outline_select_bezier(bezier, transform); }
}
fn layer_path_overlays(
layer: LayerNodeIdentifier,
vector: &VectorGeometry,
transform: DAffine2,
draw_handles: &DrawHandles,
selected_shape_state: &SelectedLayerState,
document_zoom: f64,
overlay_context: &mut OverlayContext,
) {
let display_path = overlay_context.visibility_settings.path();
let display_handles = overlay_context.visibility_settings.handles();
let display_anchors = overlay_context.visibility_settings.anchors();
if display_path {
overlay_context.outline_vector(vector, transform);
}
for (segment_id, bezier, _, _) in vector.segment_iter() {
if selected_shape_state.is_segment_selected(segment_id) {
overlay_context.outline_select_bezier(bezier, transform);
}
}
let path_index_labels = path_marker_overlays(vector, transform, document_zoom, false, overlay_context);
let is_selected = |point: ManipulatorPointId| selected_shape_state.is_point_selected(point);
let mut drawn_handles = Vec::new();
if display_handles {
let opposite_handles_data = selected_shape_state.selected_points().filter_map(|point_id| vector.adjacent_segment(&point_id)).collect::<Vec<_>>();
match draw_handles {
DrawHandles::All => {
vector.segment_iter().for_each(|(segment_id, segment, _start, _end)| {
drawn_handles.extend(overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context).into_iter().flatten());
});
} }
} DrawHandles::SelectedAnchors(selected_segments) => {
let focused_segments = selected_segments.get(&layer).map(Vec::as_slice).unwrap_or_default();
let path_index_labels = path_marker_overlays(&vector, transform, document_zoom, false, overlay_context); vector
.segment_iter()
let is_selected = |point: ManipulatorPointId| selected_shape_state.is_point_selected(point); .filter(|(segment_id, ..)| focused_segments.contains(segment_id))
.for_each(|(segment_id, segment, _start, _end)| {
let mut drawn_handles = Vec::new();
if display_handles {
let opposite_handles_data = selected_shape_state.selected_points().filter_map(|point_id| vector.adjacent_segment(&point_id)).collect::<Vec<_>>();
match draw_handles {
DrawHandles::All => {
vector.segment_iter().for_each(|(segment_id, segment, _start, _end)| {
drawn_handles.extend(overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context).into_iter().flatten()); drawn_handles.extend(overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context).into_iter().flatten());
}); });
for (segment_id, segment, start, end) in vector.segment_iter() {
if let Some((corresponding_anchor, _)) = opposite_handles_data.iter().find(|(_, adj_segment_id)| adj_segment_id == &segment_id) {
let drawn = overlay_bezier_handle_specific_point(segment, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
drawn_handles.extend(drawn.into_iter().flatten());
}
} }
DrawHandles::SelectedAnchors(ref selected_segments) => { }
let focused_segments = selected_segments.get(&layer).map(Vec::as_slice).unwrap_or_default(); DrawHandles::FrontierHandles(segment_endpoints_by_layer) => {
if let Some(segment_endpoints) = segment_endpoints_by_layer.get(&layer) {
vector
.segment_iter()
.filter(|(segment_id, ..)| focused_segments.contains(segment_id))
.for_each(|(segment_id, segment, _start, _end)| {
drawn_handles.extend(overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context).into_iter().flatten());
});
for (segment_id, segment, start, end) in vector.segment_iter() { for (segment_id, segment, start, end) in vector.segment_iter() {
if let Some((corresponding_anchor, _)) = opposite_handles_data.iter().find(|(_, adj_segment_id)| adj_segment_id == &segment_id) { let Some(endpoints) = segment_endpoints.get(&segment_id) else { continue };
let drawn = overlay_bezier_handle_specific_point(segment, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
drawn_handles.extend(drawn.into_iter().flatten()); let drawn = match endpoints.as_slice() {
} &[point_to_render] => overlay_bezier_handle_specific_point(segment, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context),
_ => overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context),
};
drawn_handles.extend(drawn.into_iter().flatten());
} }
} }
DrawHandles::FrontierHandles(ref segment_endpoints_by_layer) => {
if let Some(segment_endpoints) = segment_endpoints_by_layer.get(&layer) {
vector
.segment_iter()
.filter(|(segment_id, ..)| segment_endpoints.contains_key(segment_id))
.for_each(|(segment_id, segment, start, end)| {
let drawn = if segment_endpoints.get(&segment_id).unwrap().len() == 1 {
let point_to_render = segment_endpoints.get(&segment_id).unwrap()[0];
overlay_bezier_handle_specific_point(segment, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context)
} else {
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context)
};
drawn_handles.extend(drawn.into_iter().flatten());
});
}
}
DrawHandles::None => {}
} }
DrawHandles::None => {}
} }
if display_anchors {
for (id, position) in vector.anchors() {
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(ManipulatorPointId::Anchor(id)), None);
}
}
index_label_overlays(&vector, transform, false, &drawn_handles, path_index_labels, overlay_context);
} }
if display_anchors {
for (id, position) in vector.anchors() {
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(ManipulatorPointId::Anchor(id)), None);
}
}
index_label_overlays(vector, transform, false, &drawn_handles, path_index_labels, overlay_context);
} }
/// Draws an anchor overlay at each endpoint of every open path on the selected visible layers, in the selected style for endpoints that are part of the path editing selection. /// Draws an anchor overlay at each endpoint of every open path on the selected visible layers, in the selected style for endpoints that are part of the path editing selection.
/// Given a pointer position, the endpoint a press there would continue from is drawn in the hover style instead. /// Given a pointer position, the endpoint a press there would continue from is drawn in the hover style instead.
/// Paths use their geometry from the render the overlays are shown over.
pub fn open_path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &ShapeState, pointer: Option<DVec2>, overlay_context: &mut OverlayContext) { pub fn open_path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &ShapeState, pointer: Option<DVec2>, overlay_context: &mut OverlayContext) {
if !overlay_context.visibility_settings.anchors() { if !overlay_context.visibility_settings.anchors() {
return; return;
} }
let selected_nodes = document.network_interface.selected_nodes(); let selected_nodes = document.network_interface.selected_nodes();
let is_selected = |layer: LayerNodeIdentifier, id: PointId| { let selected_anchors_of = |layer: LayerNodeIdentifier| -> HashSet<PointId> {
shape_editor let Some(state) = shape_editor.selected_shape_state.get(&layer) else { return HashSet::new() };
.selected_shape_state state
.get(&layer) .selected_points()
.is_some_and(|state| state.is_point_selected(ManipulatorPointId::Anchor(id))) .filter_map(|point| if let ManipulatorPointId::Anchor(id) = point { Some(id) } else { None })
.collect()
}; };
let hovered = pointer.and_then(|pointer| closest_open_path_endpoint(document, pointer, SNAP_POINT_TOLERANCE, selected_nodes.selected_visible_layers(&document.network_interface))); let hovered = pointer.and_then(|pointer| closest_open_path_endpoint(document, pointer, SNAP_POINT_TOLERANCE, selected_nodes.selected_visible_layers(&document.network_interface)));
let document_zoom = document_zoom(document); let document_zoom = document_zoom(document);
for layer in selected_nodes.selected_visible_layers(&document.network_interface) { for layer in selected_nodes.selected_visible_layers(&document.network_interface) {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); let source = document.network_interface.layer_vector_source(layer);
let selected_anchors = selected_anchors_of(layer);
let hovered_anchor = hovered.and_then(|(hovered_layer, id, _)| (hovered_layer == layer).then_some(id));
let path_index_labels = path_marker_overlays(&vector, transform, document_zoom, true, overlay_context); overlay_context.with_rendered_layers(move |overlay_context, rendered| {
let (vector, transform) = rendered.vector(source).unwrap_or((Cow::Borrowed(&vector), source.layer_to_viewport));
let path_index_labels = path_marker_overlays(&vector, transform, document_zoom, true, overlay_context);
for id in vector.anchor_endpoints() { for id in vector.anchor_endpoints() {
if hovered.is_some_and(|(hovered_layer, hovered_id, _)| hovered_layer == layer && hovered_id == id) { if hovered_anchor == Some(id) {
continue; continue;
}
let Some(position) = vector.position_from_id(id) else { continue };
overlay_context.manipulator_anchor(transform.transform_point2(position), selected_anchors.contains(&id), None);
} }
let Some(position) = vector.position_from_id(id) else { continue };
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(layer, id), None); index_label_overlays(&vector, transform, true, &[], path_index_labels, overlay_context);
} });
index_label_overlays(&vector, transform, true, &[], path_index_labels, overlay_context);
} }
// Drawn last so its halo sits above any other endpoint at the same spot // Drawn last so its halo sits above any other endpoint at the same spot
if let Some((layer, id, position)) = hovered { if let Some((layer, id, position)) = hovered {
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); let source = document.network_interface.layer_vector_source(layer);
overlay_context.hover_manipulator_anchor(transform.transform_point2(position), is_selected(layer, id)); let selected = selected_anchors_of(layer).contains(&id);
overlay_context.with_rendered_layers(move |overlay_context, rendered| {
let (position, transform) = rendered
.vector(source)
.and_then(|(vector, transform)| Some((vector.position_from_id(id)?, transform)))
.unwrap_or((position, source.layer_to_viewport));
overlay_context.hover_manipulator_anchor(transform.transform_point2(position), selected);
});
} }
} }
@@ -14,16 +14,20 @@ use crate::messages::viewport::ToPhysical;
use core::borrow::Borrow; use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, PI, TAU}; use core::f64::consts::{FRAC_PI_2, PI, TAU};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphene_std::ATTR_TRANSFORM; use graph_craft::document::value::TaggedValue;
use graphene_std::list::List; use graph_craft::document::{NodeId, NodeNetwork};
use graphene_std::list::{Item, List};
use graphene_std::math::quad::Quad; use graphene_std::math::quad::Quad;
use graphene_std::renderer::RenderMetadata;
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder; use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig}; use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::point_to_dvec2; use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, paths_from_list_row_attributes}; use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
use kurbo::{self, BezPath, ParamCurve}; use kurbo::{self, BezPath, ParamCurve};
use kurbo::{Affine, PathSeg}; use kurbo::{Affine, PathSeg};
use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard}; use std::sync::{Arc, Mutex, MutexGuard};
use vello_gpu::peniko; use vello_gpu::peniko;
@@ -197,30 +201,21 @@ impl OverlaysVisibilitySettings {
} }
} }
/// Records overlay draw commands, which the graph runtime replays over each new frame of artwork.
/// Commands can look up layers in that frame's render, so the overlays stay aligned with the artwork.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(serde::Serialize, serde::Deserialize)] #[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct OverlayContext { pub struct OverlayContext {
// Serde functionality isn't used but is required by the message system macros // Serde functionality isn't used but is required by the message system macros
#[serde(skip)] #[serde(skip)]
internal: Arc<Mutex<OverlayContextInternal>>, commands: Arc<Mutex<Vec<OverlayCommand>>>,
pub viewport: ViewportMessageHandler, pub viewport: ViewportMessageHandler,
pub visibility_settings: OverlaysVisibilitySettings, pub visibility_settings: OverlaysVisibilitySettings,
} }
impl Clone for OverlayContext { type OverlayCommand = Box<dyn Fn(&mut OverlayContextInternal, &RenderedLayers) + Send>;
fn clone(&self) -> Self {
let internal = self.internal.lock().expect("Failed to lock internal overlay context");
let visibility_settings = internal.visibility_settings;
drop(internal); // Explicitly release the lock before cloning the Arc<Mutex<_>>
Self {
internal: self.internal.clone(),
viewport: self.viewport,
visibility_settings,
}
}
}
// Manual implementations since VelloSceneBuilder doesn't implement PartialEq or Debug // Manual implementations since the commands are closures
impl PartialEq for OverlayContext { impl PartialEq for OverlayContext {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.viewport == other.viewport && self.visibility_settings == other.visibility_settings self.viewport == other.viewport && self.visibility_settings == other.visibility_settings
@@ -230,21 +225,9 @@ impl PartialEq for OverlayContext {
impl std::fmt::Debug for OverlayContext { impl std::fmt::Debug for OverlayContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OverlayContext") f.debug_struct("OverlayContext")
.field("scene", &"VelloSceneBuilder { ... }")
.field("viewport", &self.viewport) .field("viewport", &self.viewport)
.field("visibility_settings", &self.visibility_settings) .field("visibility_settings", &self.visibility_settings)
.finish() .finish_non_exhaustive()
}
}
// Default implementation for VelloSceneBuilder
impl Default for OverlayContext {
fn default() -> Self {
Self {
internal: Mutex::new(OverlayContextInternal::default()).into(),
viewport: ViewportMessageHandler::default(),
visibility_settings: OverlaysVisibilitySettings::default(),
}
} }
} }
@@ -253,98 +236,234 @@ impl core::hash::Hash for OverlayContext {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {} fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
} }
/// Layer geometry and transforms from one render, used to place overlays over its artwork.
#[derive(Debug, Default)]
pub struct RenderedLayers {
/// The footprint transform of each rendered layer, from document space to the viewport.
footprints: HashMap<NodeId, DAffine2>,
local_transforms: HashMap<NodeId, DAffine2>,
/// The outline targets of each layer, or its click targets if it has no outlines.
/// A group's targets exclude those of its descendants.
targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
/// The output of each Path node, computed by applying its modification to the input the render recorded.
path_vectors: HashMap<NodeId, VectorGeometry>,
layer_vectors: HashMap<NodeId, Arc<Item<Vector>>>,
}
/// Identifies where a layer's editable vector and its transform come from, matching `compute_modified_vector` and `transform_to_viewport_if_feeds`.
#[derive(Clone, Copy, Debug)]
pub struct LayerVectorSource {
pub layer: LayerNodeIdentifier,
/// The visible upstream Path node. Its rendered output is the vector if the render recorded it.
pub path_node: Option<NodeId>,
pub local_transform_feeds: bool,
/// The editor's transform from the editable vector to the viewport, for when the render lacks the layer.
pub layer_to_viewport: DAffine2,
}
impl RenderedLayers {
/// Collects the layers from the render metadata and computes each Path node's output from its recorded input and its modification in `network`.
pub fn new(metadata: &RenderMetadata, path_inputs: &HashMap<NodeId, VectorGeometry>, network: Option<&NodeNetwork>) -> Self {
let mut targets = metadata.click_targets.clone();
targets.extend(metadata.outlines.iter().map(|(node, outlines)| (*node, outlines.clone())));
let path_vectors = path_inputs
.iter()
.map(|(&path_node, input)| {
let mut vector = input.clone();
let modification = network
.and_then(|network| network.nodes.get(&path_node))
.and_then(|node| node.inputs.get(path::ModificationInput::INDEX))
.and_then(|input| input.as_value());
if let Some(TaggedValue::VectorModification(modification)) = modification {
modification.apply(&mut vector.vector, &mut vector.paths);
}
(path_node, vector)
})
.collect();
Self {
footprints: metadata.upstream_footprints.iter().map(|(node, footprint)| (*node, footprint.transform)).collect(),
local_transforms: metadata.local_transforms.clone(),
targets,
path_vectors,
layer_vectors: metadata.vector_data.clone(),
}
}
/// The layer's transform to the viewport, if the render has the layer.
fn transform_to_viewport(&self, layer: LayerNodeIdentifier, include_local: bool) -> Option<DAffine2> {
let node = layer.to_node();
let local_transform = include_local.then(|| self.local_transforms.get(&node).copied()).flatten().unwrap_or_default();
self.footprints.get(&node).map(|footprint| *footprint * local_transform)
}
/// The layer's transform to the viewport and its own targets, if the render has the layer.
fn layer(&self, layer: LayerNodeIdentifier) -> Option<(DAffine2, &[Arc<ClickTarget>])> {
let transform = self.transform_to_viewport(layer, true)?;
Some((transform, self.targets.get(&layer.to_node()).map(Vec::as_slice).unwrap_or_default()))
}
/// The viewport-space movement of the layer from `layer_to_viewport`, its transform when the overlays were made, to its transform in this render.
/// Returns the identity if the render lacks the layer or `layer_to_viewport` isn't invertible.
pub fn movement(&self, layer: LayerNodeIdentifier, layer_to_viewport: DAffine2) -> DAffine2 {
match self.transform_to_viewport(layer, true) {
Some(rendered) if layer_to_viewport.matrix2.determinant() != 0. => rendered * layer_to_viewport.inverse(),
_ => DAffine2::IDENTITY,
}
}
/// The layer's editable vector and its transform to the viewport, if the render has them.
pub fn vector(&self, source: LayerVectorSource) -> Option<(Cow<'_, VectorGeometry>, DAffine2)> {
let transform = self.transform_to_viewport(source.layer, source.local_transform_feeds)?;
let vector = match source.path_node.and_then(|path_node| self.path_vectors.get(&path_node)) {
Some(vector) => Cow::Borrowed(vector),
None => Cow::Owned(VectorGeometry::from_item(self.layer_vectors.get(&source.layer.to_node())?)),
};
Some((vector, transform))
}
}
fn owned(color: Option<&str>) -> Option<String> {
color.map(str::to_owned)
}
impl OverlayContext { impl OverlayContext {
#[cfg_attr(test, expect(dead_code, reason = "Tests skip drawing overlays"))]
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self { pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
Self { Self {
internal: Arc::new(Mutex::new(OverlayContextInternal::new(viewport, visibility_settings))), commands: Arc::default(),
viewport, viewport,
visibility_settings, visibility_settings,
} }
} }
pub fn take_scene(self) -> VelloSceneBuilder<'static> { /// Draws the recorded overlays, resolving layers against `rendered`.
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context"); pub fn render(&self, rendered: &RenderedLayers) -> VelloSceneBuilder<'static> {
let empty_scene = overlay_scene(&internal.viewport); let mut overlays = OverlayContextInternal::new(self.viewport);
std::mem::replace(&mut internal.scene, empty_scene) for command in self.commands().iter() {
command(&mut overlays, rendered);
}
overlays.scene
} }
fn internal(&'_ self) -> MutexGuard<'_, OverlayContextInternal> { fn commands(&'_ self) -> MutexGuard<'_, Vec<OverlayCommand>> {
self.internal.lock().expect("Failed to lock internal overlay context") self.commands.lock().expect("Failed to lock the overlay commands")
}
fn record(&self, command: impl Fn(&mut OverlayContextInternal) + Send + 'static) {
self.record_resolved(move |overlays, _| command(overlays));
}
fn record_resolved(&self, command: impl Fn(&mut OverlayContextInternal, &RenderedLayers) + Send + 'static) {
self.commands().push(Box::new(command));
}
/// Defers `draw` until render time and passes it the movement of `layer` since `layer_to_viewport` (see [`RenderedLayers::movement`]).
/// Used for overlays placed by a layer's transform, such as its transform cage.
pub fn follow_layer(&mut self, layer: LayerNodeIdentifier, layer_to_viewport: DAffine2, draw: impl Fn(&mut OverlayContext, DAffine2) + Send + 'static) {
self.with_rendered_layers(move |overlay_context, rendered| draw(overlay_context, rendered.movement(layer, layer_to_viewport)));
}
/// Defers `draw` until render time and passes it the layers of the render the overlays are shown over.
pub fn with_rendered_layers(&mut self, draw: impl Fn(&mut OverlayContext, &RenderedLayers) + Send + 'static) {
let (viewport, visibility_settings) = (self.viewport, self.visibility_settings);
self.record_resolved(move |overlays, rendered| {
let overlay_context = &mut OverlayContext::new(viewport, visibility_settings);
draw(overlay_context, rendered);
for command in overlay_context.commands().iter() {
command(overlays, rendered);
}
});
} }
pub fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) { pub fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) {
self.internal().quad(quad, stroke_color, color_fill); let (stroke_color, color_fill) = (owned(stroke_color), owned(color_fill));
self.record(move |overlays| overlays.quad(quad, stroke_color.as_deref(), color_fill.as_deref()));
} }
pub fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) { pub fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.internal().draw_triangle(base, direction, size, color_fill, color_stroke); let (color_fill, color_stroke) = (owned(color_fill), owned(color_stroke));
self.record(move |overlays| overlays.draw_triangle(base, direction, size, color_fill.as_deref(), color_stroke.as_deref()));
} }
pub fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) { pub fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.internal().dashed_quad(quad, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset); let (stroke_color, color_fill) = (owned(stroke_color), owned(color_fill));
self.record(move |overlays| overlays.dashed_quad(quad, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
} }
pub fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) { pub fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) {
self.internal().polygon(polygon, stroke_color, color_fill); let (polygon, stroke_color, color_fill) = (polygon.to_vec(), owned(stroke_color), owned(color_fill));
self.record(move |overlays| overlays.polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref()));
} }
pub fn dashed_polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) { pub fn dashed_polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.internal().dashed_polygon(polygon, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset); let (polygon, stroke_color, color_fill) = (polygon.to_vec(), owned(stroke_color), owned(color_fill));
self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
} }
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) { pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.internal().line(start, end, color, thickness); let color = owned(color);
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) { pub fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
self.internal().dashed_line(start, end, color, thickness, dash_width, dash_gap_width, dash_offset); let color = owned(color);
self.record(move |overlays| overlays.dashed_line(start, end, color.as_deref(), thickness, dash_width, dash_gap_width, dash_offset));
} }
pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) { pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
self.internal().hover_manipulator_handle(position, selected); self.record(move |overlays| overlays.hover_manipulator_handle(position, selected));
} }
pub fn hover_manipulator_anchor(&mut self, position: DVec2, selected: bool) { pub fn hover_manipulator_anchor(&mut self, position: DVec2, selected: bool) {
self.internal().hover_manipulator_anchor(position, selected); self.record(move |overlays| overlays.hover_manipulator_anchor(position, selected));
} }
pub fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) { pub fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
self.internal().manipulator_handle(position, selected, color); let color = owned(color);
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
} }
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) { pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
self.internal().manipulator_anchor(position, selected, color); let color = owned(color);
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
} }
pub fn gradient_color_stop(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, small: bool) { pub fn gradient_color_stop(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, small: bool) {
self.internal().gradient_color_stop(position, emphasis, color, small); let color = color.to_owned();
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
} }
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) { pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
self.internal().gradient_midpoint(position, emphasis, angle); self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
} }
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) { pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
self.internal().resize_handle(position, rotation); self.record(move |overlays| overlays.resize_handle(position, rotation));
} }
pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) { pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
self.internal().skew_handles(edge_start, edge_end); self.record(move |overlays| overlays.skew_handles(edge_start, edge_end));
} }
pub fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) { pub fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.internal().square(position, size, color_fill, color_stroke); let (color_fill, color_stroke) = (owned(color_fill), owned(color_stroke));
self.record(move |overlays| overlays.square(position, size, color_fill.as_deref(), color_stroke.as_deref()));
} }
/// Fills a square dot about `size` pixels across at each position, all in one fill, with their edges on whole physical pixels so they stay crisp. /// Fills a square dot about `size` pixels across at each position, all in one fill, with their edges on whole physical pixels so they stay crisp.
pub fn dots(&mut self, positions: &[DVec2], size: f64, color: Option<&str>) { pub fn dots(&mut self, positions: &[DVec2], size: f64, color: Option<&str>) {
self.internal().dots(positions, size, color); let (positions, color) = (positions.to_vec(), owned(color));
self.record(move |overlays| overlays.dots(&positions, size, color.as_deref()));
} }
pub fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) { pub fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
self.internal().circle(position, radius, color_fill, color_stroke); let (color_fill, color_stroke) = (owned(color_fill), owned(color_stroke));
self.record(move |overlays| overlays.circle(position, radius, color_fill.as_deref(), color_stroke.as_deref()));
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
@@ -363,106 +482,135 @@ impl OverlayContext {
dash_gap_width: Option<f64>, dash_gap_width: Option<f64>,
dash_offset: Option<f64>, dash_offset: Option<f64>,
) { ) {
self.internal().dashed_ellipse( let (color_fill, color_stroke) = (owned(color_fill), owned(color_stroke));
center, self.record(move |overlays| {
radius_x, overlays.dashed_ellipse(
radius_y, center,
rotation, radius_x,
start_angle, radius_y,
end_angle, rotation,
counterclockwise, start_angle,
color_fill, end_angle,
color_stroke, counterclockwise,
dash_width, color_fill.as_deref(),
dash_gap_width, color_stroke.as_deref(),
dash_offset, dash_width,
); dash_gap_width,
dash_offset,
)
});
} }
pub fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) { pub fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
self.internal().draw_arc(center, radius, start_from, end_at); self.record(move |overlays| overlays.draw_arc(center, radius, start_from, end_at));
} }
pub fn draw_arc_gizmo_angle(&mut self, pivot: DVec2, bold_radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) { pub fn draw_arc_gizmo_angle(&mut self, pivot: DVec2, bold_radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
self.internal().draw_arc_gizmo_angle(pivot, bold_radius, arc_radius, offset_angle, angle); self.record(move |overlays| overlays.draw_arc_gizmo_angle(pivot, bold_radius, arc_radius, offset_angle, angle));
} }
pub fn draw_angle(&mut self, pivot: DVec2, radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) { pub fn draw_angle(&mut self, pivot: DVec2, radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
self.internal().draw_angle(pivot, radius, arc_radius, offset_angle, angle); self.record(move |overlays| overlays.draw_angle(pivot, radius, arc_radius, offset_angle, angle));
} }
pub fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) { pub fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
self.internal().draw_scale(start, scale, radius, text); let text = text.to_owned();
self.record(move |overlays| overlays.draw_scale(start, scale, radius, &text));
} }
pub fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) { pub fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) {
self.internal().compass_rose(compass_center, angle, show_compass_with_hover_ring); self.record(move |overlays| overlays.compass_rose(compass_center, angle, show_compass_with_hover_ring));
} }
pub fn pivot(&mut self, position: DVec2, angle: f64) { pub fn pivot(&mut self, position: DVec2, angle: f64) {
self.internal().pivot(position, angle); self.record(move |overlays| overlays.pivot(position, angle));
} }
pub fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) { pub fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
self.internal().dowel_pin(position, angle, color); let color = owned(color);
self.record(move |overlays| overlays.dowel_pin(position, angle, color.as_deref()));
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub fn arc_sweep_angle(&mut self, offset_angle: f64, angle: f64, end_point_position: DVec2, bold_radius: f64, pivot: DVec2, text: &str, transform: DAffine2) { pub fn arc_sweep_angle(&mut self, offset_angle: f64, angle: f64, end_point_position: DVec2, bold_radius: f64, pivot: DVec2, text: &str, transform: DAffine2) {
self.internal().arc_sweep_angle(offset_angle, angle, end_point_position, bold_radius, pivot, text, transform); let text = text.to_owned();
self.record(move |overlays| overlays.arc_sweep_angle(offset_angle, angle, end_point_position, bold_radius, pivot, &text, transform));
} }
/// Used by the Pen and Path tools to outline the path of the shape. /// Used by the Pen and Path tools to outline the path of the shape.
pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) { pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) {
self.internal().outline_vector(vector, transform); let vector = vector.clone();
self.record(move |overlays| overlays.outline_vector(&vector, transform));
} }
/// Used by the Pen tool in order to show how the bezier curve would look like. /// Used by the Pen tool in order to show how the bezier curve would look like.
pub fn outline_bezier(&mut self, bezier: PathSeg, transform: DAffine2) { pub fn outline_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.internal().outline_bezier(bezier, transform); self.record(move |overlays| overlays.outline_bezier(bezier, transform));
} }
/// Used by the path tool segment mode in order to show the selected segments. /// Used by the path tool segment mode in order to show the selected segments.
pub fn outline_select_bezier(&mut self, bezier: PathSeg, transform: DAffine2) { pub fn outline_select_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.internal().outline_select_bezier(bezier, transform); self.record(move |overlays| overlays.outline_select_bezier(bezier, transform));
} }
pub fn outline_overlay_bezier(&mut self, bezier: PathSeg, transform: DAffine2) { pub fn outline_overlay_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
self.internal().outline_overlay_bezier(bezier, transform); self.record(move |overlays| overlays.outline_overlay_bezier(bezier, transform));
} }
/// Used by the Select tool to outline a path or a free point when selected or hovered. /// Used by the Select tool to outline a path or a free point when selected or hovered.
pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) { pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
self.internal().outline(target_types, transform, color); let (target_types, color) = (target_types.map(|target_type| target_type.borrow().clone()).collect::<Vec<_>>(), owned(color));
self.record(move |overlays| overlays.outline(target_types.iter(), transform, color.as_deref()));
}
/// Outlines each layer with its own targets from the render the overlays are shown over.
/// Falls back to `target_types` placed by `transform` if the render lacks any of the layers.
/// To outline a group, pass it together with its descendants.
pub fn outline_rendered_layers(&mut self, layers: Vec<LayerNodeIdentifier>, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
let (target_types, color) = (target_types.map(|target_type| target_type.borrow().clone()).collect::<Vec<_>>(), owned(color));
self.record_resolved(move |overlays, rendered| {
let Some(rendered_layers) = layers.iter().map(|&layer| rendered.layer(layer)).collect::<Option<Vec<_>>>() else {
overlays.outline(target_types.iter(), transform, color.as_deref());
return;
};
for (layer_to_viewport, targets) in rendered_layers {
overlays.outline(targets.iter().map(|target| target.target_type()), layer_to_viewport, color.as_deref());
}
});
} }
/// Strokes the path with a 1px line, leaving any open subpaths open. /// Strokes the path with a 1px line, leaving any open subpaths open.
pub fn stroke_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) { pub fn stroke_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
self.internal().stroke_path(bezpath, transform, color); let (bezpath, color) = (bezpath.clone(), color.to_owned());
self.record(move |overlays| overlays.stroke_path(&bezpath, transform, &color));
} }
/// Fills the area inside the path. Assumes `color` is in gamma space. /// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed. /// Used by the Pen tool to show the path being closed.
pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) { pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
self.internal().fill_path(bezpath, transform, color); let (bezpath, color) = (bezpath.clone(), color.to_owned());
self.record(move |overlays| overlays.fill_path(&bezpath, transform, &color));
} }
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string. /// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
/// Used by the fill tool to show the area to be filled. /// Used by the fill tool to show the area to be filled.
pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) { pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
self.internal().fill_path_pattern(bezpath, transform, color); let (bezpath, color) = (bezpath.clone(), color.to_owned());
self.record(move |overlays| overlays.fill_path_pattern(&bezpath, transform, &color));
} }
pub fn text(&self, text: &str, font_color: &str, background_color: Option<&str>, transform: DAffine2, padding: f64, pivot: [Pivot; 2]) { pub fn text(&self, text: &str, font_color: &str, background_color: Option<&str>, transform: DAffine2, padding: f64, pivot: [Pivot; 2]) {
let mut internal = self.internal(); let (text, font_color, background_color) = (text.to_owned(), font_color.to_owned(), owned(background_color));
internal.text(text, font_color, background_color, transform, padding, pivot); self.record(move |overlays| overlays.text(&text, &font_color, background_color.as_deref(), transform, padding, pivot));
} }
pub fn translation_box(&mut self, translation: DVec2, quad: Quad, typed_string: Option<String>) { pub fn translation_box(&mut self, translation: DVec2, quad: Quad, typed_string: Option<String>) {
self.internal().translation_box(translation, quad, typed_string); self.record(move |overlays| overlays.translation_box(translation, quad, typed_string.clone()));
} }
} }
#[derive(Clone, Copy)]
pub enum Pivot { pub enum Pivot {
Start, Start,
Middle, Middle,
@@ -476,10 +624,9 @@ pub enum DrawHandles {
None, None,
} }
pub(super) struct OverlayContextInternal { struct OverlayContextInternal {
scene: VelloSceneBuilder<'static>, scene: VelloSceneBuilder<'static>,
viewport: ViewportMessageHandler, viewport: ViewportMessageHandler,
visibility_settings: OverlaysVisibilitySettings,
} }
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at. /// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
@@ -491,18 +638,11 @@ fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static
VelloSceneBuilder::new(size.x as u16, size.y as u16, Affine::IDENTITY, MAX_TEXTURE_SIZE) VelloSceneBuilder::new(size.x as u16, size.y as u16, Affine::IDENTITY, MAX_TEXTURE_SIZE)
} }
impl Default for OverlayContextInternal {
fn default() -> Self {
Self::new(ViewportMessageHandler::default(), OverlaysVisibilitySettings::default())
}
}
impl OverlayContextInternal { impl OverlayContextInternal {
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self { fn new(viewport: ViewportMessageHandler) -> Self {
Self { Self {
scene: overlay_scene(&viewport), scene: overlay_scene(&viewport),
viewport, viewport,
visibility_settings,
} }
} }
@@ -137,6 +137,49 @@ async fn saving_writes_a_zip_archive_with_the_graphite_extension() {
assert_eq!(ArchiveFormat::detect(&content), Some(ArchiveFormat::Zip)); assert_eq!(ArchiveFormat::detect(&content), Some(ArchiveFormat::Zip));
} }
#[tokio::test]
async fn opening_a_file_moves_its_resources_into_the_resource_storage() {
use graphene_std::raster::{Color, Image};
fn save(editor: &mut EditorTestUtils) -> Vec<u8> {
let saved = dispatch(editor, DocumentMessage::SaveDocumentAs);
let content = saved.iter().find_map(|message| match message {
FrontendMessage::TriggerSaveDocument { content, .. } => Some(content.to_vec()),
_ => None,
});
content.expect("the save is sent to the frontend")
}
async fn saved_resources(content: &[u8]) -> Vec<String> {
let mut unpacked = document_container::backends::memory::MemoryBackend::new();
document_container::archive::open_auto(content, &mut unpacked).unwrap();
let mut resources = unpacked.list("resources").await.unwrap_or_default();
resources.sort();
resources
}
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Saved");
editor.create_raster_image(Image::new(2, 2, Color::WHITE), None).await;
let content = save(&mut editor);
let resources = saved_resources(&content).await;
assert!(!resources.is_empty(), "the file carries the document's resources");
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: Some("Opened".into()),
document_path: None,
content,
fresh_identity: true,
})
.await;
let opened = portfolio(&editor).active_document_id.unwrap();
assert_ne!(opened, id);
let container = container(&editor, opened).await;
assert_eq!(container.list("resources").await.unwrap_or_default(), Vec::<String>::new(), "the working copy keeps no resources");
assert_eq!(saved_resources(&save(&mut editor)).await, resources, "saving writes them from the resource storage");
}
#[tokio::test] #[tokio::test]
async fn storage_only_container_recovers_and_writes_legacy() { async fn storage_only_container_recovers_and_writes_legacy() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
@@ -112,15 +112,7 @@ impl DocumentMetadata {
} }
pub fn transform_to_viewport(&self, layer: LayerNodeIdentifier) -> DAffine2 { pub fn transform_to_viewport(&self, layer: LayerNodeIdentifier) -> DAffine2 {
// We're not allowed to convert the root parent to a node id self.transform_to_viewport_including_local(layer, true)
if layer == LayerNodeIdentifier::ROOT_PARENT {
return self.document_to_viewport;
}
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport);
let local_transform = self.local_transforms.get(&layer.to_node()).copied().unwrap_or_default();
footprint * local_transform
} }
pub fn transform_to_viewport_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 { pub fn transform_to_viewport_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
@@ -129,9 +121,25 @@ impl DocumentMetadata {
return self.document_to_viewport; return self.document_to_viewport;
} }
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport); self.transform_to_viewport_including_local(layer, self.local_transform_feeds(layer, network_interface))
}
let mut use_local = true; /// The layer's footprint transform to the viewport, followed by its local transform if `include_local` is set.
pub fn transform_to_viewport_including_local(&self, layer: LayerNodeIdentifier, include_local: bool) -> DAffine2 {
// We're not allowed to convert the root parent to a node id
if layer == LayerNodeIdentifier::ROOT_PARENT {
return self.document_to_viewport;
}
let footprint = self.upstream_footprints.get(&layer.to_node()).map(|footprint| footprint.transform).unwrap_or(self.document_to_viewport);
let local_transform = include_local.then(|| self.local_transforms.get(&layer.to_node()).copied()).flatten().unwrap_or_default();
footprint * local_transform
}
/// Whether the layer's local transform applies to the vector edited by its upstream Path node.
/// It doesn't if the layer's first element comes from a node that isn't upstream of the Path node.
pub fn local_transform_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface); let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER); let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier) if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier)
@@ -140,12 +148,10 @@ impl DocumentMetadata {
.upstream_flow_back_from_nodes(vec![path_node], &[], FlowType::HorizontalFlow) .upstream_flow_back_from_nodes(vec![path_node], &[], FlowType::HorizontalFlow)
.any(|upstream| Some(upstream) == source) .any(|upstream| Some(upstream) == source)
{ {
use_local = false; return false;
info!("Local transform is invalid. Using the identity for the local transform instead.");
} }
let local_transform = use_local.then(|| self.local_transforms.get(&layer.to_node()).copied()).flatten().unwrap_or_default();
footprint * local_transform true
} }
pub fn transform_to_document_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 { pub fn transform_to_document_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
@@ -190,6 +196,15 @@ impl DocumentMetadata {
footprint * transform footprint * transform
} }
/// The first of the layer and its descendants that has a local transform, or the layer itself if none has one.
/// Overlays around a group without a local transform follow the movement of this layer.
pub fn layer_to_follow(&self, layer: LayerNodeIdentifier) -> LayerNodeIdentifier {
std::iter::once(layer)
.chain(layer.descendants(self))
.find(|layer| self.local_transforms.contains_key(&layer.to_node()))
.unwrap_or(layer)
}
pub fn upstream_transform(&self, node_id: NodeId) -> DAffine2 { pub fn upstream_transform(&self, node_id: NodeId) -> DAffine2 {
self.local_transforms.get(&node_id).copied().unwrap_or(DAffine2::IDENTITY) self.local_transforms.get(&node_id).copied().unwrap_or(DAffine2::IDENTITY)
} }
@@ -37,6 +37,7 @@ pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use reconcile::{ReconcileError, Reconciled}; pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded; use store::Guarded;
pub use store::NodeLocator; pub use store::NodeLocator;
pub use structure::vector_outline_targets;
pub use template::*; pub use template::*;
pub use types::*; pub use types::*;
pub use view::{NetworkError, NetworkView}; pub use view::{NetworkError, NetworkView};
@@ -4,7 +4,7 @@ use super::*;
impl NodeNetworkInterface { impl NodeNetworkInterface {
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) { pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_view_state_mut(|path, view| { self.for_each_network_view_state_mut(|path, view| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) { if let Some(other_network_metadata) = other_interface.nested_metadata(path) {
*view.navigation = other_network_metadata.persistent_metadata.navigation_metadata.clone(); *view.navigation = other_network_metadata.persistent_metadata.navigation_metadata.clone();
} }
}); });
@@ -1,4 +1,5 @@
use super::*; use super::*;
use crate::messages::portfolio::document::overlays::utility_types::LayerVectorSource;
use graphene_std::list::Item; use graphene_std::list::Item;
use graphene_std::vector::VectorGeometry; use graphene_std::vector::VectorGeometry;
@@ -22,6 +23,19 @@ impl NodeNetworkInterface {
self.document_metadata.layer_vector_data.get(&layer).map(|item| VectorGeometry::from_item(item)) self.document_metadata.layer_vector_data.get(&layer).map(|item| VectorGeometry::from_item(item))
} }
/// The source of [`Self::compute_modified_vector`] and the layer's transform, so overlays can look them up in the render.
pub fn layer_vector_source(&self, layer: LayerNodeIdentifier) -> LayerVectorSource {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
let local_transform_feeds = self.document_metadata.local_transform_feeds(layer, self);
LayerVectorSource {
layer,
path_node: graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER)),
local_transform_feeds,
layer_to_viewport: self.document_metadata.transform_to_viewport_including_local(layer, local_transform_feeds),
}
}
/// The vector geometry an upstream Path node would surface for editing. /// The vector geometry an upstream Path node would surface for editing.
/// This is the result of `compute_modified_vector`, but only if a visible 'Path' node is actually upstream. /// This is the result of `compute_modified_vector`, but only if a visible 'Path' node is actually upstream.
/// Useful for tool overlays and snap target collection usages that want to match the Path tool's view /// Useful for tool overlays and snap target collection usages that want to match the Path tool's view
@@ -37,22 +51,7 @@ impl NodeNetworkInterface {
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer); returns `None` otherwise so the /// (e.g. the pre-solidified centerline for a Solidify Stroke layer); returns `None` otherwise so the
/// caller can fall back to the layer's recorded `outlines`/`click_targets`. /// caller can fall back to the layer's recorded `outlines`/`click_targets`.
pub fn path_aware_outline_targets(&self, layer: LayerNodeIdentifier) -> Option<Vec<ClickTargetType>> { pub fn path_aware_outline_targets(&self, layer: LayerNodeIdentifier) -> Option<Vec<ClickTargetType>> {
let vector = self.upstream_path_node_vector(layer)?; self.upstream_path_node_vector(layer).map(|vector| vector_outline_targets(&vector))
let mut targets = Vec::new();
let mut combined = BezPath::new();
for bezpath in vector.stroke_bezpath_iter() {
combined.extend(bezpath.elements().iter().copied());
}
if !combined.is_empty() {
targets.push(ClickTargetType::Path(combined));
}
for (point_id, position) in vector.free_points() {
targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position)));
}
Some(targets)
} }
/// Loads the structure of layer nodes from a node graph. /// Loads the structure of layer nodes from a node graph.
@@ -207,3 +206,21 @@ impl NodeNetworkInterface {
self.document_metadata.layer_effects_reach = new_layer_effects_reach; self.document_metadata.layer_effects_reach = new_layer_effects_reach;
} }
} }
/// The vector's paths combined into one outline target, followed by a target for each free point.
pub fn vector_outline_targets(vector: &VectorGeometry) -> Vec<ClickTargetType> {
let mut targets = Vec::new();
let mut combined = BezPath::new();
for bezpath in vector.stroke_bezpath_iter() {
combined.extend(bezpath.elements().iter().copied());
}
if !combined.is_empty() {
targets.push(ClickTargetType::Path(combined));
}
for (point_id, position) in vector.free_points() {
targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position)));
}
targets
}
@@ -20,7 +20,6 @@ use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
use document_container::{AnyContainer, AsyncContainer}; use document_container::{AnyContainer, AsyncContainer};
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError}; use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError};
use document_graph_storage::{Declarations, PeerId, UserId}; use document_graph_storage::{Declarations, PeerId, UserId};
use graph_craft::application_io::resource::LoadResource;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage}; use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
use std::collections::HashSet; use std::collections::HashSet;
use std::path::PathBuf; use std::path::PathBuf;
@@ -221,8 +220,19 @@ pub(super) async fn open_document_file(
) -> Message { ) -> Message {
document_locks::claim(document_id).await; document_locks::claim(document_id).await;
let materialized = async { let materialized = async {
let mut container = store.open(document_key(document_id)).await.map_err(|error| error.to_string())?; let container = store.open(document_key(document_id)).await.map_err(|error| error.to_string())?;
document_container::archive::open_auto(&content, &mut container).map_err(|error| error.to_string())?; let resources_prefix = format!("{}/", GddV1Layout.resources_dir());
document_container::archive::unpack_auto(&content, &mut |path, size, fill| {
if path.starts_with(&resources_prefix) {
let mut bytes = vec![0; size];
fill(&mut bytes)?;
resources.store(&bytes);
return Ok(());
}
container.write_sized_non_blocking(path, size, fill)
})
.map_err(|error| error.to_string())?;
Ok::<_, String>(container) Ok::<_, String>(container)
} }
.await; .await;
@@ -287,12 +297,12 @@ pub(super) async fn load_from_container(container: AnyContainer, document_id: Do
} }
/// Open a document's storage, offering its migrations the compiler and the global cache's declarations. /// Open a document's storage, offering its migrations the compiler and the global cache's declarations.
async fn open_migrating(container: AnyContainer, resources: &dyn LoadResource) -> Result<GddV1, DocumentFormatError> { async fn open_migrating(container: AnyContainer, resources: &dyn ResourceStorage) -> Result<GddV1, DocumentFormatError> {
let host = migration_compiled::CompilerHost::default(); let host = migration_compiled::CompilerHost::default();
GddV1::open_in_with(container, GddV1Layout, Some(resources), Some(&host)).await GddV1::open_in_with(container, GddV1Layout, Some(resources), Some(&host)).await
} }
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId, resources: &dyn LoadResource) -> Option<GddV1> { async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId, resources: &dyn ResourceStorage) -> Option<GddV1> {
match open_migrating(container.clone(), resources).await { match open_migrating(container.clone(), resources).await {
Ok(gdd) => return Some(gdd), Ok(gdd) => return Some(gdd),
Err(DocumentFormatError::MissingManifest) => {} Err(DocumentFormatError::MissingManifest) => {}
@@ -327,12 +337,12 @@ async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id
async fn load_declarations(gdd: Option<&GddV1>, resources: &ResourcesHandle, document_id: DocumentId) -> Declarations { async fn load_declarations(gdd: Option<&GddV1>, resources: &ResourcesHandle, document_id: DocumentId) -> Declarations {
let Some(gdd) = gdd else { return Declarations::new() }; let Some(gdd) = gdd else { return Declarations::new() };
// Migrations store the declarations they introduce in the container, which this device's cache may not have seen // A container written before resources stayed out of it still holds some
hydrate_resources(gdd, resources, document_id).await; hydrate_resources(gdd, resources, document_id).await;
gdd.declarations(resources).await gdd.declarations(resources).await
} }
/// Copy every resource stored in `gdd`'s container that the global cache lacks into it. /// Move every resource stored in `gdd`'s container into the global cache.
async fn hydrate_resources(gdd: &GddV1, byte_store: &ResourcesHandle, document_id: DocumentId) { async fn hydrate_resources(gdd: &GddV1, byte_store: &ResourcesHandle, document_id: DocumentId) {
let hashes = match gdd.resource_hashes().await { let hashes = match gdd.resource_hashes().await {
Ok(hashes) => hashes, Ok(hashes) => hashes,
@@ -342,12 +352,20 @@ async fn hydrate_resources(gdd: &GddV1, byte_store: &ResourcesHandle, document_i
} }
}; };
for hash in hashes.into_iter().filter(|hash| !byte_store.contains(hash)) { for hash in hashes {
match gdd.read_resource(&hash).await { if !byte_store.contains(&hash) {
Ok(holder) => { match gdd.read_resource(&hash).await {
byte_store.store(holder.as_slice()); Ok(holder) => {
byte_store.store(holder.as_slice());
}
Err(error) => {
log::error!("Opening document {document_id:?}: failed to read resource {hash}: {error}");
continue;
}
} }
Err(error) => log::error!("Opening document {document_id:?}: failed to read resource {hash}: {error}"), }
if let Err(error) = gdd.remove_resource(&hash) {
log::error!("Opening document {document_id:?}: failed to remove resource {hash}: {error}");
} }
} }
} }
@@ -11,6 +11,7 @@ pub enum HistoryMessage {
RemoveStep { id: String }, RemoveStep { id: String },
BringBack { id: String }, BringBack { id: String },
Follow { id: Option<String> }, Follow { id: Option<String> },
Preview { id: Option<String> },
RetirePending, RetirePending,
Rename { id: String, label: String }, Rename { id: String, label: String },
Tag { id: String, tag: String, on: bool }, Tag { id: String, tag: String, on: bool },
@@ -30,6 +30,8 @@ pub struct HistoryMessageHandler {
expanded: BTreeSet<Rev>, expanded: BTreeSet<Rev>,
limit: usize, limit: usize,
following: Option<Rev>, following: Option<Rev>,
/// The head last sent, to stop following a branch once the head moves.
seen_head: Option<Rev>,
last_sent: Option<u64>, last_sent: Option<u64>,
} }
@@ -66,6 +68,9 @@ impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessag
} }
HistoryMessage::LoadMore => self.limit = self.limit.max(PAGE) + PAGE, HistoryMessage::LoadMore => self.limit = self.limit.max(PAGE) + PAGE,
HistoryMessage::Follow { id } => self.following = id.as_deref().and_then(parse_rev), HistoryMessage::Follow { id } => self.following = id.as_deref().and_then(parse_rev),
HistoryMessage::Preview { id } => responses.add(DocumentMessage::PreviewHistoryStep {
rev: id.as_deref().and_then(parse_rev),
}),
HistoryMessage::RetirePending => { HistoryMessage::RetirePending => {
let Some(document) = context.active_document_id.and_then(|id| context.documents.get_mut(&id)) else { let Some(document) = context.active_document_id.and_then(|id| context.documents.get_mut(&id)) else {
return; return;
@@ -76,11 +81,13 @@ impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessag
} }
HistoryMessage::GoBack { id } => { HistoryMessage::GoBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return }; let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
responses.add(DocumentMessage::PreviewHistoryStep { rev: None });
match place(gdd.session(), rev) { match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)), Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(0)) => {} Some(Place::Line(0)) => {}
Some(Place::Line(_)) => responses.add(DocumentMessage::ChangeHistoryLine { rev, change: LineChange::MoveHead }), Some(Place::Line(_)) => responses.add(DocumentMessage::ChangeHistoryLine { rev, change: LineChange::MoveHead }),
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"), None if gdd.session().delta(rev).is_some() => responses.add(DocumentMessage::ChangeHistoryLine { rev, change: LineChange::MoveHead }),
None => log::warn!("The History panel went back to a step not in history"),
} }
} }
HistoryMessage::RemoveStep { id } => { HistoryMessage::RemoveStep { id } => {
@@ -90,6 +97,7 @@ impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessag
} }
HistoryMessage::BringBack { id } => { HistoryMessage::BringBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return }; let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
responses.add(DocumentMessage::PreviewHistoryStep { rev: None });
match place(gdd.session(), rev) { match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)), Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(_)) => {} Some(Place::Line(_)) => {}
@@ -121,18 +129,26 @@ impl HistoryMessageHandler {
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>) { fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>) {
let document = context.active_document_id.and_then(|id| context.documents.get(&id)); let document = context.active_document_id.and_then(|id| context.documents.get(&id));
let gdd = document.and_then(|document| document.storage()); let gdd = document.and_then(|document| document.storage());
if self.following.is_some_and(|tip| gdd.is_none_or(|gdd| gdd.session().delta(tip).is_none())) { let head = gdd.and_then(|gdd| gdd.session().head_rev());
let followed_tip_gone = self.following.is_some_and(|tip| gdd.is_none_or(|gdd| gdd.session().delta(tip).is_none()));
if followed_tip_gone || head != self.seen_head {
self.following = None; self.following = None;
} }
self.seen_head = head;
let previewing = document.and_then(|document| document.previewed_history_step());
let limit = self.limit.max(PAGE); let limit = self.limit.max(PAGE);
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following); let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following, previewing);
if self.last_sent == Some(fingerprint) { if self.last_sent == Some(fingerprint) {
return; return;
} }
self.last_sent = Some(fingerprint); self.last_sent = Some(fingerprint);
let state = document let state = document
.zip(gdd) .zip(gdd)
.map(|(document, gdd)| panel_state(gdd, document.declarations(), limit, &self.expanded, self.following)) .map(|(document, gdd)| HistoryPanelState {
previewing: previewing.map(|rev| rev.to_string()),
..panel_state(gdd, document.declarations(), limit, &self.expanded, self.following)
})
.unwrap_or_default(); .unwrap_or_default();
responses.add(FrontendMessage::UpdateHistoryPanel { state }); responses.add(FrontendMessage::UpdateHistoryPanel { state });
} }
@@ -151,7 +167,7 @@ fn parse_rev(id: &str) -> Option<Rev> {
} }
/// Where an interaction sits relative to the head. /// Where an interaction sits relative to the head.
enum Place { pub(crate) enum Place {
/// On the head's line, this many interactions back. /// On the head's line, this many interactions back.
Line(usize), Line(usize),
/// Undone above the head, this many redos forward. /// Undone above the head, this many redos forward.
@@ -159,7 +175,7 @@ enum Place {
} }
/// Where `rev` is relative to the head. `None` for a step on a branch. /// Where `rev` is relative to the head. `None` for a step on a branch.
fn place(session: &Session, rev: Rev) -> Option<Place> { pub(crate) fn place(session: &Session, rev: Rev) -> Option<Place> {
let head = session.head_rev(); let head = session.head_rev();
let (kept, _) = line(session, head, None, usize::MAX); let (kept, _) = line(session, head, None, usize::MAX);
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) { if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
@@ -174,9 +190,9 @@ fn place(session: &Session, rev: Rev) -> Option<Place> {
} }
/// A hash of the panel's inputs, cheap enough for every frame. /// 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>) -> u64 { fn fingerprint(document_id: Option<DocumentId>, gdd: Option<&GddV1>, limit: usize, expanded: &BTreeSet<Rev>, following: Option<Rev>, previewing: Option<Rev>) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new(); let mut hasher = std::collections::hash_map::DefaultHasher::new();
(document_id, limit, expanded, following).hash(&mut hasher); (document_id, limit, expanded, following, previewing).hash(&mut hasher);
if let Some(gdd) = gdd { if let Some(gdd) = gdd {
let session = gdd.session(); let session = gdd.session();
(session.history_len(), session.head_rev(), session.redo_stack(), session.hot_log().len(), session.pending_action()).hash(&mut hasher); (session.history_len(), session.head_rev(), session.redo_stack(), session.hot_log().len(), session.pending_action()).hash(&mut hasher);
@@ -241,6 +257,7 @@ fn panel_state(gdd: &GddV1, declarations: &Declarations, limit: usize, expanded:
progress: progress_rows(session, &people, &names), progress: progress_rows(session, &people, &names),
more, more,
following: following.map(|tip| tip.to_string()), following: following.map(|tip| tip.to_string()),
previewing: None,
collaborating, collaborating,
} }
} }
@@ -828,4 +845,148 @@ mod tests {
assert!(rows[0].undone, "the ellipse stays on the panel, undone"); assert!(rows[0].undone, "the ellipse stays on the panel, undone");
assert!(rows[1].head); assert!(rows[1].head);
} }
/// Bringing a deletion back onto a stack that grew on the deleted layer since removes the layer and reconnects the
/// newer one to what was below it, rather than leaving it on nothing.
#[tokio::test]
async fn bringing_a_deletion_back_onto_a_grown_stack_reconnects_it() {
use crate::test_utils::test_prelude::*;
async fn close_step(editor: &mut EditorTestUtils) {
editor.handle_message(DocumentMessage::StartTransaction).await;
editor.handle_message(DocumentMessage::EndTransaction).await;
editor.active_document_mut().retire_storage_interaction();
}
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
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
editor.drag_tool(ToolType::Ellipse, 150., 0., 250., 100., ModifierKeys::empty()).await;
close_step(&mut editor).await;
let ellipse = editor
.active_document()
.network_interface
.selected_nodes()
.selected_layers(editor.active_document().metadata())
.next()
.expect("the ellipse is selected");
editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await;
close_step(&mut editor).await;
let rows = panel_rows(&editor, None);
editor.handle_message(HistoryMessage::GoBack { id: rows[1].id.clone() }).await;
editor.drag_tool(ToolType::Rectangle, 300., 0., 350., 50., ModifierKeys::empty()).await;
close_step(&mut editor).await;
let branch = panel_rows(&editor, None).into_iter().flat_map(|row| row.branches).next().expect("the deletion is left on a branch");
let deletion = panel_rows(&editor, parse_rev(&branch.id)).into_iter().find(|row| row.abandoned).expect("the deletion is off the line");
editor.handle_message(HistoryMessage::BringBack { id: deletion.id }).await;
let document = editor.active_document();
let layers: Vec<_> = document.metadata().all_layers().collect();
assert!(!layers.contains(&ellipse), "the deletion took the ellipse");
assert_eq!(layers.len(), 2, "both rectangles are still drawn: {layers:?}");
let violations = document.network_interface.validate_invariants();
assert!(violations.is_empty(), "{violations:#?}");
}
fn layer_count(editor: &crate::test_utils::EditorTestUtils) -> usize {
editor.active_document().metadata().all_layers().count()
}
#[tokio::test]
async fn removing_a_step_and_then_an_earlier_one_reopens() {
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::build_interface_from_storage;
let mut editor = three_rectangles().await;
let second = rows(&editor)[1].id.clone();
editor.handle_message(HistoryMessage::RemoveStep { id: second }).await;
// The first rectangle's step brought the layer subgraph the third one is built from
let first = rows(&editor).into_iter().rfind(|row| row.label.contains("Rectangle")).expect("the first rectangle").id;
editor.handle_message(HistoryMessage::RemoveStep { id: first }).await;
assert_eq!(layer_count(&editor), 1);
let violations = editor.active_document().network_interface.validate_invariants();
assert!(violations.is_empty(), "{violations:#?}");
let document = editor.active_document();
let gdd = document.storage().expect("every document has a working copy").clone();
let registry = gdd.registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = document_format::GddV1::open_in(working, layout).await.expect("reopen");
assert_eq!(reopened.registry(), &registry);
let (network, nodes, networks) = reopened.registry().to_runtime_with_full_metadata(document.declarations(), reopened.blobs()).expect("convert");
let interface = build_interface_from_storage(network, nodes, networks);
let violations = interface.validate_invariants();
assert!(violations.is_empty(), "{violations:#?}");
}
#[tokio::test]
async fn removing_a_step_is_undone_and_redone_like_any_other() {
let mut editor = three_rectangles().await;
let second = rows(&editor)[1].id.clone();
editor.handle_message(HistoryMessage::RemoveStep { id: second }).await;
assert_eq!(layer_count(&editor), 2);
editor.handle_message(DocumentMessage::DocumentHistoryBackward).await;
assert_eq!(layer_count(&editor), 3, "undo brings the removed rectangle back");
editor.handle_message(DocumentMessage::DocumentHistoryForward).await;
assert_eq!(layer_count(&editor), 2, "redo removes it again");
editor.handle_message(DocumentMessage::DocumentHistoryBackward).await;
assert_eq!(layer_count(&editor), 3, "and undo takes the removal back again");
}
#[tokio::test]
async fn undo_continues_past_a_taken_back_head_move() {
let mut editor = three_rectangles().await;
let first = rows(&editor)[2].id.clone();
editor.handle_message(HistoryMessage::GoBack { id: first }).await;
assert_eq!(layer_count(&editor), 1);
editor.handle_message(DocumentMessage::DocumentHistoryBackward).await;
assert_eq!(layer_count(&editor), 3, "undo takes the head move back");
editor.handle_message(DocumentMessage::DocumentHistoryBackward).await;
assert_eq!(layer_count(&editor), 2, "and then undoes the third rectangle");
}
#[tokio::test]
async fn previewing_a_step_shows_it_until_the_preview_ends_without_changing_history() {
let mut editor = three_rectangles().await;
let before = rows(&editor);
let first = before[2].id.clone();
editor.handle_message(HistoryMessage::Preview { id: Some(first.clone()) }).await;
assert_eq!(layer_count(&editor), 1, "the first rectangle's step shows one rectangle");
assert_eq!(editor.active_document().previewed_history_step(), parse_rev(&first));
editor.handle_message(HistoryMessage::Preview { id: None }).await;
assert_eq!(layer_count(&editor), 3);
assert_eq!(editor.active_document().previewed_history_step(), None);
assert_eq!(rows(&editor), before, "previewing leaves history as it was");
}
#[tokio::test]
async fn editing_while_previewing_continues_from_the_previewed_step() {
use crate::test_utils::test_prelude::*;
let mut editor = three_rectangles().await;
let first = rows(&editor)[2].id.clone();
editor.handle_message(HistoryMessage::Preview { id: Some(first.clone()) }).await;
editor.drag_tool(ToolType::Ellipse, 0., 150., 100., 250., ModifierKeys::empty()).await;
editor.active_document_mut().retire_storage_interaction();
assert_eq!(editor.active_document().previewed_history_step(), None);
assert_eq!(layer_count(&editor), 2, "the ellipse is drawn next to the first rectangle only");
let rows = rows(&editor);
assert_eq!(rows[0].label, "Drew an Ellipse");
let previewed = rows.iter().find(|row| row.id == first).expect("the previewed step is on the line");
assert_eq!(previewed.branches.len(), 1, "the steps after it stay as a branch");
let violations = editor.active_document().network_interface.validate_invariants();
assert!(violations.is_empty(), "{violations:#?}");
}
} }
@@ -6,3 +6,4 @@ pub mod utility_types;
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant}; pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
#[doc(inline)] #[doc(inline)]
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler}; pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
pub(crate) use history_message_handler::{Place, place};
@@ -19,6 +19,8 @@ pub struct HistoryPanelState {
pub progress: Vec<HistoryProgressRow>, pub progress: Vec<HistoryProgressRow>,
pub more: bool, pub more: bool,
pub following: Option<String>, pub following: Option<String>,
/// The step the document shows in place of its current state.
pub previewing: Option<String>,
/// Whether others are connected. /// Whether others are connected.
pub collaborating: bool, pub collaborating: bool,
} }
@@ -41,6 +41,10 @@ pub enum PortfolioMessage {
AutoSaveDocument { AutoSaveDocument {
document_id: DocumentId, document_id: DocumentId,
}, },
/// Cancels the work in progress of the active document's node at this full path from the root network.
CancelNodeWork {
node_path: Vec<graphene_std::uuid::NodeId>,
},
CloseActiveDocumentWithConfirmation, CloseActiveDocumentWithConfirmation,
CloseAllDocuments, CloseAllDocuments,
CloseAllDocumentsWithConfirmation, CloseAllDocumentsWithConfirmation,
@@ -166,6 +166,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
has_no_documents: self.document_ids.is_empty(), has_no_documents: self.document_ids.is_empty(),
}; };
self.workspace.process_message(message, responses, context); self.workspace.process_message(message, responses, context);
self.end_history_preview_without_panel(responses);
} }
// Messages // Messages
@@ -268,7 +269,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let Some(document) = self.documents.get_mut(&document_id) else { return }; let Some(document) = self.documents.get_mut(&document_id) else { return };
let Some(container) = document.container.clone() else { return }; let Some(container) = document.container.clone() else { return };
match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) { document.with_current_state(|document| match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) {
Ok(()) => { Ok(()) => {
document.commit_storage_snapshot(&resource_storage.resources_mut()); document.commit_storage_snapshot(&resource_storage.resources_mut());
document.set_auto_save_state(true); document.set_auto_save_state(true);
@@ -281,9 +282,12 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
description: format!("Save your documents manually to avoid losing changes.\n\n{error}"), description: format!("Save your documents manually to avoid losing changes.\n\n{error}"),
}); });
} }
} });
responses.add(PersistentStateMessage::WriteState); responses.add(PersistentStateMessage::WriteState);
} }
PortfolioMessage::CancelNodeWork { node_path } => {
self.executor.cancel_node_work(node_path);
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => { PortfolioMessage::CloseActiveDocumentWithConfirmation => {
if let Some(document_id) = self.active_document_id { if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id }); responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id });
@@ -941,6 +945,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.active_document_id = Some(document_id); self.active_document_id = Some(document_id);
self.restore_select = None; self.restore_select = None;
self.end_history_preview_without_panel(responses);
responses.add(MenuBarMessage::SendLayout); responses.add(MenuBarMessage::SendLayout);
responses.add(PortfolioMessage::UpdateOpenDocumentsList); responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(FrontendMessage::UpdateActiveDocument { document_id }); responses.add(FrontendMessage::UpdateActiveDocument { document_id });
@@ -1213,6 +1219,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} }
impl PortfolioMessageHandler { impl PortfolioMessageHandler {
/// Ends the active document's preview while the History panel is hidden, since the next edit would continue from it.
fn end_history_preview_without_panel(&self, responses: &mut VecDeque<Message>) {
let history_panel_shown = self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document;
if !history_panel_shown && self.active_document().is_some_and(|document| document.previewed_history_step().is_some()) {
responses.add(DocumentMessage::PreviewHistoryStep { rev: None });
}
}
pub fn new(executor: NodeGraphExecutor, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self { pub fn new(executor: NodeGraphExecutor, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
Self { Self {
documents: Default::default(), documents: Default::default(),
@@ -29,18 +29,20 @@ pub fn draw_for_selected_layers(overlay_context: &mut OverlayContext, document:
continue; continue;
} }
// A transformation from the layer's local space to the viewport space (where overlays are drawn) let layer_to_viewport = document.metadata().transform_to_viewport(layer);
let transform_to_viewport = document.metadata().transform_to_viewport(layer);
// The origin of the layer in viewport space which is the center of the origin cross overlay_context.follow_layer(layer, layer_to_viewport, move |overlay_context, movement| {
let origin_viewport = transform_to_viewport.transform_point2(DVec2::ZERO); let layer_to_viewport = movement * layer_to_viewport;
// The forward +X direction vector from layer space (used to orient the origin cross)
let forward = transform_to_viewport.transform_vector2(DVec2::X).normalize_or_zero();
// Draw the origin cross // The origin of the layer in viewport space which is the center of the origin cross
let offsets = [forward + forward.perp(), forward - forward.perp()].map(|offset| offset * core::f64::consts::FRAC_1_SQRT_2 * LAYER_ORIGIN_CROSS_DIAMETER / 2.); let origin_viewport = layer_to_viewport.transform_point2(DVec2::ZERO);
for offset in offsets { // The forward +X direction vector from layer space (used to orient the origin cross)
overlay_context.line(origin_viewport - offset, origin_viewport + offset, Some(COLOR_OVERLAY_BLUE), Some(LAYER_ORIGIN_CROSS_THICKNESS)); let forward = layer_to_viewport.transform_vector2(DVec2::X).normalize_or_zero();
}
let offsets = [forward + forward.perp(), forward - forward.perp()].map(|offset| offset * core::f64::consts::FRAC_1_SQRT_2 * LAYER_ORIGIN_CROSS_DIAMETER / 2.);
for offset in offsets {
overlay_context.line(origin_viewport - offset, origin_viewport + offset, Some(COLOR_OVERLAY_BLUE), Some(LAYER_ORIGIN_CROSS_THICKNESS));
}
});
} }
} }
@@ -382,6 +382,14 @@ pub struct BoundingBoxManager {
} }
impl BoundingBoxManager { impl BoundingBoxManager {
/// A copy of the cage with `movement` applied after its transform.
pub fn moved_by(&self, movement: DAffine2) -> Self {
Self {
transform: movement * self.transform,
..self.clone()
}
}
/// Calculates the transformed handle positions based on the bounding box and the transform /// Calculates the transformed handle positions based on the bounding box and the transform
pub fn evaluate_transform_handle_positions(&self) -> [DVec2; 8] { pub fn evaluate_transform_handle_positions(&self) -> [DVec2; 8] {
let (left, top): (f64, f64) = self.bounds[0].into(); let (left, top): (f64, f64) = self.bounds[0].into();
@@ -7,7 +7,7 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Transf
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier}; use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GroupFolderType}; use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GroupFolderType};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeNetworkInterface, NodeTemplate}; use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeNetworkInterface, NodeTemplate, vector_outline_targets};
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes; use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
use crate::messages::preferences::SelectionMode; use crate::messages::preferences::SelectionMode;
use crate::messages::tool::common_functionality::auto_panning::AutoPanning; use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
@@ -875,11 +875,17 @@ impl SelectToolData {
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer); otherwise uses the layer's recorded outlines. /// (e.g. the pre-solidified centerline for a Solidify Stroke layer); otherwise uses the layer's recorded outlines.
pub fn draw_layer_outline(overlay_context: &mut OverlayContext, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, color: Option<&str>) { pub fn draw_layer_outline(overlay_context: &mut OverlayContext, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, color: Option<&str>) {
if let Some(targets) = document.network_interface.path_aware_outline_targets(layer) { if let Some(targets) = document.network_interface.path_aware_outline_targets(layer) {
let layer_to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); let source = document.network_interface.layer_vector_source(layer);
overlay_context.outline(targets.iter(), layer_to_viewport, color); let color = color.map(str::to_owned);
overlay_context.with_rendered_layers(move |overlay_context, rendered| match rendered.vector(source) {
Some((vector, transform)) => overlay_context.outline(vector_outline_targets(&vector).iter(), transform, color.as_deref()),
None => overlay_context.outline(targets.iter(), source.layer_to_viewport, color.as_deref()),
});
} else { } else {
let layer_to_viewport = document.metadata().transform_to_viewport(layer); let metadata = document.metadata();
overlay_context.outline(document.metadata().layer_with_free_points_outline(layer), layer_to_viewport, color); let layers = std::iter::once(layer).chain(layer.descendants(metadata)).collect();
overlay_context.outline_rendered_layers(layers, metadata.layer_with_free_points_outline(layer), metadata.transform_to_viewport(layer), color);
} }
} }
@@ -896,6 +902,38 @@ pub fn create_bounding_box_transform(document: &DocumentMessageHandler) -> DAffi
.unwrap_or_default() .unwrap_or_default()
} }
/// Draws the dowel pin at the layer's origin, following the layer's movement in the render.
fn draw_dowel_pin(overlay_context: &mut OverlayContext, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, origin: DVec2, angle: f64, color: Option<&'static str>) {
let followed = document.metadata().layer_to_follow(layer);
let layer_to_viewport = document.metadata().transform_to_viewport(followed);
overlay_context.follow_layer(followed, layer_to_viewport, move |overlay_context, movement| {
overlay_context.dowel_pin(movement.transform_point2(origin), moved_angle(movement, angle), color);
});
}
/// The direction at `angle` after `movement` rotates it.
fn moved_angle(movement: DAffine2, angle: f64) -> f64 {
movement.transform_vector2(DVec2::from_angle(angle)).to_angle()
}
/// Defers `draw` until render time and passes it the movement of the selection since the overlays were made.
/// Takes the movement of the first selected layer that isn't an artboard, assuming the selection moves as one.
fn follow_selection(overlay_context: &mut OverlayContext, document: &DocumentMessageHandler, draw: impl Fn(&mut OverlayContext, DAffine2) + Send + 'static) {
let metadata = document.metadata();
let layer = document
.network_interface
.selected_nodes()
.selected_visible_and_unlocked_layers(&document.network_interface)
.find(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]))
.map(|layer| metadata.layer_to_follow(layer));
match layer {
Some(layer) => overlay_context.follow_layer(layer, metadata.transform_to_viewport(layer), draw),
None => draw(overlay_context, DAffine2::IDENTITY),
}
}
impl Fsm for SelectToolFsmState { impl Fsm for SelectToolFsmState {
type ToolData = SelectToolData; type ToolData = SelectToolData;
type ToolOptions = (); type ToolOptions = ();
@@ -935,7 +973,9 @@ impl Fsm for SelectToolFsmState {
if document.metadata().is_text_layer(layer) { if document.metadata().is_text_layer(layer) {
let layer_to_viewport = document.metadata().transform_to_viewport(layer); let layer_to_viewport = document.metadata().transform_to_viewport(layer);
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, fonts, responses); let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, fonts, responses);
overlay_context.dashed_quad(transformed_quad, None, None, Some(7.), Some(5.), None); overlay_context.follow_layer(layer, layer_to_viewport, move |overlay_context, movement| {
overlay_context.dashed_quad(movement * transformed_quad, None, None, Some(7.), Some(5.), None);
});
} }
} }
} }
@@ -1047,7 +1087,10 @@ impl Fsm for SelectToolFsmState {
bounding_box_manager.transform = transform; bounding_box_manager.transform = transform;
bounding_box_manager.transform_tampered = transform_tampered; bounding_box_manager.transform_tampered = transform_tampered;
if overlay_context.visibility_settings.transform_cage() { if overlay_context.visibility_settings.transform_cage() {
bounding_box_manager.render_overlays(&mut overlay_context, true); let cage = bounding_box_manager.clone();
follow_selection(&mut overlay_context, document, move |overlay_context, movement| {
cage.moved_by(movement).render_overlays(overlay_context, true)
});
} }
} else { } else {
tool_data.bounding_box_manager.take(); tool_data.bounding_box_manager.take();
@@ -1087,7 +1130,10 @@ impl Fsm for SelectToolFsmState {
let is_skewing = matches!(self, SelectToolFsmState::SkewingBounds { .. }); let is_skewing = matches!(self, SelectToolFsmState::SkewingBounds { .. });
let is_near_square = edges.is_some_and(|hover_edge| bounds.over_extended_edge_midpoint(input.mouse.position, hover_edge)); let is_near_square = edges.is_some_and(|hover_edge| bounds.over_extended_edge_midpoint(input.mouse.position, hover_edge));
if is_skewing || (dragging_bounds && is_near_square && !is_resizing_or_rotating) { if is_skewing || (dragging_bounds && is_near_square && !is_resizing_or_rotating) {
bounds.render_skew_gizmos(&mut overlay_context, tool_data.skew_edge); let (cage, skew_edge) = (bounds.clone(), tool_data.skew_edge);
follow_selection(&mut overlay_context, document, move |overlay_context, movement| {
cage.moved_by(movement).render_skew_gizmos(overlay_context, skew_edge)
});
} }
if !is_skewing if !is_skewing
&& dragging_bounds && dragging_bounds
@@ -1147,14 +1193,14 @@ impl Fsm for SelectToolFsmState {
for layer in document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface) { for layer in document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface) {
let origin = graph_modification_utils::get_viewport_origin(layer, &document.network_interface); let origin = graph_modification_utils::get_viewport_origin(layer, &document.network_interface);
if Some(layer) == tool_data.pivot_gizmo.layer { if Some(layer) == tool_data.pivot_gizmo.layer {
active_origin = Some(origin); active_origin = Some((layer, origin));
continue; continue;
} }
overlay_context.dowel_pin(origin, origin_angle, None); draw_dowel_pin(&mut overlay_context, document, layer, origin, origin_angle, None);
} }
} }
if let Some(origin) = active_origin { if let Some((layer, origin)) = active_origin {
overlay_context.dowel_pin(origin, origin_angle, Some(COLOR_OVERLAY_YELLOW)); draw_dowel_pin(&mut overlay_context, document, layer, origin, origin_angle, Some(COLOR_OVERLAY_YELLOW));
} }
let has_layers = document.network_interface.selected_nodes().has_selected_nodes(); let has_layers = document.network_interface.selected_nodes().has_selected_nodes();
@@ -1173,7 +1219,10 @@ impl Fsm for SelectToolFsmState {
}) })
.unwrap_or_default(); .unwrap_or_default();
let shift = tool_data.pivot_gizmo_shift.unwrap_or_default(); let shift = tool_data.pivot_gizmo_shift.unwrap_or_default();
overlay_context.pivot(pivot + offset + shift, angle); let position = pivot + offset + shift;
follow_selection(&mut overlay_context, document, move |overlay_context, movement| {
overlay_context.pivot(movement.transform_point2(position), moved_angle(movement, angle))
});
} }
// Update compass rose // Update compass rose
@@ -1184,7 +1233,9 @@ impl Fsm for SelectToolFsmState {
tool_data.line_center = compass_center; tool_data.line_center = compass_center;
} }
overlay_context.compass_rose(compass_center, angle, show_compass_with_ring); follow_selection(&mut overlay_context, document, move |overlay_context, movement| {
overlay_context.compass_rose(movement.transform_point2(compass_center), moved_angle(movement, angle), show_compass_with_ring);
});
let axis_state = if let SelectToolFsmState::Dragging { axis, .. } = self { let axis_state = if let SelectToolFsmState::Dragging { axis, .. } = self {
Some((axis, false)) Some((axis, false))
+59 -9
View File
@@ -41,6 +41,8 @@ pub struct ExecutionResponse {
dropped_thumbnails: Vec<NodeId>, dropped_thumbnails: Vec<NodeId>,
/// The latest result of each observation. /// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>, observations: HashMap<ObservationKey, InspectResult>,
/// The progress of each source with work in progress, by the path of the value node injecting the source.
progress: Vec<(Vec<NodeId>, f64)>,
} }
/// Names an observation so it can be changed or stopped without touching the others. /// Names an observation so it can be changed or stopped without touching the others.
@@ -59,6 +61,8 @@ pub enum ObservationKey {
pub enum ExecutionResult { pub enum ExecutionResult {
Pending, Pending,
Value(TaggedValue), Value(TaggedValue),
/// A value computed from provisional data, which is evaluated again once that data is final.
Partial(TaggedValue),
Fallback(TaggedValue, EvaluationErrors), Fallback(TaggedValue, EvaluationErrors),
Error(EvaluationErrors), Error(EvaluationErrors),
Panic(Box<dyn Any + Send>), Panic(Box<dyn Any + Send>),
@@ -123,6 +127,8 @@ pub struct NodeGraphExecutor {
inspect_context_overrides: ContextOverrides, inspect_context_overrides: ContextOverrides,
/// The canvas images the frontend holds, so a render sends only those it lacks. /// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>, canvas_images_sent: HashSet<u64>,
/// The progress of the active document's nodes with work in progress, by their full path from the root network.
node_progress: Vec<(Vec<NodeId>, f64)>,
/// Evaluation errors of the last evaluation, used in tests /// Evaluation errors of the last evaluation, used in tests
#[cfg(test)] #[cfg(test)]
evaluation_errors: Option<EvaluationErrors>, evaluation_errors: Option<EvaluationErrors>,
@@ -177,6 +183,7 @@ impl NodeGraphExecutor {
previous_node_to_inspect: Vec::new(), previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(), inspect_context_overrides: ContextOverrides::default(),
canvas_images_sent: HashSet::new(), canvas_images_sent: HashSet::new(),
node_progress: Vec::new(),
#[cfg(test)] #[cfg(test)]
evaluation_errors: None, evaluation_errors: None,
gradient_migration: None, gradient_migration: None,
@@ -212,6 +219,16 @@ impl NodeGraphExecutor {
execution_id execution_id
} }
/// The progress of the work of the node at this full path from the root network, if it has work in progress.
pub fn node_progress(&self, node_path: &[NodeId]) -> Option<f64> {
self.node_progress.iter().find(|(path, _)| path == node_path).map(|(_, progress)| *progress)
}
/// Cancels the work in progress of the node at this full path from the root network.
pub fn cancel_node_work(&self, node_path: Vec<NodeId>) {
self.sender.send(GraphRuntimeRequest::Cancel(node_path)).expect("Failed to send the cancellation");
}
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) { pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) { if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
log::error!("Failed to send the overlays: {error}"); log::error!("Failed to send the overlays: {error}");
@@ -531,6 +548,7 @@ impl NodeGraphExecutor {
responses: existing_responses, responses: existing_responses,
dropped_thumbnails, dropped_thumbnails,
mut observations, mut observations,
progress,
} = *execution_response; } = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -575,14 +593,24 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
// The deepest document node containing each source shows its progress
if execution_context.document_id == document_id {
let node_progress: Vec<_> = progress
.into_iter()
.filter_map(|(path, progress)| {
let node_path = (1..=path.len()).rev().map(|length| &path[..length]).find(|path| is_document_node(document, path))?;
Some((node_path.to_vec(), progress))
})
.collect();
self.update_node_progress(node_progress, responses);
}
// A pending graph keeps the last frame, and the errors shown with it // A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) { if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
let errors = match &result { let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => { ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| { let in_document = |path: &&[NodeId]| is_document_node(document, path);
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
};
errors errors
.iter() .iter()
.flat_map(|(error, trace)| { .flat_map(|(error, trace)| {
@@ -599,7 +627,7 @@ impl NodeGraphExecutor {
}) })
.collect() .collect()
} }
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => Vec::new(), ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => Vec::new(),
}; };
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors }); responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
} }
@@ -608,9 +636,14 @@ impl NodeGraphExecutor {
{ {
self.evaluation_errors = None; self.evaluation_errors = None;
} }
let render_status = match result {
ExecutionResult::Partial(_) => RenderStatus::Partial,
ExecutionResult::Fallback(..) => RenderStatus::Fallback,
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Error(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => RenderStatus::Rendering,
};
let node_graph_output = match result { let node_graph_output = match result {
ExecutionResult::Pending => Ok(None), ExecutionResult::Pending => Ok(None),
ExecutionResult::Value(value) => Ok(Some(value)), ExecutionResult::Value(value) | ExecutionResult::Partial(value) => Ok(Some(value)),
ExecutionResult::Fallback(value, _errors) => { ExecutionResult::Fallback(value, _errors) => {
#[cfg(test)] #[cfg(test)]
{ {
@@ -664,7 +697,7 @@ impl NodeGraphExecutor {
match (node_graph_output, execution_context.export_config) { match (node_graph_output, execution_context.export_config) {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), (Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, responses), (Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(None, _) => {} (None, _) => {}
} }
responses.add(DeferMessage::TriggerGraphRun { responses.add(DeferMessage::TriggerGraphRun {
@@ -712,6 +745,7 @@ impl NodeGraphExecutor {
document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new());
self.update_node_progress(Vec::new(), responses);
// The graph only shows errors tied to nodes, so the console gets the others // The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() { if node_graph_errors.is_empty() {
@@ -786,6 +820,16 @@ impl NodeGraphExecutor {
all_dropped_thumbnails all_dropped_thumbnails
} }
/// Sends the active document's node progress to its graph, which keeps its own copy, and refreshes the Properties panel when it changed.
fn update_node_progress(&mut self, node_progress: Vec<(Vec<NodeId>, f64)>, responses: &mut VecDeque<Message>) {
responses.add(NodeGraphMessage::UpdateNodeProgress { progress: node_progress.clone() });
if self.node_progress != node_progress {
self.node_progress = node_progress;
responses.add(InspectorMessage::Refresh);
}
}
fn receive_thumbnails(document: &mut DocumentMessageHandler, thumbnails: VecDeque<FrontendMessage>, responses: &mut VecDeque<Message>) { fn receive_thumbnails(document: &mut DocumentMessageHandler, thumbnails: VecDeque<FrontendMessage>, responses: &mut VecDeque<Message>) {
for thumbnail in thumbnails { for thumbnail in thumbnails {
match LayersInView::thumbnail_layer(&thumbnail) { match LayersInView::thumbnail_layer(&thumbnail) {
@@ -999,7 +1043,7 @@ impl NodeGraphExecutor {
self.node_graph_hash = 0; self.node_graph_hash = 0;
} }
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque<Message>) { fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, render_status: RenderStatus, responses: &mut VecDeque<Message>) {
let TaggedValue::RenderOutput(render_output) = node_graph_output else { let TaggedValue::RenderOutput(render_output) = node_graph_output else {
log::error!("Invalid node graph output type: {node_graph_output:#?}"); log::error!("Invalid node graph output type: {node_graph_output:#?}");
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
@@ -1081,7 +1125,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Rendering }); responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
} }
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) { fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
@@ -1139,6 +1183,12 @@ impl NodeGraphExecutor {
} }
} }
/// Whether the node at this full path from the root network exists in the document.
fn is_document_node(document: &DocumentMessageHandler, path: &[NodeId]) -> bool {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked /// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
/// (or set by the user), so a measured bake may safely be written. /// (or set by the user), so a measured bake may safely be written.
+117 -24
View File
@@ -1,6 +1,6 @@
use super::*; use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType}; use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode; use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task}; use crate::task::{Spawn, Spawner, Task};
use glam::UVec2; use glam::UVec2;
@@ -11,6 +11,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler}; use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors}; use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
use graphene_hash::CacheHash; use graphene_hash::CacheHash;
use graphene_std::SourceId;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture}; use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::ops::ConvertAsync; use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
@@ -62,6 +63,8 @@ pub struct NodeRuntime {
resources: ResourceRegistry, resources: ResourceRegistry,
node_graph_errors: GraphErrors, node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors, node_graph_warnings: GraphErrors,
/// Each source of the compiled network, with the path of the value node injecting it.
source_paths: Vec<(SourceId, Vec<NodeId>)>,
thumbnails: Thumbnails, thumbnails: Thumbnails,
observer: Observer<ObservationKey>, observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent. /// Whether an observation changed since its results were last sent.
@@ -74,8 +77,12 @@ pub struct NodeRuntime {
wasm_canvas_cache: CanvasSurfaceHandle, wasm_canvas_cache: CanvasSurfaceHandle,
/// The viewport's latest artwork. /// The viewport's latest artwork.
viewport_artwork: Option<Texture>, viewport_artwork: Option<Texture>,
/// The overlays to render once the viewport has artwork. /// The layers from the render of the viewport's latest artwork.
pending_overlays: Option<OverlayContext>, rendered_layers: RenderedLayers,
/// The latest overlays, rendered again over each new artwork.
overlays: Option<OverlayContext>,
/// Whether the overlays or the artwork changed since the overlays were last rendered.
overlays_stale: bool,
overlays_canvas: VelloCanvas, overlays_canvas: VelloCanvas,
/// The latest rendered overlays. /// The latest rendered overlays.
overlays_texture: Option<Texture>, overlays_texture: Option<Texture>,
@@ -100,6 +107,8 @@ pub enum GraphRuntimeRequest {
layers: Vec<NodeId>, layers: Vec<NodeId>,
}, },
RenderOverlays(OverlayContext), RenderOverlays(OverlayContext),
/// Cancels the work in progress of the sources within the node at this full path from the root network.
Cancel(Vec<NodeId>),
} }
#[derive(Debug, serde::Serialize, serde::Deserialize)] #[derive(Debug, serde::Serialize, serde::Deserialize)]
@@ -184,6 +193,7 @@ impl NodeRuntime {
node_graph_errors: Vec::new(), node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(), node_graph_warnings: Vec::new(),
source_paths: Vec::new(),
thumbnails: Thumbnails::new(), thumbnails: Thumbnails::new(),
observer: Observer::default(), observer: Observer::default(),
observations_changed: false, observations_changed: false,
@@ -193,7 +203,9 @@ impl NodeRuntime {
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(), wasm_canvas_cache: CanvasSurfaceHandle::new(),
viewport_artwork: None, viewport_artwork: None,
pending_overlays: None, rendered_layers: RenderedLayers::default(),
overlays: None,
overlays_stale: false,
overlays_canvas: VelloCanvas::default(), overlays_canvas: VelloCanvas::default(),
overlays_texture: None, overlays_texture: None,
} }
@@ -235,7 +247,19 @@ impl NodeRuntime {
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor)); let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
} }
GraphRuntimeRequest::RenderOverlays(context) => self.pending_overlays = Some(context), GraphRuntimeRequest::RenderOverlays(context) => {
self.overlays = Some(context);
self.overlays_stale = true;
}
GraphRuntimeRequest::Cancel(node_path) => {
let mut canceled = false;
for (source, _) in self.source_paths.iter().filter(|(_, path)| path.starts_with(&node_path)) {
canceled |= self.async_runtime().cancel(*source);
}
if canceled {
self.dirty.store(true, Ordering::Release);
}
}
} }
} }
@@ -311,7 +335,7 @@ impl NodeRuntime {
} }
// Overlays that changed without new artwork are drawn over the artwork already shown // Overlays that changed without new artwork are drawn over the artwork already shown
if self.pending_overlays.is_some() { if self.overlays_stale {
texture = self.composite_viewport_frame(); texture = self.composite_viewport_frame();
} }
} }
@@ -324,11 +348,15 @@ impl NodeRuntime {
self.thumbnails.set_scale(request.render_config.scale); self.thumbnails.set_scale(request.render_config.scale);
let mut result = self.evaluate(request)?; let mut result = self.evaluate(request)?;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let texture = if let Some(data) = result.render_output() let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
&& let RenderOutputType::Texture(texture) = data && let RenderOutputType::Texture(texture) = data
{ {
self.viewport_artwork = Some(texture.clone()); self.viewport_artwork = Some(texture.clone());
let path_contents = path_contents(&observations);
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
self.overlays_stale = true;
let frame = self.composite_viewport_frame(); let frame = self.composite_viewport_frame();
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
@@ -345,7 +373,7 @@ impl NodeRuntime {
}; };
self.resolve_effect_maps(&mut result).await; self.resolve_effect_maps(&mut result).await;
self.respond(request.execution_id, result).await; self.respond(request.execution_id, result, observations).await;
texture texture
} }
@@ -357,9 +385,11 @@ impl NodeRuntime {
return None; return None;
}; };
if let Some(overlays) = self.pending_overlays.take() { if std::mem::take(&mut self.overlays_stale)
&& let Some(overlays) = &self.overlays
{
self.overlays_texture = executor self.overlays_texture = executor
.render_vello_scene_on_canvas(&mut self.overlays_canvas, overlays.take_scene()) .render_vello_scene_on_canvas(&mut self.overlays_canvas, overlays.render(&self.rendered_layers))
.inspect_err(|error| log::error!("Failed to render the overlays: {error:?}")) .inspect_err(|error| log::error!("Failed to render the overlays: {error:?}"))
.ok(); .ok();
} }
@@ -398,14 +428,15 @@ impl NodeRuntime {
let Some(mut result) = result else { return }; let Some(mut result) = result else { return };
self.dirty.store(true, Ordering::Release); self.dirty.store(true, Ordering::Release);
if let Some(data) = result.render_output() if let Some(RenderOutput { data, .. }) = result.render_output()
&& let RenderOutputType::Texture(texture) = data && let RenderOutputType::Texture(texture) = data
{ {
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8(); let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
*data = RenderOutputType::Buffer { data: buffer, width, height }; *data = RenderOutputType::Buffer { data: buffer, width, height };
} }
self.resolve_effect_maps(&mut result).await; self.resolve_effect_maps(&mut result).await;
self.respond(request.execution_id, result).await; let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.respond(request.execution_id, result, observations).await;
} }
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) { async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
@@ -416,7 +447,10 @@ impl NodeRuntime {
} }
if let Some(mut result) = self.evaluate(request) if let Some(mut result) = self.evaluate(request)
&& let Some(RenderOutputType::Texture(texture)) = result.render_output() && let Some(RenderOutput {
data: RenderOutputType::Texture(texture),
..
}) = result.render_output()
{ {
let raster = self.read_back(texture.clone()).await; let raster = self.read_back(texture.clone()).await;
self.sender.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response");
@@ -439,7 +473,8 @@ impl NodeRuntime {
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) { let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending, Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value), Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => { Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed; let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(&error)) ExecutionResult::Fallback(value, self.resolve_errors(&error))
@@ -453,6 +488,7 @@ impl NodeRuntime {
responses: VecDeque::new(), responses: VecDeque::new(),
dropped_thumbnails: Vec::new(), dropped_thumbnails: Vec::new(),
observations: HashMap::new(), observations: HashMap::new(),
progress: Vec::new(),
}; };
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None; return None;
@@ -461,12 +497,21 @@ impl NodeRuntime {
Some(result) Some(result)
} }
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) { async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did // While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await }; let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let progress = self
.async_runtime()
.progress()
.into_iter()
.filter_map(|(source, progress)| {
let (_, path) = self.source_paths.iter().find(|(candidate, _)| *candidate == source)?;
Some((path.clone(), progress))
})
.collect();
let response = ExecutionResponse { let response = ExecutionResponse {
execution_id, execution_id,
@@ -474,6 +519,7 @@ impl NodeRuntime {
responses, responses,
dropped_thumbnails, dropped_thumbnails,
observations, observations,
progress,
}; };
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
} }
@@ -488,7 +534,11 @@ impl NodeRuntime {
/// Puts the maps of effects' coverages the GPU rendered into an SVG result, in place of the placeholders its filters hold for them. /// Puts the maps of effects' coverages the GPU rendered into an SVG result, in place of the placeholders its filters hold for them.
async fn resolve_effect_maps(&self, result: &mut ExecutionResult) { async fn resolve_effect_maps(&self, result: &mut ExecutionResult) {
let Some(RenderOutputType::Svg { svg, effect_maps, .. }) = result.render_output() else { let Some(RenderOutput {
data: RenderOutputType::Svg { svg, effect_maps, .. },
..
}) = result.render_output()
else {
return; return;
}; };
if effect_maps.is_empty() { if effect_maps.is_empty() {
@@ -539,6 +589,7 @@ impl NodeRuntime {
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)), Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
}; };
self.node_graph_warnings.extend(warnings); self.node_graph_warnings.extend(warnings);
self.source_paths = proto_network.source_paths().map(|(source, path)| (*source, path.to_vec())).collect();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| { let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -579,10 +630,12 @@ impl NodeRuntime {
} }
impl ExecutionResult { impl ExecutionResult {
fn render_output(&mut self) -> Option<&mut RenderOutputType> { fn render_output(&mut self) -> Option<&mut RenderOutput> {
let (Self::Value(value) | Self::Fallback(value, _)) = self else { return None }; let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
let TaggedValue::RenderOutput(RenderOutput { data, .. }) = value else { return None }; return None;
Some(data) };
let TaggedValue::RenderOutput(output) = value else { return None };
Some(output)
} }
} }
@@ -643,6 +696,7 @@ impl Spawn for NodeTaskExecutor {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::messages::frontend::utility_types::RenderStatus;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::test_utils::EditorTestUtils; use crate::test_utils::EditorTestUtils;
use glam::DVec2; use glam::DVec2;
@@ -664,12 +718,17 @@ mod tests {
/// Sends a network update and a request to evaluate it, as the editor does for a change to the graph. /// Sends a network update and a request to evaluate it, as the editor does for a change to the graph.
fn send_update(editor: &mut EditorTestUtils) { fn send_update(editor: &mut EditorTestUtils) {
send_update_at(editor, UVec2::ONE);
}
/// Sends a network update and a request to evaluate it at a viewport of `resolution` pixels.
fn send_update_at(editor: &mut EditorTestUtils, resolution: UVec2) {
let portfolio = editor.portfolio_message_handler_mut(); let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap(); let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap(); let document = documents.get_mut(&document_id).unwrap();
executor executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO) .submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
.unwrap(); .unwrap();
} }
@@ -699,8 +758,8 @@ mod tests {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. })) editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
} }
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations. /// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations. Returns the Vectorize node.
fn vectorize_layer(editor: &mut EditorTestUtils) { fn vectorize_layer(editor: &mut EditorTestUtils) -> NodeId {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
@@ -725,6 +784,7 @@ mod tests {
output_connector: OutputConnector::primary_output(vectorize), output_connector: OutputConnector::primary_output(vectorize),
input_connector: InputConnector::node_at_index(layer.to_node(), 1), input_connector: InputConnector::node_at_index(layer.to_node(), 1),
}); });
vectorize
} }
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one. /// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
@@ -1085,6 +1145,39 @@ mod tests {
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again"); assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
} }
/// A trace renders partial frames and shows its progress on its node until it is canceled, which keeps the shapes traced so far.
#[tokio::test]
async fn a_trace_shows_its_progress_until_it_is_canceled() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 512., 512.).await;
let vectorize = vectorize_layer(&mut editor);
send_update_at(&mut editor, UVec2::splat(512));
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
assert!(
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Partial }),
"the trace's frame isn't partial"
);
assert!(editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_some(), "the trace shows no progress");
editor.dispatch(PortfolioMessage::CancelNodeWork { node_path: vec![vectorize] });
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
assert!(
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Fallback }),
"the canceled trace's frame isn't a fallback"
);
assert!(
editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_none(),
"the canceled trace still shows progress"
);
}
#[test] #[test]
fn a_preview_replaces_the_export_of_the_graph_being_compiled() { fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
let previewed_node = NodeId(1); let previewed_node = NodeId(1);
+19 -1
View File
@@ -718,9 +718,14 @@
<div bind:this={textInput} style:transform="matrix({textInputMatrix})" on:scroll={preventTextEditingScroll}></div> <div bind:this={textInput} style:transform="matrix({textInputMatrix})" on:scroll={preventTextEditingScroll}></div>
{/if} {/if}
</div> </div>
{#if isWeb && $document.renderStatus === "Rendering"} {#if isWeb && !["Error", "Panic"].includes($document.renderStatus)}
<TextLabel class="shader-compiling-overlay" italic={true} classes={{ show: !firstArtworkReceived }}>Initializing Renderer…</TextLabel> <TextLabel class="shader-compiling-overlay" italic={true} classes={{ show: !firstArtworkReceived }}>Initializing Renderer…</TextLabel>
{/if} {/if}
{#if $document.renderStatus === "Partial"}
<div class="render-status-outline"></div>
{:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
<div class="render-status-outline failed"></div>
{/if}
{#if $document.renderStatus === "Error"} {#if $document.renderStatus === "Error"}
<LayoutCol class="render-status-overlay"> <LayoutCol class="render-status-overlay">
<TextLabel> <TextLabel>
@@ -983,6 +988,19 @@
} }
} }
.render-status-outline {
position: absolute;
inset: 0;
// Above the error overlays so the outline frames them too
z-index: 1;
box-shadow: inset 0 0 0 1px var(--color-warning-yellow);
pointer-events: none;
&.failed {
box-shadow: inset 0 0 0 1px var(--color-error-red);
}
}
.render-status-overlay { .render-status-overlay {
position: absolute; position: absolute;
inset: 0; inset: 0;
+81 -13
View File
@@ -67,15 +67,26 @@
function retirePending() { function retirePending() {
if (pendingHead) editor.retirePendingHistory(); if (pendingHead) editor.retirePendingHistory();
} }
function clickedRowControl(e: MouseEvent): boolean {
return e.target instanceof Element && Boolean(e.target.closest("[data-row-control]"));
}
function preview(e: MouseEvent, row: { id: string; head: boolean }) {
if (clickedRowControl(e) || row.id === $history.previewing) return;
const showsCurrent = row.head && !pendingHead;
editor.previewHistoryInteraction(showsCurrent ? undefined : row.id);
}
function goBackTo(e: MouseEvent, row: { id: string }) {
if (clickedRowControl(e) || $history.collaborating) return;
editor.goBackToHistoryInteraction(row.id);
}
</script> </script>
<LayoutCol class="history-panel" on:pointerenter={retirePending}> <LayoutCol class="history-panel" on:pointerenter={retirePending}>
{#if $history.following}
<LayoutRow class="following">
<TextLabel>Viewing a branch</TextLabel>
<TextButton label="Back to now" action={() => editor.followHistoryBranch(undefined)} />
</LayoutRow>
{/if}
<LayoutCol class="body" scrollableY={true}> <LayoutCol class="body" scrollableY={true}>
{#each $history.progress as row, index} {#each $history.progress as row, index}
<!-- Alone, work not yet in history is shown as an ordinary step --> <!-- Alone, work not yet in history is shown as an ordinary step -->
@@ -99,10 +110,20 @@
</div> </div>
{/each} {/each}
{#each $history.rows as row (row.id)} {#each $history.rows as row (row.id)}
<div class="row" class:head={row.head && !pendingHead} class:undone={row.undone} class:abandoned={row.abandoned}> <!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<div
class="row step"
class:head={row.head && !pendingHead}
class:previewed={row.id === $history.previewing}
class:undone={row.undone}
class:abandoned={row.abandoned}
on:click={(e) => preview(e, row)}
on:dblclick={(e) => goBackTo(e, row)}
>
{#if row.deltas > 1} {#if row.deltas > 1}
<button <button
class="expand" class="expand"
data-row-control
class:expanded={row.expanded} class:expanded={row.expanded}
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"} data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)} on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
@@ -115,7 +136,7 @@
> >
<div class="text"> <div class="text">
{#if renamingId === row.id} {#if renamingId === row.id}
<span class="editing" use:focusInput on:focusout={() => (renamingId = undefined)}> <span class="editing" data-row-control use:focusInput on:focusout={() => (renamingId = undefined)}>
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} /> <TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
</span> </span>
{:else} {:else}
@@ -127,7 +148,7 @@
{count(row.deltas, "change", "changes")} {count(row.deltas, "change", "changes")}
</span> </span>
{#if row.tags.length > 0 || taggingId === row.id || (row.head && !pendingHead) || row.undone || row.abandoned} {#if row.tags.length > 0 || taggingId === row.id || (row.head && !pendingHead) || row.undone || row.abandoned}
<span class="tags"> <span class="tags" data-row-control>
{#if row.head && !pendingHead}<span class="marker">Current</span>{/if} {#if row.head && !pendingHead}<span class="marker">Current</span>{/if}
{#if row.undone}<span class="marker">Undone</span>{/if} {#if row.undone}<span class="marker">Undone</span>{/if}
{#if row.abandoned}<span class="marker">Branch</span>{/if} {#if row.abandoned}<span class="marker">Branch</span>{/if}
@@ -142,14 +163,14 @@
</span> </span>
{/if} {/if}
{#if row.branches.length > 0} {#if row.branches.length > 0}
<span class="branches"> <span class="branches" data-row-control>
{#each row.branches as branch (branch.id)} {#each row.branches as branch (branch.id)}
<button class="chip branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button> <button class="chip branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button>
{/each} {/each}
</span> </span>
{/if} {/if}
</div> </div>
<span class="actions"> <span class="actions" data-row-control>
<button class="chip" data-tooltip-label="Name this step" on:click={() => (renamingId = row.id)}>Name</button> <button class="chip" data-tooltip-label="Name this step" on:click={() => (renamingId = row.id)}>Name</button>
<button class="chip" data-tooltip-label="Tag this step" on:click={() => (taggingId = row.id)}>Tag</button> <button class="chip" data-tooltip-label="Tag this step" on:click={() => (taggingId = row.id)}>Tag</button>
{#if row.undone || row.abandoned} {#if row.undone || row.abandoned}
@@ -207,6 +228,27 @@
<TextLabel italic={true}>Nothing in the history yet.</TextLabel> <TextLabel italic={true}>Nothing in the history yet.</TextLabel>
{/if} {/if}
</LayoutCol> </LayoutCol>
{#if $history.previewing}
<LayoutRow class="banner">
<TextLabel>Previewing</TextLabel>
<LayoutRow class="banner-actions">
{#if !$history.collaborating}
<TextButton
label="Go back to here"
tooltipDescription="Make this step current. The steps since stay as a branch. Editing while previewing does the same."
action={() => $history.previewing && editor.goBackToHistoryInteraction($history.previewing)}
/>
{/if}
<TextButton label="Back to now" tooltipDescription="Show the current state again. Esc does the same." action={() => editor.previewHistoryInteraction(undefined)} />
</LayoutRow>
</LayoutRow>
{/if}
{#if $history.following && !$history.previewing}
<LayoutRow class="banner">
<TextLabel>Viewing a branch</TextLabel>
<TextButton label="Back to now" action={() => editor.followHistoryBranch(undefined)} />
</LayoutRow>
{/if}
</LayoutCol> </LayoutCol>
<style lang="scss"> <style lang="scss">
@@ -214,11 +256,24 @@
flex-grow: 1; flex-grow: 1;
padding: 4px 0; padding: 4px 0;
.following { .banner {
flex: 0 0 auto; flex: 0 0 auto;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 0 8px 4px 8px; gap: 4px;
padding: 4px 8px 0 8px;
.text-label {
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.banner-actions {
flex: 0 0 auto;
gap: 4px;
}
} }
.row { .row {
@@ -232,6 +287,19 @@
background: var(--color-3-darkgray); background: var(--color-3-darkgray);
} }
&.step {
cursor: pointer;
&:hover {
background: var(--color-4-dimgray);
}
}
&.previewed {
background: var(--color-5-dullgray);
box-shadow: inset 2px 0 var(--color-e-nearwhite);
}
&.undone, &.undone,
&.abandoned { &.abandoned {
.rail, .rail,
@@ -973,10 +973,12 @@
{@const clipPathId = String(Math.random()).substring(2)} {@const clipPathId = String(Math.random()).substring(2)}
{@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined} {@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined}
{@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"} {@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"}
{@const progress = $nodeGraph.progress.get(node.id)}
<div <div
class="node" class="node"
class:selected={$nodeGraph.selected.includes(node.id)} class:selected={$nodeGraph.selected.includes(node.id)}
class:previewed={node.previewed} class:previewed={node.previewed}
class:in-progress={progress !== undefined}
class:disabled={!node.visible} class:disabled={!node.visible}
style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)} style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)}
style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)} style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)}
@@ -992,6 +994,9 @@
<IconLabel {icon} /> <IconLabel {icon} />
<!-- TODO: Allow the user to edit the name, just like in the Layers panel --> <!-- TODO: Allow the user to edit the name, just like in the Layers panel -->
<TextLabel>{node.displayName}</TextLabel> <TextLabel>{node.displayName}</TextLabel>
{#if progress !== undefined}
<div class="progress" style:width={`${Math.min(Math.max(progress, 0), 1) * 100}%`}></div>
{/if}
</div> </div>
<!-- Secondary rows --> <!-- Secondary rows -->
{#if exposedInputsOutputs.length > 0} {#if exposedInputsOutputs.length > 0}
@@ -1515,6 +1520,10 @@
border: 1px dashed var(--color-e-nearwhite); border: 1px dashed var(--color-e-nearwhite);
} }
&.in-progress::after {
border-color: var(--color-warning-yellow);
}
.connectors { .connectors {
position: absolute; position: absolute;
// Keeps the connectors above the wires // Keeps the connectors above the wires
@@ -1900,6 +1909,15 @@
margin-left: 0; margin-left: 0;
margin-right: 4px; margin-right: 4px;
} }
.progress {
position: absolute;
left: 0;
bottom: 0;
height: 3px;
background: var(--color-e-nearwhite);
transition: width 0.1s linear;
}
} }
.secondary { .secondary {
@@ -3,6 +3,7 @@
import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte"; import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte"; import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import ProgressBar from "/src/components/widgets/labels/ProgressBar.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte"; import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import NodeSection from "/src/components/widgets/NodeSection.svelte"; import NodeSection from "/src/components/widgets/NodeSection.svelte";
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte"; import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
@@ -93,6 +94,18 @@
<div class="expand-arrow"></div> <div class="expand-arrow"></div>
</div> </div>
<TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description}>{widgetData.name}</TextLabel> <TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description}>{widgetData.name}</TextLabel>
{#if typeof widgetData.progress === "number"}
<ProgressBar fraction={widgetData.progress} label={`${Math.floor(Math.min(Math.max(widgetData.progress, 0), 1) * 100)}%`} />
<IconButton
icon="CloseX"
tooltipDescription="Stop the work in progress, keeping its result so far."
size={24}
action={(e) => {
editor.cancelNodeWork(widgetData.id);
e?.stopPropagation();
}}
/>
{/if}
<IconButton <IconButton
icon={widgetData.visible ? "EyeVisible" : "EyeHidden"} icon={widgetData.visible ? "EyeVisible" : "EyeHidden"}
hoverIcon={widgetData.visible ? "EyeHide" : "EyeShow"} hoverIcon={widgetData.visible ? "EyeHide" : "EyeShow"}
@@ -461,6 +474,12 @@
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.progress-bar {
flex: 1 1 auto;
min-width: 0;
margin-left: 8px;
}
} }
// Hovering the chain sections within doesn't count // Hovering the chain sections within doesn't count
@@ -0,0 +1,71 @@
<script lang="ts">
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
export let classes: Record<string, boolean> = {};
// Content
export let fraction: number;
export let label = "";
// Tooltips
export let tooltipLabel: string | undefined = undefined;
export let tooltipDescription: string | undefined = undefined;
export let tooltipShortcut: ActionShortcut | undefined = undefined;
$: extraClasses = Object.entries(classes)
.flatMap(([className, stateName]) => (stateName ? [className] : []))
.join(" ");
$: percent = `${Math.min(Math.max(fraction, 0), 1) * 100}%`;
</script>
<div
class={`progress-bar ${className} ${extraClasses}`.trim()}
role="progressbar"
aria-valuemin={0}
aria-valuemax={1}
aria-valuenow={Math.min(Math.max(fraction, 0), 1)}
data-tooltip-label={tooltipLabel}
data-tooltip-description={tooltipDescription}
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
>
<div class="track">
<div class="fill" style:width={percent}></div>
</div>
{#if label}
<span class="label">{label}</span>
{/if}
</div>
<style lang="scss">
.progress-bar {
display: flex;
align-items: center;
gap: 8px;
flex: 1 1 100%;
height: 24px;
.track {
position: relative;
flex: 1 1 100%;
height: 4px;
border-radius: 2px;
overflow: hidden;
background: var(--color-1-nearblack);
}
.fill {
position: absolute;
inset: 0 auto 0 0;
background: var(--color-e-nearwhite);
transition: width 0.1s linear;
}
.label {
flex: 0 0 auto;
font-size: 12px;
white-space: nowrap;
color: var(--color-a-softgray);
}
}
</style>
+1 -1
View File
@@ -5,7 +5,7 @@ import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
export type HistoryStore = ReturnType<typeof createHistoryStore>; export type HistoryStore = ReturnType<typeof createHistoryStore>;
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, collaborating: false }; const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, previewing: undefined, collaborating: false };
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // 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); const store: Writable<HistoryPanelState> = import.meta.hot?.data?.store || writable<HistoryPanelState>(initialState);
+10
View File
@@ -25,6 +25,7 @@ type NodeGraphStoreState = {
clickTargets: FrontendClickTargets | undefined; clickTargets: FrontendClickTargets | undefined;
contextMenuInformation: ContextMenuInformation | undefined; contextMenuInformation: ContextMenuInformation | undefined;
errors: NodeGraphErrorDiagnostic[]; errors: NodeGraphErrorDiagnostic[];
progress: Map<bigint, number>;
layerWidths: Map<bigint, number>; layerWidths: Map<bigint, number>;
chainWidths: Map<bigint, number>; chainWidths: Map<bigint, number>;
hasLeftInputWire: Map<bigint, boolean>; hasLeftInputWire: Map<bigint, boolean>;
@@ -48,6 +49,7 @@ const initialState: NodeGraphStoreState = {
clickTargets: undefined, clickTargets: undefined,
contextMenuInformation: undefined, contextMenuInformation: undefined,
errors: [], errors: [],
progress: new Map(),
layerWidths: new Map(), layerWidths: new Map(),
chainWidths: new Map(), chainWidths: new Map(),
hasLeftInputWire: new Map(), hasLeftInputWire: new Map(),
@@ -236,6 +238,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
}); });
}); });
subscriptions.subscribeFrontendMessage("UpdateNodeGraphProgress", (data) => {
update((state) => {
state.progress = new Map(data.progress.map(({ nodeId, progress }) => [nodeId, progress]));
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => { subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
const newNodes = new Set<bigint>(data.nodes); const newNodes = new Set<bigint>(data.nodes);
@@ -360,6 +369,7 @@ export function destroyNodeGraphStore() {
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths"); subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphProgress");
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes"); subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets"); subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
+10
View File
@@ -291,6 +291,11 @@ mod editor_commands {
HistoryMessage::Follow { id }.into() HistoryMessage::Follow { id }.into()
} }
/// Show the document as it was once an interaction was done, or its current state when `id` is `None`
fn preview_history_interaction(id: Option<String>) -> Message {
HistoryMessage::Preview { id }.into()
}
/// Put the steps not yet in history into it, when editing alone /// Put the steps not yet in history into it, when editing alone
fn retire_pending_history() -> Message { fn retire_pending_history() -> Message {
HistoryMessage::RetirePending.into() HistoryMessage::RetirePending.into()
@@ -745,6 +750,11 @@ mod editor_commands {
DocumentMessage::ToggleNodeVisibility { node_id: NodeId(id) }.into() DocumentMessage::ToggleNodeVisibility { node_id: NodeId(id) }.into()
} }
/// Stop the work in progress of a node shown in the Inspector, which may be in a subgraph
fn cancel_node_work(id: u64) -> Message {
DocumentMessage::CancelNodeWork { node_id: NodeId(id) }.into()
}
/// Pin or unpin a node given its node ID /// Pin or unpin a node given its node ID
fn set_node_pinned(id: u64, pinned: bool) -> Message { fn set_node_pinned(id: u64, pinned: bool) -> Message {
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into() DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
+6 -1
View File
@@ -385,9 +385,14 @@ impl ProtoNetwork {
} }
pub fn source_ids(&self) -> impl Iterator<Item = &SourceId> { pub fn source_ids(&self) -> impl Iterator<Item = &SourceId> {
self.source_paths().map(|(source, _)| source)
}
/// Each source with the path of the value node that injects it, which lies within the node that owns the source.
pub fn source_paths(&self) -> impl Iterator<Item = (&SourceId, &[NodeId])> {
self.nodes.iter().filter_map(|(_, node)| match &node.construction_args { self.nodes.iter().filter_map(|(_, node)| match &node.construction_args {
ConstructionArgs::Value(value) => match &**value { ConstructionArgs::Value(value) => match &**value {
TaggedValue::SourceId(source) => Some(source), TaggedValue::SourceId(source) => Some((source, node.original_location.path.as_deref().unwrap_or_default())),
_ => None, _ => None,
}, },
_ => None, _ => None,
+91 -4
View File
@@ -2,11 +2,11 @@ use crate::poll::Poll;
use crate::uuid::NodeId; use crate::uuid::NodeId;
use dyn_any::WasmNotSend; use dyn_any::WasmNotSend;
use futures::future::{AbortHandle, Abortable}; use futures::future::{AbortHandle, Abortable};
use std::collections::HashMap; use std::collections::{HashMap, HashSet};
use std::future::Future; use std::future::Future;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::pin::Pin; use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Waker}; use std::task::{Context, Waker};
pub use web_time::Instant; pub use web_time::Instant;
@@ -34,7 +34,12 @@ impl SourceId {
pub type Generations = Arc<[(SourceId, u64)]>; pub type Generations = Arc<[(SourceId, u64)]>;
pub trait Runtime { pub trait Runtime {
/// Runs `task` outside of the graph, bumping the generation of `source` once it finishes.
fn spawn(&self, source: SourceId, task: Task); fn spawn(&self, source: SourceId, task: Task);
/// Sets how far the work of `source` has come from 0 to 1, or with `None` clears it along with any cancellation request.
fn report_progress(&self, source: SourceId, progress: Option<f64>);
/// Whether cancellation of the work of `source` was requested since this was last called.
fn take_cancellation(&self, source: SourceId) -> bool;
} }
#[derive(Clone, dyn_any::DynAny)] #[derive(Clone, dyn_any::DynAny)]
@@ -44,6 +49,14 @@ impl Runtime for RuntimeHandle {
fn spawn(&self, source: SourceId, task: Task) { fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task); self.0.spawn(source, task);
} }
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
self.0.report_progress(source, progress);
}
fn take_cancellation(&self, source: SourceId) -> bool {
self.0.take_cancellation(source)
}
} }
impl std::fmt::Debug for RuntimeHandle { impl std::fmt::Debug for RuntimeHandle {
@@ -68,16 +81,42 @@ impl AsyncRuntime {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self { pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
Self(Arc::new(RuntimeInner { Self(Arc::new(RuntimeInner {
generations: Mutex::default(), generations: Mutex::default(),
progress: Mutex::default(),
cancellations: Mutex::default(),
spawner, spawner,
})) }))
} }
pub fn update_sources(&self, live: &[SourceId]) { pub fn update_sources(&self, live: &[SourceId]) {
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner); let mut generations = lock(&self.0.generations);
generations.retain(|source, _| live.contains(source)); generations.retain(|source, _| live.contains(source));
for source in live { for source in live {
generations.entry(*source).or_insert(0); generations.entry(*source).or_insert(0);
} }
lock(&self.0.progress).retain(|source, _| live.contains(source));
lock(&self.0.cancellations).retain(|source| live.contains(source));
}
/// The progress of every source that reported some and has not cleared it, sorted by source.
pub fn progress(&self) -> Vec<(SourceId, f64)> {
let mut progress: Vec<_> = lock(&self.0.progress).iter().map(|(source, progress)| (*source, *progress)).collect();
progress.sort_unstable_by_key(|(source, _)| *source);
progress
}
/// Requests cancellation of the work of `source` and bumps its generation, so the node is evaluated again to see the request.
/// Only work that reports progress can be canceled, so a request can't outlive the work it was meant for. Returns whether there was any.
pub fn cancel(&self, source: SourceId) -> bool {
if !lock(&self.0.progress).contains_key(&source) {
return false;
}
lock(&self.0.cancellations).insert(source);
if let Some(generation) = lock(&self.0.generations).get_mut(&source) {
*generation += 1;
}
true
} }
pub fn snapshot(&self) -> Generations { pub fn snapshot(&self) -> Generations {
@@ -97,10 +136,20 @@ impl Runtime for AsyncRuntime {
fn spawn(&self, source: SourceId, task: Task) { fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task); self.0.spawn(source, task);
} }
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
self.0.report_progress(source, progress);
}
fn take_cancellation(&self, source: SourceId) -> bool {
self.0.take_cancellation(source)
}
} }
struct RuntimeInner { struct RuntimeInner {
generations: Mutex<HashMap<SourceId, u64>>, generations: Mutex<HashMap<SourceId, u64>>,
progress: Mutex<HashMap<SourceId, f64>>,
cancellations: Mutex<HashSet<SourceId>>,
spawner: Arc<dyn Spawn + Send + Sync>, spawner: Arc<dyn Spawn + Send + Sync>,
} }
@@ -109,11 +158,31 @@ impl RuntimeInner {
let inner = Arc::clone(self); let inner = Arc::clone(self);
self.spawner.spawn(Box::pin(async move { self.spawner.spawn(Box::pin(async move {
task.await; task.await;
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) { if let Some(generation) = lock(&inner.generations).get_mut(&source) {
*generation += 1; *generation += 1;
} }
})); }));
} }
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
match progress {
Some(progress) => {
lock(&self.progress).insert(source, progress);
}
None => {
lock(&self.progress).remove(&source);
lock(&self.cancellations).remove(&source);
}
}
}
fn take_cancellation(&self, source: SourceId) -> bool {
lock(&self.cancellations).remove(&source)
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
} }
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>); pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
@@ -289,6 +358,24 @@ mod tests {
assert!(runtime.snapshot().is_empty()); assert!(runtime.snapshot().is_empty());
} }
#[test]
fn only_work_in_progress_can_be_canceled() {
let runtime = AsyncRuntime::new(Arc::new(CollectSpawner::default()));
runtime.update_sources(&[SOURCE]);
assert!(!runtime.cancel(SOURCE));
runtime.report_progress(SOURCE, Some(0.5));
assert!(runtime.cancel(SOURCE));
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)], "a cancellation bumps the generation");
assert!(runtime.take_cancellation(SOURCE));
assert!(!runtime.take_cancellation(SOURCE));
runtime.cancel(SOURCE);
runtime.report_progress(SOURCE, None);
assert!(!runtime.take_cancellation(SOURCE), "clearing the progress drops the request");
assert!(runtime.progress().is_empty());
}
#[test] #[test]
fn a_slot_serves_the_placeholder_until_the_response_lands() { fn a_slot_serves_the_placeholder_until_the_response_lands() {
let spawner = Arc::new(CollectSpawner::default()); let spawner = Arc::new(CollectSpawner::default());
+10 -10
View File
@@ -14,7 +14,7 @@ use vector_types::{Gradient, ReferencePoint};
/// Returns the list with the item at the specified index removed. /// Returns the list with the item at the specified index removed.
/// If no value exists at that index, the list is returned unchanged. /// If no value exists at that index, the list is returned unchanged.
#[node_macro::node(category("Data: List"), icon("NodeRemoveAtIndex"), name("Remove at Index"))] #[node_macro::node(category("Data: List"), icon("NodeRemoveAtIndex"), name("Remove at Index"), footprint_invariant)]
fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>( fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
_: impl Ctx, _: impl Ctx,
/// The list of data. /// The list of data.
@@ -48,7 +48,7 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
/// Returns the item at the specified index in a list, keeping its attributes. /// Returns the item at the specified index in a list, keeping its attributes.
/// If no value exists at that index, the element type's default is returned. /// If no value exists at that index, the element type's default is returned.
#[node_macro::node(category("Data: List"), icon("NodeItemAtIndex"), name("Item at Index"))] #[node_macro::node(category("Data: List"), icon("NodeItemAtIndex"), name("Item at Index"), footprint_invariant)]
fn item_at_index<T: Clone + Default + Send + Sync + 'static>( fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to take the item from. /// The list of data to take the item from.
@@ -85,7 +85,7 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
} }
/// Keeps chosen items from a list (those corresponding to `true` values) and discards the others (those corresponding to `false` values) based on the *Keep Pattern* `Bool` list. A short pattern is repeated over the remainder of the filtered list, allowing a pattern like `[true, false]` to keep every other item starting from the first. An empty pattern keeps all items. /// Keeps chosen items from a list (those corresponding to `true` values) and discards the others (those corresponding to `false` values) based on the *Keep Pattern* `Bool` list. A short pattern is repeated over the remainder of the filtered list, allowing a pattern like `[true, false]` to keep every other item starting from the first. An empty pattern keeps all items.
#[node_macro::node(category("Data: List"), icon("NodeFilter"))] #[node_macro::node(category("Data: List"), icon("NodeFilter"), footprint_invariant)]
fn filter<T: Send + Sync + Clone + 'static>( fn filter<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to filter. /// The list of data to filter.
@@ -143,7 +143,7 @@ fn reverse<T: Send + Sync + Clone + 'static>(
} }
/// Shifts the items in a list by a number of positions. With wrapping, items pushed off one end reappear at the other. Otherwise they are dropped, shortening the list. /// Shifts the items in a list by a number of positions. With wrapping, items pushed off one end reappear at the other. Otherwise they are dropped, shortening the list.
#[node_macro::node(category("Data: List"), icon("NodeShift"))] #[node_macro::node(category("Data: List"), icon("NodeShift"), footprint_invariant)]
fn shift<T: Send + Sync + Clone + 'static>( fn shift<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to shift. /// The list of data to shift.
@@ -188,7 +188,7 @@ fn shift<T: Send + Sync + Clone + 'static>(
} }
/// Randomly reorders the items in a list. The same seed always produces the same ordering. /// Randomly reorders the items in a list. The same seed always produces the same ordering.
#[node_macro::node(category("Data: List"), icon("NodeShuffle"))] #[node_macro::node(category("Data: List"), icon("NodeShuffle"), footprint_invariant)]
fn shuffle<T: Send + Sync + Clone + 'static>( fn shuffle<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list to have its items randomly reordered. /// The list to have its items randomly reordered.
@@ -244,7 +244,7 @@ fn number_sequence(
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall these indices off from the generic math nodes. // TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall these indices off from the generic math nodes.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.) // TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
/// Counts out the index of each item in a list (0, 1, 2, and so on), producing a list of numbers with one for each item. /// Counts out the index of each item in a list (0, 1, 2, and so on), producing a list of numbers with one for each item.
#[node_macro::node(category("Data: List"), icon("NodeIndices"))] #[node_macro::node(category("Data: List"), icon("NodeIndices"), footprint_invariant)]
fn indices( fn indices(
_: impl Ctx, _: impl Ctx,
/// The list whose items are counted. /// The list whose items are counted.
@@ -260,7 +260,7 @@ fn indices(
/// Extracts a portion of a list, starting at "Start" and ending before "End". /// Extracts a portion of a list, starting at "Start" and ending before "End".
/// ///
/// Negative indices count from the end of the list. If the index of "Start" equals or exceeds "End", the result is an empty list. /// Negative indices count from the end of the list. If the index of "Start" equals or exceeds "End", the result is an empty list.
#[node_macro::node(category("Data: List"), icon("NodeSlice"))] #[node_macro::node(category("Data: List"), icon("NodeSlice"), footprint_invariant)]
fn slice<T: Send + Sync + Clone + 'static>( fn slice<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to take a portion of. /// The list of data to take a portion of.
@@ -342,7 +342,7 @@ pub enum SortError {
} }
/// Reorders a list's items from smallest to largest, either by each item's own value or by a parallel list of sortable values in the *Sort Order* input. The sort is stable, so items with the same sort order retain their relative positions. /// Reorders a list's items from smallest to largest, either by each item's own value or by a parallel list of sortable values in the *Sort Order* input. The sort is stable, so items with the same sort order retain their relative positions.
#[node_macro::node(category("Data: List"), icon("NodeSort"))] #[node_macro::node(category("Data: List"), icon("NodeSort"), footprint_invariant)]
fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send + Sync + 'static>( fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send + Sync + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to reorder. /// The list of data to reorder.
@@ -396,7 +396,7 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
Ok(result) Ok(result)
} }
#[node_macro::node(category("Data: List"), icon("NodeMap"))] #[node_macro::node(category("Data: List"), icon("NodeMap"), footprint_invariant)]
fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>( fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + CloneVarArgs + ExtractAll,
#[implementations( #[implementations(
@@ -514,7 +514,7 @@ impl HasText for Raster<GPU> {}
impl HasText for Color {} impl HasText for Color {}
impl HasText for Gradient {} impl HasText for Gradient {}
#[node_macro::node(category("Graphic"), icon("NodeMirror"))] #[node_macro::node(category("Graphic"), icon("NodeMirror"), footprint_invariant)]
fn mirror<T: BoundingBox + HasText + Send + Clone>( fn mirror<T: BoundingBox + HasText + Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
+6 -6
View File
@@ -366,7 +366,7 @@ fn operator_reducer(operator: &str) -> Result<Reducer, MathExpressionError> {
/// Reduces all the items to a single value by folding an operator like `+` or `*` across them, or by passing them all to a function like `max` or `mean`. /// Reduces all the items to a single value by folding an operator like `+` or `*` across them, or by passing them all to a function like `max` or `mean`.
/// ///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts. /// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts.
#[node_macro::node(category("Math"), icon("NodeMathAggregate"))] #[node_macro::node(category("Math"), icon("NodeMathAggregate"), footprint_invariant)]
fn math_aggregate<T: ExpressionValue, U: ExpressionValue>( fn math_aggregate<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx, _: impl Ctx,
/// The items reduced to one value. /// The items reduced to one value.
@@ -416,7 +416,7 @@ fn math_aggregate<T: ExpressionValue, U: ExpressionValue>(
/// Scans along the items, giving each one the result of folding an operator like `+` over it and every item before it, such as a running total, or of a function like `max`, such as the highest value so far. /// Scans along the items, giving each one the result of folding an operator like `+` over it and every item before it, such as a running total, or of a function like `max`, such as the highest value so far.
/// ///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` composes in order, which turns a list of steps into where each step ends up. /// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` composes in order, which turns a list of steps into where each step ends up.
#[node_macro::node(category("Math"), icon("NodeMathRunning"))] #[node_macro::node(category("Math"), icon("NodeMathRunning"), footprint_invariant)]
fn math_running<T: ExpressionValue, U: ExpressionValue>( fn math_running<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx, _: impl Ctx,
/// The items scanned along, each giving one result. /// The items scanned along, each giving one result.
@@ -1532,13 +1532,13 @@ fn least_common_multiple(
} }
/// Adds together all the numbers in the input list, producing their total. /// Adds together all the numbers in the input list, producing their total.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeSum"))] #[node_macro::node(category("Math: Arithmetic"), icon("NodeSum"), footprint_invariant)]
fn sum(_: impl Ctx, values: List<f64>) -> Item<f64> { fn sum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().sum()) Item::new_from_element(values.iter_element_values().sum())
} }
/// Averages all the numbers in the input list. An empty list gives 0. /// Averages all the numbers in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeAverage"))] #[node_macro::node(category("Math: Numeric"), icon("NodeAverage"), footprint_invariant)]
fn average(_: impl Ctx, values: List<f64>) -> Item<f64> { fn average(_: impl Ctx, values: List<f64>) -> Item<f64> {
let count = values.len(); let count = values.len();
let average = if count == 0 { 0. } else { values.iter_element_values().sum::<f64>() / count as f64 }; let average = if count == 0 { 0. } else { values.iter_element_values().sum::<f64>() / count as f64 };
@@ -1547,13 +1547,13 @@ fn average(_: impl Ctx, values: List<f64>) -> Item<f64> {
} }
/// Gives the smallest number in the input list. An empty list gives 0. /// Gives the smallest number in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeMinimum"))] #[node_macro::node(category("Math: Numeric"), icon("NodeMinimum"), footprint_invariant)]
fn minimum(_: impl Ctx, values: List<f64>) -> Item<f64> { fn minimum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().copied().reduce(f64::min).unwrap_or_default()) Item::new_from_element(values.iter_element_values().copied().reduce(f64::min).unwrap_or_default())
} }
/// Gives the largest number in the input list. An empty list gives 0. /// Gives the largest number in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeMaximum"))] #[node_macro::node(category("Math: Numeric"), icon("NodeMaximum"), footprint_invariant)]
fn maximum(_: impl Ctx, values: List<f64>) -> Item<f64> { fn maximum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().copied().reduce(f64::max).unwrap_or_default()) Item::new_from_element(values.iter_element_values().copied().reduce(f64::max).unwrap_or_default())
} }
+1 -1
View File
@@ -29,7 +29,7 @@ pub enum BooleanOperationError {
// TODO: with multiple items while still assuming a single item for the boolean operations. // TODO: with multiple items while still assuming a single item for the boolean operations.
/// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method. /// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method.
#[node_macro::node(category("Vector: Path"), icon("NodeBooleanOperation"), memoize)] #[node_macro::node(category("Vector: Path"), icon("NodeBooleanOperation"), memoize, footprint_invariant)]
fn boolean_operation( fn boolean_operation(
_: impl Ctx, _: impl Ctx,
/// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened. /// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened.
+203 -2
View File
@@ -1,8 +1,9 @@
use crate::gcore::Context; use crate::gcore::Context;
use core::f64::consts::TAU; use core::f64::consts::TAU;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, OwnedContextImpl}; use core_types::transform::{ApplyTransform, Footprint};
use glam::{DAffine2, DVec2}; use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, ExtractFootprint, InjectFootprint, InjectVarArgs, Interrupt, NodeError, OwnedContextImpl, Poll};
use glam::{DAffine2, DVec2, I64Vec2};
use graphic_types::{Artboard, Graphic, Vector}; use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster}; use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient; use vector_types::Gradient;
@@ -114,6 +115,122 @@ fn repeat_array<T: Send + Clone + 'static>(
Ok(result_list) Ok(result_list)
} }
const MAX_TILE_COUNT: f64 = 10_000.;
const DEGENERATE_VIEWPORT_CELL_COUNT: f64 = 4.;
/// The range of cells covering the viewport, or a fixed block of cells at the origin when the footprint can't map the viewport into local space.
fn visible_cell_range(footprint: &Footprint, spacing: DVec2) -> (DVec2, DVec2) {
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let viewport_size = viewport_bounds.size();
let is_degenerate = !(viewport_size.x > 0. && viewport_size.y > 0. && viewport_size.is_finite() && viewport_bounds.start.is_finite());
if is_degenerate {
return (DVec2::ZERO, DVec2::splat(DEGENERATE_VIEWPORT_CELL_COUNT));
}
// One cell of padding on each side keeps content reaching past its own cell from being culled at the viewport edges
let first_cell = (viewport_bounds.start / spacing).floor() - DVec2::ONE;
let last_cell = (viewport_bounds.end / spacing).ceil() + DVec2::ONE;
(first_cell, last_cell)
}
/// Shrinks the cell range to a window of at most `max_count` cells centered on the original range.
fn centered_cell_window(first_cell: DVec2, last_cell: DVec2, max_count: f64) -> (I64Vec2, I64Vec2) {
let cell_count = last_cell - first_cell;
let scale = (max_count / (cell_count.x * cell_count.y)).sqrt();
let width = (cell_count.x * scale).floor().clamp(1., cell_count.x.min(max_count));
let height = (max_count / width).floor().clamp(1., cell_count.y);
let window = DVec2::new(width, height);
let start = (first_cell + (cell_count - window) / 2.).floor();
(start.as_i64vec2(), (start + window).as_i64vec2())
}
/// Repeats the content on a grid that covers the visible viewport.
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"))]
fn tile<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx + ExtractFootprint + InjectFootprint,
#[implementations(
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
)]
content: impl Node<Context<'static>, Output = List<T>>,
#[unit(" px")]
#[default(100., 100.)]
spacing: Item<DVec2>,
) -> Poll<List<T>> {
let spacing = spacing.into_element();
if spacing.x <= 0. || spacing.y <= 0. || !spacing.is_finite() {
return Poll::Final(List::new());
}
let footprint = *ctx.footprint();
let (first_cell, last_cell) = visible_cell_range(&footprint, spacing);
let cell_count = last_cell - first_cell;
let visible_tile_count = cell_count.x * cell_count.y;
let exceeds_limit = visible_tile_count > MAX_TILE_COUNT;
let (first_cell, last_cell) = if exceeds_limit {
centered_cell_window(first_cell, last_cell, MAX_TILE_COUNT)
} else {
(first_cell.as_i64vec2(), last_cell.as_i64vec2())
};
let mut result_list = List::new();
let mut partial = false;
let mut upstream_error = None;
for y in first_cell.y..last_cell.y {
for x in first_cell.x..last_cell.x {
let tile_origin = DVec2::new(x as f64, y as f64) * spacing;
let offset = DAffine2::from_translation(tile_origin);
let mut tile_footprint = footprint;
tile_footprint.apply_transform(&offset);
let tile_ctx = OwnedContextImpl::from(ctx.clone()).with_footprint(tile_footprint).with_position(tile_origin);
let generated_content = match content.eval(&tile_ctx.into_context()) {
Poll::Final(value) => value,
Poll::Partial(value) => {
partial = true;
value
}
Poll::Fallback(boxed) => {
let (value, error) = *boxed;
upstream_error.get_or_insert(error);
value
}
Poll::Pending => return Poll::Pending,
// Like `Status`, an error after a partial result waits for the final inputs before it is reported
Poll::Error(error) => return if partial { Poll::Pending } else { Poll::Error(error) },
};
for mut generated_row in generated_content.into_iter() {
let local_transform: DAffine2 = generated_row.attribute_cloned_or_default(ATTR_TRANSFORM);
*generated_row.attribute_mut_or_insert_default(ATTR_TRANSFORM) = offset * local_transform;
result_list.push(generated_row);
}
}
}
if partial {
Poll::Partial(result_list)
} else if exceeds_limit {
let message = format!("The view needs {visible_tile_count:.0} tiles but at most {MAX_TILE_COUNT} are drawn. Zoom in or increase the spacing.");
let error = NodeError::new(message).with_upstream(upstream_error.into_iter().collect());
Poll::Fallback(Box::new((result_list, error)))
} else if let Some(error) = upstream_error {
Poll::Fallback(Box::new((result_list, error)))
} else {
Poll::Final(result_list)
}
}
#[node_macro::node(category("Graphic"), icon("NodeRepeatRadial"))] #[node_macro::node(category("Graphic"), icon("NodeRepeatRadial"))]
fn repeat_radial<T: Send + Clone + 'static>( fn repeat_radial<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl ExtractAll + CloneVarArgs + Ctx,
@@ -391,6 +508,90 @@ mod test {
} }
} }
#[test]
fn tile_covers_viewport() {
let footprint = Footprint {
transform: DAffine2::from_translation(DVec2::new(50., 0.)),
resolution: glam::UVec2::new(250, 100),
..Default::default()
};
let context = OwnedContextImpl::default().with_footprint(footprint).into_context();
let content = vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY));
let Poll::Final(tiled) = super::tile(context, &ValueNode(content), Item::new_from_element(DVec2::splat(100.))) else {
panic!("Expected a final result");
};
let offsets: Vec<DVec2> = (0..tiled.len()).map(|index| tiled.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index).translation).collect();
let expected: Vec<DVec2> = (-1..2).flat_map(|y| (-2..3).map(move |x| DVec2::new(x as f64, y as f64) * 100.)).collect();
assert_eq!(offsets, expected);
}
#[test]
fn tile_falls_back_to_centered_window_above_limit() {
let footprint = Footprint {
transform: DAffine2::IDENTITY,
resolution: glam::UVec2::new(1000, 500),
..Default::default()
};
let context = OwnedContextImpl::default().with_footprint(footprint).into_context();
let content = vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY));
let Poll::Fallback(boxed) = super::tile(context, &ValueNode(content), Item::new_from_element(DVec2::ONE)) else {
panic!("Expected a fallback result");
};
let (tiled, _) = *boxed;
assert!(tiled.len() as f64 <= MAX_TILE_COUNT);
assert!(tiled.len() as f64 > MAX_TILE_COUNT * 0.9);
let center_offsets = (0..tiled.len()).map(|index| tiled.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index).translation);
let mean_offset = center_offsets.fold(DVec2::ZERO, |sum, offset| sum + offset) / tiled.len() as f64;
assert!(
mean_offset.abs_diff_eq(DVec2::new(499.5, 249.5), 1.),
"Expected the window to be centered, found mean offset {mean_offset}"
);
}
fn tile_count(footprint: Footprint, spacing: DVec2) -> usize {
let context = OwnedContextImpl::default().with_footprint(footprint).into_context();
let content = vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY));
match super::tile(context, &ValueNode(content), Item::new_from_element(spacing)) {
Poll::Final(tiled) => tiled.len(),
Poll::Fallback(boxed) => boxed.0.len(),
_ => panic!("Expected a final or fallback result"),
}
}
#[test]
fn tile_window_stays_within_limit_for_uneven_cell_counts() {
let footprint = Footprint {
transform: DAffine2::IDENTITY,
resolution: glam::UVec2::new(1_000_000, 3),
..Default::default()
};
assert!(tile_count(footprint, DVec2::ONE) as f64 <= MAX_TILE_COUNT);
}
#[test]
fn tile_survives_extreme_spacing() {
let footprint = Footprint {
transform: DAffine2::IDENTITY,
resolution: glam::UVec2::new(1000, 1000),
..Default::default()
};
assert!(tile_count(footprint, DVec2::splat(1e-17)) as f64 <= MAX_TILE_COUNT);
}
#[test]
fn tile_draws_fixed_area_for_degenerate_footprint() {
let expected = (DEGENERATE_VIEWPORT_CELL_COUNT * DEGENERATE_VIEWPORT_CELL_COUNT) as usize;
assert_eq!(tile_count(Footprint::BOUNDLESS, DVec2::splat(100.)), expected);
}
#[test] #[test]
fn repeat_radial() { fn repeat_radial() {
let context = OwnedContextImpl::default().into_context(); let context = OwnedContextImpl::default().into_context();
+1 -1
View File
@@ -941,7 +941,7 @@ fn string_split(
/// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node. /// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node.
/// ///
/// For example, joining `["a", "b", "c"]` with separator ", " produces "a, b, c". /// For example, joining `["a", "b", "c"]` with separator ", " produces "a, b, c".
#[node_macro::node(category("String"), icon("NodeStringJoin"))] #[node_macro::node(category("String"), icon("NodeStringJoin"), footprint_invariant)]
fn string_join( fn string_join(
_: impl Ctx, _: impl Ctx,
/// The list of strings to join together. /// The list of strings to join together.
@@ -220,7 +220,7 @@ fn decompose_skew(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
} }
/// Rotates every item of the content about its origin by its own angle, selected from along a chosen range. /// Rotates every item of the content about its origin by its own angle, selected from along a chosen range.
#[node_macro::node(category("Transform"), icon("NodeVaryRotations"), version(2))] #[node_macro::node(category("Transform"), icon("NodeVaryRotations"), version(2), footprint_invariant)]
fn vary_rotations<T: Send>( fn vary_rotations<T: Send>(
_: impl Ctx, _: impl Ctx,
/// The content with items to rotate individually. /// The content with items to rotate individually.
@@ -274,7 +274,7 @@ fn vary_rotations<T: Send>(
} }
/// Scales every item of the content about its origin by its own factor, selected from along a chosen range. /// Scales every item of the content about its origin by its own factor, selected from along a chosen range.
#[node_macro::node(category("Transform"), icon("NodeVaryScales"))] #[node_macro::node(category("Transform"), icon("NodeVaryScales"), footprint_invariant)]
fn vary_scales<T: Send>( fn vary_scales<T: Send>(
_: impl Ctx, _: impl Ctx,
/// The content with items to scale individually. /// The content with items to scale individually.
+24 -20
View File
@@ -11,7 +11,7 @@ use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::{ use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_FORM, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_FORM, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx,
ExtractAll, OwnedContextImpl, ExtractAll, InjectFootprint, OwnedContextImpl,
}; };
use core_types::{Interrupt, NodeError}; use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DMat2, DVec2}; use glam::{DAffine2, DMat2, DVec2};
@@ -282,7 +282,7 @@ pub enum VaryColorsError {
} }
/// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient. /// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector), version(2))] #[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector), version(2), footprint_invariant)]
fn vary_fill_colors<T>( fn vary_fill_colors<T>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the fill style to. /// The content with vector paths to apply the fill style to.
@@ -313,7 +313,7 @@ where
} }
/// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient. /// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector), footprint_invariant)]
fn vary_stroke_colors<T>( fn vary_stroke_colors<T>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the stroke style to. /// The content with vector paths to apply the stroke style to.
@@ -794,7 +794,7 @@ fn unweld<V: MapVectorItems + Send + Sync + 'static>(
} }
/// Wraps the points and paths of the vector content in a closed path in the shape of a rubber band stretched around everything. A curvature above zero may be given to obtain the concave hull, letting the (closed, open, or mesh-like) path or paths press into indents of the content where a ball with that curvature would be able to reach. /// Wraps the points and paths of the vector content in a closed path in the shape of a rubber band stretched around everything. A curvature above zero may be given to obtain the concave hull, letting the (closed, open, or mesh-like) path or paths press into indents of the content where a ball with that curvature would be able to reach.
#[node_macro::node(category("Vector: Point"), icon("NodeConvexHull"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeConvexHull"), path(core_types::vector), footprint_invariant)]
fn convex_hull<V: MapVectorItems + Send>( fn convex_hull<V: MapVectorItems + Send>(
_: impl Ctx, _: impl Ctx,
/// The vector content to envelop in the hull, which may be points, paths, or both. /// The vector content to envelop in the hull, which may be points, paths, or both.
@@ -1102,7 +1102,7 @@ pub enum BoxWarpError {
TooFewCorners, TooFewCorners,
} }
#[node_macro::node(category("Vector: Deform"), icon("NodeBoxWarp"), path(core_types::vector))] #[node_macro::node(category("Vector: Deform"), icon("NodeBoxWarp"), path(core_types::vector), footprint_invariant)]
fn box_warp<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>, #[expose] rectangle: Item<Vector>) -> Result<Item<V>, BoxWarpError> { fn box_warp<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>, #[expose] rectangle: Item<Vector>) -> Result<Item<V>, BoxWarpError> {
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM); let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM);
let target_paths = shared_paths_from_item_attributes(&rectangle); let target_paths = shared_paths_from_item_attributes(&rectangle);
@@ -1171,7 +1171,7 @@ fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y
} }
#[node_macro::node(category("Transform"), icon("NodePackStrips"), path(graphene_core::vector))] #[node_macro::node(category("Transform"), icon("NodePackStrips"), path(graphene_core::vector), footprint_invariant)]
fn pack_strips<T: Send + Clone>( fn pack_strips<T: Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
@@ -1473,7 +1473,7 @@ fn push_contour(vector: &mut Vector, paths: &mut List<Path>, anchors: &[u32], ma
push_paths(paths, runs); push_paths(paths, runs);
} }
#[node_macro::node(category("Vector: Geometry"), icon("NodeBoundingBox"), path(core_types::vector))] #[node_macro::node(category("Vector: Geometry"), icon("NodeBoundingBox"), path(core_types::vector), footprint_invariant)]
fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> Item<V> { fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> Item<V> {
V::map_vector_items(content, |content| { V::map_vector_items(content, |content| {
let mut content = content; let mut content = content;
@@ -1490,7 +1490,7 @@ fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic
}) })
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector), footprint_invariant)]
fn dimensions(_: impl Ctx, content: Item<Vector>) -> Item<DVec2> { fn dimensions(_: impl Ctx, content: Item<Vector>) -> Item<DVec2> {
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let dimensions = content let dimensions = content
@@ -1509,7 +1509,7 @@ fn as_vector(_: impl Ctx, value: Item<Vector>) -> Item<Vector> {
} }
/// Creates vector points at the given positions, as a point cloud with nothing connecting them. **Points to Polyline** can join them into a path. /// Creates vector points at the given positions, as a point cloud with nothing connecting them. **Points to Polyline** can join them into a path.
#[node_macro::node(category("Vector: Point"), icon("NodePointsToVector"), name("Points to Vector"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodePointsToVector"), name("Points to Vector"), path(core_types::vector), footprint_invariant)]
fn points_to_vector( fn points_to_vector(
_: impl Ctx, _: impl Ctx,
/// The positions to place the points at, in order. /// The positions to place the points at, in order.
@@ -1635,7 +1635,7 @@ fn relax_points<V: MapVectorItems + Send>(
/// Builds a Voronoi diagram from the anchor points. Each point claims the region of space closest to it, and those regions tessellate the plane. Cells around the outside are clipped to the convex hull of the points so the diagram stays finite. /// Builds a Voronoi diagram from the anchor points. Each point claims the region of space closest to it, and those regions tessellate the plane. Cells around the outside are clipped to the convex hull of the points so the diagram stays finite.
/// ///
/// When Connect Cells is off, every cell becomes its own closed, fillable subpath. When on, the cells share their common points and segments, forming a single connected mesh. /// When Connect Cells is off, every cell becomes its own closed, fillable subpath. When on, the cells share their common points and segments, forming a single connected mesh.
#[node_macro::node(category("Vector: Point"), icon("NodeVoronoiCells"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeVoronoiCells"), path(core_types::vector), footprint_invariant)]
fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> { fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| { V::try_map_vector_items(source, |source| {
let mut source = source; let mut source = source;
@@ -1658,7 +1658,7 @@ fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphi
/// Builds a Delaunay triangulation connecting the anchor points. It is the geometric dual of the **Voronoi** node: a mesh of triangles in which no point lies inside any triangle's circumscribed circle. /// Builds a Delaunay triangulation connecting the anchor points. It is the geometric dual of the **Voronoi** node: a mesh of triangles in which no point lies inside any triangle's circumscribed circle.
/// ///
/// When Connect Cells is off, every triangle becomes its own closed, fillable subpath. When on, the triangles share their common points and segments, forming a single connected mesh. /// When Connect Cells is off, every triangle becomes its own closed, fillable subpath. When on, the triangles share their common points and segments, forming a single connected mesh.
#[node_macro::node(category("Vector: Point"), icon("NodeTriangulate"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeTriangulate"), path(core_types::vector), footprint_invariant)]
fn triangulate<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> { fn triangulate<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| { V::try_map_vector_items(source, |source| {
let mut source = source; let mut source = source;
@@ -2836,7 +2836,7 @@ fn offset_points<V: MapVectorItems + Send>(
/// Interpolates the geometry, appearance, and transform between multiple vector layers, producing a single morphed vector shape. /// Interpolates the geometry, appearance, and transform between multiple vector layers, producing a single morphed vector shape.
/// ///
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments. /// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
#[node_macro::node(category("Vector: Deform"), icon("NodeMorph"), path(core_types::vector))] #[node_macro::node(category("Vector: Deform"), icon("NodeMorph"), path(core_types::vector), footprint_invariant)]
fn morph( fn morph(
_: impl Ctx, _: impl Ctx,
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements. /// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
@@ -3871,12 +3871,12 @@ fn point_inside(_: impl Ctx, source: Item<Vector>, point: Item<DVec2>) -> Item<b
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this count off from the generic math nodes. // TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this count off from the generic math nodes.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.) // TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
#[node_macro::node(category("Data: List"), icon("NodeCount"), path(graphene_core::vector))] #[node_macro::node(category("Data: List"), icon("NodeCount"), path(graphene_core::vector), footprint_invariant)]
fn count(_: impl Ctx, content: ListDyn) -> Item<f64> { fn count(_: impl Ctx, content: ListDyn) -> Item<f64> {
Item::new_from_element(content.len() as f64) Item::new_from_element(content.len() as f64)
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector), footprint_invariant)]
fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> { fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> {
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let count = content.element().anchor_indices(paths).len() as f64; let count = content.element().anchor_indices(paths).len() as f64;
@@ -3886,7 +3886,7 @@ fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> {
/// Retrieves the vec2 position (in local space) of the anchor point at the specified index within a vector element. /// Retrieves the vec2 position (in local space) of the anchor point at the specified index within a vector element.
/// If no value exists at that index, the position (0, 0) is returned. /// If no value exists at that index, the position (0, 0) is returned.
#[node_macro::node(category("Vector: Measure"), icon("NodeIndexPoints"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeIndexPoints"), path(graphene_core::vector), footprint_invariant)]
fn index_points( fn index_points(
_: impl Ctx, _: impl Ctx,
/// The vector element containing the anchor points to be retrieved. /// The vector element containing the anchor points to be retrieved.
@@ -3912,7 +3912,7 @@ fn index_points(
Item::new_from_element(positions[index]) Item::new_from_element(positions[index])
} }
#[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector), footprint_invariant)]
fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> { fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths());
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
@@ -3928,8 +3928,8 @@ fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
Item::new_from_element(length) Item::new_from_element(length)
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector), version(2))]
fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = Item<Vector>>) -> Result<Item<f64>, Interrupt> { fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectFootprint, content: impl Node<Context<'static>, Output = Item<Vector>>) -> Result<Item<f64>, Interrupt> {
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
let vector = content.eval(new_ctx)?; let vector = content.eval(new_ctx)?;
@@ -3947,8 +3947,12 @@ pub enum CentroidError {
NoPoints, NoPoints,
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector), version(2))]
fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = Item<Vector>>, centroid_type: Item<CentroidType>) -> Result<Item<DVec2>, Interrupt> { fn centroid(
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectFootprint,
content: impl Node<Context<'static>, Output = Item<Vector>>,
centroid_type: Item<CentroidType>,
) -> Result<Item<DVec2>, Interrupt> {
let centroid_type = centroid_type.into_element(); let centroid_type = centroid_type.into_element();
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
let vector = content.eval(new_ctx)?; let vector = content.eval(new_ctx)?;
+70 -12
View File
@@ -89,19 +89,32 @@ fn vectorize(
instancing: *instancing.element(), instancing: *instancing.element(),
path_gradients: *path_gradients.element(), path_gradients: *path_gradients.element(),
}; };
let runtime = runtime.element();
let source = *source.element();
let max_megabytes = Some(*max_memory.element()).filter(|&megabytes| megabytes > 0.); let max_megabytes = Some(*max_memory.element()).filter(|&megabytes| megabytes > 0.);
if cfg!(target_family = "wasm") && !*exceed_browser_limit.element() && max_megabytes.is_none_or(|megabytes| megabytes > BROWSER_MAX_MEGABYTES) { if cfg!(target_family = "wasm") && !*exceed_browser_limit.element() && max_megabytes.is_none_or(|megabytes| megabytes > BROWSER_MAX_MEGABYTES) {
trace.clear(); trace.clear();
runtime.report_progress(source, None);
return Poll::error(format!( return Poll::error(format!(
"A memory limit above {BROWSER_MAX_MEGABYTES} MB, or none, can crash the editor in the browser. Lower the limit or turn on \"Exceed Browser Limit\"." "A memory limit above {BROWSER_MAX_MEGABYTES} MB, or none, can crash the editor in the browser. Lower the limit or turn on \"Exceed Browser Limit\"."
)); ));
} }
let max_pixels = max_megabytes.map(|megabytes| (megabytes * 1e6 / BYTES_PER_PIXEL) as usize); let max_pixels = max_megabytes.map(|megabytes| (megabytes * 1e6 / BYTES_PER_PIXEL) as usize);
let runtime = runtime.element();
if runtime.take_cancellation(source) {
trace.cancel();
}
let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE); let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE);
if let Poll::Partial(_) = state { match state {
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice Poll::Partial(_) => {
runtime.spawn(*source.element(), Box::pin(async {})); runtime.report_progress(source, trace.progress());
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
runtime.spawn(source, Box::pin(async {}));
}
_ => runtime.report_progress(source, None),
} }
state state
} }
@@ -135,14 +148,13 @@ fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: o
width, width,
height, height,
}; };
let options = ollev::TraceOptions { let mut options = ollev::TraceOptions::default();
tolerance, options.tolerance = tolerance;
detail: ollev::Detail::Scaled(detail), options.detail = ollev::Detail::Scaled(detail);
max_pixels, options.max_pixels = max_pixels;
host: CAPABILITIES, options.host = CAPABILITIES;
stages, options.stages = stages;
..Default::default()
};
ollev::Tracing::new(&source, &options).map(|tracing| (tracing, pixels_to_document)) ollev::Tracing::new(&source, &options).map(|tracing| (tracing, pixels_to_document))
}; };
@@ -404,4 +416,50 @@ mod test {
assert_eq!(spawner.drain(), 2); assert_eq!(spawner.drain(), 2);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 2)]); assert_eq!(&*runtime.snapshot(), &[(SOURCE, 2)]);
} }
/// A running trace reports progress that never goes down until it is done.
#[test]
fn a_trace_reports_progress_until_it_is_done() {
let (spawner, runtime) = collecting_runtime();
let (image, slot) = (busy(96), TraceSlot::default());
let mut previous = 0.;
while matches!(evaluate(&slot, &image, &runtime), Poll::Partial(_)) {
let progress = runtime.progress();
let [(source, fraction)] = progress.as_slice() else { panic!("the trace reported {progress:?}") };
assert_eq!(*source, SOURCE);
assert!((previous..=1.).contains(fraction), "progress went from {previous} to {fraction}");
previous = *fraction;
spawner.drain();
}
assert!(previous > 0., "the trace never reported any progress");
assert!(runtime.progress().is_empty(), "a finished trace still reports progress");
}
/// A canceled trace keeps its shapes so far, with an error, until its inputs change.
#[test]
fn a_canceled_trace_keeps_its_shapes_until_the_inputs_change() {
let (_spawner, runtime) = collecting_runtime();
let slot = TraceSlot::default();
let image = busy(96);
let shown = loop {
match evaluate(&slot, &image, &runtime) {
Poll::Partial(shown) if !shown.is_empty() => break shown,
Poll::Partial(_) => {}
state => panic!("the trace ended in {state:?} before showing shapes"),
}
};
assert!(runtime.cancel(SOURCE));
let Poll::Fallback(boxed) = evaluate(&slot, &image, &runtime) else {
panic!("the canceled trace went on")
};
assert!(boxed.0.len() >= shown.len(), "the canceled trace dropped its shapes");
assert!(runtime.progress().is_empty());
assert!(!runtime.cancel(SOURCE), "a canceled trace can be canceled again");
assert!(matches!(evaluate(&slot, &image, &runtime), Poll::Fallback(_)), "the canceled trace was started again");
assert!(matches!(evaluate(&slot, &busy(128), &runtime), Poll::Partial(_)), "new inputs were not traced");
}
} }
+29 -7
View File
@@ -1,6 +1,6 @@
use core_types::Poll;
use core_types::list::List; use core_types::list::List;
use core_types::runtime::Instant; use core_types::runtime::Instant;
use core_types::{NodeError, Poll};
use glam::DAffine2; use glam::DAffine2;
use graphic_types::Graphic; use graphic_types::Graphic;
use ollev::model::Model; use ollev::model::Model;
@@ -23,13 +23,15 @@ struct Trace {
inputs: u64, inputs: u64,
/// `None` once the trace is done and `shown` is its result, or once it failed. /// `None` once the trace is done and `shown` is its result, or once it failed.
tracing: Option<ollev::Tracing>, tracing: Option<ollev::Tracing>,
/// Why the trace failed, kept so the same inputs are not traced again. /// Why the trace failed or was canceled, kept so the same inputs are not traced again.
failed: Option<ollev::TraceError>, failed: Option<NodeError>,
/// Places the traced image's pixels in the document. /// Places the traced image's pixels in the document.
pixels_to_document: DAffine2, pixels_to_document: DAffine2,
shown: List<Graphic>, shown: List<Graphic>,
/// The revision of the scene in `shown`. /// The revision of the scene in `shown`.
revision: Option<u64>, revision: Option<u64>,
/// How much of the trace is done from 0 to 1, as ollev last reported it.
progress: f64,
} }
impl TraceSlot { impl TraceSlot {
@@ -54,6 +56,7 @@ impl TraceSlot {
pixels_to_document, pixels_to_document,
shown: List::new(), shown: List::new(),
revision: None, revision: None,
progress: 0.,
}, },
Err(error) => return Poll::fallback(List::new(), error), Err(error) => return Poll::fallback(List::new(), error),
}, },
@@ -61,7 +64,11 @@ impl TraceSlot {
if let Some(tracing) = &mut trace.tracing { if let Some(tracing) = &mut trace.tracing {
let deadline = Instant::now() + slice; let deadline = Instant::now() + slice;
let step = tracing.step(|_| if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }); let progress = &mut trace.progress;
let step = tracing.step(|checkpoint| {
*progress = checkpoint.overall;
if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
});
match step { match step {
Ok(ollev::Step::Done(model)) => { Ok(ollev::Step::Done(model)) => {
trace.shown = convert(&model, trace.pixels_to_document); trace.shown = convert(&model, trace.pixels_to_document);
@@ -69,7 +76,7 @@ impl TraceSlot {
} }
Err(error) => { Err(error) => {
trace.tracing = None; trace.tracing = None;
trace.failed = Some(error); trace.failed = Some(error.into());
} }
Ok(ollev::Step::Paused(progress)) => { Ok(ollev::Step::Paused(progress)) => {
if progress.showable() if progress.showable()
@@ -84,8 +91,8 @@ impl TraceSlot {
} }
let shown = trace.shown.clone(); let shown = trace.shown.clone();
let state = match trace.failed { let state = match &trace.failed {
Some(error) => Poll::fallback(shown, error), Some(error) => Poll::Fallback(Box::new((shown, error.clone()))),
None if trace.tracing.is_some() => Poll::Partial(shown), None if trace.tracing.is_some() => Poll::Partial(shown),
None => Poll::Final(shown), None => Poll::Final(shown),
}; };
@@ -93,6 +100,21 @@ impl TraceSlot {
state state
} }
/// How much of the slot's trace is done from 0 to 1, while it is not yet done.
pub fn progress(&self) -> Option<f64> {
let held = self.lock();
held.as_ref().filter(|trace| trace.tracing.is_some()).map(|trace| trace.progress)
}
/// Stops the slot's trace, keeping the scene traced so far as the result for its inputs.
pub fn cancel(&self) {
let mut held = self.lock();
let Some(trace) = held.as_mut().filter(|trace| trace.tracing.is_some()) else { return };
trace.tracing = None;
trace.failed = Some(NodeError::new("The trace was canceled"));
}
/// Drops the slot's trace. /// Drops the slot's trace.
pub fn clear(&self) { pub fn clear(&self) {
self.lock().take(); self.lock().take();