mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5862823504 | ||
|
|
5ca0ed032f | ||
|
|
efdf51023b | ||
|
|
3381e0b24e | ||
|
|
bf0e35197b |
No files matched your search
@@ -54,18 +54,11 @@ pub trait Archive {
|
||||
|
||||
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
|
||||
/// archive nor the full container ever sits in memory at once.
|
||||
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))
|
||||
}
|
||||
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()>;
|
||||
}
|
||||
|
||||
/// See [`Archive::unpack`].
|
||||
pub type UnpackEntry<'a> = dyn FnMut(&str, usize, &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> + 'a;
|
||||
|
||||
pub trait ArchiveWriter: Sized {
|
||||
type Sink;
|
||||
|
||||
@@ -107,18 +100,12 @@ impl ArchiveFormat {
|
||||
/// Errors if the bytes are neither a recognized xz nor zip archive.
|
||||
#[cfg(any(feature = "xz", feature = "zip"))]
|
||||
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);
|
||||
match ArchiveFormat::detect(bytes) {
|
||||
#[cfg(feature = "xz")]
|
||||
Some(ArchiveFormat::Xz) => Xz::unpack(source, sink),
|
||||
Some(ArchiveFormat::Xz) => Xz::open(source, dest),
|
||||
#[cfg(feature = "zip")]
|
||||
Some(ArchiveFormat::Zip) => Zip::unpack(source, sink),
|
||||
Some(ArchiveFormat::Zip) => Zip::open(source, dest),
|
||||
#[allow(unreachable_patterns)]
|
||||
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())),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Xz-compressed tarball archive codec.
|
||||
|
||||
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, UnpackEntry, checked_entry_size};
|
||||
use crate::{ContainerError, Result, validate_path};
|
||||
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size};
|
||||
use crate::{AsyncContainer, ContainerError, Result, validate_path};
|
||||
use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Archive for Xz {
|
||||
})
|
||||
}
|
||||
|
||||
fn unpack<R: Read + Seek>(source: R, sink: &mut UnpackEntry) -> Result<()> {
|
||||
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
|
||||
// `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
|
||||
// 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())?;
|
||||
|
||||
sink(&path, size, &mut |buffer| {
|
||||
dest.write_sized_non_blocking(&path, size, &mut |buffer| {
|
||||
entry.read_exact(buffer).map_err(ContainerError::Io)?;
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Zip archive codec.
|
||||
|
||||
use crate::archive::{Archive, ArchiveWriter, UnpackEntry, checked_entry_size};
|
||||
use crate::{ContainerError, Result, validate_path};
|
||||
use crate::archive::{Archive, ArchiveWriter, checked_entry_size};
|
||||
use crate::{AsyncContainer, ContainerError, Result, validate_path};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
use zip::ZipArchive;
|
||||
@@ -24,7 +24,7 @@ impl Archive for Zip {
|
||||
})
|
||||
}
|
||||
|
||||
fn unpack<R: Read + Seek>(source: R, sink: &mut UnpackEntry) -> Result<()> {
|
||||
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
|
||||
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
|
||||
@@ -41,7 +41,7 @@ impl Archive for Zip {
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
sink(&name, size, &mut |buffer| {
|
||||
dest.write_sized_non_blocking(&name, size, &mut |buffer| {
|
||||
entry.read_exact(buffer).map_err(ContainerError::Io)?;
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -160,7 +160,7 @@ pub(crate) struct PendingPersist {
|
||||
#[derive(Default)]
|
||||
struct MigrationInputs<'a> {
|
||||
#[cfg(feature = "migrations")]
|
||||
byte_store: Option<&'a dyn ResourceStorage>,
|
||||
byte_store: Option<&'a dyn graphene_resource::LoadResource>,
|
||||
#[cfg(feature = "migrations")]
|
||||
host: Option<&'a dyn migration_core::MigrationHost>,
|
||||
#[cfg(not(feature = "migrations"))]
|
||||
@@ -255,7 +255,7 @@ impl<L: Layout> Gdd<L> {
|
||||
bytes: &[u8],
|
||||
mut working: AnyContainer,
|
||||
layout: L,
|
||||
byte_store: Option<&dyn ResourceStorage>,
|
||||
byte_store: Option<&dyn graphene_resource::LoadResource>,
|
||||
host: Option<&dyn migration_core::MigrationHost>,
|
||||
) -> Result<Self, Error> {
|
||||
document_container::archive::open_auto(bytes, &mut working)?;
|
||||
@@ -278,10 +278,9 @@ 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
|
||||
/// 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.
|
||||
/// settle on their fallback for good. `byte_store` holds declarations the container doesn't, such as the editor's global cache.
|
||||
#[cfg(feature = "migrations")]
|
||||
pub async fn open_in_with(working: AnyContainer, layout: L, byte_store: Option<&dyn ResourceStorage>, host: Option<&dyn migration_core::MigrationHost>) -> Result<Self, Error> {
|
||||
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> {
|
||||
Self::open_stored(working, layout, MigrationInputs { byte_store, host }).await
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use document_container::AsyncContainer;
|
||||
use document_graph_storage::BlobHash;
|
||||
use document_graph_storage::blob::NewBlobs;
|
||||
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
|
||||
use graphene_resource::ResourceStorage;
|
||||
use graphene_resource::LoadResource;
|
||||
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};
|
||||
|
||||
@@ -70,7 +70,7 @@ fn payload_codec(codec: Codec) -> PayloadCodec {
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// 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 ResourceStorage>, host: Option<&dyn MigrationHost>) -> Result<bool, Error> {
|
||||
pub(crate) async fn migrate_nodes(&mut self, byte_store: Option<&dyn LoadResource>, host: Option<&dyn MigrationHost>) -> Result<bool, Error> {
|
||||
let migrations = migration_core::registered_migrations();
|
||||
if migrations.is_empty() {
|
||||
return Ok(false);
|
||||
@@ -112,10 +112,6 @@ impl<L: Layout> Gdd<L> {
|
||||
// Declarations the migrations introduced need their bytes next to the other resources
|
||||
let referenced = self.session.all_declaration_resources();
|
||||
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);
|
||||
if !self.working.exists(&path).await {
|
||||
self.working.write_non_blocking(&path, &declaration.bytes)?;
|
||||
@@ -128,7 +124,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.
|
||||
async fn load_stored_declarations(&self, byte_store: Option<&dyn ResourceStorage>) -> Declarations {
|
||||
async fn load_stored_declarations(&self, byte_store: Option<&dyn LoadResource>) -> Declarations {
|
||||
let mut declarations = Declarations::new();
|
||||
|
||||
for (id, hash) in self.session.all_declaration_resources() {
|
||||
|
||||
@@ -286,9 +286,6 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
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.pending_persist.history = true;
|
||||
self.pending_persist.hot_log = true;
|
||||
@@ -314,9 +311,6 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
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.pending_persist.snapshot = true;
|
||||
Ok(moved)
|
||||
|
||||
@@ -504,8 +504,6 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
#[cfg(feature = "network")]
|
||||
self.publish_head_move(&moved);
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
@@ -516,13 +514,12 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.publish_head_move(&moved);
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
@@ -534,16 +531,6 @@ impl<L: Layout> Gdd<L> {
|
||||
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.
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
|
||||
@@ -73,18 +73,6 @@ 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 {
|
||||
let node = |identifier: &'static str| DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
|
||||
@@ -12,7 +12,6 @@ pub mod model;
|
||||
mod network_reference;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
mod repair;
|
||||
pub mod resources;
|
||||
mod schema;
|
||||
pub mod session;
|
||||
@@ -53,7 +52,6 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod history_simulation;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
|
||||
@@ -1,420 +0,0 @@
|
||||
//! 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, ®istry, intended].into_iter().flat_map(head_slots).filter(|&slot| owner_is_live(®istry, 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(®istry, 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 = [¤t, &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(®istry, &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(®istry, 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(®istry, id, slot_network(®istry, 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(®istry) {
|
||||
if registry.node_instances.contains_key(&named) {
|
||||
continue;
|
||||
}
|
||||
let reconnected = reconnect(®istry, named, slot_network(®istry, slot), known)
|
||||
.or_else(|| slot_value(before, slot).filter(|earlier| !names_missing(®istry, 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 ®istry.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 ®istry.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(¤t) {
|
||||
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
|
||||
None => known.primary.get(¤t).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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -446,91 +446,23 @@ impl Session {
|
||||
}
|
||||
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. Each copied interaction ends with the
|
||||
// repairs it needs on the changed line.
|
||||
// Minted on a scratch fold first, so a failing copy changes nothing.
|
||||
let mut scratch = self.fold_scratch_at(Some(base))?;
|
||||
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 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() {
|
||||
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((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();
|
||||
newest_first[position..].iter().for_each(|delta| touched.record(&delta.kind));
|
||||
for (copy, _) in copies.iter().zip(&sources).filter(|(_, (original, _))| original.is_none()) {
|
||||
touched.record(©.kind);
|
||||
}
|
||||
// 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 {
|
||||
for (original, copy) in newest_first[..position].iter().rev().zip(&mut copies) {
|
||||
self.document.history.push(copy.clone());
|
||||
self.carry_attributes(original, copy.id);
|
||||
if let Some(carried) = self.document.history.get(copy.id) {
|
||||
*copy = carried.clone();
|
||||
}
|
||||
@@ -542,6 +474,9 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
if let Some(head) = self.document.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
@@ -552,15 +487,14 @@ impl Session {
|
||||
))
|
||||
}
|
||||
|
||||
/// Move the shared head to `target`, back to an ancestor or over to a branch, leaving the line it was on as a
|
||||
/// 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.
|
||||
/// Move the shared head back to its ancestor `target`, leaving the line since as a branch. Returns the move to
|
||||
/// broadcast and what the steps left behind named. Only the retirer does this; a guest asks it to.
|
||||
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
|
||||
let from = self.document.head;
|
||||
if from == Some(target) {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let touched = self.touched_between_lines(Some(target))?;
|
||||
let touched = self.touched_since(Some(target))?;
|
||||
let snapshot = self.fold_at(Some(target))?;
|
||||
|
||||
self.document.head = Some(target);
|
||||
@@ -568,6 +502,7 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
self.publish_up_to(target);
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
@@ -579,8 +514,8 @@ impl Session {
|
||||
}
|
||||
|
||||
/// 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 a known rev to the
|
||||
/// move's head.
|
||||
/// where the move started, since this peer has then diverged, or when the copies don't chain from an ancestor of
|
||||
/// the head to the move's head.
|
||||
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
|
||||
if self.document.head != moved.from {
|
||||
return Err(CrdtError::CursorMismatch {
|
||||
@@ -589,12 +524,7 @@ impl Session {
|
||||
});
|
||||
}
|
||||
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
|
||||
// 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 touched = self.touched_since(base)?;
|
||||
let mut tip = base;
|
||||
for copy in &moved.copies {
|
||||
if copy.parent != tip || matches!(copy.kind, RegistryDelta::Merge { .. }) {
|
||||
@@ -638,26 +568,26 @@ impl Session {
|
||||
touched
|
||||
}
|
||||
|
||||
/// What the deltas on just one of the head's and `other`'s lines named, merged branches included.
|
||||
fn touched_between_lines(&self, other: Option<Rev>) -> Result<Touched, CrdtError> {
|
||||
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is
|
||||
/// on the head's line.
|
||||
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
|
||||
let history = &self.document.history;
|
||||
if let Some(other) = other
|
||||
&& !history.contains(other)
|
||||
{
|
||||
return Err(CrdtError::NotFoundInHistory(other));
|
||||
}
|
||||
let line = history.ancestors(self.document.head);
|
||||
let other_line = history.ancestors(other);
|
||||
if let Some(base) = base
|
||||
&& !line.contains(&base)
|
||||
{
|
||||
return Err(CrdtError::NotAncestor(base));
|
||||
}
|
||||
let kept = history.ancestors(base);
|
||||
let mut touched = Touched::default();
|
||||
for delta in history.iter().filter(|delta| line.contains(&delta.id) != other_line.contains(&delta.id)) {
|
||||
for delta in history.iter().filter(|delta| line.contains(&delta.id) && !kept.contains(&delta.id)) {
|
||||
touched.record(&delta.kind);
|
||||
}
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// 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, and the graph is repaired where that
|
||||
/// left it broken (see [`repair_ops`](crate::repair::repair_ops)). Returns the new revs.
|
||||
/// original stamps, so a field someone wrote since keeps the newer value. Returns the new revs.
|
||||
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 mut originals = Vec::new();
|
||||
@@ -669,32 +599,10 @@ impl Session {
|
||||
originals.push(delta);
|
||||
}
|
||||
originals.reverse();
|
||||
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();
|
||||
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
|
||||
for (original, &rev) in originals.iter().zip(&revs) {
|
||||
let closes = original.id == dropped;
|
||||
self.carry_attributes(original, rev, closing.filter(|_| closes));
|
||||
self.carry_attributes(original, rev);
|
||||
}
|
||||
revs.extend(repaired);
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
}
|
||||
@@ -743,11 +651,6 @@ impl Session {
|
||||
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 {
|
||||
self.document.history.len()
|
||||
}
|
||||
@@ -1039,74 +942,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a minted copy the attributes and retirement time of its original. The interaction end and action move to
|
||||
/// `closing` when repairs after the copy now end the interaction.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev, closing: Option<Rev>) {
|
||||
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);
|
||||
}
|
||||
/// Give a minted copy the attributes and retirement time of the delta it stands for.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
self.document.history.set_retired_at(copy, wall_ms);
|
||||
}
|
||||
for (key, value) in original.attributes.live() {
|
||||
let moved = closing.filter(|_| key == INTERACTION_END || key == ACTION);
|
||||
self.document.history.annotate(moved.unwrap_or(copy), key, value.value.clone(), value.timestamp);
|
||||
self.document.history.annotate(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.
|
||||
/// 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.
|
||||
@@ -1571,6 +1416,8 @@ pub enum CrdtError {
|
||||
NotUndoable(Rev),
|
||||
#[error("Cursor is at {found:?}, the move expected {expected:?}")]
|
||||
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")]
|
||||
MalformedHeadMove,
|
||||
#[error("Node {0} already exists")]
|
||||
|
||||
@@ -1,451 +0,0 @@
|
||||
//! 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(®istry);
|
||||
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(®istry, layer, below(®istry, 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(®istry, layer, below(®istry, 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 ®istry.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 ®istry.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()));
|
||||
}
|
||||
@@ -913,126 +913,6 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
|
||||
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
|
||||
/// peer id still undoes what its user did from the old one, and nobody else's.
|
||||
#[test]
|
||||
@@ -1131,40 +1011,10 @@ 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(dropped)));
|
||||
let sibling = if target == host_step { guest_step } else { host_step };
|
||||
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)));
|
||||
assert!(matches!(moved.move_head_to(sibling), Err(CrdtError::NotAncestor(rev)) if rev == sibling));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn a_head_move_with_copies_is_followed_onto_them() {
|
||||
@@ -1207,14 +1057,7 @@ 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 off_first = copy(50, Some(first));
|
||||
let off_base_again = copy(51, Some(first));
|
||||
let off_the_line = copy(52, Some(off_first.id));
|
||||
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.
|
||||
crate::HeadMove {
|
||||
from: Some(second),
|
||||
@@ -1236,9 +1079,9 @@ fn a_malformed_head_move_changes_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The retirer publishes a head move only when it broadcasts it, while a follower holds the line it was sent.
|
||||
/// Peers hold the line up to where the head moved, so a silent undo must not reach behind it.
|
||||
#[test]
|
||||
fn a_followed_head_move_publishes_the_new_head() {
|
||||
fn a_head_move_publishes_the_new_head() {
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let [_, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| {
|
||||
host.commit_op_for_test(set_attribute(key, value)).expect("step");
|
||||
@@ -1251,7 +1094,7 @@ fn a_followed_head_move_publishes_the_new_head() {
|
||||
guest.publish_up_to(third);
|
||||
|
||||
let (moved, _) = host.move_head_to(second).expect("move");
|
||||
assert!(host.can_undo(), "an unbroadcast move stays silently undoable");
|
||||
assert!(!host.can_undo(), "the step the room holds stays put");
|
||||
guest.apply_head_move(&moved).expect("follow");
|
||||
assert!(!guest.can_undo(), "the follower holds the same line");
|
||||
}
|
||||
|
||||
@@ -6,3 +6,5 @@ use migration_core::rename;
|
||||
rename!("graphene_core::ops::PassthroughNode"@1 => @2);
|
||||
// The removed Monitor node passes its one input on, as a Passthrough does
|
||||
rename!("graphene_core::memo::MonitorNode"@1 => "graphene_core::ops::PassthroughNode"@2);
|
||||
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
|
||||
rename!("graphene_core::vector::MapPointsNode"@1 => @2);
|
||||
@@ -0,0 +1,3 @@
|
||||
//! Migrations of the nodes in `graphic_nodes`.
|
||||
|
||||
mod renames;
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
|
||||
rename!("graphic_nodes::graphic::MapNode"@1 => @2);
|
||||
rename!("graphic_nodes::graphic::IterateNode"@1 => @2);
|
||||
rename!("graphic_nodes::graphic::WriteAttributeNode"@1 => @2);
|
||||
@@ -4,6 +4,9 @@
|
||||
mod blending_nodes;
|
||||
mod graphene_core;
|
||||
mod graphene_std;
|
||||
mod graphic_nodes;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
mod repeat_nodes;
|
||||
mod text_nodes;
|
||||
mod vector_nodes;
|
||||
@@ -0,0 +1,3 @@
|
||||
//! Migrations of the nodes in `repeat_nodes`.
|
||||
|
||||
mod renames;
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
|
||||
rename!("repeat_nodes::repeat_nodes::RepeatNode"@1 => @2);
|
||||
rename!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2);
|
||||
rename!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2);
|
||||
rename!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1 => @2);
|
||||
@@ -0,0 +1,3 @@
|
||||
//! Migrations of the nodes in `text_nodes`.
|
||||
|
||||
mod renames;
|
||||
@@ -0,0 +1,6 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
|
||||
rename!("text_nodes::StringMapNode"@1 => @2);
|
||||
@@ -48,7 +48,7 @@ pub trait SyncTarget {
|
||||
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`].
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>;
|
||||
/// 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`].
|
||||
/// Host only. Move the shared head to an ancestor, leaving the line since as a branch. See [`Session::move_head_to`].
|
||||
fn move_head_to(&mut self, _rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
Err("this target cannot move its head".into())
|
||||
}
|
||||
|
||||
@@ -199,18 +199,6 @@ pub enum FrontendMessage {
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
/// A History panel step's captured image as an SVG, sent when the GPU is unavailable, which the panel shows wherever a row names `id`.
|
||||
UpdateHistoryThumbnail {
|
||||
id: String,
|
||||
svg: String,
|
||||
},
|
||||
/// A History panel step's captured image as straight RGBA pixels.
|
||||
UpdateHistoryThumbnailPixels {
|
||||
id: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: serde_bytes::ByteBuf,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
|
||||
@@ -44,7 +44,6 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
entry!(KeyUp(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZ { abort_transform: false }),
|
||||
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=DocumentMessage::PreviewHistoryStep { rev: None }),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseLeft }),
|
||||
entry!(KeyDown(MouseMiddle); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseMiddle }),
|
||||
entry!(KeyDown(MouseRight); action_dispatch=NavigationMessage::EndCanvasPTZWithClick { commit_key: MouseRight }),
|
||||
|
||||
@@ -31,14 +31,6 @@ pub struct DocumentHistory {
|
||||
needs_whole_document_stage: bool,
|
||||
/// How storage undid each step that redo can bring back, latest last.
|
||||
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)]
|
||||
@@ -49,8 +41,6 @@ enum UndoNote {
|
||||
Dropped(document_graph_storage::Rev),
|
||||
/// The storage cursor moved back over the step.
|
||||
Cursor,
|
||||
/// A History panel change was taken back.
|
||||
LineMove(LineMove),
|
||||
}
|
||||
|
||||
impl DocumentHistory {
|
||||
@@ -133,9 +123,6 @@ impl DocumentHistory {
|
||||
if let Some(ops) = retracted {
|
||||
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
|
||||
if in_session {
|
||||
return self.undo_retired_step().map(UndoNote::Dropped);
|
||||
@@ -152,7 +139,6 @@ impl DocumentHistory {
|
||||
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
|
||||
UndoNote::Dropped(rev) => line_reachable && self.redo_retired_step(*rev),
|
||||
UndoNote::Cursor => self.move_cursor(false),
|
||||
UndoNote::LineMove(line_move) => self.redo_line_move(*line_move),
|
||||
};
|
||||
if !redone {
|
||||
self.undo_notes.push_back(note);
|
||||
@@ -212,62 +198,12 @@ impl DocumentHistory {
|
||||
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
|
||||
return false;
|
||||
};
|
||||
let from = storage.session().head_rev();
|
||||
let result = match change {
|
||||
LineChange::MoveHead => storage.move_head(rev),
|
||||
LineChange::Remove => storage.drop_step(rev),
|
||||
LineChange::Restore => storage.redo_retired_step(rev),
|
||||
};
|
||||
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));
|
||||
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
pub fn retire_storage_interaction(&mut self) {
|
||||
@@ -369,25 +305,10 @@ impl DocumentHistory {
|
||||
|
||||
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
|
||||
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(®istry)
|
||||
}
|
||||
|
||||
fn interface_from(&self, registry: &document_graph_storage::Registry) -> Option<NodeNetworkInterface> {
|
||||
let storage = self.storage.as_ref()?;
|
||||
|
||||
registry
|
||||
storage
|
||||
.registry()
|
||||
.to_runtime_with_full_metadata(&self.declarations, storage.blobs())
|
||||
.map_err(|error| error.to_string())
|
||||
.map(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries))
|
||||
|
||||
@@ -60,9 +60,6 @@ pub enum DocumentMessage {
|
||||
rev: document_graph_storage::Rev,
|
||||
change: crate::messages::portfolio::history::utility_types::LineChange,
|
||||
},
|
||||
PreviewHistoryStep {
|
||||
rev: Option<document_graph_storage::Rev>,
|
||||
},
|
||||
DocumentStructureChanged,
|
||||
DrawArtboardOverlays {
|
||||
context: OverlayContext,
|
||||
|
||||
@@ -24,7 +24,6 @@ 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::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
|
||||
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::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
@@ -170,12 +169,9 @@ pub struct DocumentMessageHandler {
|
||||
/// Path to network that is currently selected. Updated based on the most recently clicked panel.
|
||||
#[serde(skip)]
|
||||
selection_network_path: Vec<NodeId>,
|
||||
/// Undo/redo state over the `Gdd` working copy.
|
||||
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
|
||||
#[serde(skip)]
|
||||
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.
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -207,12 +203,6 @@ pub struct DocumentMessageHandler {
|
||||
pub is_loaded: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct HistoryPreview {
|
||||
rev: Rev,
|
||||
current: NodeNetworkInterface,
|
||||
}
|
||||
|
||||
impl Default for DocumentMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -251,7 +241,6 @@ impl Default for DocumentMessageHandler {
|
||||
breadcrumb_network_path: Vec::new(),
|
||||
selection_network_path: Vec::new(),
|
||||
history: DocumentHistory::default(),
|
||||
history_preview: None,
|
||||
container: None,
|
||||
pending_remote: Default::default(),
|
||||
saved_hash: None,
|
||||
@@ -489,13 +478,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
}
|
||||
DocumentMessage::ChangeHistoryLine { rev, change } => {
|
||||
self.change_history_line(document_id, rev, change, viewport, &resource_storage.resources_mut(), responses);
|
||||
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), 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 } => {
|
||||
if let Some(storage) = self.history.storage_mut() {
|
||||
storage.name_interaction(&action);
|
||||
@@ -1157,7 +1142,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(ToolMessage::ActivateTool { tool_type: ToolType::Select });
|
||||
}
|
||||
DocumentMessage::Redo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
responses.add(SelectToolMessage::Abort);
|
||||
@@ -1282,7 +1267,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
});
|
||||
}
|
||||
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
|
||||
self.end_history_preview(viewport, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveActiveDocument);
|
||||
|
||||
let include_history = preferences.save_with_history;
|
||||
@@ -1712,7 +1696,6 @@ 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.
|
||||
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.end_storage_interaction();
|
||||
|
||||
@@ -1948,7 +1931,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2186,10 +2169,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
ZoomCanvasToFitAll,
|
||||
);
|
||||
|
||||
if self.history_preview.is_some() {
|
||||
common.extend(actions!(DocumentMessageDiscriminant::PreviewHistoryStep));
|
||||
}
|
||||
|
||||
// Additional actions available on desktop
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
common.extend(actions!(DocumentMessageDiscriminant::SaveDocumentAs));
|
||||
@@ -2631,9 +2610,6 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// 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 {
|
||||
if self.history_preview.is_some() {
|
||||
return false;
|
||||
}
|
||||
let changes = std::mem::take(&mut self.pending_remote);
|
||||
if changes.is_empty() {
|
||||
return true;
|
||||
@@ -3102,87 +3078,12 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// 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, viewport: &ViewportMessageHandler, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
self.end_history_preview(viewport, responses);
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
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.history.retire_storage_interaction();
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
@@ -3196,20 +3097,6 @@ impl DocumentMessageHandler {
|
||||
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`.
|
||||
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
|
||||
@@ -15,9 +15,7 @@ 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::{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 std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn selected_segments(network_interface: &NodeNetworkInterface, shape_editor: &ShapeState) -> HashMap<LayerNodeIdentifier, Vec<SegmentId>> {
|
||||
let mut map = HashMap::new();
|
||||
@@ -173,159 +171,128 @@ 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) {
|
||||
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 draw_handles = Arc::new(draw_handles);
|
||||
|
||||
// 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) {
|
||||
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
|
||||
let source = document.network_interface.layer_vector_source(layer);
|
||||
let selected_shape_state = shape_editor.selected_shape_state.entry(layer).or_default().clone();
|
||||
let draw_handles = draw_handles.clone();
|
||||
|
||||
overlay_context.with_rendered_layers(move |overlay_context, rendered| {
|
||||
let (vector, transform) = rendered.vector(source).unwrap_or((Cow::Borrowed(&vector), source.layer_to_viewport));
|
||||
layer_path_overlays(layer, &vector, transform, &draw_handles, &selected_shape_state, document_zoom, overlay_context);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
|
||||
if display_path {
|
||||
overlay_context.outline_vector(&vector, 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());
|
||||
});
|
||||
let selected_shape_state = shape_editor.selected_shape_state.entry(layer).or_default();
|
||||
// Get the selected segments and then add a bold line overlay on them
|
||||
for (segment_id, bezier, _, _) in vector.segment_iter() {
|
||||
if selected_shape_state.is_segment_selected(segment_id) {
|
||||
overlay_context.outline_select_bezier(bezier, transform);
|
||||
}
|
||||
DrawHandles::SelectedAnchors(selected_segments) => {
|
||||
let focused_segments = selected_segments.get(&layer).map(Vec::as_slice).unwrap_or_default();
|
||||
}
|
||||
|
||||
vector
|
||||
.segment_iter()
|
||||
.filter(|(segment_id, ..)| focused_segments.contains(segment_id))
|
||||
.for_each(|(segment_id, segment, _start, _end)| {
|
||||
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());
|
||||
});
|
||||
|
||||
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::FrontierHandles(segment_endpoints_by_layer) => {
|
||||
if let Some(segment_endpoints) = segment_endpoints_by_layer.get(&layer) {
|
||||
DrawHandles::SelectedAnchors(ref selected_segments) => {
|
||||
let focused_segments = selected_segments.get(&layer).map(Vec::as_slice).unwrap_or_default();
|
||||
|
||||
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() {
|
||||
let Some(endpoints) = segment_endpoints.get(&segment_id) else { continue };
|
||||
|
||||
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());
|
||||
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::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);
|
||||
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);
|
||||
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.
|
||||
/// 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) {
|
||||
if !overlay_context.visibility_settings.anchors() {
|
||||
return;
|
||||
}
|
||||
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let selected_anchors_of = |layer: LayerNodeIdentifier| -> HashSet<PointId> {
|
||||
let Some(state) = shape_editor.selected_shape_state.get(&layer) else { return HashSet::new() };
|
||||
state
|
||||
.selected_points()
|
||||
.filter_map(|point| if let ManipulatorPointId::Anchor(id) = point { Some(id) } else { None })
|
||||
.collect()
|
||||
let is_selected = |layer: LayerNodeIdentifier, id: PointId| {
|
||||
shape_editor
|
||||
.selected_shape_state
|
||||
.get(&layer)
|
||||
.is_some_and(|state| state.is_point_selected(ManipulatorPointId::Anchor(id)))
|
||||
};
|
||||
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);
|
||||
|
||||
for layer in selected_nodes.selected_visible_layers(&document.network_interface) {
|
||||
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
|
||||
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 transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
|
||||
|
||||
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);
|
||||
let path_index_labels = path_marker_overlays(&vector, transform, document_zoom, true, overlay_context);
|
||||
|
||||
for id in vector.anchor_endpoints() {
|
||||
if hovered_anchor == Some(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(position) = vector.position_from_id(id) else { continue };
|
||||
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), selected_anchors.contains(&id), None);
|
||||
for id in vector.anchor_endpoints() {
|
||||
if hovered.is_some_and(|(hovered_layer, hovered_id, _)| hovered_layer == layer && hovered_id == id) {
|
||||
continue;
|
||||
}
|
||||
let Some(position) = vector.position_from_id(id) else { continue };
|
||||
|
||||
index_label_overlays(&vector, transform, true, &[], path_index_labels, overlay_context);
|
||||
});
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(layer, id), None);
|
||||
}
|
||||
|
||||
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
|
||||
if let Some((layer, id, position)) = hovered {
|
||||
let source = document.network_interface.layer_vector_source(layer);
|
||||
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);
|
||||
});
|
||||
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
|
||||
overlay_context.hover_manipulator_anchor(transform.transform_point2(position), is_selected(layer, id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,20 +14,16 @@ use crate::messages::viewport::ToPhysical;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::ATTR_TRANSFORM;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::renderer::RenderMetadata;
|
||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, paths_from_list_row_attributes};
|
||||
use kurbo::{self, BezPath, ParamCurve};
|
||||
use kurbo::{Affine, PathSeg};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use vello_gpu::peniko;
|
||||
@@ -201,21 +197,30 @@ 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))]
|
||||
#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub struct OverlayContext {
|
||||
// Serde functionality isn't used but is required by the message system macros
|
||||
#[serde(skip)]
|
||||
commands: Arc<Mutex<Vec<OverlayCommand>>>,
|
||||
internal: Arc<Mutex<OverlayContextInternal>>,
|
||||
pub viewport: ViewportMessageHandler,
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
type OverlayCommand = Box<dyn Fn(&mut OverlayContextInternal, &RenderedLayers) + Send>;
|
||||
impl Clone for OverlayContext {
|
||||
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 the commands are closures
|
||||
// Manual implementations since VelloSceneBuilder doesn't implement PartialEq or Debug
|
||||
impl PartialEq for OverlayContext {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.viewport == other.viewport && self.visibility_settings == other.visibility_settings
|
||||
@@ -225,9 +230,21 @@ impl PartialEq for OverlayContext {
|
||||
impl std::fmt::Debug for OverlayContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OverlayContext")
|
||||
.field("scene", &"VelloSceneBuilder { ... }")
|
||||
.field("viewport", &self.viewport)
|
||||
.field("visibility_settings", &self.visibility_settings)
|
||||
.finish_non_exhaustive()
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,234 +253,98 @@ impl core::hash::Hash for OverlayContext {
|
||||
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 {
|
||||
#[cfg_attr(test, expect(dead_code, reason = "Tests skip drawing overlays"))]
|
||||
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
|
||||
Self {
|
||||
commands: Arc::default(),
|
||||
internal: Arc::new(Mutex::new(OverlayContextInternal::new(viewport, visibility_settings))),
|
||||
viewport,
|
||||
visibility_settings,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the recorded overlays, resolving layers against `rendered`.
|
||||
pub fn render(&self, rendered: &RenderedLayers) -> VelloSceneBuilder<'static> {
|
||||
let mut overlays = OverlayContextInternal::new(self.viewport);
|
||||
for command in self.commands().iter() {
|
||||
command(&mut overlays, rendered);
|
||||
}
|
||||
overlays.scene
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
}
|
||||
|
||||
fn commands(&'_ self) -> MutexGuard<'_, Vec<OverlayCommand>> {
|
||||
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);
|
||||
}
|
||||
});
|
||||
fn internal(&'_ self) -> MutexGuard<'_, OverlayContextInternal> {
|
||||
self.internal.lock().expect("Failed to lock internal overlay context")
|
||||
}
|
||||
|
||||
pub fn quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>) {
|
||||
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()));
|
||||
self.internal().quad(quad, stroke_color, color_fill);
|
||||
}
|
||||
|
||||
pub fn draw_triangle(&mut self, base: DVec2, direction: DVec2, size: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
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()));
|
||||
self.internal().draw_triangle(base, direction, size, color_fill, color_stroke);
|
||||
}
|
||||
|
||||
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>) {
|
||||
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));
|
||||
self.internal().dashed_quad(quad, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
|
||||
}
|
||||
|
||||
pub fn polygon(&mut self, polygon: &[DVec2], stroke_color: Option<&str>, color_fill: Option<&str>) {
|
||||
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()));
|
||||
self.internal().polygon(polygon, stroke_color, color_fill);
|
||||
}
|
||||
|
||||
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>) {
|
||||
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));
|
||||
self.internal().dashed_polygon(polygon, stroke_color, color_fill, dash_width, dash_gap_width, dash_offset);
|
||||
}
|
||||
|
||||
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
|
||||
self.internal().line(start, end, color, thickness);
|
||||
}
|
||||
|
||||
#[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>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.dashed_line(start, end, color.as_deref(), thickness, dash_width, dash_gap_width, dash_offset));
|
||||
self.internal().dashed_line(start, end, color, thickness, dash_width, dash_gap_width, dash_offset);
|
||||
}
|
||||
|
||||
pub fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
|
||||
self.record(move |overlays| overlays.hover_manipulator_handle(position, selected));
|
||||
self.internal().hover_manipulator_handle(position, selected);
|
||||
}
|
||||
|
||||
pub fn hover_manipulator_anchor(&mut self, position: DVec2, selected: bool) {
|
||||
self.record(move |overlays| overlays.hover_manipulator_anchor(position, selected));
|
||||
self.internal().hover_manipulator_anchor(position, selected);
|
||||
}
|
||||
|
||||
pub fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
|
||||
self.internal().manipulator_handle(position, selected, color);
|
||||
}
|
||||
|
||||
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
|
||||
self.internal().manipulator_anchor(position, selected, color);
|
||||
}
|
||||
|
||||
pub fn gradient_color_stop(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, small: bool) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
|
||||
self.internal().gradient_color_stop(position, emphasis, color, small);
|
||||
}
|
||||
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
|
||||
self.internal().gradient_midpoint(position, emphasis, angle);
|
||||
}
|
||||
|
||||
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
self.record(move |overlays| overlays.resize_handle(position, rotation));
|
||||
self.internal().resize_handle(position, rotation);
|
||||
}
|
||||
|
||||
pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
|
||||
self.record(move |overlays| overlays.skew_handles(edge_start, edge_end));
|
||||
self.internal().skew_handles(edge_start, edge_end);
|
||||
}
|
||||
|
||||
pub fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
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()));
|
||||
self.internal().square(position, size, color_fill, color_stroke);
|
||||
}
|
||||
|
||||
/// 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>) {
|
||||
let (positions, color) = (positions.to_vec(), owned(color));
|
||||
self.record(move |overlays| overlays.dots(&positions, size, color.as_deref()));
|
||||
self.internal().dots(positions, size, color);
|
||||
}
|
||||
|
||||
pub fn circle(&mut self, position: DVec2, radius: f64, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
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()));
|
||||
self.internal().circle(position, radius, color_fill, color_stroke);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -482,135 +363,106 @@ impl OverlayContext {
|
||||
dash_gap_width: Option<f64>,
|
||||
dash_offset: Option<f64>,
|
||||
) {
|
||||
let (color_fill, color_stroke) = (owned(color_fill), owned(color_stroke));
|
||||
self.record(move |overlays| {
|
||||
overlays.dashed_ellipse(
|
||||
center,
|
||||
radius_x,
|
||||
radius_y,
|
||||
rotation,
|
||||
start_angle,
|
||||
end_angle,
|
||||
counterclockwise,
|
||||
color_fill.as_deref(),
|
||||
color_stroke.as_deref(),
|
||||
dash_width,
|
||||
dash_gap_width,
|
||||
dash_offset,
|
||||
)
|
||||
});
|
||||
self.internal().dashed_ellipse(
|
||||
center,
|
||||
radius_x,
|
||||
radius_y,
|
||||
rotation,
|
||||
start_angle,
|
||||
end_angle,
|
||||
counterclockwise,
|
||||
color_fill,
|
||||
color_stroke,
|
||||
dash_width,
|
||||
dash_gap_width,
|
||||
dash_offset,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
|
||||
self.record(move |overlays| overlays.draw_arc(center, radius, start_from, end_at));
|
||||
self.internal().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) {
|
||||
self.record(move |overlays| overlays.draw_arc_gizmo_angle(pivot, bold_radius, arc_radius, offset_angle, angle));
|
||||
self.internal().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) {
|
||||
self.record(move |overlays| overlays.draw_angle(pivot, radius, arc_radius, offset_angle, angle));
|
||||
self.internal().draw_angle(pivot, radius, arc_radius, offset_angle, angle);
|
||||
}
|
||||
|
||||
pub fn draw_scale(&mut self, start: DVec2, scale: f64, radius: f64, text: &str) {
|
||||
let text = text.to_owned();
|
||||
self.record(move |overlays| overlays.draw_scale(start, scale, radius, &text));
|
||||
self.internal().draw_scale(start, scale, radius, text);
|
||||
}
|
||||
|
||||
pub fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) {
|
||||
self.record(move |overlays| overlays.compass_rose(compass_center, angle, show_compass_with_hover_ring));
|
||||
self.internal().compass_rose(compass_center, angle, show_compass_with_hover_ring);
|
||||
}
|
||||
|
||||
pub fn pivot(&mut self, position: DVec2, angle: f64) {
|
||||
self.record(move |overlays| overlays.pivot(position, angle));
|
||||
self.internal().pivot(position, angle);
|
||||
}
|
||||
|
||||
pub fn dowel_pin(&mut self, position: DVec2, angle: f64, color: Option<&str>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.dowel_pin(position, angle, color.as_deref()));
|
||||
self.internal().dowel_pin(position, angle, color);
|
||||
}
|
||||
|
||||
#[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) {
|
||||
let text = text.to_owned();
|
||||
self.record(move |overlays| overlays.arc_sweep_angle(offset_angle, angle, end_point_position, bold_radius, pivot, &text, transform));
|
||||
self.internal().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.
|
||||
pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) {
|
||||
let vector = vector.clone();
|
||||
self.record(move |overlays| overlays.outline_vector(&vector, transform));
|
||||
self.internal().outline_vector(vector, transform);
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
self.record(move |overlays| overlays.outline_bezier(bezier, transform));
|
||||
self.internal().outline_bezier(bezier, transform);
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
self.record(move |overlays| overlays.outline_select_bezier(bezier, transform));
|
||||
self.internal().outline_select_bezier(bezier, transform);
|
||||
}
|
||||
|
||||
pub fn outline_overlay_bezier(&mut self, bezier: PathSeg, transform: DAffine2) {
|
||||
self.record(move |overlays| overlays.outline_overlay_bezier(bezier, transform));
|
||||
self.internal().outline_overlay_bezier(bezier, transform);
|
||||
}
|
||||
|
||||
/// 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>) {
|
||||
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());
|
||||
}
|
||||
});
|
||||
self.internal().outline(target_types, transform, color);
|
||||
}
|
||||
|
||||
/// Strokes the path with a 1px line, leaving any open subpaths open.
|
||||
pub fn stroke_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
let (bezpath, color) = (bezpath.clone(), color.to_owned());
|
||||
self.record(move |overlays| overlays.stroke_path(&bezpath, transform, &color));
|
||||
self.internal().stroke_path(bezpath, transform, color);
|
||||
}
|
||||
|
||||
/// Fills the area inside the path. Assumes `color` is in gamma space.
|
||||
/// Used by the Pen tool to show the path being closed.
|
||||
pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
let (bezpath, color) = (bezpath.clone(), color.to_owned());
|
||||
self.record(move |overlays| overlays.fill_path(&bezpath, transform, &color));
|
||||
self.internal().fill_path(bezpath, transform, color);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
let (bezpath, color) = (bezpath.clone(), color.to_owned());
|
||||
self.record(move |overlays| overlays.fill_path_pattern(&bezpath, transform, &color));
|
||||
self.internal().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]) {
|
||||
let (text, font_color, background_color) = (text.to_owned(), font_color.to_owned(), owned(background_color));
|
||||
self.record(move |overlays| overlays.text(&text, &font_color, background_color.as_deref(), transform, padding, pivot));
|
||||
let mut internal = self.internal();
|
||||
internal.text(text, font_color, background_color, transform, padding, pivot);
|
||||
}
|
||||
|
||||
pub fn translation_box(&mut self, translation: DVec2, quad: Quad, typed_string: Option<String>) {
|
||||
self.record(move |overlays| overlays.translation_box(translation, quad, typed_string.clone()));
|
||||
self.internal().translation_box(translation, quad, typed_string);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Pivot {
|
||||
Start,
|
||||
Middle,
|
||||
@@ -624,9 +476,10 @@ pub enum DrawHandles {
|
||||
None,
|
||||
}
|
||||
|
||||
struct OverlayContextInternal {
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
@@ -638,11 +491,18 @@ fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static
|
||||
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 {
|
||||
fn new(viewport: ViewportMessageHandler) -> Self {
|
||||
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
|
||||
Self {
|
||||
scene: overlay_scene(&viewport),
|
||||
viewport,
|
||||
visibility_settings,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -137,49 +137,6 @@ async fn saving_writes_a_zip_archive_with_the_graphite_extension() {
|
||||
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]
|
||||
async fn storage_only_container_recovers_and_writes_legacy() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -112,7 +112,15 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
pub fn transform_to_viewport(&self, layer: LayerNodeIdentifier) -> DAffine2 {
|
||||
self.transform_to_viewport_including_local(layer, true)
|
||||
// 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 = 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 {
|
||||
@@ -121,25 +129,9 @@ impl DocumentMetadata {
|
||||
return self.document_to_viewport;
|
||||
}
|
||||
|
||||
self.transform_to_viewport_including_local(layer, self.local_transform_feeds(layer, network_interface))
|
||||
}
|
||||
|
||||
/// 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 mut use_local = true;
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
|
||||
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)
|
||||
@@ -148,10 +140,12 @@ impl DocumentMetadata {
|
||||
.upstream_flow_back_from_nodes(vec![path_node], &[], FlowType::HorizontalFlow)
|
||||
.any(|upstream| Some(upstream) == source)
|
||||
{
|
||||
return false;
|
||||
use_local = 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();
|
||||
|
||||
true
|
||||
footprint * local_transform
|
||||
}
|
||||
|
||||
pub fn transform_to_document_if_feeds(&self, layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DAffine2 {
|
||||
@@ -196,15 +190,6 @@ impl DocumentMetadata {
|
||||
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 {
|
||||
self.local_transforms.get(&node_id).copied().unwrap_or(DAffine2::IDENTITY)
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use structure::vector_outline_targets;
|
||||
pub use template::*;
|
||||
pub use types::*;
|
||||
pub use view::{NetworkError, NetworkView};
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::*;
|
||||
impl NodeNetworkInterface {
|
||||
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
|
||||
self.for_each_network_view_state_mut(|path, view| {
|
||||
if let Some(other_network_metadata) = other_interface.nested_metadata(path) {
|
||||
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
|
||||
*view.navigation = other_network_metadata.persistent_metadata.navigation_metadata.clone();
|
||||
}
|
||||
});
|
||||
|
||||
+16
-33
@@ -1,5 +1,4 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::LayerVectorSource;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::vector::VectorGeometry;
|
||||
|
||||
@@ -23,19 +22,6 @@ impl NodeNetworkInterface {
|
||||
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.
|
||||
/// 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
|
||||
@@ -51,7 +37,22 @@ impl NodeNetworkInterface {
|
||||
/// (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`.
|
||||
pub fn path_aware_outline_targets(&self, layer: LayerNodeIdentifier) -> Option<Vec<ClickTargetType>> {
|
||||
self.upstream_path_node_vector(layer).map(|vector| vector_outline_targets(&vector))
|
||||
let vector = self.upstream_path_node_vector(layer)?;
|
||||
|
||||
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.
|
||||
@@ -206,21 +207,3 @@ impl NodeNetworkInterface {
|
||||
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,6 +20,7 @@ use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError};
|
||||
use document_graph_storage::{Declarations, PeerId, UserId};
|
||||
use graph_craft::application_io::resource::LoadResource;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
@@ -220,19 +221,8 @@ pub(super) async fn open_document_file(
|
||||
) -> Message {
|
||||
document_locks::claim(document_id).await;
|
||||
let materialized = async {
|
||||
let container = store.open(document_key(document_id)).await.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())?;
|
||||
let mut 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())?;
|
||||
Ok::<_, String>(container)
|
||||
}
|
||||
.await;
|
||||
@@ -297,12 +287,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.
|
||||
async fn open_migrating(container: AnyContainer, resources: &dyn ResourceStorage) -> Result<GddV1, DocumentFormatError> {
|
||||
async fn open_migrating(container: AnyContainer, resources: &dyn LoadResource) -> Result<GddV1, DocumentFormatError> {
|
||||
let host = migration_compiled::CompilerHost::default();
|
||||
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 ResourceStorage) -> Option<GddV1> {
|
||||
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId, resources: &dyn LoadResource) -> Option<GddV1> {
|
||||
match open_migrating(container.clone(), resources).await {
|
||||
Ok(gdd) => return Some(gdd),
|
||||
Err(DocumentFormatError::MissingManifest) => {}
|
||||
@@ -337,12 +327,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 {
|
||||
let Some(gdd) = gdd else { return Declarations::new() };
|
||||
|
||||
// A container written before resources stayed out of it still holds some
|
||||
// Migrations store the declarations they introduce in the container, which this device's cache may not have seen
|
||||
hydrate_resources(gdd, resources, document_id).await;
|
||||
gdd.declarations(resources).await
|
||||
}
|
||||
|
||||
/// Move every resource stored in `gdd`'s container into the global cache.
|
||||
/// Copy every resource stored in `gdd`'s container that the global cache lacks into it.
|
||||
async fn hydrate_resources(gdd: &GddV1, byte_store: &ResourcesHandle, document_id: DocumentId) {
|
||||
let hashes = match gdd.resource_hashes().await {
|
||||
Ok(hashes) => hashes,
|
||||
@@ -352,20 +342,12 @@ async fn hydrate_resources(gdd: &GddV1, byte_store: &ResourcesHandle, document_i
|
||||
}
|
||||
};
|
||||
|
||||
for hash in hashes {
|
||||
if !byte_store.contains(&hash) {
|
||||
match gdd.read_resource(&hash).await {
|
||||
Ok(holder) => {
|
||||
byte_store.store(holder.as_slice());
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Opening document {document_id:?}: failed to read resource {hash}: {error}");
|
||||
continue;
|
||||
}
|
||||
for hash in hashes.into_iter().filter(|hash| !byte_store.contains(hash)) {
|
||||
match gdd.read_resource(&hash).await {
|
||||
Ok(holder) => {
|
||||
byte_store.store(holder.as_slice());
|
||||
}
|
||||
}
|
||||
if let Err(error) = gdd.remove_resource(&hash) {
|
||||
log::error!("Opening document {document_id:?}: failed to remove resource {hash}: {error}");
|
||||
Err(error) => log::error!("Opening document {document_id:?}: failed to read resource {hash}: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
//! Tints what a step changed onto a close-up of the document, colored by how the layer under each changed pixel changed.
|
||||
|
||||
use super::utility_types::Pixels;
|
||||
use glam::{DVec2, UVec2};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
Added,
|
||||
Removed,
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// Where a layer's change shows, in document coordinates.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ChangedArea {
|
||||
pub change: Change,
|
||||
pub bounds: [DVec2; 2],
|
||||
}
|
||||
|
||||
/// How far apart two premultiplied channels must be for a pixel to count as changed, out of 255.
|
||||
const THRESHOLD: u8 = 16;
|
||||
/// How much of a tint's color covers a changed pixel.
|
||||
const TINT_STRENGTH: f32 = 0.6;
|
||||
/// How opaque unchanged pixels stay, so the tints stand out.
|
||||
const UNCHANGED_OPACITY: f32 = 0.35;
|
||||
|
||||
fn tint_color(change: Change) -> [u8; 3] {
|
||||
match change {
|
||||
Change::Added => [64, 200, 96],
|
||||
Change::Removed => [232, 64, 64],
|
||||
Change::Changed => [240, 176, 32],
|
||||
}
|
||||
}
|
||||
|
||||
/// The close-up `after` of `frame` with each pixel that differs from `before`, the whole document before the step
|
||||
/// showing `before_frame`, tinted by the change of the area it falls in. A pixel that lost coverage shows as it was.
|
||||
pub fn tint_changes(after: &Pixels, frame: [DVec2; 2], before: &Pixels, before_frame: [DVec2; 2], areas: &[ChangedArea]) -> Pixels {
|
||||
let size = after.size;
|
||||
let mut rgba = Vec::with_capacity(after.rgba.len());
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let point = frame[0] + (DVec2::new(x as f64, y as f64) + 0.5) / size.as_dvec2() * (frame[1] - frame[0]);
|
||||
let now = pixel(after, UVec2::new(x, y));
|
||||
let then = sample(before, before_frame, point);
|
||||
let shown = if differs(now, then) {
|
||||
let lost = now[3] < then[3];
|
||||
tint(if lost { then } else { now }, change_at(areas, point, lost))
|
||||
} else {
|
||||
[now[0], now[1], now[2], (now[3] as f32 * UNCHANGED_OPACITY) as u8]
|
||||
};
|
||||
rgba.extend_from_slice(&shown);
|
||||
}
|
||||
}
|
||||
Pixels { size, rgba }
|
||||
}
|
||||
|
||||
/// The area around every change, with a margin, at the thumbnails' aspect ratio. None when nothing changed.
|
||||
pub fn close_up(areas: &[ChangedArea]) -> Option<[DVec2; 2]> {
|
||||
/// The thumbnails' width over their height.
|
||||
const ASPECT_RATIO: f64 = 1.5;
|
||||
|
||||
let [min, max] = areas.iter().map(|area| area.bounds).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])?;
|
||||
let margin = ((max - min) * 0.15).max(DVec2::splat(4.));
|
||||
let (min, max) = (min - margin, max + margin);
|
||||
|
||||
let size = max - min;
|
||||
let size = if size.x >= size.y * ASPECT_RATIO {
|
||||
DVec2::new(size.x, size.x / ASPECT_RATIO)
|
||||
} else {
|
||||
DVec2::new(size.y * ASPECT_RATIO, size.y)
|
||||
};
|
||||
let center = (min + max) / 2.;
|
||||
Some([center - size / 2., center + size / 2.])
|
||||
}
|
||||
|
||||
/// The change of the areas holding `point`, preferring a removal where the pixel lost coverage and an addition elsewhere.
|
||||
fn change_at(areas: &[ChangedArea], point: DVec2, lost: bool) -> Change {
|
||||
let holding = |change: Change| areas.iter().any(|area| area.change == change && contains(area.bounds, point));
|
||||
let order = match lost {
|
||||
true => [Change::Removed, Change::Changed, Change::Added],
|
||||
false => [Change::Added, Change::Changed, Change::Removed],
|
||||
};
|
||||
order.into_iter().find(|&change| holding(change)).unwrap_or(Change::Changed)
|
||||
}
|
||||
|
||||
fn contains(bounds: [DVec2; 2], point: DVec2) -> bool {
|
||||
point.cmpge(bounds[0]).all() && point.cmple(bounds[1]).all()
|
||||
}
|
||||
|
||||
fn pixel(pixels: &Pixels, at: UVec2) -> [u8; 4] {
|
||||
let index = (at.y * pixels.size.x + at.x) as usize * 4;
|
||||
pixels.rgba.get(index..index + 4).and_then(|pixel| pixel.try_into().ok()).unwrap_or([0; 4])
|
||||
}
|
||||
|
||||
/// The pixel of `pixels`, which shows `frame`, at a document point, transparent outside it.
|
||||
fn sample(pixels: &Pixels, frame: [DVec2; 2], point: DVec2) -> [u8; 4] {
|
||||
let at = (point - frame[0]) / (frame[1] - frame[0]) * pixels.size.as_dvec2();
|
||||
if at.cmplt(DVec2::ZERO).any() || at.cmpge(pixels.size.as_dvec2()).any() {
|
||||
return [0; 4];
|
||||
}
|
||||
pixel(pixels, at.as_uvec2())
|
||||
}
|
||||
|
||||
fn differs(a: [u8; 4], b: [u8; 4]) -> bool {
|
||||
let premultiplied = |pixel: [u8; 4]| pixel.map(|channel| (channel as u16 * pixel[3] as u16 / 255) as u8);
|
||||
let (a, b) = (premultiplied(a), premultiplied(b));
|
||||
a.iter().zip(&b).any(|(a, b)| a.abs_diff(*b) > THRESHOLD) || a[3].abs_diff(b[3]) > THRESHOLD
|
||||
}
|
||||
|
||||
fn tint(pixel: [u8; 4], change: Change) -> [u8; 4] {
|
||||
let color = tint_color(change);
|
||||
let mix = |channel: u8, tint: u8| (channel as f32 + (tint as f32 - channel as f32) * TINT_STRENGTH) as u8;
|
||||
[mix(pixel[0], color[0]), mix(pixel[1], color[1]), mix(pixel[2], color[2]), pixel[3]]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FRAME: [DVec2; 2] = [DVec2::ZERO, DVec2::new(4., 2.)];
|
||||
const CLEAR: [u8; 4] = [0; 4];
|
||||
const WHITE: [u8; 4] = [255; 4];
|
||||
|
||||
/// A 4×2 image of the given pixels, row by row.
|
||||
fn image(pixels: [[u8; 4]; 8]) -> Pixels {
|
||||
Pixels {
|
||||
size: UVec2::new(4, 2),
|
||||
rgba: pixels.concat(),
|
||||
}
|
||||
}
|
||||
|
||||
fn left_half(change: Change) -> ChangedArea {
|
||||
ChangedArea {
|
||||
change,
|
||||
bounds: [DVec2::ZERO, DVec2::new(2., 2.)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_stayed_fades_and_what_came_is_tinted_as_added() {
|
||||
let before = image([CLEAR; 8]);
|
||||
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Added)]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Added));
|
||||
assert_eq!(pixel(&tinted, UVec2::new(3, 1))[3], 0, "transparent pixels that stayed stay transparent");
|
||||
|
||||
let unchanged = tint_changes(&after, FRAME, &after, FRAME, &[]);
|
||||
assert_eq!(pixel(&unchanged, UVec2::new(0, 0))[3], (255. * UNCHANGED_OPACITY) as u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_went_shows_as_it_was_tinted_as_removed() {
|
||||
let before = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let after = image([CLEAR; 8]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Removed)]);
|
||||
|
||||
let removed = pixel(&tinted, UVec2::new(1, 1));
|
||||
assert_eq!(removed, tint(WHITE, Change::Removed));
|
||||
assert_eq!(removed[3], 255, "a removed pixel keeps the coverage it had");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_layer_is_tinted_as_changed_where_it_was_and_where_it_is() {
|
||||
let before = image([WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
|
||||
let after = image([CLEAR, WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Changed)]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Changed), "where it was");
|
||||
assert_eq!(pixel(&tinted, UVec2::new(1, 0)), tint(WHITE, Change::Changed), "where it is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_close_up_samples_the_whole_document_before_at_its_own_scale() {
|
||||
// The before image shows twice the area, so its left pixel column covers the close-up's left two
|
||||
let before = image([WHITE, CLEAR, CLEAR, CLEAR, WHITE, CLEAR, CLEAR, CLEAR]);
|
||||
let before_frame = [DVec2::ZERO, DVec2::new(8., 4.)];
|
||||
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, before_frame, &[]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(1, 0))[3], (255. * UNCHANGED_OPACITY) as u8, "still covered, so unchanged");
|
||||
assert_eq!(pixel(&tinted, UVec2::new(2, 0))[3], 0);
|
||||
}
|
||||
}
|
||||
@@ -5,39 +5,13 @@ use crate::messages::prelude::*;
|
||||
pub enum HistoryMessage {
|
||||
Refresh,
|
||||
Tick,
|
||||
Expand {
|
||||
id: String,
|
||||
expanded: bool,
|
||||
},
|
||||
Expand { id: String, expanded: bool },
|
||||
LoadMore,
|
||||
GoBack {
|
||||
id: String,
|
||||
},
|
||||
RemoveStep {
|
||||
id: String,
|
||||
},
|
||||
BringBack {
|
||||
id: String,
|
||||
},
|
||||
Follow {
|
||||
id: Option<String>,
|
||||
},
|
||||
Preview {
|
||||
id: Option<String>,
|
||||
},
|
||||
GoBack { id: String },
|
||||
RemoveStep { id: String },
|
||||
BringBack { id: String },
|
||||
Follow { id: Option<String> },
|
||||
RetirePending,
|
||||
Rename {
|
||||
id: String,
|
||||
label: String,
|
||||
},
|
||||
Tag {
|
||||
id: String,
|
||||
tag: String,
|
||||
on: bool,
|
||||
},
|
||||
Captured {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
capture: Option<Box<super::utility_types::DocumentCapture>>,
|
||||
},
|
||||
Rename { id: String, label: String },
|
||||
Tag { id: String, tag: String, on: bool },
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,3 @@
|
||||
mod changes;
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
@@ -7,4 +6,3 @@ pub mod utility_types;
|
||||
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
|
||||
pub(crate) use history_message_handler::{Place, place};
|
||||
@@ -1,39 +1,5 @@
|
||||
//! What the History panel shows, as the frontend receives it, and the changes it asks of the head's line.
|
||||
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The document as rendered once a step is done, for the History panel to show and compare.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DocumentCapture {
|
||||
/// The whole document.
|
||||
pub image: CaptureImage,
|
||||
/// The document area `image` shows.
|
||||
pub frame: [DVec2; 2],
|
||||
/// The area asked for in detail, and its image.
|
||||
pub detail: Option<([DVec2; 2], CaptureImage)>,
|
||||
/// The proto node giving each layer's own content, whose ID changes with that content.
|
||||
pub layer_sources: HashMap<NodeId, NodeId>,
|
||||
/// Where each layer's own content lies, measured alike for the current state and past ones, which the editor holds no
|
||||
/// layer metadata for.
|
||||
pub layer_bounds: Option<HashMap<NodeId, [DVec2; 2]>>,
|
||||
}
|
||||
|
||||
/// A capture rendered like the layer thumbnails: pixels from Vello, or an SVG for the frontend to draw when the GPU is unavailable.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum CaptureImage {
|
||||
Pixels(Pixels),
|
||||
Svg(String),
|
||||
}
|
||||
|
||||
/// Straight RGBA pixels, row by row.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Pixels {
|
||||
pub size: glam::UVec2,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum LineChange {
|
||||
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
|
||||
@@ -53,8 +19,6 @@ pub struct HistoryPanelState {
|
||||
pub progress: Vec<HistoryProgressRow>,
|
||||
pub more: bool,
|
||||
pub following: Option<String>,
|
||||
/// The step the document shows in place of its current state.
|
||||
pub previewing: Option<String>,
|
||||
/// Whether others are connected.
|
||||
pub collaborating: bool,
|
||||
}
|
||||
@@ -84,17 +48,6 @@ pub struct HistoryRow {
|
||||
pub head: bool,
|
||||
pub expanded: bool,
|
||||
pub details: Vec<HistoryDeltaRow>,
|
||||
/// How the document looked once this step was done, if the panel was open to capture it.
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryThumbnail {
|
||||
/// The ID the frontend received the whole document's image under.
|
||||
pub whole: String,
|
||||
/// The ID of a close-up of what the step changed, tinted by how, when the step before was captured too.
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -126,5 +79,4 @@ pub struct HistoryProgressRow {
|
||||
pub ops: u32,
|
||||
/// Still being made, not closed and waiting.
|
||||
pub open: bool,
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
@@ -60,7 +60,7 @@ pub struct PortfolioMessageHandler {
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
ingest: IngestMessageHandler,
|
||||
pub(crate) history: HistoryMessageHandler,
|
||||
history: HistoryMessageHandler,
|
||||
sync: SyncMessageHandler,
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
@@ -144,7 +144,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
|
||||
executor: &self.executor,
|
||||
};
|
||||
self.history.process_message(message, responses, context);
|
||||
}
|
||||
@@ -167,7 +166,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
has_no_documents: self.document_ids.is_empty(),
|
||||
};
|
||||
self.workspace.process_message(message, responses, context);
|
||||
self.end_history_preview_without_panel(responses);
|
||||
}
|
||||
|
||||
// Messages
|
||||
@@ -270,7 +268,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
let Some(document) = self.documents.get_mut(&document_id) else { return };
|
||||
let Some(container) = document.container.clone() else { return };
|
||||
|
||||
document.with_current_state(|document| match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) {
|
||||
match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) {
|
||||
Ok(()) => {
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut());
|
||||
document.set_auto_save_state(true);
|
||||
@@ -283,7 +281,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
description: format!("Save your documents manually to avoid losing changes.\n\n{error}"),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
responses.add(PersistentStateMessage::WriteState);
|
||||
}
|
||||
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
|
||||
@@ -943,8 +941,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
self.active_document_id = Some(document_id);
|
||||
self.restore_select = None;
|
||||
|
||||
self.end_history_preview_without_panel(responses);
|
||||
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(FrontendMessage::UpdateActiveDocument { document_id });
|
||||
@@ -1217,14 +1213,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
|
||||
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 {
|
||||
Self {
|
||||
documents: Default::default(),
|
||||
|
||||
@@ -29,20 +29,18 @@ pub fn draw_for_selected_layers(overlay_context: &mut OverlayContext, document:
|
||||
continue;
|
||||
}
|
||||
|
||||
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
|
||||
// A transformation from the layer's local space to the viewport space (where overlays are drawn)
|
||||
let transform_to_viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
overlay_context.follow_layer(layer, layer_to_viewport, move |overlay_context, movement| {
|
||||
let layer_to_viewport = movement * layer_to_viewport;
|
||||
// The origin of the layer in viewport space which is the center of the origin cross
|
||||
let origin_viewport = transform_to_viewport.transform_point2(DVec2::ZERO);
|
||||
// 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();
|
||||
|
||||
// The origin of the layer in viewport space which is the center of the origin cross
|
||||
let origin_viewport = layer_to_viewport.transform_point2(DVec2::ZERO);
|
||||
// The forward +X direction vector from layer space (used to orient the origin cross)
|
||||
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));
|
||||
}
|
||||
});
|
||||
// Draw 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.);
|
||||
for offset in offsets {
|
||||
overlay_context.line(origin_viewport - offset, origin_viewport + offset, Some(COLOR_OVERLAY_BLUE), Some(LAYER_ORIGIN_CROSS_THICKNESS));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -382,14 +382,6 @@ pub struct 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
|
||||
pub fn evaluate_transform_handle_positions(&self) -> [DVec2; 8] {
|
||||
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::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::network_interface::{FlowType, NodeNetworkInterface, NodeTemplate, vector_outline_targets};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeNetworkInterface, NodeTemplate};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
@@ -875,17 +875,11 @@ impl SelectToolData {
|
||||
/// (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>) {
|
||||
if let Some(targets) = document.network_interface.path_aware_outline_targets(layer) {
|
||||
let source = document.network_interface.layer_vector_source(layer);
|
||||
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()),
|
||||
});
|
||||
let layer_to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
|
||||
overlay_context.outline(targets.iter(), layer_to_viewport, color);
|
||||
} else {
|
||||
let metadata = document.metadata();
|
||||
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);
|
||||
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
|
||||
overlay_context.outline(document.metadata().layer_with_free_points_outline(layer), layer_to_viewport, color);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -902,38 +896,6 @@ pub fn create_bounding_box_transform(document: &DocumentMessageHandler) -> DAffi
|
||||
.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 {
|
||||
type ToolData = SelectToolData;
|
||||
type ToolOptions = ();
|
||||
@@ -973,9 +935,7 @@ impl Fsm for SelectToolFsmState {
|
||||
if document.metadata().is_text_layer(layer) {
|
||||
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
|
||||
let transformed_quad = layer_to_viewport * text_bounding_box(layer, document, fonts, responses);
|
||||
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);
|
||||
});
|
||||
overlay_context.dashed_quad(transformed_quad, None, None, Some(7.), Some(5.), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1087,10 +1047,7 @@ impl Fsm for SelectToolFsmState {
|
||||
bounding_box_manager.transform = transform;
|
||||
bounding_box_manager.transform_tampered = transform_tampered;
|
||||
if overlay_context.visibility_settings.transform_cage() {
|
||||
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)
|
||||
});
|
||||
bounding_box_manager.render_overlays(&mut overlay_context, true);
|
||||
}
|
||||
} else {
|
||||
tool_data.bounding_box_manager.take();
|
||||
@@ -1130,10 +1087,7 @@ impl Fsm for SelectToolFsmState {
|
||||
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));
|
||||
if is_skewing || (dragging_bounds && is_near_square && !is_resizing_or_rotating) {
|
||||
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)
|
||||
});
|
||||
bounds.render_skew_gizmos(&mut overlay_context, tool_data.skew_edge);
|
||||
}
|
||||
if !is_skewing
|
||||
&& dragging_bounds
|
||||
@@ -1193,14 +1147,14 @@ impl Fsm for SelectToolFsmState {
|
||||
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);
|
||||
if Some(layer) == tool_data.pivot_gizmo.layer {
|
||||
active_origin = Some((layer, origin));
|
||||
active_origin = Some(origin);
|
||||
continue;
|
||||
}
|
||||
draw_dowel_pin(&mut overlay_context, document, layer, origin, origin_angle, None);
|
||||
overlay_context.dowel_pin(origin, origin_angle, None);
|
||||
}
|
||||
}
|
||||
if let Some((layer, origin)) = active_origin {
|
||||
draw_dowel_pin(&mut overlay_context, document, layer, origin, origin_angle, Some(COLOR_OVERLAY_YELLOW));
|
||||
if let Some(origin) = active_origin {
|
||||
overlay_context.dowel_pin(origin, origin_angle, Some(COLOR_OVERLAY_YELLOW));
|
||||
}
|
||||
|
||||
let has_layers = document.network_interface.selected_nodes().has_selected_nodes();
|
||||
@@ -1219,10 +1173,7 @@ impl Fsm for SelectToolFsmState {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let shift = tool_data.pivot_gizmo_shift.unwrap_or_default();
|
||||
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))
|
||||
});
|
||||
overlay_context.pivot(pivot + offset + shift, angle);
|
||||
}
|
||||
|
||||
// Update compass rose
|
||||
@@ -1233,9 +1184,7 @@ impl Fsm for SelectToolFsmState {
|
||||
tool_data.line_center = compass_center;
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
overlay_context.compass_rose(compass_center, angle, show_compass_with_ring);
|
||||
|
||||
let axis_state = if let SelectToolFsmState::Dragging { axis, .. } = self {
|
||||
Some((axis, false))
|
||||
|
||||
@@ -99,12 +99,6 @@ pub enum NodeGraphUpdate {
|
||||
responses: VecDeque<FrontendMessage>,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
DocumentCapture {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
/// `None` when a newer graph replaced the one the request was for, so it can be asked again.
|
||||
capture: Option<Box<crate::messages::portfolio::history::utility_types::DocumentCapture>>,
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
@@ -257,36 +251,6 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the thumbnails in view");
|
||||
}
|
||||
|
||||
/// Asks for the document as rendered once what was submitted before has run, for the History panel's `step`, with the area `detail` close up.
|
||||
/// Returns false when the runtime doesn't hold the document's graph as it is now, so nothing was asked.
|
||||
pub fn submit_document_capture(&self, document: &DocumentMessageHandler, document_id: DocumentId, step: document_graph_storage::TimeStamp, detail: Option<[DVec2; 2]>) -> bool {
|
||||
if self.node_graph_document != Some(document_id) || self.node_graph_hash != document.network_interface.network_hash() {
|
||||
return false;
|
||||
}
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::CaptureDocument { document_id, step, detail })
|
||||
.expect("Failed to send the capture request");
|
||||
true
|
||||
}
|
||||
|
||||
/// Asks for a past state of the document, `network` with its `layers`, rendered for the History panel's `step` like
|
||||
/// [`submit_document_capture`](Self::submit_document_capture) renders the current one. Returns false when the runtime
|
||||
/// holds another document's graph, which the past state wouldn't share any nodes with.
|
||||
pub fn submit_past_capture(&self, document_id: DocumentId, step: document_graph_storage::TimeStamp, network: NodeNetwork, layers: Vec<Vec<NodeId>>, detail: Option<[DVec2; 2]>) -> bool {
|
||||
if self.node_graph_document != Some(document_id) {
|
||||
return false;
|
||||
}
|
||||
let past = runtime::PastCapture {
|
||||
document_id,
|
||||
step,
|
||||
network,
|
||||
layers,
|
||||
detail,
|
||||
};
|
||||
self.sender.send(GraphRuntimeRequest::CapturePast(past)).expect("Failed to send the capture request");
|
||||
true
|
||||
}
|
||||
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
@@ -796,7 +760,6 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -816,7 +779,6 @@ impl NodeGraphExecutor {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
||||
use crate::messages::portfolio::history::utility_types::DocumentCapture;
|
||||
use crate::task::{Spawn, Spawner, Task};
|
||||
use glam::UVec2;
|
||||
use graph_craft::application_io::resource::{Resource, ResourceRegistry};
|
||||
@@ -10,7 +9,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
|
||||
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors, ProtoNetwork};
|
||||
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
@@ -53,16 +52,10 @@ pub struct NodeRuntime {
|
||||
pending_export: Option<ExecutionRequest>,
|
||||
pending_eyedropper: Option<ExecutionRequest>,
|
||||
pending_thumbnails: Option<DocumentId>,
|
||||
/// The step the History panel wants the document captured for, once what is pending has run.
|
||||
pending_capture: Option<(DocumentId, document_graph_storage::TimeStamp, Option<[DVec2; 2]>)>,
|
||||
/// A past state the History panel wants captured, once nothing else is waiting to run.
|
||||
pending_past: Option<PastCapture>,
|
||||
/// The network the executor last compiled successfully, with previews applied.
|
||||
old_graph: Option<NodeNetwork>,
|
||||
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
||||
compile_failed: bool,
|
||||
/// What `old_graph` compiled to, which a past state is compiled alongside.
|
||||
compiled: Option<ProtoNetwork>,
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
@@ -81,12 +74,8 @@ pub struct NodeRuntime {
|
||||
wasm_canvas_cache: CanvasSurfaceHandle,
|
||||
/// The viewport's latest artwork.
|
||||
viewport_artwork: Option<Texture>,
|
||||
/// The layers from the render of the viewport's latest artwork.
|
||||
rendered_layers: RenderedLayers,
|
||||
/// The latest overlays, rendered again over each new artwork.
|
||||
overlays: Option<OverlayContext>,
|
||||
/// Whether the overlays or the artwork changed since the overlays were last rendered.
|
||||
overlays_stale: bool,
|
||||
/// The overlays to render once the viewport has artwork.
|
||||
pending_overlays: Option<OverlayContext>,
|
||||
overlays_canvas: VelloCanvas,
|
||||
/// The latest rendered overlays.
|
||||
overlays_texture: Option<Texture>,
|
||||
@@ -111,13 +100,6 @@ pub enum GraphRuntimeRequest {
|
||||
layers: Vec<NodeId>,
|
||||
},
|
||||
RenderOverlays(OverlayContext),
|
||||
CaptureDocument {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
/// The area to render close up as well.
|
||||
detail: Option<[DVec2; 2]>,
|
||||
},
|
||||
CapturePast(PastCapture),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -132,18 +114,6 @@ pub struct GraphUpdate {
|
||||
pub(super) observations: HashMap<ObservationKey, Observation>,
|
||||
}
|
||||
|
||||
/// A past state of a document to render like [`GraphRuntimeRequest::CaptureDocument`] renders the current one.
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PastCapture {
|
||||
pub(super) document_id: DocumentId,
|
||||
pub(super) step: document_graph_storage::TimeStamp,
|
||||
pub(super) network: NodeNetwork,
|
||||
/// Full path from the root network to every layer of the past state.
|
||||
pub(super) layers: Vec<Vec<NodeId>>,
|
||||
/// The area to render close up as well.
|
||||
pub(super) detail: Option<[DVec2; 2]>,
|
||||
}
|
||||
|
||||
/// Replaces each network's primary export with its previewed node.
|
||||
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
|
||||
for (network_path, previewed) in previewed {
|
||||
@@ -198,11 +168,8 @@ impl NodeRuntime {
|
||||
pending_export: None,
|
||||
pending_eyedropper: None,
|
||||
pending_thumbnails: None,
|
||||
pending_capture: None,
|
||||
pending_past: None,
|
||||
old_graph: None,
|
||||
compile_failed: false,
|
||||
compiled: None,
|
||||
resources: ResourceRegistry::default(),
|
||||
async_runtime: None,
|
||||
|
||||
@@ -226,9 +193,7 @@ impl NodeRuntime {
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle::new(),
|
||||
viewport_artwork: None,
|
||||
rendered_layers: RenderedLayers::default(),
|
||||
overlays: None,
|
||||
overlays_stale: false,
|
||||
pending_overlays: None,
|
||||
overlays_canvas: VelloCanvas::default(),
|
||||
overlays_texture: None,
|
||||
}
|
||||
@@ -242,15 +207,7 @@ impl NodeRuntime {
|
||||
let mut graph = None;
|
||||
for request in self.receiver.try_iter() {
|
||||
match request {
|
||||
GraphRuntimeRequest::GraphUpdate(update) => {
|
||||
graph = Some(update);
|
||||
// The graph may be another document's, or show a later step than the one asked for
|
||||
if let Some((document_id, step, _)) = self.pending_capture.take() {
|
||||
self.sender
|
||||
.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture: None })
|
||||
.expect("Failed to send response");
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
|
||||
self.pending_export = Some(request);
|
||||
@@ -265,8 +222,6 @@ impl NodeRuntime {
|
||||
self.thumbnails.set_in_view(layers);
|
||||
self.pending_thumbnails = Some(document_id);
|
||||
}
|
||||
GraphRuntimeRequest::CaptureDocument { document_id, step, detail } => self.pending_capture = Some((document_id, step, detail)),
|
||||
GraphRuntimeRequest::CapturePast(past) => self.pending_past = Some(past),
|
||||
// A graph update applied after this loop would otherwise replace this with what it observed before
|
||||
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
|
||||
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
|
||||
@@ -280,10 +235,7 @@ impl NodeRuntime {
|
||||
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
|
||||
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
||||
}
|
||||
GraphRuntimeRequest::RenderOverlays(context) => {
|
||||
self.overlays = Some(context);
|
||||
self.overlays_stale = true;
|
||||
}
|
||||
GraphRuntimeRequest::RenderOverlays(context) => self.pending_overlays = Some(context),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,7 +260,7 @@ impl NodeRuntime {
|
||||
let result = self.update_network(&network);
|
||||
self.compile_failed = result.is_err();
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &thumbnails::compiled_sources(&self.executor));
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
self.old_graph = Some(network);
|
||||
}
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
@@ -359,33 +311,9 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||
if self.overlays_stale {
|
||||
if self.pending_overlays.is_some() {
|
||||
texture = self.composite_viewport_frame();
|
||||
}
|
||||
|
||||
if let Some((document_id, step, detail)) = self.pending_capture.take() {
|
||||
let capture = match &self.old_graph {
|
||||
Some(network) => {
|
||||
self.thumbnails
|
||||
.capture_document(network, &self.executor, &thumbnails::compiled_sources(&self.executor), &self.editor_api, detail)
|
||||
.await
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let capture = capture.map(|mut capture| {
|
||||
capture.layer_bounds = Some(self.thumbnails.layer_bounds(&self.executor));
|
||||
Box::new(capture)
|
||||
});
|
||||
self.sender.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture }).expect("Failed to send response");
|
||||
}
|
||||
|
||||
if viewport.is_none()
|
||||
&& let Some(past) = self.pending_past.take()
|
||||
{
|
||||
let capture = self.capture_past(&past).await.map(Box::new);
|
||||
let (document_id, step) = (past.document_id, past.step);
|
||||
self.sender.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture }).expect("Failed to send response");
|
||||
}
|
||||
}
|
||||
|
||||
(self.editor_wake)();
|
||||
@@ -396,15 +324,11 @@ impl NodeRuntime {
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let mut result = self.evaluate(request)?;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
|
||||
let texture = if let Some(data) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
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();
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
@@ -421,7 +345,7 @@ impl NodeRuntime {
|
||||
};
|
||||
|
||||
self.resolve_effect_maps(&mut result).await;
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(request.execution_id, result).await;
|
||||
texture
|
||||
}
|
||||
|
||||
@@ -433,11 +357,9 @@ impl NodeRuntime {
|
||||
return None;
|
||||
};
|
||||
|
||||
if std::mem::take(&mut self.overlays_stale)
|
||||
&& let Some(overlays) = &self.overlays
|
||||
{
|
||||
if let Some(overlays) = self.pending_overlays.take() {
|
||||
self.overlays_texture = executor
|
||||
.render_vello_scene_on_canvas(&mut self.overlays_canvas, overlays.render(&self.rendered_layers))
|
||||
.render_vello_scene_on_canvas(&mut self.overlays_canvas, overlays.take_scene())
|
||||
.inspect_err(|error| log::error!("Failed to render the overlays: {error:?}"))
|
||||
.ok();
|
||||
}
|
||||
@@ -476,15 +398,14 @@ impl NodeRuntime {
|
||||
let Some(mut result) = result else { return };
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
|
||||
if let Some(RenderOutput { data, .. }) = result.render_output()
|
||||
if let Some(data) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
self.resolve_effect_maps(&mut result).await;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(request.execution_id, result).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
@@ -495,10 +416,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
if let Some(mut result) = self.evaluate(request)
|
||||
&& let Some(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
}) = result.render_output()
|
||||
&& let Some(RenderOutputType::Texture(texture)) = result.render_output()
|
||||
{
|
||||
let raster = self.read_back(texture.clone()).await;
|
||||
self.sender.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response");
|
||||
@@ -543,11 +461,12 @@ impl NodeRuntime {
|
||||
Some(result)
|
||||
}
|
||||
|
||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
@@ -569,11 +488,7 @@ 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.
|
||||
async fn resolve_effect_maps(&self, result: &mut ExecutionResult) {
|
||||
let Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, effect_maps, .. },
|
||||
..
|
||||
}) = result.render_output()
|
||||
else {
|
||||
let Some(RenderOutputType::Svg { svg, effect_maps, .. }) = result.render_output() else {
|
||||
return;
|
||||
};
|
||||
if effect_maps.is_empty() {
|
||||
@@ -592,8 +507,7 @@ impl NodeRuntime {
|
||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||
}
|
||||
|
||||
/// Compiles a document network to the proto network the executor runs.
|
||||
fn compile(&mut self, graph: &NodeNetwork) -> Result<CompiledNetwork, CompileError> {
|
||||
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph.clone(), self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
// A missing resource compiles as the empty one, which its consumers draw with a fallback, and warns on the nodes using it
|
||||
@@ -605,21 +519,17 @@ impl NodeRuntime {
|
||||
})
|
||||
};
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &resolve_resource) {
|
||||
return Err(CompileError::Message(e.to_string()));
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
}
|
||||
if resource_missing.get() {
|
||||
self.node_graph_warnings = missing_resource_warnings(graph, &self.resources);
|
||||
}
|
||||
|
||||
// We assume only one output
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
let mut compiled_network = Compiler {}.compile_single(scoped_network)?;
|
||||
if resource_missing.get() {
|
||||
compiled_network.warnings.splice(0..0, missing_resource_warnings(graph, &self.resources));
|
||||
}
|
||||
Ok(compiled_network)
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let CompiledNetwork { network: proto_network, warnings } = match self.compile(graph) {
|
||||
let c = Compiler {};
|
||||
let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
|
||||
Ok(compiled_network) => compiled_network,
|
||||
Err(CompileError::Graph(errors)) => {
|
||||
let message = format!("{errors:?}");
|
||||
@@ -628,61 +538,17 @@ impl NodeRuntime {
|
||||
}
|
||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
||||
};
|
||||
self.node_graph_warnings = warnings;
|
||||
self.node_graph_warnings.extend(warnings);
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
let compiled = proto_network.clone();
|
||||
let result = self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
self.node_graph_errors.clone_from(&e);
|
||||
(types, format!("{e:?}"))
|
||||
});
|
||||
self.compiled = result.is_ok().then_some(compiled);
|
||||
self.async_runtime().update_sources(self.executor.sources());
|
||||
result
|
||||
}
|
||||
|
||||
/// Renders a past state of the document, compiled alongside the current graph as a second output. A proto node's ID
|
||||
/// hashes everything upstream of it, so what the two states share is one node, which keeps its cache. The current
|
||||
/// nodes go in last, so the executor still names them for their document paths, and the past state's own nodes are
|
||||
/// freed once a later graph update leaves them out.
|
||||
async fn capture_past(&mut self, past: &PastCapture) -> Option<DocumentCapture> {
|
||||
let current = self.compiled.clone()?;
|
||||
let CompiledNetwork { network: past_network, .. } = self
|
||||
.compile(&past.network)
|
||||
.inspect_err(|error| log::warn!("The History panel's past state didn't compile: {error:?}"))
|
||||
.ok()?;
|
||||
|
||||
let past_output = past_network.output;
|
||||
let past_sources: HashMap<Vec<NodeId>, NodeId> = past_network.nodes.iter().filter_map(|(id, node)| Some((node.original_location.path.clone()?, *id))).collect();
|
||||
let current_ids: HashSet<NodeId> = current.nodes.iter().map(|(id, _)| *id).collect();
|
||||
let mut merged = current.clone();
|
||||
merged.nodes = past_network.nodes.into_iter().filter(|(id, _)| !current_ids.contains(id)).chain(current.nodes).collect();
|
||||
if let Err((_, error)) = self.executor.update(merged) {
|
||||
log::warn!("The History panel's past state didn't compile alongside the document: {error:?}");
|
||||
return None;
|
||||
}
|
||||
self.async_runtime().update_sources(self.executor.sources());
|
||||
|
||||
// Thumbnail content evaluates from the context it last ran in, so the past state runs once as the viewport does
|
||||
let mut render_config = self.pending?.render_config;
|
||||
if render_config.export_format == ExportFormat::Raster && self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_none() {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let evaluated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(past_output, &context)));
|
||||
if !matches!(evaluated, Ok(Ok(_))) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let source_of = |path: &[NodeId]| past_sources.get(path).copied();
|
||||
let mut thumbnails = Thumbnails::new();
|
||||
thumbnails.set_scale(self.thumbnails.scale());
|
||||
thumbnails.update_sources(&past.layers, &past.network, &source_of);
|
||||
let mut capture = thumbnails.capture_document(&past.network, &self.executor, &source_of, &self.editor_api, past.detail).await?;
|
||||
capture.layer_bounds = Some(thumbnails.layer_bounds(&self.executor));
|
||||
Some(capture)
|
||||
}
|
||||
|
||||
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
||||
let source_map = self.executor.tree().source_map();
|
||||
let paths = |node: NodeId| -> NodePaths {
|
||||
@@ -713,10 +579,10 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
impl ExecutionResult {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutputType> {
|
||||
let (Self::Value(value) | Self::Fallback(value, _)) = self else { return None };
|
||||
let TaggedValue::RenderOutput(output) = value else { return None };
|
||||
Some(output)
|
||||
let TaggedValue::RenderOutput(RenderOutput { data, .. }) = value else { return None };
|
||||
Some(data)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::evaluated_output;
|
||||
use crate::messages::frontend::FrontendMessage;
|
||||
use crate::messages::portfolio::history::utility_types::{CaptureImage, DocumentCapture, Pixels};
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
@@ -27,14 +26,6 @@ mod atlas;
|
||||
/// The time thumbnails are evaluated at, so they don't depend on the playhead.
|
||||
const THUMBNAIL_TIME: f64 = 0.;
|
||||
|
||||
/// Finds the proto node compiled from the document node at a path.
|
||||
pub type SourceLookup<'a> = &'a dyn Fn(&[NodeId]) -> Option<NodeId>;
|
||||
|
||||
/// Looks paths up in what `executor` last compiled.
|
||||
pub fn compiled_sources(executor: &DynamicExecutor) -> impl Fn(&[NodeId]) -> Option<NodeId> + '_ {
|
||||
|path| executor.tree().source_map().get(path).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
/// The size in pixels of a thumbnail rendered at this device pixel ratio.
|
||||
fn cell_size(scale: f64) -> UVec2 {
|
||||
/// The size thumbnails are shown at in the node graph, in CSS pixels.
|
||||
@@ -92,11 +83,11 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
|
||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, source_of: SourceLookup) {
|
||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
|
||||
// O(layers * depth)
|
||||
let sources: HashMap<NodeId, NodeId> = layer_paths
|
||||
.iter()
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, source_of)?)))
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
|
||||
.collect();
|
||||
|
||||
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
|
||||
@@ -225,71 +216,22 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
|
||||
self.show_svg(layer, content.svg(), responses).await;
|
||||
}
|
||||
|
||||
/// Renders the whole document as the network's export gives it, and the area `detail` close up, the way layer
|
||||
/// thumbnails are rendered, along with what each layer currently shows.
|
||||
pub async fn capture_document(
|
||||
&self,
|
||||
network: &NodeNetwork,
|
||||
executor: &DynamicExecutor,
|
||||
source_of: SourceLookup<'_>,
|
||||
editor_api: &PlatformEditorApi,
|
||||
detail: Option<[DVec2; 2]>,
|
||||
) -> Option<DocumentCapture> {
|
||||
let content = match network.exports.first().and_then(|export| network.input_source(&[], export)) {
|
||||
Some(source) => {
|
||||
let content_node = source_of(source.as_slice())?;
|
||||
ThumbnailContent::evaluate(executor, content_node)?
|
||||
}
|
||||
// Nothing reaches the export, so the document shows nothing
|
||||
None => ThumbnailContent::Graphics(List::default()),
|
||||
let bounds = content.bounds(false);
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_translation(bounds[0]),
|
||||
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
|
||||
quality: RenderQuality::Full,
|
||||
};
|
||||
|
||||
let maps_resolved = editor_api.application_io.as_ref().and_then(|io| io.gpu_executor()).is_some();
|
||||
let frame = content.bounds(maps_resolved);
|
||||
let frames: Vec<[DVec2; 2]> = std::iter::once(frame).chain(detail).collect();
|
||||
let mut images: Vec<CaptureImage> = match self.render_frames_with_vello(&content, &frames, editor_api).await {
|
||||
Some(pixels) => pixels.into_iter().map(CaptureImage::Pixels).collect(),
|
||||
None => frames.iter().map(|&frame| CaptureImage::Svg(content.svg_of(frame))).collect(),
|
||||
let render_params = RenderParams {
|
||||
footprint,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let detail_image = (images.len() > 1).then(|| images.pop()).flatten();
|
||||
Some(DocumentCapture {
|
||||
image: images.pop()?,
|
||||
frame,
|
||||
detail: detail.zip(detail_image),
|
||||
layer_sources: self.sources.clone(),
|
||||
layer_bounds: None,
|
||||
})
|
||||
}
|
||||
let mut render = SvgRender::new();
|
||||
content.graphic().render_svg(&mut render, &render_params);
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
|
||||
pub fn scale(&self) -> f64 {
|
||||
self.scale
|
||||
}
|
||||
|
||||
/// Where each layer's own content lies, from the content its thumbnail shows.
|
||||
pub fn layer_bounds(&self, executor: &DynamicExecutor) -> HashMap<NodeId, [DVec2; 2]> {
|
||||
let bounds = |source: NodeId| ThumbnailContent::evaluate(executor, source)?.content_bounds(true);
|
||||
self.sources.iter().filter_map(|(&layer, &source)| Some((layer, bounds(source)?))).collect()
|
||||
}
|
||||
|
||||
/// Renders each frame of the content into a cell the size of a layer thumbnail, giving none if Vello is unavailable.
|
||||
async fn render_frames_with_vello(&self, content: &ThumbnailContent, frames: &[[DVec2; 2]], editor_api: &PlatformEditorApi) -> Option<Vec<Pixels>> {
|
||||
let executor = editor_api.application_io.as_ref()?.gpu_executor()?;
|
||||
let cell_size = cell_size(self.scale);
|
||||
let size = UVec2::new(cell_size.x * frames.len() as u32, cell_size.y);
|
||||
|
||||
let texture = executor.render_vello(size, DAffine2::IDENTITY, &mut |scene| atlas::draw_frames(scene, cell_size, content, frames));
|
||||
let texture = texture.inspect_err(|error| log::error!("Failed to render the document capture: {error}")).ok()?;
|
||||
let raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await;
|
||||
let (pixels, _, _) = raster.to_flat_u8();
|
||||
|
||||
let cell = |index: usize| Pixels {
|
||||
size: cell_size,
|
||||
rgba: atlas::cell_pixels(&pixels, size.x, cell_size, UVec2::new(index as u32 * cell_size.x, 0)),
|
||||
};
|
||||
Some((0..frames.len()).map(cell).collect())
|
||||
self.show_svg(layer, render.svg.to_svg_string(), responses).await;
|
||||
}
|
||||
|
||||
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
|
||||
@@ -394,59 +336,40 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
fn svg(&self) -> String {
|
||||
self.svg_of(self.bounds(false))
|
||||
}
|
||||
|
||||
/// The SVG of the area `bounds`.
|
||||
fn svg_of(&self, bounds: [DVec2; 2]) -> String {
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_translation(bounds[0]),
|
||||
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
|
||||
quality: RenderQuality::Full,
|
||||
};
|
||||
let render_params = RenderParams {
|
||||
footprint,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
self.graphic().render_svg(&mut render, &render_params);
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
render.svg.to_svg_string()
|
||||
}
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self, maps_resolved: bool) -> [DVec2; 2] {
|
||||
expand_to_thumbnail_aspect(self.content_bounds(maps_resolved).unwrap_or([DVec2::ZERO, DVec2::ONE]))
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered, if it has any extent, counting the effects drawn through maps and images only if they're `maps_resolved`, which an SVG without a GPU leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> Option<[DVec2; 2]> {
|
||||
let bounds = match self {
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which an SVG without a GPU leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||
};
|
||||
match bounds {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self, maps_resolved: bool) -> [DVec2; 2] {
|
||||
let bounds = match self.content_bounds(maps_resolved) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||
_ => [DVec2::ZERO, DVec2::ONE],
|
||||
};
|
||||
expand_to_thumbnail_aspect(bounds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
|
||||
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
||||
let contents: Vec<ThumbnailContent> = layers
|
||||
.iter()
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, &compiled_sources(executor))?))
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||
.collect();
|
||||
|
||||
let bounds = contents
|
||||
.iter()
|
||||
.filter_map(|content| content.content_bounds(false))
|
||||
.filter_map(|content| match content.content_bounds(false) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
})
|
||||
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
||||
|
||||
let render_params = RenderParams {
|
||||
@@ -467,10 +390,10 @@ pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicEx
|
||||
}
|
||||
|
||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, source_of: SourceLookup) -> Option<NodeId> {
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
source_of(source.as_slice())
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
/// Converts the other kinds of graphical content into a graphic.
|
||||
@@ -536,7 +459,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::messages::portfolio::history::utility_types::CaptureImage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -560,30 +482,6 @@ mod tests {
|
||||
editor.runtime.executor.tree().source_map().get(path).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_document_capture_shows_the_document_and_what_each_layer_shows() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let runtime = &editor.runtime;
|
||||
let network = runtime.old_graph.as_ref().expect("The document should have compiled");
|
||||
let capture = runtime
|
||||
.thumbnails
|
||||
.capture_document(network, &runtime.executor, &super::compiled_sources(&runtime.executor), &runtime.editor_api, None)
|
||||
.await;
|
||||
let capture = capture.expect("The document should render");
|
||||
match &capture.image {
|
||||
CaptureImage::Pixels(pixels) => assert!(pixels.rgba.chunks(4).any(|pixel| pixel[3] > 0), "The rectangle should be drawn"),
|
||||
CaptureImage::Svg(svg) => assert!(svg.contains("<path"), "The rectangle should be drawn: {svg}"),
|
||||
}
|
||||
assert!(capture.layer_sources.contains_key(&layer), "The rectangle's layer should have its content");
|
||||
let [min, max] = capture.frame;
|
||||
assert!(min.cmple(DVec2::ZERO).all() && max.cmpge(DVec2::splat(10.)).all(), "The frame {min} to {max} should hold the rectangle");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_merge_layer_shows_its_content_and_another_layer_its_output() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{ThumbnailContent, cell_size};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||
use graphene_std::renderer::{RenderOutputType, RenderParams};
|
||||
@@ -43,59 +43,46 @@ impl ThumbnailAtlasLayout {
|
||||
}
|
||||
|
||||
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
|
||||
cell_pixels(atlas_pixels, self.size().x, self.cell_size, self.cell_origin(index))
|
||||
let atlas_row_length = self.size().x as usize * 4;
|
||||
let row_length = self.cell_size.x as usize * 4;
|
||||
let origin = self.cell_origin(index).as_usizevec2();
|
||||
|
||||
(origin.y..origin.y + self.cell_size.y as usize)
|
||||
.filter_map(|row| {
|
||||
let start = row * atlas_row_length + origin.x * 4;
|
||||
atlas_pixels.get(start..start + row_length)
|
||||
})
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels of the cell at `origin` in an atlas `atlas_width` pixels wide, row by row.
|
||||
pub fn cell_pixels(atlas_pixels: &[u8], atlas_width: u32, cell_size: UVec2, origin: UVec2) -> Vec<u8> {
|
||||
let atlas_row_length = atlas_width as usize * 4;
|
||||
let row_length = cell_size.x as usize * 4;
|
||||
let origin = origin.as_usizevec2();
|
||||
|
||||
(origin.y..origin.y + cell_size.y as usize)
|
||||
.filter_map(|row| {
|
||||
let start = row * atlas_row_length + origin.x * 4;
|
||||
atlas_pixels.get(start..start + row_length)
|
||||
})
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Draws the content of each layer in the layout centered within its cell.
|
||||
pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout, contents: &HashMap<NodeId, ThumbnailContent>) {
|
||||
for (index, layer) in layout.layers.iter().enumerate() {
|
||||
let Some(content) = contents.get(layer) else { continue };
|
||||
draw_cell(scene, layout.cell_origin(index), layout.cell_size, content, content.bounds(true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the area `frame` of the content into each cell of a row of them, one per frame.
|
||||
pub fn draw_frames(scene: &mut VelloSceneBuilder, cell_size: UVec2, content: &ThumbnailContent, frames: &[[DVec2; 2]]) {
|
||||
for (index, &frame) in frames.iter().enumerate() {
|
||||
draw_cell(scene, UVec2::new(index as u32 * cell_size.x, 0), cell_size, content, frame);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_cell(scene: &mut VelloSceneBuilder, origin: UVec2, cell_size: UVec2, content: &ThumbnailContent, frame: [DVec2; 2]) {
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::BOUNDLESS,
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (origin, cell_size) = (origin.as_dvec2(), cell_size.as_dvec2());
|
||||
let [min, max] = frame;
|
||||
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
|
||||
let cell_size = layout.cell_size.as_dvec2();
|
||||
|
||||
// The clip also limits content filling the whole scene, like a background, to the cell
|
||||
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
|
||||
scene.draw_placed(Affine::new(transform.to_cols_array()), |scene| {
|
||||
content.graphic().render_to_vello(scene, DAffine2::IDENTITY, &render_params)
|
||||
});
|
||||
scene.pop_layer();
|
||||
for (index, layer) in layout.layers.iter().enumerate() {
|
||||
let Some(content) = contents.get(layer) else { continue };
|
||||
|
||||
let origin = layout.cell_origin(index).as_dvec2();
|
||||
let [min, max] = content.bounds(true);
|
||||
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
|
||||
|
||||
// The clip also limits content filling the whole scene, like a background, to the cell
|
||||
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
|
||||
scene.draw_placed(Affine::new(transform.to_cols_array()), |scene| {
|
||||
content.graphic().render_to_vello(scene, DAffine2::IDENTITY, &render_params)
|
||||
});
|
||||
scene.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGBA pixels with runs of fully transparent ones left out, which most of a thumbnail's margins are.
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { getContext, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import HistoryShot from "/src/components/views/HistoryShot.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
|
||||
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
|
||||
@@ -14,7 +13,6 @@
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const history = getContext<HistoryStore>("history");
|
||||
const portfolio = getContext<PortfolioStore>("portfolio");
|
||||
const thumbnails = history.thumbnails;
|
||||
|
||||
// Relative times age while the panel stays open
|
||||
let now = Date.now();
|
||||
@@ -69,26 +67,15 @@
|
||||
function retirePending() {
|
||||
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>
|
||||
|
||||
<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}>
|
||||
{#each $history.progress as row, index}
|
||||
<!-- Alone, work not yet in history is shown as an ordinary step -->
|
||||
@@ -98,7 +85,6 @@
|
||||
<span class="rail"
|
||||
>{#if $history.collaborating}<span class="dot hollow" style:border-color={row.color}></span>{/if}</span
|
||||
>
|
||||
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />
|
||||
<div class="text">
|
||||
<span class="label">{row.label || (row.open ? "In Progress" : "Waiting to Enter History")}</span>
|
||||
<span class="meta">
|
||||
@@ -113,20 +99,10 @@
|
||||
</div>
|
||||
{/each}
|
||||
{#each $history.rows as row (row.id)}
|
||||
<!-- 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 || row.thumbnail?.detail}
|
||||
<div class="row" class:head={row.head && !pendingHead} class:undone={row.undone} class:abandoned={row.abandoned}>
|
||||
{#if row.deltas > 1}
|
||||
<button
|
||||
class="expand"
|
||||
data-row-control
|
||||
class:expanded={row.expanded}
|
||||
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
|
||||
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
|
||||
@@ -137,10 +113,9 @@
|
||||
<span class="rail"
|
||||
>{#if $history.collaborating || !row.mine}<span class="dot" style:background={row.color}></span>{/if}</span
|
||||
>
|
||||
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />
|
||||
<div class="text">
|
||||
{#if renamingId === row.id}
|
||||
<span class="editing" data-row-control use:focusInput on:focusout={() => (renamingId = undefined)}>
|
||||
<span class="editing" use:focusInput on:focusout={() => (renamingId = undefined)}>
|
||||
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
|
||||
</span>
|
||||
{:else}
|
||||
@@ -152,7 +127,7 @@
|
||||
{count(row.deltas, "change", "changes")}
|
||||
</span>
|
||||
{#if row.tags.length > 0 || taggingId === row.id || (row.head && !pendingHead) || row.undone || row.abandoned}
|
||||
<span class="tags" data-row-control>
|
||||
<span class="tags">
|
||||
{#if row.head && !pendingHead}<span class="marker">Current</span>{/if}
|
||||
{#if row.undone}<span class="marker">Undone</span>{/if}
|
||||
{#if row.abandoned}<span class="marker">Branch</span>{/if}
|
||||
@@ -167,14 +142,14 @@
|
||||
</span>
|
||||
{/if}
|
||||
{#if row.branches.length > 0}
|
||||
<span class="branches" data-row-control>
|
||||
<span class="branches">
|
||||
{#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>
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="actions" data-row-control>
|
||||
<span class="actions">
|
||||
<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>
|
||||
{#if row.undone || row.abandoned}
|
||||
@@ -208,13 +183,6 @@
|
||||
</span>
|
||||
</div>
|
||||
{#if row.expanded}
|
||||
{#if row.thumbnail?.detail}
|
||||
<div class="row comparison" class:undone={row.undone}>
|
||||
<span class="gutter"></span>
|
||||
<span class="rail"></span>
|
||||
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} large={true} />
|
||||
</div>
|
||||
{/if}
|
||||
{#each row.details as delta (delta.id)}
|
||||
<div class="row delta" class:undone={row.undone}>
|
||||
<span class="gutter"></span>
|
||||
@@ -239,27 +207,6 @@
|
||||
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
|
||||
{/if}
|
||||
</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>
|
||||
|
||||
<style lang="scss">
|
||||
@@ -267,24 +214,11 @@
|
||||
flex-grow: 1;
|
||||
padding: 4px 0;
|
||||
|
||||
.banner {
|
||||
.following {
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
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;
|
||||
}
|
||||
padding: 0 8px 4px 8px;
|
||||
}
|
||||
|
||||
.row {
|
||||
@@ -298,19 +232,6 @@
|
||||
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,
|
||||
&.abandoned {
|
||||
.rail,
|
||||
@@ -322,16 +243,6 @@
|
||||
&.delta {
|
||||
min-height: 24px;
|
||||
font-size: 11px;
|
||||
|
||||
// Lines up with the step's label, past its thumbnail and the gap after it
|
||||
.text {
|
||||
padding-left: 42px;
|
||||
}
|
||||
}
|
||||
|
||||
&.comparison {
|
||||
padding-top: 4px;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { HistoryThumbnail } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// An empty slot until the step is captured, so every row keeps one
|
||||
export let thumbnail: HistoryThumbnail | undefined;
|
||||
// The images the frontend received, by ID
|
||||
export let images: Record<string, string>;
|
||||
export let large = false;
|
||||
</script>
|
||||
|
||||
<span class="history-shot" class:large>
|
||||
<span class="image" data-tooltip-label="The document once this step was done">
|
||||
{#if thumbnail && images[thumbnail.whole]}<img src={images[thumbnail.whole]} alt="" />{/if}
|
||||
</span>
|
||||
<!-- The close-up is shown large only, beside the whole document, so a row never has two -->
|
||||
{#if large && thumbnail?.detail}
|
||||
<span class="image" data-tooltip-label="What this step changed, close up" data-tooltip-description="Green was added, red removed, and yellow changed.">
|
||||
{#if images[thumbnail.detail]}<img src={images[thumbnail.detail]} alt="" />{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
|
||||
<style lang="scss">
|
||||
.history-shot {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
|
||||
.image {
|
||||
width: 36px;
|
||||
height: 24px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
background-image: var(--color-transparent-checkered-background);
|
||||
background-size: var(--color-transparent-checkered-background-size-mini);
|
||||
background-position: var(--color-transparent-checkered-background-position-mini);
|
||||
background-repeat: var(--color-transparent-checkered-background-repeat);
|
||||
}
|
||||
|
||||
&.large {
|
||||
gap: 4px;
|
||||
|
||||
.image {
|
||||
// The size captures are rendered at, like layer thumbnails
|
||||
width: 72px;
|
||||
height: 48px;
|
||||
background-size: var(--color-transparent-checkered-background-size);
|
||||
background-position: var(--color-transparent-checkered-background-position);
|
||||
}
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -5,61 +5,14 @@ import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type HistoryStore = ReturnType<typeof createHistoryStore>;
|
||||
|
||||
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, previewing: undefined, collaborating: false };
|
||||
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, collaborating: false };
|
||||
|
||||
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
|
||||
const store: Writable<HistoryPanelState> = import.meta.hot?.data?.store || writable<HistoryPanelState>(initialState);
|
||||
// The captured images by the ID rows name them with, sent once each
|
||||
const thumbnails: Writable<Record<string, string>> = import.meta.hot?.data?.thumbnails || writable<Record<string, string>>({});
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.store = store;
|
||||
import.meta.hot.data.thumbnails = thumbnails;
|
||||
}
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
|
||||
const { subscribe, set } = store;
|
||||
|
||||
// The most recent images kept, oldest dropped first. Each step has a whole image and maybe a close-up, so twice as many as the editor keeps captures
|
||||
const MAX_THUMBNAILS = 600;
|
||||
// The size an SVG capture is drawn at, twice the largest a capture is shown
|
||||
const RASTER_WIDTH = 144;
|
||||
const RASTER_HEIGHT = 96;
|
||||
|
||||
// Kept as a small PNG rather than the pixels themselves
|
||||
function encodePixels(pixels: Uint8Array, width: number, height: number): string {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
canvas.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(pixels), width, height), 0, 0);
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
// Without the GPU a capture comes as an SVG, which can embed whole images, so it is kept as a small PNG, or as the SVG when the browser can't draw it
|
||||
async function rasterize(svg: string): Promise<string> {
|
||||
// An SVG drawn as an image needs an intrinsic size, which the capture's only gives as a view box
|
||||
const sized = svg.replace("<svg ", `<svg width="${RASTER_WIDTH}" height="${RASTER_HEIGHT}" `);
|
||||
const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(sized)}`;
|
||||
try {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = RASTER_WIDTH;
|
||||
canvas.height = RASTER_HEIGHT;
|
||||
canvas.getContext("2d")?.drawImage(image, 0, 0, RASTER_WIDTH, RASTER_HEIGHT);
|
||||
return canvas.toDataURL("image/png");
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function keepThumbnail(id: string, url: string) {
|
||||
thumbnails.update((images) => {
|
||||
const ids = Object.keys(images);
|
||||
const kept = ids.length < MAX_THUMBNAILS ? images : Object.fromEntries(ids.slice(ids.length - MAX_THUMBNAILS + 1).map((id) => [id, images[id]]));
|
||||
return { ...kept, [id]: url };
|
||||
});
|
||||
}
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
|
||||
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
@@ -70,16 +23,7 @@ export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
set(data.state);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnail", async (data) => {
|
||||
const url = await rasterize(data.svg);
|
||||
keepThumbnail(data.id, url);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnailPixels", (data) => {
|
||||
keepThumbnail(data.id, encodePixels(data.pixels, data.width, data.height));
|
||||
});
|
||||
|
||||
return { subscribe, thumbnails: { subscribe: thumbnails.subscribe } };
|
||||
return { subscribe };
|
||||
}
|
||||
|
||||
export function destroyHistoryStore() {
|
||||
@@ -87,7 +31,5 @@ export function destroyHistoryStore() {
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnail");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnailPixels");
|
||||
subscriptionsRouter = undefined;
|
||||
}
|
||||
@@ -291,11 +291,6 @@ mod editor_commands {
|
||||
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
|
||||
fn retire_pending_history() -> Message {
|
||||
HistoryMessage::RetirePending.into()
|
||||
|
||||
@@ -28,6 +28,7 @@ impl DocumentNode {
|
||||
original_location: self.original_location,
|
||||
compile_metadata: self.compile_metadata.unwrap_or_default(),
|
||||
upstream_context_features: Default::default(),
|
||||
upstream_index_levels: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,8 @@ pub struct ProtoNode {
|
||||
pub(crate) compile_metadata: NodeCompileMetadata,
|
||||
/// The context features read by this node and everything upstream of it.
|
||||
pub upstream_context_features: ContextFeatures,
|
||||
/// The loop levels whose index this node and everything upstream of it read, as a bitmask where bit `k` is the `k`-th innermost loop.
|
||||
pub upstream_index_levels: u64,
|
||||
}
|
||||
|
||||
impl Default for ProtoNode {
|
||||
@@ -138,6 +140,7 @@ impl Default for ProtoNode {
|
||||
original_location: OriginalLocation::default(),
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
upstream_index_levels: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -169,6 +172,7 @@ impl ProtoNode {
|
||||
},
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
upstream_index_levels: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,22 +308,42 @@ impl ProtoNetwork {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolves_to_value(&self, mut id: NodeId) -> bool {
|
||||
fn resolves_to_value(&self, id: NodeId) -> bool {
|
||||
self.constant_value(id).is_some()
|
||||
}
|
||||
|
||||
/// The value feeding this node, following nodes which forward their first input.
|
||||
fn constant_value(&self, mut id: NodeId) -> Option<&TaggedValue> {
|
||||
loop {
|
||||
let Some((node_id, node)) = self.nodes.get(id.0 as usize) else { return false };
|
||||
let (node_id, node) = self.nodes.get(id.0 as usize)?;
|
||||
debug_assert_eq!(*node_id, id, "Node IDs must be dense indices");
|
||||
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(_) => return true,
|
||||
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => match inputs.first() {
|
||||
Some(&input) => id = input,
|
||||
None => return false,
|
||||
},
|
||||
_ => return false,
|
||||
ConstructionArgs::Value(value) => return Some(&**value),
|
||||
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => id = *inputs.first()?,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The loop levels a node reads the index from itself, assuming all levels when the level isn't known at compile time.
|
||||
fn own_index_levels(&self, node: &ProtoNode) -> u64 {
|
||||
if !node.compile_metadata.extract.contains(ContextFeatures::INDEX) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let ConstructionArgs::Nodes(inputs) = &node.construction_args else { return u64::MAX };
|
||||
let level_value = node
|
||||
.compile_metadata
|
||||
.index_level_input
|
||||
.and_then(|index| inputs.get(index as usize))
|
||||
.and_then(|&input| self.constant_value(input));
|
||||
match level_value {
|
||||
Some(TaggedValue::Integer(level)) => u32::try_from((*level).max(0)).ok().and_then(|level| 1_u64.checked_shl(level)).unwrap_or(u64::MAX),
|
||||
_ => u64::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
|
||||
let (_, node) = &self.nodes[node_id.0 as usize];
|
||||
let mut path = node.original_location.path.clone();
|
||||
@@ -330,6 +354,7 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
let features = context_deps.features;
|
||||
let index_levels = node.upstream_index_levels;
|
||||
let forwarding = NodeCompileMetadata {
|
||||
forwards_input: true,
|
||||
..Default::default()
|
||||
@@ -348,6 +373,7 @@ impl ProtoNetwork {
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
upstream_index_levels: index_levels,
|
||||
},
|
||||
));
|
||||
|
||||
@@ -379,6 +405,7 @@ impl ProtoNetwork {
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
upstream_index_levels: index_levels,
|
||||
},
|
||||
));
|
||||
nullification_node_id
|
||||
@@ -427,16 +454,34 @@ impl ProtoNetwork {
|
||||
};
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
for &node in &inputs {
|
||||
// An index injection without a loop body replaces the whole index stack for everything upstream
|
||||
let replaces_index_stack = dependencies.inject.contains(ContextFeatures::INDEX) && dependencies.loop_body_inputs == 0;
|
||||
|
||||
let mut index_levels = self.own_index_levels(&self.nodes[node_index].1);
|
||||
for (input_index, &node) in inputs.iter().enumerate() {
|
||||
let branch = self.find_context_dependencies(node, analyzed);
|
||||
self.nodes[node.0 as usize].1.upstream_context_features = branch.0.features;
|
||||
|
||||
// A loop body's innermost index is the one this node pushes, so its outer levels are one closer to us
|
||||
let branch_index_levels = self.nodes[node.0 as usize].1.upstream_index_levels;
|
||||
index_levels |= if replaces_index_stack {
|
||||
0
|
||||
} else if dependencies.is_loop_body_input(input_index) {
|
||||
branch_index_levels >> 1
|
||||
} else {
|
||||
branch_index_levels
|
||||
};
|
||||
|
||||
combined_deps.features |= branch.0.features;
|
||||
combined_deps.sources.extend(&branch.0.sources);
|
||||
branch_dependencies.push(branch);
|
||||
}
|
||||
// Remove requirements which this node provides and add requirements we have
|
||||
let features = (combined_deps.features & !dependencies.inject) | dependencies.extract;
|
||||
self.nodes[node_index].1.upstream_index_levels = index_levels;
|
||||
|
||||
// Remove requirements which this node provides and add requirements we have, with the index tracked per loop level instead
|
||||
let inject = dependencies.inject - ContextFeatures::INDEX;
|
||||
let mut features = (combined_deps.features & !inject) | (dependencies.extract - ContextFeatures::INDEX);
|
||||
features.set(ContextFeatures::INDEX, index_levels != 0);
|
||||
|
||||
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
|
||||
let we_introduces_new_deps = !combined_deps.features.contains(features);
|
||||
@@ -451,14 +496,8 @@ impl ProtoNetwork {
|
||||
}
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
|
||||
// Which dependencies do we supply (and don't need ourselves)?
|
||||
let net_injections = dependencies.inject.difference(dependencies.extract);
|
||||
|
||||
// Which dependencies still need to be met after this node?
|
||||
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
|
||||
|
||||
// Do we satisfy any existing dependencies?
|
||||
let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
|
||||
// Do we satisfy any existing dependencies, so they are no longer needed after this node?
|
||||
let we_supply_existing_deps = !combined_deps.features.difference(features).is_empty();
|
||||
|
||||
let new_deps = ContextModification {
|
||||
features,
|
||||
@@ -1330,6 +1369,66 @@ mod test {
|
||||
assert!(warnings(true).is_empty());
|
||||
}
|
||||
|
||||
fn loop_test_node(name: &'static str, inputs: Vec<NodeId>, compile_metadata: NodeCompileMetadata) -> ProtoNode {
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new(name),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(inputs),
|
||||
compile_metadata,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn integer_value(value: i64) -> ProtoNode {
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(value).into()), vec![])
|
||||
}
|
||||
|
||||
const INDEX_READER: NodeCompileMetadata = NodeCompileMetadata {
|
||||
extract: ContextFeatures::INDEX,
|
||||
inject: ContextFeatures::empty(),
|
||||
footprint_invariant: false,
|
||||
forwards_input: false,
|
||||
constant_inputs: 0b1,
|
||||
loop_body_inputs: 0,
|
||||
index_level_input: Some(0),
|
||||
};
|
||||
|
||||
/// A loop evaluating its second input once per row of its first input.
|
||||
const MAP: NodeCompileMetadata = NodeCompileMetadata {
|
||||
extract: ContextFeatures::empty(),
|
||||
inject: ContextFeatures::INDEX,
|
||||
footprint_invariant: false,
|
||||
forwards_input: false,
|
||||
constant_inputs: 0,
|
||||
loop_body_inputs: 0b10,
|
||||
index_level_input: None,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn nested_loops_keep_the_outer_index_for_the_inner_body() {
|
||||
let nodes = vec![
|
||||
(NodeId(0), integer_value(1)),
|
||||
(NodeId(1), loop_test_node("index_reader", vec![NodeId(0)], INDEX_READER)),
|
||||
(NodeId(2), integer_value(2)),
|
||||
(NodeId(3), loop_test_node("inner_map", vec![NodeId(2), NodeId(1)], MAP)),
|
||||
(NodeId(4), integer_value(3)),
|
||||
(NodeId(5), loop_test_node("outer_map", vec![NodeId(4), NodeId(3)], MAP)),
|
||||
];
|
||||
|
||||
let mut network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(5),
|
||||
nodes,
|
||||
};
|
||||
network.insert_context_nullification_nodes().unwrap();
|
||||
|
||||
let node_named = |name: &str| &network.nodes.iter().find(|(_, node)| node.identifier.as_str() == name).unwrap().1;
|
||||
assert!(node_named("inner_map").upstream_context_features.contains(ContextFeatures::INDEX));
|
||||
assert_eq!(node_named("inner_map").upstream_index_levels, 0b1);
|
||||
assert_eq!(node_named("outer_map").upstream_index_levels, 0);
|
||||
assert!(!node_named("outer_map").upstream_context_features.contains(ContextFeatures::INDEX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_inputs_must_resolve_to_values_through_forwarding_nodes() {
|
||||
let value = || ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("name".into()).into()), vec![]);
|
||||
|
||||
@@ -233,11 +233,25 @@ pub struct NodeCompileMetadata {
|
||||
pub forwards_input: bool,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub constant_inputs: u64,
|
||||
/// Inputs evaluated inside the loop scope this node pushes an index for.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub loop_body_inputs: u64,
|
||||
/// The input whose constant value selects the loop level this node reads the index from.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub index_level_input: Option<u8>,
|
||||
}
|
||||
|
||||
impl NodeCompileMetadata {
|
||||
pub fn requires_constant_input(&self, index: usize) -> bool {
|
||||
index < u64::BITS as usize && self.constant_inputs & (1 << index) != 0
|
||||
Self::contains_input(self.constant_inputs, index)
|
||||
}
|
||||
|
||||
pub fn is_loop_body_input(&self, index: usize) -> bool {
|
||||
Self::contains_input(self.loop_body_inputs, index)
|
||||
}
|
||||
|
||||
fn contains_input(mask: u64, index: usize) -> bool {
|
||||
index < u64::BITS as usize && mask & (1 << index) != 0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,18 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
pub index_role: FieldIndexRole,
|
||||
/// Whether the node evaluates the input itself (an `impl Node` parameter) rather than receiving its value.
|
||||
pub lazy: bool,
|
||||
}
|
||||
|
||||
/// How an input takes part in loop index tracking.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum FieldIndexRole {
|
||||
#[default]
|
||||
None,
|
||||
/// This input's constant value selects which loop level's index is read, from `#[index_level]`.
|
||||
Level,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
@@ -318,6 +318,20 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote!(#constant)
|
||||
})
|
||||
.collect();
|
||||
let index_role: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.index_role {
|
||||
ParsedIndexRole::None => quote!(gcore::registry::FieldIndexRole::None),
|
||||
ParsedIndexRole::Level => quote!(gcore::registry::FieldIndexRole::Level),
|
||||
})
|
||||
.collect();
|
||||
let lazy: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let lazy = matches!(field.ty, ParsedFieldType::Node(_));
|
||||
quote!(#lazy)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exposed: Vec<_> = regular_fields
|
||||
.iter()
|
||||
@@ -1078,6 +1092,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
index_role: #index_role,
|
||||
lazy: #lazy,
|
||||
},
|
||||
)*
|
||||
],
|
||||
|
||||
@@ -123,6 +123,15 @@ impl Parse for ParsedWidgetOverride {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a field takes part in loop index tracking, from `#[index_level]`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ParsedIndexRole {
|
||||
#[default]
|
||||
None,
|
||||
/// This field's constant value selects which loop level's index the node reads.
|
||||
Level,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParsedField {
|
||||
pub pat_ident: PatIdent,
|
||||
@@ -136,6 +145,7 @@ pub struct ParsedField {
|
||||
pub multiline: bool,
|
||||
pub progression: bool,
|
||||
pub constant: bool,
|
||||
pub index_role: ParsedIndexRole,
|
||||
pub is_data_field: bool,
|
||||
}
|
||||
|
||||
@@ -169,6 +179,7 @@ impl ParsedField {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}
|
||||
}
|
||||
@@ -856,8 +867,14 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
|
||||
let exposed = extract_attribute(attrs, "expose").is_some();
|
||||
|
||||
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time
|
||||
let constant = extract_attribute(attrs, "constant").is_some();
|
||||
let index_role = match extract_attribute(attrs, "index_level") {
|
||||
Some(_) => ParsedIndexRole::Level,
|
||||
None => ParsedIndexRole::None,
|
||||
};
|
||||
|
||||
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time.
|
||||
// An `#[index_level]` must be constant too, so the compiler knows which loop's index is read.
|
||||
let constant = extract_attribute(attrs, "constant").is_some() || index_role == ParsedIndexRole::Level;
|
||||
|
||||
// Gives a synchronous node its `SourceId`, as async nodes get it, so it can bump its own generation
|
||||
let source_id = extract_attribute(attrs, "source_id").is_some();
|
||||
@@ -888,6 +905,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
"Data fields (#[data]) cannot be #[constant]. They are internal state, not node parameters",
|
||||
));
|
||||
}
|
||||
if index_role != ParsedIndexRole::None {
|
||||
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot be #[index_level]"));
|
||||
}
|
||||
if source_id {
|
||||
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute"));
|
||||
}
|
||||
@@ -1035,6 +1055,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
index_role,
|
||||
is_data_field,
|
||||
})
|
||||
} else {
|
||||
@@ -1087,6 +1108,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
index_role,
|
||||
is_data_field,
|
||||
})
|
||||
}
|
||||
@@ -1386,6 +1408,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1448,6 +1471,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
},
|
||||
ParsedField {
|
||||
@@ -1472,6 +1496,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
},
|
||||
],
|
||||
@@ -1535,6 +1560,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1601,6 +1627,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1670,6 +1697,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1764,6 +1792,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
|
||||
@@ -88,6 +88,7 @@ fn read_index(
|
||||
///
|
||||
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
|
||||
#[hard(0..)]
|
||||
#[index_level]
|
||||
loop_level: Item<i64>,
|
||||
) -> Result<Item<f64>, ReadContextError> {
|
||||
// The graph outside any loop runs once, as index 0
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
|
||||
use core_types::{
|
||||
ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectIndex, Interrupt, OwnedContextImpl,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -396,9 +398,9 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Data: List"), icon("NodeMap"), footprint_invariant)]
|
||||
#[node_macro::node(category("Data: List"), icon("NodeMap"), version(2), footprint_invariant)]
|
||||
fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
@@ -446,9 +448,9 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
}
|
||||
|
||||
/// Feeds the content through the same steps over and over, each time starting from the previous result. Inside the steps, a **Read** node like **Read String** or **Read Vector** reads the result so far, and **Read Index** reads how many times around it has been.
|
||||
#[node_macro::node(category("Routing"), icon("NodeIterate"))]
|
||||
#[node_macro::node(category("Routing"), icon("NodeIterate"), version(2))]
|
||||
fn iterate<T: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
/// The starting value, which the steps rework each time around.
|
||||
#[implementations(String, f64, Vector, Graphic, Raster<CPU>, Color, Gradient)]
|
||||
content: Item<T>,
|
||||
@@ -617,9 +619,9 @@ fn write_layer_path<T: 'static + Send>(
|
||||
/// be derived from the item's own data. If the attribute already exists, its values are replaced; if not, it's added.
|
||||
/// The value is type-erased into an `Item<AttributeValueDyn>` by the auto-inserted input adapter, so this node only
|
||||
/// monomorphizes over `T` instead of the cartesian product `(T, U)`.
|
||||
#[node_macro::node(category("Data: Attribute"), icon("NodeWriteAttribute"))]
|
||||
#[node_macro::node(category("Data: Attribute"), icon("NodeWriteAttribute"), version(2))]
|
||||
fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
/// The list to set the named attribute on (one value per item).
|
||||
#[implementations(
|
||||
List<String>,
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
use crate::gcore::Context;
|
||||
use core::f64::consts::TAU;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{ApplyTransform, Footprint};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, ExtractFootprint, InjectFootprint, InjectVarArgs, Interrupt, NodeError, OwnedContextImpl, Poll};
|
||||
use glam::{DAffine2, DVec2, I64Vec2};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectIndex, InjectVarArgs, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
use vector_types::vector::{no_paths, paths_from_list_row_attributes};
|
||||
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeat"))]
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeat"), version(2))]
|
||||
fn repeat<T: Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
@@ -54,9 +53,9 @@ fn repeat<T: Send + Clone + 'static>(
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"))]
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"), version(2))]
|
||||
fn repeat_array<T: Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
@@ -115,125 +114,9 @@ fn repeat_array<T: Send + Clone + 'static>(
|
||||
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"), version(2))]
|
||||
fn repeat_radial<T: Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
@@ -288,9 +171,9 @@ fn repeat_radial<T: Send + Clone + 'static>(
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Repeat on Points"))]
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Repeat on Points"), version(2))]
|
||||
fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs + InjectIndex,
|
||||
points: List<Vector>,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
@@ -508,90 +391,6 @@ 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]
|
||||
fn repeat_radial() {
|
||||
let context = OwnedContextImpl::default().into_context();
|
||||
|
||||
@@ -13,7 +13,7 @@ use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::float_noise::round_away_float_noise;
|
||||
use core_types::misc::{format_f64, parse_f64};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, InjectIndex, OwnedContextImpl};
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
use rand::{RngExt, SeedableRng};
|
||||
@@ -963,9 +963,9 @@ fn string_join(
|
||||
}
|
||||
|
||||
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
|
||||
#[node_macro::node(category("String"), icon("NodeStringMap"))]
|
||||
#[node_macro::node(category("String"), icon("NodeStringMap"), version(2))]
|
||||
fn string_map(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
strings: List<String>,
|
||||
#[expose]
|
||||
#[implementations(Context -> Item<String>)]
|
||||
|
||||
@@ -11,7 +11,7 @@ use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
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,
|
||||
ExtractAll, InjectFootprint, OwnedContextImpl,
|
||||
ExtractAll, InjectFootprint, InjectIndex, OwnedContextImpl,
|
||||
};
|
||||
use core_types::{Interrupt, NodeError};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
@@ -2043,9 +2043,9 @@ fn path_is_closed(
|
||||
Item::new_from_element(closed)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector))]
|
||||
#[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector), version(2))]
|
||||
fn map_points<V: MapVectorItems + Send>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
#[implementations(Graphic, Vector)] content: Item<V>,
|
||||
mapped: impl Node<Context<'static>, Output = Item<DVec2>>,
|
||||
) -> Result<Item<V>, Interrupt> {
|
||||
|
||||
@@ -205,12 +205,17 @@ impl Preprocessor {
|
||||
context_features,
|
||||
..
|
||||
} = metadata;
|
||||
let constant_inputs = fields.iter().enumerate().filter(|(_, field)| field.constant).fold(0, |mask, (index, _)| mask | 1 << index);
|
||||
let input_mask = |predicate: &dyn Fn(&FieldMetadata) -> bool| fields.iter().enumerate().filter(|(_, field)| predicate(field)).fold(0, |mask, (index, _)| mask | 1 << index);
|
||||
let context_metadata = NodeCompileMetadata::from(context_features.as_slice());
|
||||
let pushes_index = context_metadata.inject.contains(ContextFeatures::INDEX);
|
||||
|
||||
let node_compile_metadata = NodeCompileMetadata {
|
||||
footprint_invariant: *footprint_invariant,
|
||||
forwards_input: *forwards_input,
|
||||
constant_inputs,
|
||||
..NodeCompileMetadata::from(context_features.as_slice())
|
||||
constant_inputs: input_mask(&|field| field.constant),
|
||||
loop_body_inputs: if pushes_index { input_mask(&|field| field.lazy) } else { 0 },
|
||||
index_level_input: fields.iter().position(|field| field.index_role == FieldIndexRole::Level).map(|index| index as u8),
|
||||
..context_metadata
|
||||
};
|
||||
compile_metadata.insert(id.clone(), node_compile_metadata);
|
||||
|
||||
@@ -864,4 +869,22 @@ mod tests {
|
||||
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_index_roles_reach_the_compile_metadata() {
|
||||
use graphene_std::context::read_index;
|
||||
use graphene_std::graphic::map;
|
||||
|
||||
let preprocessor = Preprocessor::new();
|
||||
let compile_metadata = |identifier: &ProtoNodeIdentifier| preprocessor.compile_metadata.get(identifier).copied().unwrap_or_default();
|
||||
|
||||
let map_metadata = compile_metadata(&map::IDENTIFIER);
|
||||
assert!(map_metadata.is_loop_body_input(<map::MappedInput as NodeParameter>::INDEX));
|
||||
assert_eq!(map_metadata.loop_body_inputs.count_ones(), 1, "Only the mapped lambda runs inside the loop");
|
||||
|
||||
let read_index_metadata = compile_metadata(&read_index::IDENTIFIER);
|
||||
let loop_level_index = <read_index::LoopLevelInput as NodeParameter>::INDEX;
|
||||
assert_eq!(read_index_metadata.index_level_input, Some(loop_level_index as u8));
|
||||
assert!(read_index_metadata.requires_constant_input(loop_level_index), "The loop level must be a constant");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user