mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
6
Commits
spike
...
sim-on-leaf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
366283d4cb | ||
|
|
dcb856ec92 | ||
|
|
4a36446f69 | ||
|
|
837bf98dec | ||
|
|
eaddede0a7 | ||
|
|
8d8393100d |
No files matched your search
Generated
+18
@@ -1777,6 +1777,19 @@ dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "document-live"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"document-container",
|
||||
"document-format",
|
||||
"document-graph-storage",
|
||||
"graph-craft",
|
||||
"log",
|
||||
"peer-transport",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "downcast-rs"
|
||||
version = "1.2.1"
|
||||
@@ -2703,7 +2716,10 @@ dependencies = [
|
||||
"clap",
|
||||
"document-container",
|
||||
"document-format",
|
||||
"document-graph-storage",
|
||||
"document-live",
|
||||
"fern",
|
||||
"getrandom 0.3.3",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"image",
|
||||
@@ -2717,6 +2733,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"wgpu",
|
||||
"wgpu-executor",
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2997,6 +3014,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"once_cell",
|
||||
"peer-transport",
|
||||
"preprocessor",
|
||||
"reqwest",
|
||||
"serde",
|
||||
|
||||
@@ -19,6 +19,7 @@ members = [
|
||||
"document/migrations/nodes",
|
||||
"document/migrations/compiled",
|
||||
"document/peer-transport",
|
||||
"document/live",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -117,6 +118,7 @@ migration-formats = { path = "document/migrations/formats" }
|
||||
migration-compiled = { path = "document/migrations/compiled" }
|
||||
migration-nodes = { path = "document/migrations/nodes" }
|
||||
peer-transport = { path = "document/peer-transport" }
|
||||
document-live = { path = "document/live" }
|
||||
raster-nodes = { path = "node-graph/nodes/raster" }
|
||||
graphene-std = { path = "node-graph/nodes/gstd" }
|
||||
interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
|
||||
@@ -99,6 +99,12 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerClipboardWrite { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
|
||||
}
|
||||
// No web origin here, so use the hosted editor
|
||||
FrontendMessage::TriggerSessionLinkCopy { token } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
|
||||
content: format!("https://editor.graphite.rs/?session={token}"),
|
||||
});
|
||||
}
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
|
||||
@@ -58,4 +58,8 @@ pub enum Error {
|
||||
#[cfg(feature = "network")]
|
||||
#[error("network error: {0}")]
|
||||
Network(#[from] peer_transport::PacketError),
|
||||
/// The room knows this device by its peer, so the user can't change.
|
||||
#[cfg(feature = "network")]
|
||||
#[error("the user cannot change while the document is connected")]
|
||||
UserChangeWhileConnected,
|
||||
}
|
||||
@@ -94,6 +94,7 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) manifest: Manifest,
|
||||
/// See [`HistoryMetadata`].
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
pub(crate) wall_clock_ms: Option<f64>,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
@@ -110,6 +111,9 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
pub(crate) own_staged_since_tick: bool,
|
||||
/// Whether the document belongs in its room, persisted so a reopen reconnects.
|
||||
pub(crate) shared: bool,
|
||||
}
|
||||
@@ -139,9 +143,13 @@ impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
Self {
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
wall_clock_ms: self.wall_clock_ms,
|
||||
byte_store: self.byte_store.clone(),
|
||||
migrated: self.migrated,
|
||||
shared: self.shared,
|
||||
interactions_seen: self.interactions_seen.clone(),
|
||||
own_last_staged_ms: self.own_last_staged_ms,
|
||||
own_staged_since_tick: self.own_staged_since_tick,
|
||||
..Self::assemble(self.session.clone(), self.working.clone(), self.layout.clone(), self.manifest.clone(), self.metadata.clone())
|
||||
}
|
||||
}
|
||||
@@ -156,6 +164,7 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
metadata,
|
||||
wall_clock_ms: None,
|
||||
view_settings: Default::default(),
|
||||
network_view_settings: Default::default(),
|
||||
byte_store: None,
|
||||
@@ -166,6 +175,9 @@ impl<L: Layout> Gdd<L> {
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
shared: false,
|
||||
}
|
||||
}
|
||||
@@ -186,10 +198,10 @@ impl<L: Layout + Default> Gdd<L> {
|
||||
|
||||
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
||||
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
||||
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
||||
let layout = L::default();
|
||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
|
||||
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,6 +237,11 @@ impl<L: Layout> Gdd<L> {
|
||||
/// # Errors
|
||||
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
|
||||
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
/// Reads the manifest without opening the copy, which may be another writer's.
|
||||
pub async fn read_manifest(working: &AnyContainer, layout: &L) -> Result<Manifest, Error> {
|
||||
Ok(io::read_single(working, layout.manifest_basename(), MANIFEST_CODEC).await?)
|
||||
}
|
||||
|
||||
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||
Self::open_stored(working, layout, MigrationInputs::default()).await
|
||||
}
|
||||
@@ -344,18 +361,18 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
||||
/// the manifest and writes each payload with its recorded codec.
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
user_id: user,
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &Sorted(&session_state))?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
let session = Session::with_identity(peer, user);
|
||||
io::write_single(&working, layout.registry_basename(), codecs.registry, &Sorted(session.registry()))?;
|
||||
|
||||
Ok(Self::assemble(session, working, layout, manifest, HistoryMetadata::default()))
|
||||
@@ -450,6 +467,10 @@ impl<L: Layout> Gdd<L> {
|
||||
self.session.all_referenced_resource_hashes()
|
||||
}
|
||||
|
||||
pub fn resource_gc_roots(&self) -> std::collections::HashSet<ResourceHash> {
|
||||
self.session.resource_gc_roots()
|
||||
}
|
||||
|
||||
/// Drop the session and return the working-copy container + layout.
|
||||
pub fn into_storage(self) -> (AnyContainer, L) {
|
||||
(self.working, self.layout)
|
||||
|
||||
@@ -124,6 +124,10 @@ impl<L: Layout> Gdd<L> {
|
||||
self.network.iter().flat_map(|replica| replica.peers())
|
||||
}
|
||||
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.session.mark_runtime_current();
|
||||
}
|
||||
|
||||
pub fn poll_peers(&mut self) -> Vec<Event> {
|
||||
let Some(mut replica) = self.network.take() else { return Vec::new() };
|
||||
let events = replica.poll(self);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, Sorted, Subject, TimeStamp, Value, WallStamp};
|
||||
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -65,6 +65,21 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Set the person using this device. `peer` must be unused, so the previous user keeps their steps. Refused while connected.
|
||||
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<(), Error> {
|
||||
if self.session.user() == user {
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some() {
|
||||
return Err(Error::UserChangeWhileConnected);
|
||||
}
|
||||
let closing = self.session.set_user(user, peer)?;
|
||||
self.own_last_staged_ms = None;
|
||||
self.persist_staged(&closing)?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Edit the cached manifest and persist it. Always JSON, synchronous.
|
||||
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
|
||||
edit(&mut self.manifest);
|
||||
@@ -131,6 +146,9 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them.
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
|
||||
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
self.own_staged_since_tick = true;
|
||||
}
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
@@ -368,6 +386,13 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many closed interactions wait before they retire. Retiring later merges more of a gesture into one delta.
|
||||
pub const RETIRE_AFTER_INTERACTIONS: usize = 10;
|
||||
/// Gives every peer time to see the whole interaction.
|
||||
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
|
||||
/// The longest anything waits, so quiet sessions and interactions with gaps still retire.
|
||||
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
|
||||
|
||||
/// Close this peer's open interaction, if any, with a marker staged like any other hot op.
|
||||
pub fn end_interaction(&mut self) -> Result<(), Error> {
|
||||
let staged = self.session.end_interaction()?;
|
||||
@@ -375,10 +400,149 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
|
||||
let Some(retraction) = self.session.retract_interaction()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.own_last_staged_ms = None;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
#[cfg(feature = "network")]
|
||||
{
|
||||
self.remote_changes.touched.extend(retraction.touched);
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&retraction.ids)?;
|
||||
}
|
||||
}
|
||||
Ok(Some(retraction.ops))
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
|
||||
if !self.can_change_line() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(rev) = self.session.latest_own_interaction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.drop_step(rev)?;
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
pub fn can_change_line(&self) -> bool {
|
||||
self.retires_locally() || self.network.as_ref().is_some_and(|replica| replica.has_host())
|
||||
}
|
||||
|
||||
/// Drop a retired interaction from the line. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_rewritten_line()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_move(rev)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let deltas = self.restore_dropped_interaction(rev)?;
|
||||
self.persist_rewritten_line()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
fn persist_rewritten_line(&mut self) -> Result<(), Error> {
|
||||
self.rewrite_history()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Stage retracted ops as a new interaction. They count as remote changes.
|
||||
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
|
||||
#[cfg(feature = "network")]
|
||||
for op in &ops {
|
||||
self.remote_changes.touched.record(op);
|
||||
}
|
||||
self.stage_ops(ops)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire what is due at `now_ms`. Open interactions never retire. `idle` means the editor is between steps.
|
||||
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
|
||||
self.wall_clock_ms = Some(now_ms);
|
||||
// Close a quiet interaction only between steps, so a pause doesn't split a gesture
|
||||
if self.own_staged_since_tick {
|
||||
self.own_staged_since_tick = false;
|
||||
self.own_last_staged_ms = Some(now_ms);
|
||||
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let closed = self.session.closed_interactions();
|
||||
let mut seen = std::mem::take(&mut self.interactions_seen);
|
||||
let mut due = Vec::new();
|
||||
let mut oldest_age: f64 = 0.0;
|
||||
for interaction in &closed {
|
||||
let Some(&marker) = interaction.ops.last() else { continue };
|
||||
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
|
||||
if age >= Self::RETIRE_MIN_AGE_MS && (interaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
|
||||
due.push(interaction.clone());
|
||||
oldest_age = oldest_age.max(age);
|
||||
}
|
||||
}
|
||||
seen.retain(|marker, _| closed.iter().any(|interaction| interaction.ops.last() == Some(marker)));
|
||||
self.interactions_seen = seen;
|
||||
|
||||
if due.len() >= Self::RETIRE_AFTER_INTERACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
|
||||
self.retire_interactions(&due)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Close this peer's open interaction and retire every closed one with no ops still on their way, whoever authored
|
||||
/// it. A peer that does not retire only closes its own.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
let closed = self.contiguous_interactions();
|
||||
self.retire_interactions(&closed)
|
||||
}
|
||||
@@ -414,8 +578,10 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Publish and persist freshly retired deltas, then broadcast them with the hot ops they retired.
|
||||
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
|
||||
if let Some(wall_ms) = self.wall_clock_ms {
|
||||
self.session.stamp_retired_at(new_revs, wall_ms as u64);
|
||||
}
|
||||
// Deltas peers hold are published, so undo past them moves the shared head instead of rewinding.
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
|
||||
@@ -137,6 +137,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
|
||||
|
||||
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{ExportFormat, ExportOptions, GddV1, GddV1Layout};
|
||||
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, to_value};
|
||||
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, UserId, to_value};
|
||||
use graph_craft::application_io::resource::{HashMapResourceStorage, ResourceStorage};
|
||||
use graphene_resource::DataSource;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -16,7 +16,7 @@ const LATEST: TimeStamp = TimeStamp {
|
||||
};
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Networks and nodes, some of each removed again, plus link-only resources whose bytes sit in the byte store.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
// History metadata has its own file, travels in exports and merges across copies.
|
||||
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{GddV1, GddV1Layout, Layout};
|
||||
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, Subject, TimeStamp, UserId, rev_attr, user_attr};
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
const ADA: Subject = Subject::User(UserId(10));
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
fn document(peer: u64, user: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Let the room settle through greetings, the sync handshake and whatever was broadcast.
|
||||
@@ -24,49 +25,76 @@ fn settle(network: &mut peer_transport::mock::MockNetwork, peers: &mut [&mut Gdd
|
||||
}
|
||||
}
|
||||
|
||||
fn document_naming_ada() -> GddV1 {
|
||||
let mut gdd = document(1);
|
||||
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
gdd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_facts_survive_a_reopen() {
|
||||
fn a_recorded_name_survives_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document_naming_ada();
|
||||
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
|
||||
let mut gdd = document(1, 10);
|
||||
assert!(gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
assert!(
|
||||
!gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
|
||||
"the same name is no change"
|
||||
);
|
||||
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
assert!(gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
|
||||
assert!(gdd.record(Subject::Rev(step), "tag:v1", true.into(), NOW_MS).expect("record"));
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"));
|
||||
|
||||
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
|
||||
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
fn recording_an_unchanged_value_writes_nothing() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = document_naming_ada();
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
|
||||
}
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let metadata = gdd.metadata().clone();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
let before = working.read(&path).await.expect("read").as_slice().to_vec();
|
||||
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert!(!reopened.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"));
|
||||
assert_eq!(reopened.metadata(), &metadata);
|
||||
let (working, _) = reopened.into_storage();
|
||||
assert_eq!(working.read(&path).await.expect("read").as_slice().trim_ascii(), before.trim_ascii());
|
||||
});
|
||||
}
|
||||
|
||||
/// A line that doesn't decode is skipped, so a torn write can't block opening.
|
||||
#[test]
|
||||
fn an_unreadable_metadata_line_is_skipped() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working
|
||||
.append_non_blocking(
|
||||
&path,
|
||||
b"{\"subject\":{\"Branch\":3},\"key\":\"name\",\"value\":1,\"stamp\":{\"ms\":1,\"peer\":1}}\n{\"subject\":{\"User\":",
|
||||
)
|
||||
.expect("append");
|
||||
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
futures::executor::block_on(async {
|
||||
let (working, layout) = document_naming_ada().into_storage();
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
|
||||
|
||||
@@ -82,29 +110,75 @@ fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
#[cfg(feature = "network")]
|
||||
#[test]
|
||||
fn names_reach_the_room_with_the_sync_and_as_they_change() {
|
||||
let mut host = document(1);
|
||||
let mut guest = document(2);
|
||||
host.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
// A name given before joining travels with the joiner and reaches the host.
|
||||
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
futures::executor::block_on(async {
|
||||
let mut host = document(1, 10);
|
||||
let mut guest = document(2, 20);
|
||||
host.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
|
||||
let mut network = peer_transport::mock::MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(10)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(20)).expect("connect");
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
let mut network = peer_transport::mock::MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(10)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(20)).expect("connect");
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
|
||||
assert!(guest.is_synced());
|
||||
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
|
||||
assert!(guest.is_synced());
|
||||
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
|
||||
|
||||
// A rename while in the room goes round on its own.
|
||||
assert!(guest.record(Subject::User(UserId(20)), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
|
||||
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
|
||||
assert!(guest.record(Subject::User(UserId(20)), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
|
||||
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retirement_records_when_it_happened() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.retire_due(NOW_MS, true).expect("tick");
|
||||
|
||||
gdd.stage_ops([RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}])
|
||||
.expect("stage");
|
||||
let everything = TimeStamp {
|
||||
counter: u64::MAX,
|
||||
peer: PeerId(u64::MAX),
|
||||
};
|
||||
let revs = gdd.retire(everything).expect("retire");
|
||||
assert!(!revs.is_empty());
|
||||
for rev in revs {
|
||||
let delta = gdd.session().delta(rev).expect("retired delta");
|
||||
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// An export without history carries no facts, since they'd name missing revs.
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
let expected = include_history.then_some("Ada");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), expected, "include_history: {include_history}");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry};
|
||||
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry, UserId};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
@@ -91,7 +91,7 @@ fn stored(nodes: &[(u64, &'static str)]) -> AnyContainer {
|
||||
|
||||
/// A document whose declaration bytes went to `store`, as the editor sends them to its global cache.
|
||||
fn stored_with_bytes_in(nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) -> AnyContainer {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
gdd.commit_from_runtime(&network_of(nodes), &NoMetadata, &ResourceRegistry::new(), store).unwrap();
|
||||
gdd.into_storage().0
|
||||
}
|
||||
@@ -143,7 +143,7 @@ fn declarations_come_from_the_container_when_the_cache_lacks_them() {
|
||||
let nodes = [(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")];
|
||||
|
||||
// An archive carries its declarations in the container, which a device's cache hasn't seen yet
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
gdd.commit_from_runtime(&network_of(&nodes), &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
||||
.unwrap();
|
||||
for (_, identifier) in nodes {
|
||||
|
||||
@@ -31,7 +31,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
|
||||
}
|
||||
|
||||
fn create() -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
}
|
||||
|
||||
fn commit(gdd: &mut GddV1, nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) {
|
||||
@@ -79,7 +79,7 @@ fn a_migration_on_disk_leaves_no_staging_behind() {
|
||||
block_on(async {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("document");
|
||||
let mut gdd = GddV1::create(&path, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create(&path, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
|
||||
commit(&mut gdd, &[(1, FADE)], &HashMapResourceStorage::new());
|
||||
drop(gdd);
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Error, GddV1, GddV1Layout, manifest};
|
||||
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId};
|
||||
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, UserId};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
@@ -28,7 +28,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
|
||||
}
|
||||
|
||||
fn create() -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
|
||||
}
|
||||
|
||||
fn implementations(gdd: &GddV1) -> Vec<Implementation> {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
|
||||
#[test]
|
||||
fn manifest_returns_what_create_in_wrote() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||
|
||||
@@ -99,7 +99,7 @@ fn an_empty_registry_file_is_corrupt_rather_than_absent() {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let codec = gdd.manifest().codecs.registry;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
@@ -114,7 +114,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let codecs = gdd.manifest().codecs;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
@@ -135,7 +135,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
|
||||
#[test]
|
||||
fn update_manifest_changes_visible_after_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||
@@ -150,7 +150,7 @@ fn update_manifest_changes_visible_after_reopen() {
|
||||
#[test]
|
||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
||||
// produces one network in the registry.
|
||||
@@ -177,7 +177,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
#[test]
|
||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
||||
let early = HotOp {
|
||||
@@ -225,7 +225,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
#[test]
|
||||
fn last_broadcast_rev_persists_across_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Retire one op so there is a real retired rev to mark as published.
|
||||
let op = HotOp {
|
||||
@@ -256,7 +256,7 @@ fn export_folder_round_trips_through_open() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
@@ -284,7 +284,7 @@ fn export_zip_round_trips_via_deserialize() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("doc.gdd.zip");
|
||||
@@ -309,7 +309,7 @@ fn export_rejects_invalid_options() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("nope");
|
||||
@@ -332,7 +332,7 @@ fn resource_round_trip_add_read_remove() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"deadbeef cafe babe";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -362,7 +362,7 @@ fn resource_survives_reopen() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"persistent bytes";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -391,7 +391,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
|
||||
// Need a folder-backed working copy to exercise the fs::copy path.
|
||||
let working_dir = tempfile::tempdir().unwrap();
|
||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Source file outside the working copy.
|
||||
let payload = b"external resource bytes";
|
||||
@@ -415,7 +415,7 @@ fn export_carries_resources() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"exported resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -443,7 +443,7 @@ fn embed_all_resources_materializes_link_only_resource() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
||||
// byte store; the working copy never holds them.
|
||||
@@ -508,7 +508,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
||||
let payload = b"embedded bytes in the cache";
|
||||
@@ -549,7 +549,7 @@ fn export_round_trips_unretired_hot_ops() {
|
||||
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"hot resource bytes";
|
||||
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||
@@ -602,7 +602,7 @@ fn open_in_rejects_future_format_version() {
|
||||
#[test]
|
||||
fn create_in_records_default_codecs_in_manifest() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let codecs = gdd.manifest().codecs;
|
||||
assert_eq!(codecs.registry, Codec::Postcard);
|
||||
@@ -623,7 +623,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
@@ -665,7 +665,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
futures::executor::block_on(async {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -718,7 +718,7 @@ fn declarations_round_trip_through_byte_store() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
@@ -746,7 +746,7 @@ fn an_export_without_history_drops_tombstones() {
|
||||
use document_graph_storage::{Network, NetworkId, RegistryDelta};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let id = NetworkId(7);
|
||||
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
|
||||
.unwrap();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry, UserId};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
@@ -25,7 +25,7 @@ fn network_with_one_node() -> NodeNetwork {
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), UserId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
@@ -57,7 +57,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
attributes: Default::default(),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), UserId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
@@ -80,28 +80,69 @@ fn a_reopen_continues_the_hot_op_sequence() {
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
}
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
stage(&mut gdd, set(1));
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), UserId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.stage_ops([set(1)]).unwrap();
|
||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
||||
gdd.retire(up_to).unwrap();
|
||||
let last = stage(&mut gdd, set(2));
|
||||
let last = gdd.stage_ops([set(2)]).unwrap().last().unwrap().sequence;
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
||||
assert_eq!(reopened.stage_ops([set(3)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
|
||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
||||
reopened.retire(up_to).unwrap();
|
||||
let last = reopened.session().last_hot_sequence().0;
|
||||
let last = reopened.session().last_hot_sequence();
|
||||
let clock = reopened.session().clock_counter();
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
||||
assert_eq!(reopened.stage_ops([set(4)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_change_survives_a_reopen() {
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
||||
let set = |key: &str| RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(serde_json::json!(1))),
|
||||
},
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(24), UserId(240), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.stage_ops([set("a")]).unwrap();
|
||||
gdd.retire_pending_interaction().unwrap();
|
||||
gdd.stage_ops([set("b")]).unwrap();
|
||||
|
||||
gdd.set_user(UserId(250), PeerId(25)).unwrap();
|
||||
let clock = gdd.session().clock_counter();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().peer(), PeerId(25));
|
||||
assert_eq!(reopened.session().user(), UserId(250));
|
||||
assert_eq!(reopened.session().clock_counter(), clock);
|
||||
|
||||
let staged = reopened.stage_ops([set("c")]).unwrap();
|
||||
assert!(staged.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(25) && hot_op.timestamp.counter > clock));
|
||||
assert_eq!(staged[0].sequence.0, 1, "the new peer's run starts over");
|
||||
reopened.retire_pending_interaction().unwrap();
|
||||
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
let session = reopened.session();
|
||||
assert!(session.hot_log().is_empty(), "the previous user's open step closed and retired");
|
||||
assert_eq!(session.user_of(PeerId(24)), Some(UserId(240)));
|
||||
assert_eq!(session.user_of(PeerId(25)), Some(UserId(250)));
|
||||
assert!(!session.is_mine(PeerId(24)));
|
||||
assert!(session.is_mine(PeerId(25)));
|
||||
let authors: Vec<PeerId> = session
|
||||
.history()
|
||||
.filter(|delta| matches!(delta.kind, RegistryDelta::ChangeDocumentAttribute { .. }))
|
||||
.map(|delta| delta.author)
|
||||
.collect();
|
||||
assert_eq!(authors, [PeerId(24), PeerId(24), PeerId(25)]);
|
||||
});
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use peer_transport::mock::MockNetwork;
|
||||
use peer_transport::{Event, SyncTarget};
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
|
||||
@@ -110,3 +110,13 @@ fn an_interaction_past_a_gap_waits_to_retire() {
|
||||
assert!(!host.retire_pending_interaction().expect("retire").is_empty());
|
||||
assert!(host.session().hot_log().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_user_cannot_change_while_connected() {
|
||||
let mut host = document(1);
|
||||
let mut network = MockNetwork::new(1);
|
||||
host.share(network.endpoint(), UserId(1)).expect("share");
|
||||
assert!(matches!(host.set_user(UserId(2), PeerId(2)), Err(document_format::Error::UserChangeWhileConnected)));
|
||||
assert_eq!(host.session().peer(), PeerId(1));
|
||||
assert_eq!(host.session().user(), UserId(1));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{Attributes, NetworkId, NodeId, PeerId, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
|
||||
use std::collections::HashMap;
|
||||
use crate::{Attributes, Implementation, NetworkId, NodeId, PeerId, ROOT_NETWORK, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
@@ -25,6 +25,31 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry as `to_runtime` renders it. A removed network the root still reaches counts as present.
|
||||
pub(crate) fn as_rendered(&self) -> Registry {
|
||||
let mut nodes_by_network: HashMap<NetworkId, Vec<&crate::Node>> = HashMap::new();
|
||||
for node in self.node_instances.values() {
|
||||
nodes_by_network.entry(node.network).or_default().push(node);
|
||||
}
|
||||
|
||||
let mut rendered = self.clone();
|
||||
let mut reached = HashSet::from([ROOT_NETWORK]);
|
||||
let mut pending = vec![ROOT_NETWORK];
|
||||
while let Some(network) = pending.pop() {
|
||||
for node in nodes_by_network.get(&network).into_iter().flatten() {
|
||||
if let Implementation::Network(id) = node.implementation
|
||||
&& reached.insert(id)
|
||||
{
|
||||
pending.push(id);
|
||||
if let Some(mark) = rendered.removed_networks.remove(&id) {
|
||||
rendered.networks.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
/// Whether both registries removed the same entities at the same times. Registries equal in value but not in their
|
||||
/// removal marks resolve later ops differently.
|
||||
pub fn removal_marks_equal(&self, other: &Self) -> bool {
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct SessionState {
|
||||
/// This peer's identity for the document, stable per (device, document). Per-peer rather than
|
||||
/// This peer's identity for the document, stable per (device, document, user). Per-peer rather than
|
||||
/// document identity, so it lives with the cursor here, not in the manifest. Used for CRDT
|
||||
/// tiebreaking and minting peer-scoped IDs.
|
||||
#[serde(default)]
|
||||
|
||||
@@ -19,6 +19,8 @@ pub struct Session {
|
||||
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
|
||||
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
|
||||
remote_tips: HashMap<PeerId, Rev>,
|
||||
/// The base of local diffs, so peers' edits to the working registry aren't diffed away.
|
||||
runtime_base: Option<Registry>,
|
||||
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
|
||||
/// hold the only copy, so they stay garbage collection roots for the life of the session.
|
||||
taken_back_resources: HashSet<ResourceHash>,
|
||||
@@ -43,6 +45,7 @@ impl Session {
|
||||
Self {
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -55,6 +58,19 @@ impl Session {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// Hand this device to `user` under `peer`, an unused id, so the old peer's ops keep their author.
|
||||
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let closing = self.end_interaction()?;
|
||||
let mut clock = LamportClock::new(peer);
|
||||
clock.counter = self.document.clock.counter;
|
||||
self.document.clock = clock;
|
||||
self.document.peer = peer;
|
||||
self.document.user = user;
|
||||
self.document.last_hot_sequence = HotSequence::NONE;
|
||||
self.document.redo_stack.clear();
|
||||
Ok(closing)
|
||||
}
|
||||
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
@@ -91,11 +107,26 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
let rendered;
|
||||
let base = match &self.runtime_base {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
rendered = self.document.working_registry.as_rendered();
|
||||
&rendered
|
||||
}
|
||||
};
|
||||
let ops = crate::delta::compute_deltas(base, &conversion.registry);
|
||||
|
||||
// Lenient since a peer's concurrent write may have reshaped what the diff names.
|
||||
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
|
||||
self.runtime_base = Some(conversion.registry.clone());
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.runtime_base = Some(self.document.working_registry.as_rendered());
|
||||
}
|
||||
|
||||
/// The stable [`NetworkId`] of each runtime network location for this document's peer, to key per-network view state in `session.json`.
|
||||
/// It depends only on the network structure, not on resources or declarations.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -169,10 +200,10 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Strict)
|
||||
}
|
||||
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>, mode: ApplyMode) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
@@ -180,7 +211,10 @@ impl Session {
|
||||
}
|
||||
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
let carried = pending
|
||||
.iter()
|
||||
.any(|(op, _)| matches!(op, RegistryDelta::RegisterPeer { peer: named, user: naming } if *named == peer && *naming == user));
|
||||
if !carried && self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, (RegistryDelta::RegisterPeer { peer, user }, Attributes::new()));
|
||||
}
|
||||
|
||||
@@ -199,7 +233,7 @@ impl Session {
|
||||
sequence,
|
||||
attributes,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), mode) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
@@ -213,9 +247,20 @@ impl Session {
|
||||
self.document.last_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
self.advance_runtime_base(&staged);
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
/// Keeps a later whole-document stage from restating a local batch.
|
||||
fn advance_runtime_base(&mut self, staged: &[HotOp]) {
|
||||
let Some(base) = self.runtime_base.take() else { return };
|
||||
let working = std::mem::replace(&mut self.document.working_registry, base);
|
||||
for hot_op in staged {
|
||||
let _ = self.document.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, ApplyMode::Idempotent);
|
||||
}
|
||||
self.runtime_base = Some(std::mem::replace(&mut self.document.working_registry, working));
|
||||
}
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
|
||||
@@ -289,6 +334,7 @@ impl Session {
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -314,6 +360,7 @@ impl Session {
|
||||
/// Drop hot ops another peer retired, without retiring them here. Until their deltas arrive, the working registry
|
||||
/// shows the snapshot plus what is still hot.
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.mark_retired(retired.iter().copied())
|
||||
}
|
||||
|
||||
@@ -338,6 +385,7 @@ impl Session {
|
||||
if ids.iter().any(|&id| retired.covers(id)) || !retired.took_back_all(peer, own[own.len() - 1].sequence, self.document.last_hot_sequence) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.runtime_base = None;
|
||||
let (touched, taken) = self.document.retract_hot_ops(&ids);
|
||||
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
|
||||
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
|
||||
@@ -346,6 +394,7 @@ impl Session {
|
||||
|
||||
/// Take back hot ops another peer retracted. See [`retract_interaction`](Self::retract_interaction).
|
||||
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.retract_hot_ops(ids).0
|
||||
}
|
||||
|
||||
@@ -408,6 +457,7 @@ 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);
|
||||
}
|
||||
@@ -435,6 +485,7 @@ impl Session {
|
||||
self.document.retired_snapshot = snapshot;
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
self.publish_up_to(target);
|
||||
Ok((
|
||||
HeadMove {
|
||||
@@ -482,6 +533,7 @@ impl Session {
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
if let Some(head) = moved.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
@@ -528,6 +580,7 @@ impl Session {
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
@@ -538,7 +591,11 @@ impl Session {
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
|
||||
self.document.absorb_retired_marks(remote)
|
||||
let touched = self.document.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.runtime_base = None;
|
||||
}
|
||||
touched
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -586,7 +643,7 @@ impl Session {
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)])
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
@@ -680,6 +737,7 @@ impl Session {
|
||||
} else {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
if !self.document.history.extends_canonically(length_before) {
|
||||
self.document.history.canonical_sort();
|
||||
@@ -754,6 +812,7 @@ impl Session {
|
||||
if refold {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
@@ -829,6 +888,13 @@ impl Session {
|
||||
self.document.history.mark_interaction_end(rev, timestamp);
|
||||
}
|
||||
|
||||
/// Record the retirer's clock for these deltas. Not part of their revs and never used for ordering.
|
||||
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
|
||||
for &rev in revs {
|
||||
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() {
|
||||
@@ -884,6 +950,7 @@ impl Session {
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
@@ -904,6 +971,7 @@ impl Session {
|
||||
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
|
||||
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
let mut forward = Vec::new();
|
||||
let mut cursor = Some(checkpoint);
|
||||
|
||||
@@ -281,7 +281,6 @@ fn newest_peer_registration_wins_in_any_order() {
|
||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
||||
|
||||
// The person at the device changes, so the next batch registers again.
|
||||
device.document.user = UserId(20);
|
||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
||||
@@ -296,6 +295,56 @@ fn newest_peer_registration_wins_in_any_order() {
|
||||
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_user_takes_a_fresh_peer_and_leaves_the_old_steps_to_their_maker() {
|
||||
fn interaction(session: &mut Session, key: &str) {
|
||||
session.stage_ops([set_attribute(key, 1)]).expect("stage");
|
||||
session.end_interaction().expect("close");
|
||||
for closed in session.closed_interactions() {
|
||||
session.retire_interaction(&closed).expect("retire");
|
||||
}
|
||||
}
|
||||
let mut device = Session::with_identity(PeerId(1), UserId(10));
|
||||
for key in ["a", "b", "c"] {
|
||||
interaction(&mut device, key);
|
||||
}
|
||||
device.undo().expect("undo c");
|
||||
assert!(device.can_redo());
|
||||
device.stage_ops([set_attribute("d", 1)]).expect("stage d, left open");
|
||||
let clock_before = device.clock_counter();
|
||||
|
||||
let closing = device.set_user(UserId(20), PeerId(2)).expect("switch");
|
||||
assert!(closing.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(1)), "the old peer closes its own interaction");
|
||||
assert!(closing.last().is_some_and(crate::HotOp::ends_interaction));
|
||||
assert_eq!(device.peer(), PeerId(2));
|
||||
assert!(device.clock_counter() >= clock_before);
|
||||
assert!(!device.can_undo(), "the previous user's steps are not this person's to undo");
|
||||
assert!(!device.can_redo());
|
||||
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
|
||||
assert!(!device.is_mine(PeerId(1)));
|
||||
|
||||
device.stage_ops([set_attribute("e", 1)]).expect("stage e");
|
||||
device.end_interaction().expect("close e");
|
||||
let new_ops: Vec<_> = device.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(2)).collect();
|
||||
assert_eq!(new_ops.first().map(|hot_op| hot_op.sequence), Some(crate::HotSequence(1)), "the new peer's run starts over");
|
||||
assert!(new_ops.iter().all(|hot_op| hot_op.timestamp.counter > clock_before));
|
||||
for closed in device.closed_interactions() {
|
||||
device.retire_interaction(&closed).expect("retire");
|
||||
}
|
||||
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10), "the old registration stands");
|
||||
assert_eq!(device.user_of(PeerId(2)), Some(UserId(20)));
|
||||
assert!(device.is_mine(PeerId(2)));
|
||||
for delta in device.history().filter(|delta| !matches!(delta.kind, RegistryDelta::RegisterPeer { .. })) {
|
||||
let expected = if delta.author == PeerId(1) { UserId(10) } else { UserId(20) };
|
||||
assert_eq!(device.user_of(delta.author), Some(expected));
|
||||
}
|
||||
|
||||
assert!(device.can_undo(), "the new user's own step undoes");
|
||||
device.undo().expect("undo e");
|
||||
assert!(!device.can_undo(), "but not past it into the previous user's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
//! Peers exchanging retired history, moving the shared head, and undoing against what other peers hold.
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput as RuntimeInput, NodeNetwork};
|
||||
|
||||
use crate::{
|
||||
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry,
|
||||
ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
|
||||
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, NoMetadata, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta,
|
||||
ResourceEntry, ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -397,6 +402,46 @@ fn rebuilt_working(session: &Session) -> Registry {
|
||||
copy.document.working_registry
|
||||
}
|
||||
|
||||
fn runtime_network(values: [u32; 2]) -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
|
||||
nodes: [(
|
||||
RuntimeNodeId(0),
|
||||
DocumentNode {
|
||||
inputs: values.iter().map(|&value| RuntimeInput::value(TaggedValue::Integer(value as i64), false)).collect(),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stage past a peer's shrunken input list lands like a peer's write, so later stages don't fail.
|
||||
#[test]
|
||||
fn a_local_stage_after_a_peers_input_list_change_still_lands() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
a.stage_from_runtime(&runtime_network([1, 2]), &NoMetadata, &resources).expect("first stage");
|
||||
let up_to = a.hot_log().last().unwrap().timestamp;
|
||||
a.retire(up_to).unwrap();
|
||||
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
let (&id, node) = b.registry().node_instances.iter().find(|(_, node)| node.inputs().len() == 2).expect("the converted node");
|
||||
let first = node.inputs()[0].clone();
|
||||
let shrink = b.stage_ops([RegistryDelta::SetNodeInputs { id, inputs: vec![first] }]).unwrap();
|
||||
for hot_op in shrink {
|
||||
a.replay_hot_op(hot_op).unwrap();
|
||||
}
|
||||
|
||||
let edit = a.stage_from_runtime(&runtime_network([1, 5]), &NoMetadata, &resources);
|
||||
let later = a.stage_from_runtime(&runtime_network([9, 5]), &NoMetadata, &resources);
|
||||
assert!(edit.is_ok() || later.is_ok(), "a later stage still lands: first {:?}, later {:?}", edit.err(), later.err());
|
||||
}
|
||||
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, bound: u64) -> u64 {
|
||||
@@ -439,7 +484,11 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
key: key.into(),
|
||||
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(50)))),
|
||||
};
|
||||
Some(match rng.below(9) {
|
||||
let source_key = |rng: &mut Lcg| crate::SourceKey {
|
||||
priority: crate::Priority::new(rng.below(2) as f64).expect("finite"),
|
||||
peer: PeerId(1 + rng.below(2)),
|
||||
};
|
||||
Some(match rng.below(17) {
|
||||
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: {
|
||||
let key = ["x", "y"][rng.below(2) as usize];
|
||||
@@ -500,7 +549,7 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
new_input: input(rng),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
8 => {
|
||||
let id = pick(rng, seen_nodes.clone())?;
|
||||
let inputs = (0..1 + rng.below(3))
|
||||
.map(|_| InputSlot {
|
||||
@@ -511,6 +560,55 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
.collect();
|
||||
RegistryDelta::SetNodeInputs { id: NodeId(id), inputs }
|
||||
}
|
||||
9 => RegistryDelta::SetNetworkExport {
|
||||
id: NetworkId(pick(rng, seen_networks.clone())?),
|
||||
index: rng.below(2) as u32,
|
||||
export: (rng.below(3) > 0).then(|| input(rng)),
|
||||
},
|
||||
10 => RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(pick(rng, seen_networks.clone())?),
|
||||
delta: attribute(rng, "name"),
|
||||
},
|
||||
11 => RegistryDelta::SetNodeImplementation {
|
||||
id: NodeId(pick(rng, seen_nodes.clone())?),
|
||||
implementation: Implementation::Network(NetworkId(pick(rng, seen_networks.clone())?)),
|
||||
},
|
||||
12 => {
|
||||
let mut entry = ResourceEntry {
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
..Default::default()
|
||||
};
|
||||
entry.force_set_source(
|
||||
source_key(rng),
|
||||
crate::SourceValue {
|
||||
source: Value::from(serde_json::json!(rng.below(9))),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
RegistryDelta::AddResource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
entry,
|
||||
}
|
||||
}
|
||||
13 => {
|
||||
let id = ResourceId::from(1 + rng.below(2));
|
||||
let snapshot = registry.resources.get(&id)?.clone();
|
||||
RegistryDelta::RemoveResource { id, snapshot }
|
||||
}
|
||||
14 => RegistryDelta::SetResourceHash {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
},
|
||||
15 => RegistryDelta::AddSource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
key: source_key(rng),
|
||||
source: Value::from(serde_json::json!(rng.below(9))),
|
||||
},
|
||||
_ => RegistryDelta::RemoveSource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
key: source_key(rng),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -774,7 +872,7 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
|
||||
host.commit_op_for_test(set_attribute("shared", 2)).expect("later step");
|
||||
let later = host.head_rev().expect("rev");
|
||||
host.mark_interaction_end(later);
|
||||
host.document.history.set_retired_at(later, 1_234);
|
||||
host.stamp_retired_at(&[later], 1_234);
|
||||
catch_up(&mut guest, &host);
|
||||
assert_eq!(guest.head_rev(), host.head_rev());
|
||||
assert_eq!(guest.latest_own_interaction(), Some(undone));
|
||||
@@ -1017,6 +1115,68 @@ fn discarded_hot_ops_leave_the_working_registry_at_the_snapshot() {
|
||||
assert_eq!(session.registry(), session.retired_registry());
|
||||
}
|
||||
|
||||
/// Staging a rebuilt runtime unchanged must not restore a network a peer removed while another kept writing to its owner.
|
||||
#[test]
|
||||
fn restaging_an_unchanged_runtime_does_not_revive_a_nested_network_removed_under_a_live_owner() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let outer = NodeNetwork {
|
||||
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
|
||||
nodes: [(
|
||||
RuntimeNodeId(0),
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(graph_craft::document::NetworkId(9)),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
definitions: [(graph_craft::document::NetworkId(9), runtime_network([1, 2]))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
let (_, conversion) = a.stage_from_runtime(&outer, &NoMetadata, &resources).expect("first stage");
|
||||
let up_to = a.hot_log().last().unwrap().timestamp;
|
||||
a.retire(up_to).unwrap();
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
|
||||
let (&owner, owner_node) = b
|
||||
.registry()
|
||||
.node_instances
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(node.implementation(), Implementation::Network(_)))
|
||||
.expect("the owner");
|
||||
let Implementation::Network(nested) = *owner_node.implementation() else { unreachable!() };
|
||||
let mut removal = vec![RegistryDelta::RemoveNode {
|
||||
id: owner,
|
||||
snapshot: owner_node.clone(),
|
||||
}];
|
||||
for (&id, node) in b.registry().node_instances.iter().filter(|(_, node)| node.network() == nested) {
|
||||
removal.push(RegistryDelta::RemoveNode { id, snapshot: node.clone() });
|
||||
}
|
||||
removal.push(RegistryDelta::RemoveNetwork {
|
||||
id: nested,
|
||||
snapshot: b.registry().networks[&nested].clone(),
|
||||
});
|
||||
let removal = b.stage_ops(removal).unwrap();
|
||||
|
||||
// A writes after the removal, so only the nested network goes.
|
||||
for _ in 0..10 {
|
||||
a.document.clock.tick();
|
||||
}
|
||||
a.stage_ops([change_node_attribute(owner, "tint", serde_json::json!(1))]).unwrap();
|
||||
for hot_op in removal {
|
||||
a.replay_hot_op(hot_op).unwrap();
|
||||
}
|
||||
assert!(a.registry().node_instances.contains_key(&owner));
|
||||
assert!(!a.registry().networks.contains_key(&nested));
|
||||
|
||||
let (runtime, _) = a.registry().to_runtime_with_metadata(&conversion.declarations).expect("to runtime");
|
||||
a.mark_runtime_current();
|
||||
a.stage_from_runtime(&runtime, &NoMetadata, &resources).expect("restage");
|
||||
assert!(!a.registry().networks.contains_key(&nested), "the removed network stays removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
@@ -1047,3 +1207,45 @@ fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
|
||||
assert_eq!(session.retired_registry(), &retired);
|
||||
assert_eq!(session.registry(), ®istry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_carrying_its_registration_is_not_given_another() {
|
||||
let mut session = Session::with_peer(crate::PeerId(1));
|
||||
let register = RegistryDelta::RegisterPeer {
|
||||
peer: crate::PeerId(1),
|
||||
user: session.user(),
|
||||
};
|
||||
assert_eq!(session.stage_computed_ops(vec![register]).expect("stage").len(), 1);
|
||||
}
|
||||
|
||||
/// Only what the root reaches renders, so a removal no rendered node undoes stays a removal.
|
||||
#[test]
|
||||
fn a_removed_network_counts_as_rendered_only_when_the_root_reaches_it() {
|
||||
let (run_by_root, nested, run_by_stray, stray) = (NetworkId(1), NetworkId(2), NetworkId(3), NetworkId(4));
|
||||
let node = |network, runs| crate::Node {
|
||||
presence: TimeStamp::default(),
|
||||
network,
|
||||
network_timestamp: TimeStamp::default(),
|
||||
implementation: Implementation::Network(runs),
|
||||
implementation_timestamp: TimeStamp::default(),
|
||||
inputs: Vec::new(),
|
||||
inputs_timestamp: TimeStamp::default(),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut registry = Registry::default();
|
||||
for (id, network, runs) in [(1, crate::ROOT_NETWORK, run_by_root), (2, run_by_root, nested), (3, stray, run_by_stray)] {
|
||||
registry.node_instances.insert(crate::NodeId(id), node(network, runs));
|
||||
}
|
||||
for id in [run_by_root, nested, run_by_stray] {
|
||||
let mark = crate::Tombstone {
|
||||
content: Network::default(),
|
||||
timestamp: TimeStamp::default(),
|
||||
placeholder: false,
|
||||
};
|
||||
registry.removed_networks.insert(id, mark);
|
||||
}
|
||||
|
||||
let rendered = registry.as_rendered();
|
||||
assert!(rendered.networks.contains_key(&run_by_root) && rendered.networks.contains_key(&nested));
|
||||
assert!(!rendered.networks.contains_key(&run_by_stray) && rendered.removed_networks.contains_key(&run_by_stray));
|
||||
}
|
||||
@@ -190,6 +190,21 @@ impl RuntimeProjection<'_> {
|
||||
(network == ROOT_NETWORK || self.reachable.contains(&network)).then(|| runtime_location(network))
|
||||
}
|
||||
|
||||
pub fn definitions(&self) -> impl Iterator<Item = RuntimeNetworkId> + '_ {
|
||||
self.reachable.iter().map(|&id| runtime_network_id(id))
|
||||
}
|
||||
|
||||
pub fn network_nodes(&self, network: NetworkId) -> impl Iterator<Item = NodeId> + '_ {
|
||||
self.context.nodes_by_network.get(&network).into_iter().flatten().map(|&(id, _)| id)
|
||||
}
|
||||
|
||||
pub fn implemented_network(&self, id: NodeId) -> Option<NetworkId> {
|
||||
match self.context.registry.node_instances.get(&id)?.implementation {
|
||||
Implementation::Network(network) => Some(network),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The location of the node's network in the runtime, and the node's ID in that network.
|
||||
pub fn node_address(&self, id: NodeId) -> Option<(NetworkLocation, RuntimeNodeId)> {
|
||||
let node = self.context.registry.node_instances.get(&id)?;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "document-live"
|
||||
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-format = { workspace = true, features = ["network"] }
|
||||
document-graph-storage = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,118 @@
|
||||
//! A memory-backed document in a collaborative session. The caller spawns the transport driver.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout, ResourceProxy};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
pub use document_graph_storage::to_runtime::ConversionError;
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LiveError {
|
||||
#[error(transparent)]
|
||||
Format(#[from] FormatError),
|
||||
#[error(transparent)]
|
||||
Conversion(#[from] ConversionError),
|
||||
}
|
||||
|
||||
pub struct LiveDocument {
|
||||
gdd: GddV1,
|
||||
token: SessionToken,
|
||||
}
|
||||
|
||||
impl LiveDocument {
|
||||
/// Host an empty document under `token`. `spawn` must drive the returned future for the whole session.
|
||||
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let gdd = Self::empty_document(peer, user).await?;
|
||||
Self::host_document(gdd, signaling_server, token, user, spawn)
|
||||
}
|
||||
|
||||
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
gdd.share(Self::connect(signaling_server, token, spawn), user)?;
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let mut gdd = Self::empty_document(peer, user).await?;
|
||||
gdd.connect(Self::connect(signaling_server, token, spawn), user)?;
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
fn connect(signaling_server: &str, token: SessionToken, spawn: impl FnOnce(MessageLoopFuture)) -> Room {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
room
|
||||
}
|
||||
|
||||
async fn empty_document(peer: PeerId, user: UserId) -> Result<GddV1, FormatError> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, user, peer.0, version.clone(), version)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> SessionToken {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.gdd.role()
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
|
||||
}
|
||||
|
||||
pub fn missing_resources(&self) -> Vec<ResourceHash> {
|
||||
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
}
|
||||
|
||||
/// Apply what peers sent and answer their requests. Call it regularly.
|
||||
pub async fn poll(&mut self) -> Vec<Event> {
|
||||
let events = self.gdd.poll_peers();
|
||||
for event in &events {
|
||||
let Event::ResourceRequested { from, hash } = event else { continue };
|
||||
match self.gdd.read_resource(hash).await {
|
||||
Ok(bytes) => {
|
||||
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
|
||||
log::warn!("Failed to send resource {hash}: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
pub fn document(&self) -> &GddV1 {
|
||||
&self.gdd
|
||||
}
|
||||
|
||||
pub fn document_mut(&mut self) -> &mut GddV1 {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
/// Async because proto-node declarations are resources.
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
|
||||
self.gdd.resource_proxy()
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,10 @@ impl Replica {
|
||||
Some(Role::Host)
|
||||
}
|
||||
|
||||
pub fn has_host(&self) -> bool {
|
||||
self.current_host().is_some()
|
||||
}
|
||||
|
||||
/// The link and id of the peer greeting as host. While two coexist this is the one with the lower id, which keeps
|
||||
/// the role once they meet.
|
||||
fn current_host(&self) -> Option<(TransportPeerId, PeerId)> {
|
||||
|
||||
+2
-1
@@ -22,12 +22,13 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
document-format = { workspace = true, features = ["migrations"] }
|
||||
document-format = { workspace = true, features = ["migrations", "network"] }
|
||||
migration-formats = { workspace = true }
|
||||
migration-compiled = { workspace = true }
|
||||
migration-nodes = { workspace = true }
|
||||
document-graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-container = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
blake3 = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
|
||||
@@ -291,6 +291,7 @@ impl Dispatcher {
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
|
||||
tools: &self.message_handlers.tool_message_handler,
|
||||
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
@@ -305,6 +306,8 @@ impl Dispatcher {
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
|
||||
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
|
||||
@@ -3,7 +3,8 @@ use crate::messages::prelude::*;
|
||||
|
||||
/// Lists the stored documents that stayed closed because another tab has them open.
|
||||
pub struct DocumentsOpenElsewhereDialog {
|
||||
pub documents: Vec<(DocumentId, String)>,
|
||||
/// Id, name and whether it is in a live session.
|
||||
pub documents: Vec<(DocumentId, String, bool)>,
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for DocumentsOpenElsewhereDialog {
|
||||
@@ -24,19 +25,23 @@ impl LayoutHolder for DocumentsOpenElsewhereDialog {
|
||||
let mut rows = vec![
|
||||
LayoutGroup::row(vec![TextLabel::new(format!("{count} {documents} open in another tab.")).bold(true).multiline(true).widget_instance()]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(format!("{are} closed here so the two tabs don't overwrite each other.\nA copy opens here as a separate document."))
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
TextLabel::new(format!(
|
||||
"{are} closed here so the two tabs don't overwrite each other.\nA copy is a separate document, while joining a session edits it live."
|
||||
))
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
];
|
||||
rows.extend(self.documents.iter().cloned().map(|(source, name)| {
|
||||
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
|
||||
let label = TextLabel::new(name.clone()).widget_instance();
|
||||
let button = TextButton::new("Open a Copy")
|
||||
let button = TextButton::new(if shared { "Join in This Tab" } else { "Open a Copy" })
|
||||
.on_update(move |_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }.into()],
|
||||
}
|
||||
.into()
|
||||
let followup = if shared {
|
||||
PortfolioMessage::JoinStoredSession { source }
|
||||
} else {
|
||||
PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }
|
||||
};
|
||||
DialogMessage::CloseAndThen { followups: vec![followup.into()] }.into()
|
||||
})
|
||||
.widget_instance();
|
||||
LayoutGroup::row(vec![label, Separator::new(SeparatorStyle::Unrelated).widget_instance(), button])
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -140,6 +140,9 @@ pub enum FrontendMessage {
|
||||
url: String,
|
||||
},
|
||||
TriggerClipboardRead,
|
||||
TriggerSessionLinkCopy {
|
||||
token: String,
|
||||
},
|
||||
TriggerClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
@@ -190,6 +193,15 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "box")]
|
||||
box_selection: Option<BoxSelection>,
|
||||
},
|
||||
UpdateDocumentCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateContextMenuInformation {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
|
||||
@@ -12,6 +12,17 @@ pub struct DocumentInfo {
|
||||
#[serde(default)]
|
||||
pub path: Option<PathBuf>,
|
||||
pub is_saved: bool,
|
||||
/// `None` when not shared.
|
||||
#[serde(default)]
|
||||
pub session: Option<SessionStatus>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SessionStatus {
|
||||
Connected,
|
||||
/// The transport is down or the document isn't mounted. It reconnects on mount.
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
|
||||
@@ -76,6 +76,7 @@ define_layout_target!(
|
||||
NodeGraphControlBar,
|
||||
/// The body of the Inspector containing many collapsable sections.
|
||||
Inspector,
|
||||
SessionPanel,
|
||||
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
||||
StatusBarHints,
|
||||
/// The version information shown in the status bar at the bottom right of the window.
|
||||
|
||||
@@ -24,6 +24,8 @@ pub struct MenuBarMessageHandler {
|
||||
pub show_storage_preferences: bool,
|
||||
pub make_path_editable_is_allowed: bool,
|
||||
pub data_panel_open: bool,
|
||||
pub session_panel_open: bool,
|
||||
pub history_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub inspector_open: bool,
|
||||
pub focus_document: bool,
|
||||
@@ -687,6 +689,16 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Session")
|
||||
.label("Session")
|
||||
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("History")
|
||||
.label("History")
|
||||
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::{Declarations, Registry, Value};
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, StagingError, construct_batch};
|
||||
@@ -35,6 +35,18 @@ pub struct DocumentHistory {
|
||||
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
|
||||
/// part of the distance between the two.
|
||||
needs_whole_document_stage: bool,
|
||||
/// How storage undid each step on the legacy redo stack, aligned with its top.
|
||||
undo_notes: Vec<UndoNote>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum UndoNote {
|
||||
/// The step was hot and got taken back.
|
||||
Retracted(Vec<document_graph_storage::RegistryDelta>),
|
||||
/// The step had retired and was dropped from the shared line.
|
||||
Dropped(document_graph_storage::Rev),
|
||||
/// The storage cursor moved back over the step.
|
||||
Cursor,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
@@ -77,6 +89,7 @@ impl DocumentHistory {
|
||||
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
|
||||
pub fn clear_redo(&mut self) {
|
||||
self.legacy_redo_stack.clear();
|
||||
self.undo_notes.clear();
|
||||
}
|
||||
|
||||
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
|
||||
@@ -99,6 +112,10 @@ impl DocumentHistory {
|
||||
self.storage.as_mut()
|
||||
}
|
||||
|
||||
pub fn declarations(&self) -> &Declarations {
|
||||
&self.declarations
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
|
||||
@@ -112,9 +129,124 @@ impl DocumentHistory {
|
||||
self.needs_whole_document_stage = true;
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
|
||||
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
|
||||
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
|
||||
pub fn end_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.end_interaction() {
|
||||
log::error!("Closing the storage interaction failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undoes the latest step in storage alone. Returns whether storage undid it.
|
||||
pub fn undo_in_storage(&mut self, in_session: bool) -> bool {
|
||||
if self.legacy_undo_stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let note = if let Some(ops) = self.retract_storage_interaction() {
|
||||
UndoNote::Retracted(ops)
|
||||
} else if in_session && let Some(rev) = self.undo_retired_step() {
|
||||
UndoNote::Dropped(rev)
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if let Some(snapshot) = self.pop_undo() {
|
||||
self.push_redo(snapshot);
|
||||
}
|
||||
self.note_undo(note);
|
||||
true
|
||||
}
|
||||
|
||||
/// Reverses [`undo_in_storage`](Self::undo_in_storage). Returns whether the next redo step was undone there.
|
||||
pub fn redo_in_storage(&mut self) -> bool {
|
||||
if self.legacy_redo_stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
|
||||
let Some(note) = self
|
||||
.undo_notes
|
||||
.pop_if(|note| matches!(note, UndoNote::Retracted(_)) || (reachable && matches!(note, UndoNote::Dropped(_))))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if let Some(snapshot) = self.pop_redo() {
|
||||
self.push_undo(snapshot);
|
||||
}
|
||||
match note {
|
||||
UndoNote::Retracted(ops) => self.restage_ops(ops),
|
||||
UndoNote::Dropped(rev) => {
|
||||
self.redo_retired_step(rev);
|
||||
}
|
||||
UndoNote::Cursor => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn note_cursor_undo(&mut self) {
|
||||
self.note_undo(UndoNote::Cursor);
|
||||
}
|
||||
|
||||
pub fn forget_undo_note(&mut self) {
|
||||
self.undo_notes.pop();
|
||||
}
|
||||
|
||||
fn note_undo(&mut self, note: UndoNote) {
|
||||
self.undo_notes.push(note);
|
||||
let evicted = self.undo_notes.len().saturating_sub(self.legacy_redo_stack.len());
|
||||
self.undo_notes.drain(..evicted);
|
||||
}
|
||||
|
||||
fn retract_storage_interaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
|
||||
self.storage.as_mut()?.retract_interaction().unwrap_or_else(|error| {
|
||||
log::error!("Taking the storage interaction back failed: {error}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.restage_ops(ops) {
|
||||
log::error!("Staging the redone step failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
|
||||
self.storage.as_mut()?.undo_retired_step().unwrap_or_else(|error| {
|
||||
log::error!("Undoing the retired step failed: {error}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
|
||||
self.storage.as_ref().map(|storage| storage.resource_gc_roots()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
self.change_line(|storage| storage.redo_retired_step(rev), "Redoing the dropped step failed")
|
||||
}
|
||||
|
||||
pub fn drop_step(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
self.change_line(|storage| storage.drop_step(rev), "Removing the step failed")
|
||||
}
|
||||
|
||||
pub fn move_head_to(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
self.change_line(|storage| storage.move_head(rev), "Moving the head failed")
|
||||
}
|
||||
|
||||
fn change_line(&mut self, change: impl FnOnce(&mut document_format::GddV1) -> Result<(), document_format::Error>, failure: &str) -> bool {
|
||||
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
|
||||
return false;
|
||||
};
|
||||
change(storage).inspect_err(|error| log::error!("{failure}: {error}")).is_ok()
|
||||
}
|
||||
|
||||
/// Forgets the legacy snapshots once the head has moved off their line.
|
||||
pub fn clear_legacy(&mut self) {
|
||||
self.legacy_undo_stack.clear();
|
||||
self.legacy_redo_stack.clear();
|
||||
self.undo_notes.clear();
|
||||
}
|
||||
|
||||
pub fn retire_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.retire_pending_interaction() {
|
||||
@@ -124,10 +256,19 @@ impl DocumentHistory {
|
||||
|
||||
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
|
||||
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
|
||||
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
|
||||
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
|
||||
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are closed into one
|
||||
/// interaction by [`end_storage_interaction`](Self::end_storage_interaction) at undo-step boundaries.
|
||||
pub fn stage_snapshot(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, view_settings: BTreeMap<String, Value>, byte_store: &dyn ResourceStorage) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if !self.stage_graph(deltas, interface, registry, byte_store) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// [`stage_snapshot`](Self::stage_snapshot) without the view state. Returns whether the working copy took the batch.
|
||||
pub fn stage_graph(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> bool {
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
|
||||
let staged = match self.needs_whole_document_stage {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
@@ -148,14 +289,13 @@ impl DocumentHistory {
|
||||
Ok(declarations) => {
|
||||
self.declarations.extend(declarations);
|
||||
self.needs_whole_document_stage = false;
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// Converts the whole document and stages the difference from what the working copy holds.
|
||||
@@ -235,15 +375,60 @@ impl DocumentHistory {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
|
||||
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
|
||||
}
|
||||
|
||||
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
|
||||
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
|
||||
let storage = self.storage.as_ref()?;
|
||||
|
||||
storage
|
||||
.registry()
|
||||
.to_runtime_with_full_metadata(&self.declarations)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
|
||||
.map_err(|error| {
|
||||
log::error!("Storage undo/redo rebuild failed: {error}");
|
||||
CursorMoveError::RebuildFailed
|
||||
})
|
||||
.inspect_err(|error| log::error!("Storage interface rebuild failed: {error}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
|
||||
let Some(storage) = self.storage.as_ref() else { return Vec::new() };
|
||||
|
||||
let mut hashes: Vec<ResourceHash> = storage
|
||||
.session()
|
||||
.all_declaration_resources()
|
||||
.into_iter()
|
||||
.filter_map(|(id, hash)| hash.filter(|_| !self.declarations.contains_key(&id)))
|
||||
.collect();
|
||||
hashes.sort_unstable();
|
||||
hashes.dedup();
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Cache a peer's resource as a declaration if one names its hash. Returns false when the bytes don't decode.
|
||||
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) -> bool {
|
||||
let Some(storage) = self.storage.as_ref() else { return true };
|
||||
|
||||
let referencing: Vec<ResourceId> = storage
|
||||
.session()
|
||||
.all_declaration_resources()
|
||||
.into_iter()
|
||||
.filter_map(|(id, declaration_hash)| (declaration_hash == Some(hash)).then_some(id))
|
||||
.collect();
|
||||
if referencing.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
match document_graph_storage::decode_declaration(bytes) {
|
||||
Ok(declaration) => {
|
||||
self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone())));
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Failed to deserialize a received ProtoNode declaration: {error}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
|
||||
|
||||
@@ -56,6 +56,17 @@ pub enum DocumentMessage {
|
||||
DeselectAllLayers,
|
||||
DocumentHistoryBackward,
|
||||
DocumentHistoryForward,
|
||||
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
|
||||
HistoryMoveHead {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
/// Drops a retired interaction and mints the later ones again on its parent.
|
||||
HistoryRemoveStep {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
HistoryRestoreStep {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
DocumentStructureChanged,
|
||||
DrawArtboardOverlays {
|
||||
context: OverlayContext,
|
||||
|
||||
@@ -23,7 +23,7 @@ use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
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};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
@@ -37,7 +37,7 @@ use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use document_container::AnyContainer;
|
||||
use document_graph_storage::Declarations;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceStorage};
|
||||
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graph_craft::list;
|
||||
@@ -53,8 +53,12 @@ use graphene_std::vector::style::{GradientStops, RenderMode};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The document attribute holding its name, shared so renames reach peers.
|
||||
pub const DOCUMENT_NAME_ATTRIBUTE: &str = "name";
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct DocumentMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
@@ -172,6 +176,9 @@ pub struct DocumentMessageHandler {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore")]
|
||||
pub(crate) container: Option<AnyContainer>,
|
||||
/// Peer changes not yet applied, held until their declarations are cached.
|
||||
#[serde(skip)]
|
||||
pub(crate) pending_remote: document_format::network::RemoteChanges,
|
||||
/// Hash of the document snapshot that was most recently saved to disk by the user.
|
||||
#[serde(skip)]
|
||||
saved_hash: Option<u64>,
|
||||
@@ -235,6 +242,7 @@ impl Default for DocumentMessageHandler {
|
||||
selection_network_path: Vec::new(),
|
||||
history: DocumentHistory::default(),
|
||||
container: None,
|
||||
pending_remote: Default::default(),
|
||||
saved_hash: None,
|
||||
auto_saved_hash: None,
|
||||
layer_range_selection_reference: None,
|
||||
@@ -465,6 +473,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
|
||||
}
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::HistoryMoveHead { rev } => self.apply_history_action(
|
||||
document_id,
|
||||
|history| history.move_head_to(rev),
|
||||
&resource_storage.resources_mut(),
|
||||
preferences.validate_storage_round_trip,
|
||||
responses,
|
||||
),
|
||||
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(
|
||||
document_id,
|
||||
|history| history.drop_step(rev),
|
||||
&resource_storage.resources_mut(),
|
||||
preferences.validate_storage_round_trip,
|
||||
responses,
|
||||
),
|
||||
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(
|
||||
document_id,
|
||||
|history| history.redo_retired_step(rev),
|
||||
&resource_storage.resources_mut(),
|
||||
preferences.validate_storage_round_trip,
|
||||
responses,
|
||||
),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -1147,6 +1176,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.path = None;
|
||||
self.set_save_state(false);
|
||||
self.set_auto_save_state(false);
|
||||
self.stage_name_attribute();
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::UpdateNewNodeGraph);
|
||||
@@ -1659,7 +1689,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
|
||||
DocumentMessage::StartTransaction => {
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
self.retire_storage_interaction();
|
||||
self.end_storage_interaction();
|
||||
|
||||
self.network_interface.start_transaction();
|
||||
self.history.push_undo(self.network_interface.clone());
|
||||
@@ -2177,7 +2207,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
impl DocumentMessageHandler {
|
||||
/// Build a document handler from a `.gdd` working copy.
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
pub fn from_storage(
|
||||
interface: NodeNetworkInterface,
|
||||
storage: document_format::GddV1,
|
||||
declarations: Declarations,
|
||||
byte_store: Arc<dyn ResourceStorage>,
|
||||
name: String,
|
||||
path: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
let mut document = Self {
|
||||
network_interface: interface,
|
||||
name,
|
||||
@@ -2186,11 +2223,7 @@ impl DocumentMessageHandler {
|
||||
};
|
||||
|
||||
document.apply_stored_document_settings(storage.view_settings());
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => document.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
|
||||
}
|
||||
document.history.set_storage(storage, declarations);
|
||||
document.set_storage(storage, declarations, byte_store);
|
||||
|
||||
document
|
||||
}
|
||||
@@ -2373,6 +2406,40 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
|
||||
fn stored_name(&self) -> Option<&str> {
|
||||
let attribute = self.storage()?.registry().attributes.get(DOCUMENT_NAME_ATTRIBUTE).filter(|attribute| !attribute.deleted)?;
|
||||
match &attribute.value {
|
||||
document_graph_storage::Value::Str(name) => Some(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stage_name_attribute(&mut self) {
|
||||
if self.stored_name() == Some(self.name.as_str()) {
|
||||
return;
|
||||
}
|
||||
let delta = document_graph_storage::AttributeDelta {
|
||||
key: DOCUMENT_NAME_ATTRIBUTE.to_string(),
|
||||
value: Some(document_graph_storage::Value::Str(self.name.clone())),
|
||||
};
|
||||
let Some(gdd) = self.storage_mut() else { return };
|
||||
if let Err(error) = gdd.stage_ops([document_graph_storage::RegistryDelta::ChangeDocumentAttribute { delta }]) {
|
||||
log::error!("Staging the document name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn adopt_name_from_storage(&mut self) -> bool {
|
||||
let Some(name) = self.stored_name().filter(|name| *name != self.name).map(str::to_string) else {
|
||||
return false;
|
||||
};
|
||||
self.name = name;
|
||||
true
|
||||
}
|
||||
|
||||
/// Path to the subnetwork that the user's selection is currently scoped to.
|
||||
/// Empty when the selection lives in the root document network.
|
||||
pub fn selection_network_path(&self) -> &[NodeId] {
|
||||
@@ -2390,8 +2457,14 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
|
||||
storage.set_byte_store(byte_store);
|
||||
self.history.set_storage(storage, declarations);
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
pub(crate) fn end_storage_interaction(&mut self) {
|
||||
self.history.end_storage_interaction();
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
|
||||
@@ -2420,7 +2493,8 @@ impl DocumentMessageHandler {
|
||||
let view_settings = self.storage_view_settings();
|
||||
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
|
||||
|
||||
if validate {
|
||||
// The interface lags the registry until peer changes are applied
|
||||
if validate && self.pending_remote.is_empty() {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
@@ -2495,6 +2569,93 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the resource registry from storage, or keep it on failure. `Resource` inputs resolve through it.
|
||||
fn refresh_resource_registry(&mut self) {
|
||||
let Some(storage) = self.history.storage() else { return };
|
||||
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => self.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn stage_pending_edits(&mut self, byte_store: &dyn ResourceStorage) {
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.history.stage_graph(&deltas, &self.network_interface, &self.resources.registry, byte_store);
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let changes = std::mem::take(&mut self.pending_remote);
|
||||
if changes.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
if !changes.rebuilt
|
||||
&& let Some(gdd) = self.history.storage()
|
||||
{
|
||||
let peer = gdd.session().peer();
|
||||
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
|
||||
Ok(reconciled) => {
|
||||
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
|
||||
return true;
|
||||
}
|
||||
Err(ReconcileError::DeclarationMissing(id)) => {
|
||||
log::debug!("Remote changes wait for declaration {id}");
|
||||
self.pending_remote = changes;
|
||||
return false;
|
||||
}
|
||||
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
match self.history.rebuild_interface() {
|
||||
Some(rebuilt) => {
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
self.pending_remote = changes;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
|
||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||
self.network_interface.unload_stack_dependents(&path);
|
||||
self.network_interface.unload_import_export_ports(&path);
|
||||
self.network_interface.unload_all_nodes_bounding_box(&path);
|
||||
self.network_interface.unload_outward_wires(&path);
|
||||
self.network_interface.unload_all_nodes_click_targets(&path);
|
||||
}
|
||||
self.network_interface.load_structure();
|
||||
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
gdd.mark_runtime_current();
|
||||
}
|
||||
if resources_changed {
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
pub(crate) fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) -> bool {
|
||||
self.history.cache_declaration_bytes(hash, bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
|
||||
self.history.undecoded_declaration_hashes()
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
@@ -2506,6 +2667,11 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
self.pending_remote = Default::default();
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
gdd.mark_runtime_current();
|
||||
}
|
||||
self.refresh_resource_registry();
|
||||
|
||||
if validate {
|
||||
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
|
||||
@@ -2827,16 +2993,73 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
// The storage path skips `undo`, which settles a glide before the snapshot moves
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
// The legacy snapshot predates peers' writes, so follow only what storage changed
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.undo_in_storage(self.is_in_session()) {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
return;
|
||||
}
|
||||
// A session's history is shared, so no legacy snapshot may be installed
|
||||
if self.is_in_session() {
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
self.history.note_cursor_undo();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
/// Performs a History panel action in storage and drops the legacy snapshots, which are off the head's line.
|
||||
fn apply_history_action(
|
||||
&mut self,
|
||||
document_id: DocumentId,
|
||||
action: impl FnOnce(&mut DocumentHistory) -> bool,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
validate: bool,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
self.stage_edits_outside_transaction(byte_store, validate);
|
||||
self.history.retire_storage_interaction();
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if !action(&mut self.history) {
|
||||
return;
|
||||
}
|
||||
self.history.clear_legacy();
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
let changes = gdd.take_remote_changes();
|
||||
self.pending_remote.extend(changes);
|
||||
}
|
||||
self.apply_remote_changes(responses);
|
||||
if self.stored_name() != name_before.as_deref() && self.adopt_name_from_storage() {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_in_session(&self) -> bool {
|
||||
self.storage().is_some_and(|gdd| gdd.role().is_some())
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
|
||||
// Set the previous network navigation metadata to the current navigation metadata
|
||||
@@ -2871,13 +3094,25 @@ impl DocumentMessageHandler {
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.redo_in_storage() {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
return;
|
||||
}
|
||||
if self.is_in_session() {
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
self.history.forget_undo_note();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
|
||||
}
|
||||
|
||||
@@ -4111,6 +4346,10 @@ impl DocumentMessageHandler {
|
||||
self.resources.collect_garbage(&used_resources);
|
||||
}
|
||||
|
||||
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
|
||||
self.history.resource_gc_roots()
|
||||
}
|
||||
|
||||
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
|
||||
let mut resources = HashSet::new();
|
||||
self.network_interface.collect_used_resources(&mut resources);
|
||||
@@ -5116,4 +5355,20 @@ mod document_message_handler_tests {
|
||||
nudge(&mut editor, DVec2::new(NUDGE_AMOUNT, 0.)).await;
|
||||
assert_bounds(&editor, rectangle, [DVec2::new(105., 32.), DVec2::new(165., 76.)]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_changes_that_neither_reconcile_nor_rebuild_are_kept_for_a_retry() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
let storage = document.storage().expect("the document has a working copy").clone();
|
||||
document.history.set_storage(storage, Declarations::default());
|
||||
assert!(document.history.rebuild_interface().is_none(), "the registry should not convert without its declarations");
|
||||
|
||||
document.pending_remote.rebuilt = true;
|
||||
document.apply_remote_changes(&mut VecDeque::new());
|
||||
assert!(document.pending_remote.rebuilt, "the changes should be kept when the interface could not be rebuilt");
|
||||
}
|
||||
}
|
||||
@@ -233,3 +233,16 @@ pub enum Direction {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Another peer's pointer over the node graph, in viewport pixels.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendRemoteCursor {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub name: String,
|
||||
/// A stand-in name, shown in italics.
|
||||
pub anonymous: bool,
|
||||
pub color: String,
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
@@ -173,6 +173,8 @@ async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
|
||||
let network_before = editor.active_document().document_network().clone();
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
|
||||
// Undoing a hot step takes it back instead of moving the cursor
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().document_network(), &network_before);
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
|
||||
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
|
||||
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, UserId, to_value};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::test_support::{RoundTrip, node_locations, node_paths, round_trip_through_gdd};
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
@@ -158,9 +160,9 @@ async fn edit_after_open_commits_cleanly() {
|
||||
|
||||
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
|
||||
// reopened registry: the editor's .gdd-open path.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
|
||||
let source = editor.active_document();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let source_network = source.network_interface.document_network().clone();
|
||||
let source_view = StorageMetadataView::new(&source.network_interface);
|
||||
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
|
||||
@@ -176,7 +178,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.set_storage(reopened, declarations);
|
||||
document.set_storage(reopened, declarations, byte_store.storage());
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
@@ -210,7 +212,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
#[tokio::test]
|
||||
async fn gdd_undo_redo_walks_interactions() {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
// Commit the active document's current runtime state as one interaction.
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
@@ -261,7 +263,7 @@ async fn gdd_undo_redo_walks_interactions() {
|
||||
#[tokio::test]
|
||||
async fn reopen_after_undo_restores_consistent_registry() {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
@@ -383,7 +385,7 @@ async fn gdd_archive_round_trips_view_settings() {
|
||||
use document_graph_storage::attr::session::doc;
|
||||
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
|
||||
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
|
||||
@@ -431,7 +433,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
|
||||
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
|
||||
|
||||
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let document = editor.active_document();
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
@@ -664,10 +666,11 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
|
||||
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
|
||||
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
|
||||
editor.active_document_mut().set_storage(gdd, Default::default());
|
||||
HashMapResourceStorage::new()
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
|
||||
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
|
||||
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
|
||||
byte_store
|
||||
}
|
||||
|
||||
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
|
||||
@@ -701,8 +704,8 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
|
||||
|
||||
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
|
||||
assert!(
|
||||
history_after_edit > history_after_open,
|
||||
@@ -936,3 +939,40 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
||||
"the transform input should shift down intact, but became {transform:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_base = editor.active_document().storage().unwrap().session().history().count();
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(64., 64., 192., 192.).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(after_edit, before_edit);
|
||||
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo restores the pre-edit network");
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
|
||||
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
// The step held for redo keeps its declaration bytes from collection
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(
|
||||
!editor.active_document().resource_gc_roots().is_subset(&storage.all_referenced_resource_hashes()),
|
||||
"the retracted step names its declaration resource"
|
||||
);
|
||||
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo restores the edit");
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
|
||||
assert_eq!(storage.session().history().count(), history_base);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::PeerId;
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
|
||||
|
||||
@@ -110,7 +110,7 @@ pub struct RoundTrip {
|
||||
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
|
||||
@@ -17,6 +17,7 @@ mod layout;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
pub mod storage_metadata;
|
||||
mod store;
|
||||
@@ -28,6 +29,7 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use template::*;
|
||||
|
||||
@@ -8,7 +8,6 @@ impl NodeNetworkInterface {
|
||||
/// never made back to whoever sent it. Writing through the store and then dropping what the store
|
||||
/// recorded keeps the two parallel trees written by one place, which is the property the store
|
||||
/// exists for, without the echo.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
|
||||
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
|
||||
let recorded = self.deltas.len();
|
||||
self.mirror(delta);
|
||||
|
||||
+12
@@ -1,6 +1,7 @@
|
||||
use super::template::NodeTemplateImplementation;
|
||||
use super::{InputConnector, OutputConnector, catalog};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkId, NodeInput};
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -148,3 +149,14 @@ async fn an_entry_that_diverged_under_a_catalog_id_gets_a_fresh_id_on_open() {
|
||||
assert!(!network.definitions.contains_key(&shipped));
|
||||
assert!(network.definitions[&renamed].exports.len() > catalog::entry(shipped).expect("shipped").network.exports.len());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reopened_document_keeps_its_catalog_entries() {
|
||||
let (editor, blends) = editor_with_blends(1).await;
|
||||
let shipped = entry_of(&editor, blends[0]);
|
||||
|
||||
let mut reopened = round_trip_through_gdd(editor.active_document()).await.rebuilt;
|
||||
reopened.give_diverged_catalog_entries_new_ids();
|
||||
|
||||
assert!(reopened.document_network().definitions.contains_key(&shipped));
|
||||
}
|
||||
+246
-1
@@ -1,7 +1,7 @@
|
||||
use super::DocumentNodePersistentMetadata;
|
||||
use super::InputConnector;
|
||||
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch, ui_attribute_writes};
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use super::{InputConnector, NodeTemplate};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||
@@ -660,6 +660,251 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
|
||||
}
|
||||
}
|
||||
|
||||
fn conversion(editor: &EditorTestUtils) -> document_graph_storage::RuntimeConversion {
|
||||
let document = editor.active_document();
|
||||
Registry::convert_from_runtime(
|
||||
document.network_interface.document_network(),
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
&document.resources.registry,
|
||||
PEER,
|
||||
)
|
||||
.expect("conversion should succeed")
|
||||
}
|
||||
|
||||
/// Checks that a clone reconciled from `edit`'s storage ops equals the edited interface.
|
||||
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
|
||||
use document_graph_storage::Touched;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let mut mirror = editor.active_document().network_interface.clone();
|
||||
let baseline = conversion(&editor);
|
||||
let mut peer = Session::with_peer(PeerId(8));
|
||||
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
|
||||
let mut declarations = baseline.declarations;
|
||||
|
||||
edit(&mut editor);
|
||||
editor.active_document_mut().network_interface.settle_definitions();
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let recorded = editor.active_document_mut().network_interface.take_deltas();
|
||||
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
|
||||
let constructed = {
|
||||
let document = editor.active_document();
|
||||
construct_batch(
|
||||
&recorded,
|
||||
&baseline.registry,
|
||||
&document.resources.registry,
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
PEER,
|
||||
)
|
||||
.expect("construction")
|
||||
};
|
||||
declarations.extend(constructed.declarations.decoded);
|
||||
|
||||
let mut touched = Touched::default();
|
||||
for op in &constructed.ops {
|
||||
touched.record(op);
|
||||
}
|
||||
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
|
||||
|
||||
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
|
||||
|
||||
let edited = &editor.active_document().network_interface;
|
||||
assert!(
|
||||
mirror.document_network() == edited.document_network(),
|
||||
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
|
||||
recorded.len(),
|
||||
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
|
||||
);
|
||||
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
|
||||
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
|
||||
assert!(
|
||||
reconciled_metadata == edited_metadata,
|
||||
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
|
||||
recorded.len(),
|
||||
json_diff(&edited_metadata, &reconciled_metadata, "")
|
||||
);
|
||||
|
||||
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
|
||||
.expect("the reconciled interface converts")
|
||||
.registry;
|
||||
assert!(
|
||||
peer.registry().value_equal(&converted),
|
||||
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
|
||||
compute_deltas(&converted, peer.registry())
|
||||
);
|
||||
}
|
||||
|
||||
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
|
||||
use serde_json::Value;
|
||||
match (expected, actual) {
|
||||
(Value::Object(expected), Value::Object(actual)) => {
|
||||
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
|
||||
keys.into_iter()
|
||||
.map(|key| match (expected.get(key), actual.get(key)) {
|
||||
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
|
||||
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
|
||||
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
|
||||
(None, None) => String::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
|
||||
.iter()
|
||||
.zip(actual)
|
||||
.enumerate()
|
||||
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
|
||||
.collect(),
|
||||
_ if expected == actual => String::new(),
|
||||
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
fn rectangle_template() -> NodeTemplate {
|
||||
crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
|
||||
.expect("rectangle definition")
|
||||
.default_node_template()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_metadata_edits_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
|
||||
network_interface.set_locked(&group, &[], true);
|
||||
network_interface.set_pinned(&group, &[], true);
|
||||
network_interface.set_visibility(&group, &[], false);
|
||||
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_arity_change_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_node_insertion_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), rectangle_template(), &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), rectangle_template(), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_new_instance_of_a_shared_network_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
insert_shared_copy(editor, group);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_edit_inside_a_shared_network_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
insert_shared_copy(editor, group);
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_group_removal_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
|
||||
panic!("the group should resolve")
|
||||
};
|
||||
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let (inner, index) = interface
|
||||
.nested_network(&[group])
|
||||
.expect("the group's network")
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
|
||||
.expect("a node with a value input inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_untouched_node_changes_nothing() {
|
||||
use document_graph_storage::Touched;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let baseline = conversion(&editor);
|
||||
let mut touched = Touched::default();
|
||||
touched.nodes.extend(baseline.registry.node_instances.keys().copied());
|
||||
touched.networks.extend(baseline.registry.networks.keys().copied());
|
||||
|
||||
let before = editor.active_document().network_interface.clone();
|
||||
let reconciled = editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.reconcile_remote(&baseline.registry, &baseline.declarations, &touched, PEER)
|
||||
.expect("reconcile");
|
||||
|
||||
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
|
||||
assert_eq!(editor.active_document().network_interface, before);
|
||||
}
|
||||
|
||||
/// A `ui::` key the registry already holds as deleted is not cleared again on every snapshot.
|
||||
#[test]
|
||||
fn a_deleted_ui_key_is_not_cleared_again() {
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Updates the interface from the registry for the entities peers touched, through `EditorDelta`s it doesn't record.
|
||||
//! The touched set may be too large. An unchanged entity compares equal and emits nothing.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_graph_storage::to_runtime::ConversionError;
|
||||
use document_graph_storage::{Declarations, NetworkId as StorageNetworkId, NodeId as StorageNodeId, Registry, RuntimeProjection, Touched};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
use super::storage_metadata::{InterfaceRebuildError, input_metadata_entry_to_runtime, node_metadata_from_projection};
|
||||
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReconcileError {
|
||||
/// A declaration the touched nodes need is not cached yet.
|
||||
#[error("waiting for proto-node declaration {0}")]
|
||||
DeclarationMissing(document_graph_storage::ResourceId),
|
||||
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
|
||||
NetworkMissing(NetworkLocation),
|
||||
/// No delta writes a held network's scope injections.
|
||||
#[error("the scope injections of the network at {0:?} changed")]
|
||||
ScopeInjectionsChanged(NetworkLocation),
|
||||
#[error(transparent)]
|
||||
Conversion(ConversionError),
|
||||
#[error(transparent)]
|
||||
Metadata(#[from] InterfaceRebuildError),
|
||||
}
|
||||
|
||||
impl From<ConversionError> for ReconcileError {
|
||||
fn from(error: ConversionError) -> Self {
|
||||
match error {
|
||||
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
|
||||
other => Self::Conversion(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Reconciled {
|
||||
pub networks: BTreeSet<NetworkLocation>,
|
||||
}
|
||||
|
||||
type StorageIndex = HashMap<StorageNodeId, (NetworkLocation, NodeId)>;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Applies what the registry holds differently for the touched entities. Can fail part-way, and a retry is safe.
|
||||
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
|
||||
let projection = registry.runtime_projection(declarations);
|
||||
let index = self.pin_storage_identities(peer);
|
||||
let mut reconciled = Reconciled::default();
|
||||
|
||||
let mut nodes = touched.nodes.clone();
|
||||
let mut networks = touched.networks.clone();
|
||||
networks.extend(nodes.iter().filter_map(|&node| projection.implemented_network(node)));
|
||||
self.add_newly_reached_networks(&projection, &mut nodes, &mut networks, &mut reconciled)?;
|
||||
|
||||
let mut items: Vec<(NetworkLocation, NodeId, StorageNodeId)> = nodes
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let (location, local_id) = projection.node_address(id).or_else(|| index.get(&id).copied())?;
|
||||
Some((location, local_id, id))
|
||||
})
|
||||
.collect();
|
||||
items.sort();
|
||||
for (location, local_id, id) in items {
|
||||
self.reconcile_node(&projection, &index, location, local_id, id, &mut reconciled)?;
|
||||
}
|
||||
|
||||
for &network in &networks {
|
||||
if projection.network_location(network).is_some() {
|
||||
self.reconcile_network(&projection, network, &mut reconciled)?;
|
||||
}
|
||||
}
|
||||
self.remove_unreached_networks(&projection, &mut reconciled);
|
||||
|
||||
Ok(reconciled)
|
||||
}
|
||||
|
||||
/// Adds each table entry the touched entities newly reach, and queues everything under it as touched.
|
||||
fn add_newly_reached_networks(
|
||||
&mut self,
|
||||
projection: &RuntimeProjection,
|
||||
nodes: &mut BTreeSet<StorageNodeId>,
|
||||
networks: &mut BTreeSet<StorageNetworkId>,
|
||||
reconciled: &mut Reconciled,
|
||||
) -> Result<(), ReconcileError> {
|
||||
let mut pending: Vec<StorageNetworkId> = networks.iter().copied().collect();
|
||||
while let Some(network) = pending.pop() {
|
||||
let Some(location) = projection.network_location(network) else { continue };
|
||||
let Some(id) = location else { continue };
|
||||
if self.holds_network(location) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let target = projection.network_entry(network)?;
|
||||
let added = NodeNetwork {
|
||||
exports: target.exports,
|
||||
scope_injections: target.scope_injections,
|
||||
..Default::default()
|
||||
};
|
||||
self.apply_reconciled(location, vec![EditorDelta::Graph(RuntimeDelta::AddNetwork { id, network: Box::new(added) })], reconciled);
|
||||
|
||||
networks.insert(network);
|
||||
for node in projection.network_nodes(network) {
|
||||
nodes.insert(node);
|
||||
pending.extend(projection.implemented_network(node));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_unreached_networks(&mut self, projection: &RuntimeProjection, reconciled: &mut Reconciled) {
|
||||
let reached: BTreeSet<NetworkId> = projection.definitions().collect();
|
||||
let unreached: Vec<NetworkId> = self.document_network().definitions.keys().copied().filter(|id| !reached.contains(id)).collect();
|
||||
for id in unreached {
|
||||
self.apply_reconciled(Some(id), vec![EditorDelta::Graph(RuntimeDelta::RemoveNetwork { id })], reconciled);
|
||||
}
|
||||
}
|
||||
|
||||
fn reconcile_network(&mut self, projection: &RuntimeProjection, network: StorageNetworkId, reconciled: &mut Reconciled) -> Result<(), ReconcileError> {
|
||||
let target = projection.network_entry(network)?;
|
||||
let location = target.network;
|
||||
let (Some(current), Some(current_metadata)) = (
|
||||
self.document_network().located_network(location),
|
||||
self.network_metadata.nested_metadata(location).map(|metadata| &metadata.persistent_metadata),
|
||||
) else {
|
||||
return Err(ReconcileError::NetworkMissing(location));
|
||||
};
|
||||
if current.scope_injections != target.scope_injections {
|
||||
return Err(ReconcileError::ScopeInjectionsChanged(location));
|
||||
}
|
||||
|
||||
let mut deltas = Vec::new();
|
||||
export_deltas(location, ¤t.exports, &target.exports, &mut deltas);
|
||||
// An export slot write resizes the names and descriptions, so restate them
|
||||
let resized = current.exports.len() != target.exports.len();
|
||||
|
||||
let change = |change| EditorDelta::NetworkMetadata { network: location, change };
|
||||
if current_metadata.reference != target.metadata.reference {
|
||||
deltas.push(change(NetworkMetadataChange::Reference(target.metadata.reference.clone())));
|
||||
}
|
||||
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
||||
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
||||
}
|
||||
// An empty list states nothing, since an older document keeps its interface on the instances
|
||||
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
||||
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
||||
deltas.push(change(NetworkMetadataChange::ImportMetadata(import_metadata)));
|
||||
}
|
||||
if !target.metadata.export_names.is_empty() && (resized || current_metadata.export_names != target.metadata.export_names) {
|
||||
deltas.push(change(NetworkMetadataChange::ExportNames(target.metadata.export_names.clone())));
|
||||
}
|
||||
if !target.metadata.export_names.is_empty() && (resized || current_metadata.export_descriptions != target.metadata.export_descriptions) {
|
||||
deltas.push(change(NetworkMetadataChange::ExportDescriptions(target.metadata.export_descriptions.clone())));
|
||||
}
|
||||
|
||||
self.apply_reconciled(location, deltas, reconciled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reconcile_node(
|
||||
&mut self,
|
||||
projection: &RuntimeProjection,
|
||||
index: &StorageIndex,
|
||||
location: NetworkLocation,
|
||||
local_id: NodeId,
|
||||
id: StorageNodeId,
|
||||
reconciled: &mut Reconciled,
|
||||
) -> Result<(), ReconcileError> {
|
||||
// A copy held under another id or in another network goes first
|
||||
if let Some(&(held_location, held_id)) = index.get(&id)
|
||||
&& (held_location != location || held_id != local_id)
|
||||
&& self.holds_node(held_location, held_id)
|
||||
{
|
||||
self.apply_reconciled(held_location, vec![remove_node(held_location, held_id)], reconciled);
|
||||
}
|
||||
|
||||
let stored = projection.node_address(id).is_some();
|
||||
match (stored, self.holds_node(location, local_id)) {
|
||||
(false, false) => {}
|
||||
(false, true) => self.apply_reconciled(location, vec![remove_node(location, local_id)], reconciled),
|
||||
(true, false) => {
|
||||
if !self.holds_network(location) {
|
||||
return Err(ReconcileError::NetworkMissing(location));
|
||||
}
|
||||
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
|
||||
let deltas = vec![
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
node: Box::new(node),
|
||||
}),
|
||||
EditorDelta::NodeMetadataSnapshot {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
metadata: Box::new(metadata),
|
||||
},
|
||||
];
|
||||
self.apply_reconciled(location, deltas, reconciled);
|
||||
}
|
||||
(true, true) => {
|
||||
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
|
||||
self.diff_node(location, local_id, node, metadata, reconciled);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn diff_node(&mut self, location: NetworkLocation, local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
|
||||
let Some(current) = self.document_network().located_network(location).and_then(|network| network.nodes.get(&local_id)) else {
|
||||
return;
|
||||
};
|
||||
let Some(current_metadata) = self
|
||||
.network_metadata
|
||||
.nested_metadata(location)
|
||||
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
|
||||
.map(|node| &node.persistent_metadata)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
|
||||
field_deltas(location, local_id, (current, current_metadata), (&target, &target_metadata))
|
||||
} else {
|
||||
vec![
|
||||
EditorDelta::Graph(RuntimeDelta::ReplaceNode {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
node: Box::new(target),
|
||||
}),
|
||||
EditorDelta::NodeMetadataSnapshot {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
metadata: Box::new(target_metadata),
|
||||
},
|
||||
]
|
||||
};
|
||||
self.apply_reconciled(location, deltas, reconciled);
|
||||
}
|
||||
|
||||
fn apply_reconciled(&mut self, location: NetworkLocation, deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
for delta in &deltas {
|
||||
self.apply(delta);
|
||||
}
|
||||
reconciled.networks.insert(location);
|
||||
}
|
||||
|
||||
/// Every document path to one of `locations`. A shared network has one per instance.
|
||||
pub(crate) fn paths_reaching(&self, locations: &BTreeSet<NetworkLocation>) -> Vec<Vec<NodeId>> {
|
||||
let root = self.document_network();
|
||||
let mut paths = Vec::new();
|
||||
let mut pending = vec![(Vec::new(), root)];
|
||||
while let Some((path, network)) = pending.pop() {
|
||||
for (&node_id, node) in &network.nodes {
|
||||
if let Some(nested) = root.implementation_network(&node.implementation) {
|
||||
pending.push(([path.as_slice(), &[node_id]].concat(), nested));
|
||||
}
|
||||
}
|
||||
if root.locate(&path).is_some_and(|location| locations.contains(&location)) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn holds_node(&self, location: NetworkLocation, local_id: NodeId) -> bool {
|
||||
self.document_network().located_network(location).is_some_and(|network| network.nodes.contains_key(&local_id))
|
||||
&& self
|
||||
.network_metadata
|
||||
.nested_metadata(location)
|
||||
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
|
||||
}
|
||||
|
||||
fn holds_network(&self, location: NetworkLocation) -> bool {
|
||||
self.document_network().located_network(location).is_some() && self.network_metadata.nested_metadata(location).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn field_deltas(
|
||||
location: NetworkLocation,
|
||||
local_id: NodeId,
|
||||
(current, current_metadata): (&DocumentNode, &DocumentNodePersistentMetadata),
|
||||
(target, target_metadata): (&DocumentNode, &DocumentNodePersistentMetadata),
|
||||
) -> Vec<EditorDelta> {
|
||||
let mut deltas = Vec::new();
|
||||
let metadata = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
change,
|
||||
};
|
||||
let input_metadata = || EditorDelta::NodeInputMetadata {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
input_metadata: target_metadata.input_metadata.clone(),
|
||||
};
|
||||
|
||||
// An instance's input metadata belongs to its implementing network
|
||||
let instance = matches!(target.implementation, DocumentNodeImplementation::Definition(_));
|
||||
|
||||
// Slots first, so the metadata indexing them finds the right length
|
||||
if current.inputs.len() != target.inputs.len() {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
inputs: target.inputs.clone(),
|
||||
}));
|
||||
if !instance {
|
||||
deltas.push(input_metadata());
|
||||
}
|
||||
} else {
|
||||
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
|
||||
if held != wanted {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
input_index,
|
||||
input: wanted.clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
if !instance && current_metadata.input_metadata != target_metadata.input_metadata {
|
||||
deltas.push(input_metadata());
|
||||
}
|
||||
}
|
||||
|
||||
if current.visible != target.visible {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
visible: target.visible,
|
||||
}));
|
||||
}
|
||||
if current.call_argument != target.call_argument {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
call_argument: target.call_argument.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
}
|
||||
if current_metadata.locked != target_metadata.locked {
|
||||
deltas.push(metadata(NodeMetadataChange::Locked(target_metadata.locked)));
|
||||
}
|
||||
if current_metadata.pinned != target_metadata.pinned {
|
||||
deltas.push(metadata(NodeMetadataChange::Pinned(target_metadata.pinned)));
|
||||
}
|
||||
if current_metadata.output_names != target_metadata.output_names {
|
||||
deltas.push(metadata(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
|
||||
}
|
||||
if current_metadata.output_descriptions != target_metadata.output_descriptions {
|
||||
deltas.push(metadata(NodeMetadataChange::OutputDescriptions(target_metadata.output_descriptions.clone())));
|
||||
}
|
||||
|
||||
deltas
|
||||
}
|
||||
|
||||
fn remove_node(location: NetworkLocation, local_id: NodeId) -> EditorDelta {
|
||||
EditorDelta::Graph(RuntimeDelta::RemoveNode { network: location, node_id: local_id })
|
||||
}
|
||||
|
||||
fn export_deltas(location: NetworkLocation, current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
|
||||
let set_export = |export_index, input| {
|
||||
EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network: location,
|
||||
export_index,
|
||||
input,
|
||||
})
|
||||
};
|
||||
let changed = target.iter().enumerate().filter(|&(export_index, input)| current.get(export_index) != Some(input));
|
||||
deltas.extend(changed.map(|(export_index, input)| set_export(export_index, Some(input.clone()))));
|
||||
deltas.extend((target.len()..current.len()).map(|_| set_export(target.len(), None)));
|
||||
}
|
||||
+24
-2
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
use document_graph_storage::attr::session;
|
||||
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
use super::{
|
||||
@@ -210,6 +210,28 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
|
||||
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
|
||||
}
|
||||
|
||||
/// The node and its metadata from a single-node projection, patched like a whole rebuild's entry.
|
||||
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
|
||||
let document_graph_storage::ProjectedNode { local_id, node, metadata: entry, .. } = projected;
|
||||
|
||||
let entry = NodeMetadataEntry { network: None, ..entry };
|
||||
|
||||
let mut scratch = NodeNetwork::default();
|
||||
scratch.nodes.insert(local_id, node);
|
||||
let mut metadata = NodeNetworkMetadata::default();
|
||||
seed_metadata_tree(&scratch, &mut metadata);
|
||||
apply_entries_into_tree(&scratch, &mut metadata, vec![entry])?;
|
||||
|
||||
let mut persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
|
||||
let node = scratch.nodes.remove(&local_id).expect("inserted above");
|
||||
if matches!(node.implementation, DocumentNodeImplementation::Definition(_)) {
|
||||
persistent.input_metadata.clear();
|
||||
persistent.output_names.clear();
|
||||
persistent.output_descriptions.clear();
|
||||
}
|
||||
Ok((node, persistent))
|
||||
}
|
||||
|
||||
/// Maps each runtime network location to its stable `NetworkId`, from the entries `to_runtime_with_full_metadata` returns.
|
||||
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<NetworkLocation, document_graph_storage::NetworkId> {
|
||||
network_entries.iter().map(|entry| (entry.network, entry.network_id)).collect()
|
||||
@@ -423,7 +445,7 @@ pub(super) fn input_metadata_entry_from_runtime(input_metadata: &InputMetadata)
|
||||
}
|
||||
|
||||
/// Storage-side `None` restores as `""` (the runtime's "unset" sentinel for `input_name` / `input_description`).
|
||||
fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
|
||||
pub(super) fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
|
||||
InputMetadata {
|
||||
persistent_metadata: InputPersistentMetadata {
|
||||
input_name: entry.input_name.unwrap_or_default(),
|
||||
|
||||
+48
-1
@@ -567,9 +567,11 @@ impl NodeNetworkInterface {
|
||||
return false;
|
||||
};
|
||||
let Some(network) = self.document_network().definitions.get(&id).cloned() else { return false };
|
||||
let Some(metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else {
|
||||
let Some(mut metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else {
|
||||
return false;
|
||||
};
|
||||
// The copy's nodes are new and can't keep the originals' storage identities
|
||||
clear_storage_ids(&mut metadata.persistent_metadata);
|
||||
|
||||
let unique = NetworkId::new();
|
||||
self.insert_definition(unique, network, metadata);
|
||||
@@ -658,6 +660,42 @@ impl NodeNetworkInterface {
|
||||
self.dots_that_lost_a_wire.clear();
|
||||
}
|
||||
|
||||
/// Pins each unpinned node to the identity a conversion derives from its location, and returns where each identity is held.
|
||||
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (NetworkLocation, NodeId)> {
|
||||
let mut index = HashMap::new();
|
||||
let mut unpinned = Vec::new();
|
||||
{
|
||||
let view = super::storage_metadata::StorageMetadataView::new(self);
|
||||
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
|
||||
let definitions = self.network_metadata.persistent_metadata.definitions.iter().map(|(id, metadata)| (Some(*id), metadata));
|
||||
for (location, metadata) in definitions.chain([(None, &*self.network_metadata)]) {
|
||||
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
|
||||
let storage_id = match node.persistent_metadata.storage_id {
|
||||
Some(pinned) => document_graph_storage::NodeId(pinned),
|
||||
None => {
|
||||
let derived = resolver.node_id(location, local_id);
|
||||
unpinned.push((location, local_id, derived));
|
||||
derived
|
||||
}
|
||||
};
|
||||
index.insert(storage_id, (location, local_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (location, local_id, storage_id) in unpinned {
|
||||
if let Some(node) = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(location)
|
||||
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
|
||||
{
|
||||
node.persistent_metadata.storage_id = Some(storage_id.0);
|
||||
}
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// Records the open transaction's bookkeeping, so writes that are undone before [`Self::restore_transaction_checkpoint`] don't count toward it.
|
||||
pub fn transaction_checkpoint(&mut self) -> TransactionCheckpoint {
|
||||
self.scan_transaction_edited_nodes();
|
||||
@@ -726,6 +764,15 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_storage_ids(metadata: &mut NodeNetworkPersistentMetadata) {
|
||||
for node in metadata.node_metadata.values_mut() {
|
||||
node.persistent_metadata.storage_id = None;
|
||||
if let Some(nested) = &mut node.persistent_metadata.network_metadata {
|
||||
clear_storage_ids(&mut nested.persistent_metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of `descriptions` says anything, since storage keeps the whole list then, but not a list that's all empty.
|
||||
fn has_description(descriptions: &[String]) -> bool {
|
||||
descriptions.iter().any(|description| !description.is_empty())
|
||||
|
||||
@@ -504,7 +504,7 @@ impl<'de> serde::Deserialize<'de> for Previewing {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two networks' metadata match, ignoring view state.
|
||||
/// Whether two networks' metadata match, ignoring view state and storage identities.
|
||||
pub(crate) fn same_content(first: &NodeNetworkPersistentMetadata, second: &NodeNetworkPersistentMetadata) -> bool {
|
||||
let content = |metadata: &NodeNetworkPersistentMetadata| {
|
||||
let mut content = metadata.clone();
|
||||
@@ -519,6 +519,9 @@ fn clear_view_state(metadata: &mut NodeNetworkPersistentMetadata) {
|
||||
metadata.navigation_metadata = NavigationMetadata::default();
|
||||
metadata.selection_undo_history.clear();
|
||||
metadata.selection_redo_history.clear();
|
||||
for node in metadata.node_metadata.values_mut() {
|
||||
node.persistent_metadata.storage_id = None;
|
||||
}
|
||||
|
||||
let nested_networks = metadata
|
||||
.node_metadata
|
||||
|
||||
@@ -11,13 +11,15 @@ use super::document_locks;
|
||||
use super::document_migration::*;
|
||||
use super::portfolio_message::PortfolioMessage;
|
||||
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::messages::dialog::DialogMessage;
|
||||
use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::utility_types::misc::DocumentId;
|
||||
use crate::messages::portfolio::sync::SyncMessage;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
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};
|
||||
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;
|
||||
@@ -138,6 +140,26 @@ pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_
|
||||
Message::NoOp
|
||||
}
|
||||
|
||||
/// Joins the session of a stored document another tab holds, as a document and peer of this tab's own.
|
||||
pub(super) async fn join_stored_session(store: DocumentStoreHandle, source: DocumentId) -> Message {
|
||||
let manifest = async {
|
||||
let container = store.open(document_key(source)).await.map_err(|error| error.to_string())?;
|
||||
GddV1::read_manifest(&container, &GddV1Layout).await.map_err(|error| error.to_string())
|
||||
}
|
||||
.await;
|
||||
match manifest {
|
||||
Ok(manifest) => SyncMessage::Join {
|
||||
token: peer_transport::SessionToken::for_document(manifest.document_id).to_string(),
|
||||
}
|
||||
.into(),
|
||||
Err(error) => DialogMessage::DisplayDialogError {
|
||||
title: "Failed to join the session".into(),
|
||||
description: format!("The session's document could not be read: {error}"),
|
||||
}
|
||||
.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a copy of a stored document that another tab may be writing. Its fresh manifest id separates it from the original.
|
||||
pub(super) async fn copy_stored_document(store: DocumentStoreHandle, source: DocumentId, document_id: DocumentId, document_name: String, resources: ResourcesHandle, reset_nodes: bool) -> Message {
|
||||
document_locks::claim(document_id).await;
|
||||
@@ -182,12 +204,14 @@ pub(super) async fn copy_stored_document(store: DocumentStoreHandle, source: Doc
|
||||
}
|
||||
|
||||
/// Materializes a `.gdd` archive into a fresh store container and loads it like a stored document.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn open_document_file(
|
||||
store: DocumentStoreHandle,
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
content: Vec<u8>,
|
||||
fresh_identity: bool,
|
||||
resources: ResourcesHandle,
|
||||
reset_nodes: bool,
|
||||
) -> Message {
|
||||
@@ -198,13 +222,21 @@ pub(super) async fn open_document_file(
|
||||
Ok::<_, String>(container)
|
||||
}
|
||||
.await;
|
||||
let (document, gdd) = match materialized {
|
||||
let (mut document, mut gdd) = match materialized {
|
||||
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes).await,
|
||||
Err(error) => {
|
||||
log::error!("Opening the document archive for {document_id:?} failed: {error}");
|
||||
(None, None)
|
||||
}
|
||||
};
|
||||
// The room derives from the manifest's document id, so a fresh id is a fresh room
|
||||
if fresh_identity
|
||||
&& let Some(storage) = gdd.as_mut().or_else(|| document.as_mut().and_then(|document| document.storage_mut()))
|
||||
&& let Err(error) = storage.update_manifest(|manifest| manifest.document_id = generate_uuid())
|
||||
{
|
||||
log::error!("Giving the copy of {document_id:?} its own id failed: {error}");
|
||||
(document, gdd) = (None, None);
|
||||
}
|
||||
let declarations = load_declarations(gdd.as_ref(), &resources, document_id).await;
|
||||
PortfolioMessage::DocumentFileLoaded {
|
||||
document_id,
|
||||
@@ -274,7 +306,8 @@ async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id
|
||||
container.remove(&path).await?;
|
||||
}
|
||||
}
|
||||
GddV1::create_in(container, GddV1Layout, PeerId(generate_uuid()), document_id.0, version.clone(), version)
|
||||
let peer = PeerId(generate_uuid());
|
||||
GddV1::create_in(container, GddV1Layout, peer, UserId(peer.0), document_id.0, version.clone(), version)
|
||||
}
|
||||
.await;
|
||||
match created {
|
||||
@@ -339,7 +372,7 @@ async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, d
|
||||
interface.give_diverged_catalog_entries_new_ids();
|
||||
// TODO: Run document upgrades here once this format has a versioned migration
|
||||
|
||||
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
|
||||
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, byte_store.storage(), String::new(), None);
|
||||
document.finalize_storage_load();
|
||||
Some(document)
|
||||
}
|
||||
@@ -428,7 +461,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn a_failed_migration_keeps_the_stored_document() {
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
let mut gdd = GddV1::create_in(container.clone(), GddV1Layout, PeerId(1), 1, "editor".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(container.clone(), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "std".into()).unwrap();
|
||||
|
||||
// No format step starts from version 0, so the migration fails
|
||||
gdd.update_manifest(|manifest| manifest.format_version = 0).unwrap();
|
||||
|
||||
@@ -229,6 +229,7 @@ mod tests {
|
||||
name: name.to_string(),
|
||||
path: None,
|
||||
is_saved: true,
|
||||
session: None,
|
||||
});
|
||||
|
||||
let names: HashSet<_> = recovery_file_names(infos.iter()).into_iter().map(|(_, name)| name).collect();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, History)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum HistoryMessage {
|
||||
Refresh,
|
||||
Tick,
|
||||
Expand { id: String, expanded: bool },
|
||||
LoadMore,
|
||||
GoBack { id: String },
|
||||
RemoveStep { id: String },
|
||||
BringBack { id: String },
|
||||
Follow { id: Option<String> },
|
||||
Rename { id: String, label: String },
|
||||
Tag { id: String, tag: String, on: bool },
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow};
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
|
||||
use crate::messages::portfolio::sync::now_ms;
|
||||
use crate::messages::prelude::*;
|
||||
use document_format::GddV1;
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOpId, PeerId, RegistryDelta, Rev, Session, Subject, UserId, rev_attr};
|
||||
use peer_transport::RemotePeer;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct HistoryMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
pub panel_open: bool,
|
||||
}
|
||||
|
||||
/// Sends the History panel the active document's history and turns its actions into head moves.
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct HistoryMessageHandler {
|
||||
ticking: bool,
|
||||
expanded: HashSet<Rev>,
|
||||
limit: usize,
|
||||
following: Option<Rev>,
|
||||
last_sent: Option<u64>,
|
||||
}
|
||||
|
||||
/// How many interactions each request adds.
|
||||
const PAGE: usize = 100;
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
|
||||
fn process_message(&mut self, message: HistoryMessage, responses: &mut VecDeque<Message>, mut context: HistoryMessageContext) {
|
||||
match message {
|
||||
HistoryMessage::Refresh => {
|
||||
if !self.ticking {
|
||||
self.ticking = true;
|
||||
responses.add(BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send: Box::new(HistoryMessage::Tick.into()),
|
||||
});
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Tick => {
|
||||
if context.panel_open {
|
||||
self.send(&context, responses, false);
|
||||
}
|
||||
}
|
||||
HistoryMessage::Expand { id, expanded } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
match expanded {
|
||||
true => self.expanded.insert(rev),
|
||||
false => self.expanded.remove(&rev),
|
||||
};
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::LoadMore => {
|
||||
self.limit = self.limit.max(PAGE) + PAGE;
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Follow { id } => {
|
||||
self.following = id.as_deref().and_then(parse_rev);
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::GoBack { id } => {
|
||||
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
|
||||
match place(gdd.session(), rev) {
|
||||
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
|
||||
Some(Place::Line(0)) => {}
|
||||
// A session moves the head for everyone at once. Alone, undo each interaction to keep undo in step
|
||||
Some(Place::Line(steps)) => match gdd.role().is_some() {
|
||||
true => responses.add(DocumentMessage::HistoryMoveHead { rev }),
|
||||
false => (0..steps).for_each(|_| responses.add(DocumentMessage::Undo)),
|
||||
},
|
||||
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"),
|
||||
}
|
||||
}
|
||||
HistoryMessage::RemoveStep { id } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
responses.add(DocumentMessage::HistoryRemoveStep { rev });
|
||||
}
|
||||
}
|
||||
HistoryMessage::BringBack { id } => {
|
||||
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
|
||||
match place(gdd.session(), rev) {
|
||||
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
|
||||
Some(Place::Line(_)) => {}
|
||||
None => responses.add(DocumentMessage::HistoryRestoreStep { rev }),
|
||||
}
|
||||
}
|
||||
HistoryMessage::Rename { id, label } => {
|
||||
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
|
||||
if let Err(error) = gdd.record(Subject::Rev(rev), rev_attr::LABEL, serde_json::Value::from(label.trim()), now_ms()) {
|
||||
log::warn!("Naming the step failed: {error}");
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Tag { id, tag, on } => {
|
||||
let tag = tag.trim();
|
||||
if tag.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
|
||||
if let Err(error) = gdd.record(Subject::Rev(rev), &format!("{}{tag}", rev_attr::TAG_PREFIX), serde_json::Value::Bool(on), now_ms()) {
|
||||
log::warn!("Tagging the step failed: {error}");
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(HistoryMessageDiscriminant;);
|
||||
}
|
||||
|
||||
impl HistoryMessageHandler {
|
||||
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>, force: bool) {
|
||||
let Some(gdd) = active_storage(context) else {
|
||||
if force || self.last_sent.is_some() {
|
||||
self.last_sent = None;
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state: HistoryPanelState::default() });
|
||||
}
|
||||
return;
|
||||
};
|
||||
if self.following.is_some_and(|tip| gdd.session().delta(tip).is_none()) {
|
||||
self.following = None;
|
||||
}
|
||||
let limit = self.limit.max(PAGE);
|
||||
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following);
|
||||
if !force && self.last_sent == Some(fingerprint) {
|
||||
return;
|
||||
}
|
||||
self.last_sent = Some(fingerprint);
|
||||
let state = panel_state(gdd, limit, &self.expanded, self.following);
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state });
|
||||
}
|
||||
}
|
||||
|
||||
fn active_storage<'a>(context: &'a HistoryMessageContext) -> Option<&'a GddV1> {
|
||||
context.active_document_id.and_then(|id| context.documents.get(&id)).and_then(|document| document.storage())
|
||||
}
|
||||
|
||||
fn active_storage_mut<'a>(context: &'a mut HistoryMessageContext) -> Option<&'a mut GddV1> {
|
||||
context.active_document_id.and_then(|id| context.documents.get_mut(&id)).and_then(|document| document.storage_mut())
|
||||
}
|
||||
|
||||
fn parse_rev(id: &str) -> Option<Rev> {
|
||||
id.parse::<u128>().ok().and_then(Rev::new)
|
||||
}
|
||||
|
||||
/// Where an interaction sits relative to the head.
|
||||
enum Place {
|
||||
/// On the head's line, this many interactions back.
|
||||
Line(usize),
|
||||
/// Undone above the head, this many redos forward.
|
||||
Undone(usize),
|
||||
}
|
||||
|
||||
fn place(session: &Session, rev: Rev) -> Option<Place> {
|
||||
let head = session.head_rev();
|
||||
let (kept, _) = line(session, head, None, usize::MAX);
|
||||
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
|
||||
return Some(Place::Line(steps));
|
||||
}
|
||||
// The stack's first entry is the farthest undone, so its line holds every undone step
|
||||
let checkpoint = *session.redo_stack().first()?;
|
||||
let (undone, _) = line(session, Some(checkpoint), head, usize::MAX);
|
||||
let groups = interactions(&undone);
|
||||
let index = groups.iter().position(|group| group[0].id == rev)?;
|
||||
Some(Place::Undone(groups.len() - index))
|
||||
}
|
||||
|
||||
/// A hash of the panel's inputs, cheap enough for every frame.
|
||||
fn fingerprint(document_id: Option<DocumentId>, gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> u64 {
|
||||
let session = gdd.session();
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
document_id.hash(&mut hasher);
|
||||
session.history_len().hash(&mut hasher);
|
||||
session.head_rev().hash(&mut hasher);
|
||||
session.redo_stack().hash(&mut hasher);
|
||||
session.hot_log().len().hash(&mut hasher);
|
||||
gdd.role().is_some().hash(&mut hasher);
|
||||
for remote in gdd.peers() {
|
||||
remote.user.hash(&mut hasher);
|
||||
remote.name.hash(&mut hasher);
|
||||
}
|
||||
for fact in gdd.metadata().facts() {
|
||||
fact.subject.hash(&mut hasher);
|
||||
fact.key.hash(&mut hasher);
|
||||
fact.stamp.hash(&mut hasher);
|
||||
}
|
||||
limit.hash(&mut hasher);
|
||||
expanded.len().hash(&mut hasher);
|
||||
following.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn panel_state(gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
let session = gdd.session();
|
||||
let people = People {
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
peers: gdd.peers().collect(),
|
||||
};
|
||||
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
for delta in session.history() {
|
||||
for parent in delta.all_parents() {
|
||||
children.entry(parent).or_default().push(delta.id);
|
||||
}
|
||||
}
|
||||
|
||||
let head = session.head_rev();
|
||||
let (head_line, _) = line(session, head, None, usize::MAX);
|
||||
let head_line_revs: HashSet<Rev> = head_line.iter().map(|delta| delta.id).collect();
|
||||
|
||||
let undone = match (following, session.redo_stack().first()) {
|
||||
(None, Some(&checkpoint)) => line(session, Some(checkpoint), head, usize::MAX).0,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let (shown, more) = line(session, following.or(head), None, limit);
|
||||
let on_line: HashSet<Rev> = undone.iter().chain(&shown).map(|delta| delta.id).collect();
|
||||
|
||||
let view = View {
|
||||
children: &children,
|
||||
on_line: &on_line,
|
||||
head_line: &head_line_revs,
|
||||
head,
|
||||
people: &people,
|
||||
expanded,
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
};
|
||||
let undone_rows = interactions(&undone).into_iter().map(|group| view.row(&group, true));
|
||||
let shown_rows = interactions(&shown).into_iter().map(|group| view.row(&group, false));
|
||||
let rows = undone_rows.chain(shown_rows).collect();
|
||||
|
||||
// Open interactions first, then closed ones waiting to retire, newest first
|
||||
let hot_log = session.hot_log();
|
||||
let closed = session.closed_interactions();
|
||||
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|interaction| interaction.ops.iter().copied()).collect();
|
||||
let mut open_by_peer: Vec<(PeerId, Vec<&RegistryDelta>)> = Vec::new();
|
||||
for hot_op in hot_log.iter().filter(|hot_op| !in_closed.contains(&hot_op.id())) {
|
||||
match open_by_peer.iter_mut().find(|(peer, _)| *peer == hot_op.timestamp.peer) {
|
||||
Some((_, ops)) => ops.push(&hot_op.op),
|
||||
None => open_by_peer.push((hot_op.timestamp.peer, vec![&hot_op.op])),
|
||||
}
|
||||
}
|
||||
let mut progress: Vec<HistoryProgressRow> = open_by_peer.into_iter().map(|(peer, ops)| progress_row(&people, peer, &ops, true)).collect();
|
||||
for interaction in closed.iter().rev() {
|
||||
let ids: HashSet<HotOpId> = interaction.ops.iter().copied().collect();
|
||||
let ops: Vec<&RegistryDelta> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).map(|hot_op| &hot_op.op).collect();
|
||||
progress.push(progress_row(&people, interaction.author, &ops, false));
|
||||
}
|
||||
|
||||
HistoryPanelState {
|
||||
rows,
|
||||
progress,
|
||||
more,
|
||||
following: following.map(|tip| tip.to_string()),
|
||||
session: gdd.role().is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The deltas from `from` back along first parents to `until` (exclusive) or the root, newest first. Stops after
|
||||
/// `limit` interaction ends, and the flag says whether it did.
|
||||
fn line(session: &Session, from: Option<Rev>, until: Option<Rev>, limit: usize) -> (Vec<Delta>, bool) {
|
||||
let mut deltas = Vec::new();
|
||||
let mut ends = 0;
|
||||
let mut current = from;
|
||||
while let Some(rev) = current
|
||||
&& Some(rev) != until
|
||||
{
|
||||
let Some(delta) = session.delta(rev) else { break };
|
||||
if delta.is_interaction_end() {
|
||||
if ends == limit {
|
||||
return (deltas, true);
|
||||
}
|
||||
ends += 1;
|
||||
}
|
||||
deltas.push(delta.clone());
|
||||
current = delta.parent;
|
||||
}
|
||||
(deltas, false)
|
||||
}
|
||||
|
||||
/// Groups a newest-first line into interactions. Newest deltas without an end, retired mid-interaction, form their own.
|
||||
fn interactions(deltas: &[Delta]) -> Vec<Vec<&Delta>> {
|
||||
let mut groups: Vec<Vec<&Delta>> = Vec::new();
|
||||
for delta in deltas {
|
||||
match groups.last_mut() {
|
||||
Some(group) if !delta.is_interaction_end() => group.push(delta),
|
||||
_ => groups.push(vec![delta]),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
struct View<'a> {
|
||||
children: &'a HashMap<Rev, Vec<Rev>>,
|
||||
on_line: &'a HashSet<Rev>,
|
||||
head_line: &'a HashSet<Rev>,
|
||||
head: Option<Rev>,
|
||||
people: &'a People<'a>,
|
||||
expanded: &'a HashSet<Rev>,
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
}
|
||||
|
||||
impl View<'_> {
|
||||
fn row(&self, group: &[&Delta], undone: bool) -> HistoryRow {
|
||||
let closing = group[0];
|
||||
let person = self.people.person(closing.author);
|
||||
let branches = group
|
||||
.iter()
|
||||
.flat_map(|delta| self.children.get(&delta.id).into_iter().flatten())
|
||||
.filter(|child| !self.on_line.contains(child))
|
||||
.map(|&child| self.branch(child))
|
||||
.collect();
|
||||
let is_expanded = self.expanded.contains(&closing.id);
|
||||
let details = match is_expanded {
|
||||
true => group
|
||||
.iter()
|
||||
.map(|delta| {
|
||||
let author = self.people.person(delta.author);
|
||||
HistoryDeltaRow {
|
||||
id: delta.id.to_string(),
|
||||
label: describe(&delta.kind),
|
||||
author: author.name,
|
||||
color: author.color,
|
||||
time: delta.retired_at().map(|ms| ms as f64),
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let given = self.metadata.rev_label(closing.id);
|
||||
HistoryRow {
|
||||
id: closing.id.to_string(),
|
||||
label: given.map(str::to_string).unwrap_or_else(|| summarize(group.iter().map(|delta| &delta.kind))),
|
||||
named: given.is_some(),
|
||||
tags: self.metadata.rev_tags(closing.id).into_iter().map(str::to_string).collect(),
|
||||
author: person.name,
|
||||
anonymous: person.anonymous,
|
||||
mine: person.mine,
|
||||
color: person.color,
|
||||
time: group.iter().find_map(|delta| delta.retired_at()).map(|ms| ms as f64),
|
||||
deltas: group.len(),
|
||||
branches,
|
||||
undone,
|
||||
abandoned: !undone && !self.head_line.contains(&closing.id),
|
||||
head: Some(closing.id) == self.head,
|
||||
expanded: is_expanded,
|
||||
details,
|
||||
}
|
||||
}
|
||||
|
||||
fn branch(&self, first: Rev) -> HistoryBranch {
|
||||
let mut tip = first;
|
||||
while let Some(&next) = self.children.get(&tip).and_then(|children| children.first()) {
|
||||
tip = next;
|
||||
}
|
||||
let (newest, _) = line(self.session, Some(tip), None, 1);
|
||||
let label = self
|
||||
.metadata
|
||||
.rev_label(tip)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| interactions(&newest).first().map(|group| summarize(group.iter().map(|delta| &delta.kind))).unwrap_or_default());
|
||||
HistoryBranch { id: tip.to_string(), label }
|
||||
}
|
||||
}
|
||||
|
||||
fn progress_row(people: &People, peer: PeerId, ops: &[&RegistryDelta], open: bool) -> HistoryProgressRow {
|
||||
let person = people.person(peer);
|
||||
HistoryProgressRow {
|
||||
label: summarize(ops.iter().copied()),
|
||||
author: person.name,
|
||||
anonymous: person.anonymous,
|
||||
mine: person.mine,
|
||||
color: person.color,
|
||||
ops: ops.len(),
|
||||
open,
|
||||
}
|
||||
}
|
||||
|
||||
/// One line for a run of changes, most frequent kind first. Peer registrations and markers are named only when alone.
|
||||
fn summarize<'a>(kinds: impl IntoIterator<Item = &'a RegistryDelta>) -> String {
|
||||
let is_bookkeeping = |kind: &RegistryDelta| matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Meta);
|
||||
let mut kinds: Vec<&RegistryDelta> = kinds.into_iter().collect();
|
||||
if kinds.iter().any(|kind| !is_bookkeeping(kind)) {
|
||||
kinds.retain(|kind| !is_bookkeeping(kind));
|
||||
}
|
||||
let mut counts: Vec<(String, usize)> = Vec::new();
|
||||
for kind in kinds {
|
||||
let label = describe(kind);
|
||||
match counts.iter_mut().find(|(known, _)| *known == label) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => counts.push((label, 1)),
|
||||
}
|
||||
}
|
||||
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
|
||||
let mut parts: Vec<String> = counts
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|(label, count)| match count {
|
||||
1 => label.clone(),
|
||||
count => format!("{label} ×{count}"),
|
||||
})
|
||||
.collect();
|
||||
if counts.len() > 2 {
|
||||
parts.push(format!("{} more", counts.len() - 2));
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
|
||||
fn describe(kind: &RegistryDelta) -> String {
|
||||
match kind {
|
||||
RegistryDelta::AddNode { .. } => "Added a node".into(),
|
||||
RegistryDelta::RemoveNode { .. } => "Removed a node".into(),
|
||||
RegistryDelta::ChangeNodeInput { .. } => "Changed an input".into(),
|
||||
RegistryDelta::SetNodeInputs { .. } => "Set a node's inputs".into(),
|
||||
RegistryDelta::SetNodeImplementation { .. } => "Changed what a node does".into(),
|
||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => format!("Set node {}", delta.key),
|
||||
RegistryDelta::ChangeNodeInputAttribute { delta, .. } => format!("Set input {}", delta.key),
|
||||
RegistryDelta::SetNetworkExport { .. } => "Changed an export".into(),
|
||||
RegistryDelta::ChangeNetworkAttribute { delta, .. } => format!("Set network {}", delta.key),
|
||||
RegistryDelta::AddNetwork { .. } => "Added a network".into(),
|
||||
RegistryDelta::RemoveNetwork { .. } => "Removed a network".into(),
|
||||
RegistryDelta::AddResource { .. } => "Added a resource".into(),
|
||||
RegistryDelta::SetResourceHash { .. } => "Updated a resource".into(),
|
||||
RegistryDelta::RemoveResource { .. } => "Removed a resource".into(),
|
||||
RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => "Changed where a resource comes from".into(),
|
||||
RegistryDelta::RegisterPeer { .. } => "Joined the document".into(),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => format!("Set document {}", delta.key),
|
||||
RegistryDelta::Merge { .. } => "Joined two lines of work".into(),
|
||||
RegistryDelta::Meta => "Marked a step".into(),
|
||||
RegistryDelta::Other(_) => "Changed something".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Names and colours authors by user id. The document's record wins, then the announced name, then the stand-in.
|
||||
struct People<'a> {
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
peers: Vec<&'a RemotePeer>,
|
||||
}
|
||||
|
||||
struct Person {
|
||||
name: String,
|
||||
anonymous: bool,
|
||||
mine: bool,
|
||||
color: String,
|
||||
}
|
||||
|
||||
impl People<'_> {
|
||||
fn person(&self, peer: PeerId) -> Person {
|
||||
// A peer that never registered is its own user
|
||||
let user = self.session.user_of(peer).unwrap_or(UserId(peer.0));
|
||||
let recorded = self.metadata.user_name(user).map(str::to_string);
|
||||
let announced = || self.peers.iter().find(|remote| remote.user == user && !remote.name.is_empty()).map(|remote| remote.name.clone());
|
||||
let (name, anonymous) = match recorded.or_else(announced) {
|
||||
Some(name) => (name, false),
|
||||
None => (anonymous_name(user), true),
|
||||
};
|
||||
Person {
|
||||
name,
|
||||
anonymous,
|
||||
mine: self.session.is_mine(peer),
|
||||
color: user_color(user),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Undoing pushes each step's head, so undone steps must be read from the first entry.
|
||||
#[test]
|
||||
fn every_undone_step_stays_on_the_panel() {
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::GddV1Layout;
|
||||
use document_graph_storage::{Network, NetworkId};
|
||||
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into()).expect("create");
|
||||
for id in 1..=3 {
|
||||
let network = Network::default();
|
||||
gdd.stage_ops([RegistryDelta::AddNetwork { id: NetworkId(id), network }]).expect("stage");
|
||||
gdd.retire_pending_interaction().expect("retire");
|
||||
}
|
||||
gdd.undo().expect("undo");
|
||||
gdd.undo().expect("undo");
|
||||
|
||||
assert_eq!(panel_state(&gdd, PAGE, &HashSet::new(), None).rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_only_markers_is_named_by_them() {
|
||||
let register = RegistryDelta::RegisterPeer { peer: PeerId(1), user: UserId(1) };
|
||||
let merge = RegistryDelta::Merge { extra_parents: Vec::new() };
|
||||
assert_eq!(summarize([&RegistryDelta::Meta, &RegistryDelta::Meta]), "Marked a step ×2");
|
||||
assert_eq!(summarize([®ister, &RegistryDelta::Meta]), "Joined the document, Marked a step");
|
||||
assert_eq!(summarize([&RegistryDelta::Meta, &merge, ®ister]), "Joined two lines of work");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
|
||||
@@ -0,0 +1,72 @@
|
||||
//! What the History panel shows, as the frontend receives it.
|
||||
|
||||
/// The panel's content, newest first. The head's line with undone interactions above it, or a followed branch's line.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryPanelState {
|
||||
pub rows: Vec<HistoryRow>,
|
||||
/// Work not yet in history. One row per person's open work and per closed interaction waiting to retire.
|
||||
pub progress: Vec<HistoryProgressRow>,
|
||||
pub more: bool,
|
||||
pub following: Option<String>,
|
||||
/// In a session, a head move affects everyone.
|
||||
pub session: bool,
|
||||
}
|
||||
|
||||
/// One interaction, a run of deltas that undo takes back together.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryRow {
|
||||
/// The rev closing the interaction, in decimal.
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub named: bool,
|
||||
pub tags: Vec<String>,
|
||||
pub author: String,
|
||||
/// `author` is a stand-in.
|
||||
pub anonymous: bool,
|
||||
pub mine: bool,
|
||||
pub color: String,
|
||||
/// Milliseconds since the Unix epoch, if the retirer recorded it.
|
||||
pub time: Option<f64>,
|
||||
pub deltas: usize,
|
||||
/// Branches off the shown line, each by its tip.
|
||||
pub branches: Vec<HistoryBranch>,
|
||||
pub undone: bool,
|
||||
/// On a followed branch, off the head's line.
|
||||
pub abandoned: bool,
|
||||
pub head: bool,
|
||||
pub expanded: bool,
|
||||
pub details: Vec<HistoryDeltaRow>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryBranch {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryDeltaRow {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub color: String,
|
||||
pub time: Option<f64>,
|
||||
}
|
||||
|
||||
/// A person with unretired work in the room's hot log.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryProgressRow {
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub anonymous: bool,
|
||||
pub mine: bool,
|
||||
pub color: String,
|
||||
pub ops: usize,
|
||||
/// Still being made, not closed and waiting.
|
||||
pub open: bool,
|
||||
}
|
||||
@@ -49,6 +49,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
IngestMessage::Ingest { data, action, mime_type, path } => {
|
||||
let data_type = DataType::detect(&data, &mime_type, path.as_deref());
|
||||
|
||||
let fresh_identity = matches!(action, IngestAction::OpenDemo);
|
||||
let placement = match action {
|
||||
IngestAction::ResourceInput {
|
||||
document_id,
|
||||
@@ -80,7 +81,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
}
|
||||
return;
|
||||
}
|
||||
IngestAction::Open => None,
|
||||
IngestAction::Open | IngestAction::OpenDemo => None,
|
||||
IngestAction::Import | IngestAction::Paste => Some((None, None)),
|
||||
IngestAction::DropOnCanvas { mouse } => Some((Some(mouse), None)),
|
||||
IngestAction::DropOnLayers { parent, insert_index } => Some((None, Some((parent, insert_index as usize)))),
|
||||
@@ -109,6 +110,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
document_name: name,
|
||||
document_path,
|
||||
content: data,
|
||||
fresh_identity,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
pub enum IngestAction {
|
||||
Open,
|
||||
/// Open a distributed file such as a demo artwork as a copy with its own session room.
|
||||
OpenDemo,
|
||||
Import,
|
||||
Paste,
|
||||
DropOnCanvas {
|
||||
|
||||
@@ -7,8 +7,10 @@ pub mod document_migration;
|
||||
pub mod document_storage_io;
|
||||
pub mod failed_documents;
|
||||
pub mod fonts;
|
||||
pub mod history;
|
||||
pub mod ingest;
|
||||
pub mod persistent_state;
|
||||
pub mod sync;
|
||||
pub mod utility_types;
|
||||
pub mod workspace;
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::history::HistoryMessage;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::sync::SyncMessage;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::prelude::*;
|
||||
use document_container::AnyContainer;
|
||||
@@ -21,6 +23,10 @@ pub enum PortfolioMessage {
|
||||
#[child]
|
||||
PersistentState(PersistentStateMessage),
|
||||
#[child]
|
||||
History(HistoryMessage),
|
||||
#[child]
|
||||
Sync(SyncMessage),
|
||||
#[child]
|
||||
Workspace(WorkspaceMessage),
|
||||
|
||||
// Messages
|
||||
@@ -64,6 +70,9 @@ pub enum PortfolioMessage {
|
||||
source: DocumentId,
|
||||
document_name: String,
|
||||
},
|
||||
JoinStoredSession {
|
||||
source: DocumentId,
|
||||
},
|
||||
CollectResources,
|
||||
StoredDocumentLoaded {
|
||||
document_id: DocumentId,
|
||||
@@ -80,6 +89,11 @@ pub enum PortfolioMessage {
|
||||
NewDocumentWithName {
|
||||
name: String,
|
||||
},
|
||||
/// Creates the document under a given id, so the sender can recognize it on mount.
|
||||
NewDocumentWithId {
|
||||
name: String,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
OpenLegacyDocumentFile {
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
@@ -89,6 +103,7 @@ pub enum PortfolioMessage {
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
content: Vec<u8>,
|
||||
fresh_identity: bool,
|
||||
},
|
||||
DocumentFileLoaded {
|
||||
document_id: DocumentId,
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::application::{Environment, generate_uuid};
|
||||
use crate::consts::DEFAULT_DOCUMENT_NAME;
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState, SessionStatus};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledShortcut};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
@@ -15,7 +15,8 @@ use crate::messages::portfolio::document::DocumentMessageContext;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions;
|
||||
use crate::messages::portfolio::document_storage_io::{
|
||||
DocumentStoreHandle, attach_container, copy_stored_document, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, remove_stored_document,
|
||||
DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file,
|
||||
remove_stored_document,
|
||||
};
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -42,6 +43,7 @@ pub struct PortfolioMessageContext<'a> {
|
||||
pub animation: &'a AnimationMessageHandler,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub tool_edit_target: &'a EditTarget,
|
||||
pub tools: &'a ToolMessageHandler,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub timing_information: TimingInformation,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
@@ -58,6 +60,8 @@ pub struct PortfolioMessageHandler {
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
ingest: IngestMessageHandler,
|
||||
history: HistoryMessageHandler,
|
||||
sync: SyncMessageHandler,
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
@@ -80,6 +84,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
animation,
|
||||
current_tool,
|
||||
tool_edit_target,
|
||||
tools,
|
||||
reset_node_definitions_on_open,
|
||||
timing_information,
|
||||
viewport,
|
||||
@@ -134,6 +139,26 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
};
|
||||
self.ingest.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::History(message) => {
|
||||
let context = HistoryMessageContext {
|
||||
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,
|
||||
};
|
||||
self.history.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::Sync(message) => {
|
||||
let context = SyncMessageContext {
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
resource_storage,
|
||||
preferences,
|
||||
ipp,
|
||||
viewport,
|
||||
tools,
|
||||
};
|
||||
self.sync.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::Workspace(message) => {
|
||||
let context = WorkspaceMessageContext {
|
||||
has_active_document: self.active_document_id.is_some(),
|
||||
@@ -385,10 +410,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
for document in self.documents.values_mut() {
|
||||
document.garbage_collect_resources();
|
||||
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
|
||||
|
||||
if let Some(storage) = document.storage() {
|
||||
used_resources.extend(storage.all_referenced_resource_hashes());
|
||||
}
|
||||
used_resources.extend(document.resource_gc_roots());
|
||||
}
|
||||
used_resources.extend(self.fonts.used_resources());
|
||||
responses.add(ResourceStorageMessage::GarbageCollect {
|
||||
@@ -409,6 +431,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
PortfolioMessage::LoadPersistedState { state } => {
|
||||
if let Some(layout) = state.workspace_layout {
|
||||
self.workspace.panel_layout = layout;
|
||||
// Add the Session panel beside the Inspector, unless the user closed it
|
||||
let panel_layout = &mut self.workspace.panel_layout;
|
||||
if !panel_layout.is_panel_present(PanelType::Session) && !panel_layout.was_closed(PanelType::Session) {
|
||||
match panel_layout.find_panel(PanelType::Inspector).and_then(|group_id| panel_layout.panel_group_mut(group_id)) {
|
||||
Some(group) => group.tabs.push(PanelType::Session),
|
||||
None => panel_layout.restore_panel(PanelType::Session),
|
||||
}
|
||||
}
|
||||
responses.add(WorkspaceMessage::UpdatePanelsLayout);
|
||||
|
||||
// Refill panels whose content was lost when the layout load remounted their frontend components
|
||||
@@ -443,12 +473,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
let elsewhere = held
|
||||
.iter()
|
||||
.map(|&document_id| {
|
||||
let name = restoring
|
||||
.iter()
|
||||
.find(|info| info.id == document_id)
|
||||
.map(|info| info.name.clone())
|
||||
.filter(|name| !name.trim().is_empty());
|
||||
(document_id, name.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string()))
|
||||
let info = restoring.iter().find(|info| info.id == document_id);
|
||||
let name = info.map(|info| info.name.clone()).filter(|name| !name.trim().is_empty());
|
||||
(document_id, name.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string()), info.is_some_and(|info| info.session.is_some()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for info in restoring {
|
||||
@@ -474,6 +501,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
name: String::new(),
|
||||
path: None,
|
||||
is_saved: false,
|
||||
session: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -514,7 +542,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document.path = info.path;
|
||||
document.set_save_state(info.is_saved);
|
||||
self.load_document(document, document_id, resource_storage.resources_mut(), responses);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
|
||||
}
|
||||
None => {
|
||||
self.document_ids.retain(|id| *id != document_id);
|
||||
@@ -534,12 +562,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
PortfolioMessage::NewDocumentWithName { name } => {
|
||||
responses.add_front(PortfolioMessage::NewDocumentWithId {
|
||||
name,
|
||||
document_id: DocumentId(generate_uuid()),
|
||||
});
|
||||
}
|
||||
PortfolioMessage::NewDocumentWithId { name, document_id } => {
|
||||
let mut new_document = DocumentMessageHandler::default();
|
||||
new_document.name = self.resolve_document_name(name, None);
|
||||
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
|
||||
let document_id = DocumentId(generate_uuid());
|
||||
if self.active_document().is_some() {
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
|
||||
@@ -583,6 +616,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_name,
|
||||
document_path,
|
||||
content,
|
||||
fresh_identity,
|
||||
} => {
|
||||
if let Some(path) = &document_path
|
||||
&& let Some(&document_id) = self.document_ids.iter().find(|&&id| self.document_details(id).is_some_and(|info| info.path.as_ref() == Some(path)))
|
||||
@@ -603,6 +637,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_name,
|
||||
document_path,
|
||||
content,
|
||||
fresh_identity,
|
||||
resource_storage.resources_mut(),
|
||||
reset_node_definitions_on_open,
|
||||
));
|
||||
@@ -622,6 +657,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
reset_node_definitions_on_open,
|
||||
));
|
||||
}
|
||||
PortfolioMessage::JoinStoredSession { source } => {
|
||||
responses.add(join_stored_session(self.document_store.clone(), source));
|
||||
}
|
||||
PortfolioMessage::DocumentFileLoaded {
|
||||
document_id,
|
||||
document_name,
|
||||
@@ -643,7 +681,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document.path = document_path;
|
||||
|
||||
self.load_document(document, document_id, resource_storage.resources_mut(), responses);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::StorageAttached {
|
||||
@@ -662,7 +700,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
return;
|
||||
};
|
||||
document.container = Some(container);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences);
|
||||
self.attach_storage(document_id, gdd, declarations, resource_storage, preferences, responses);
|
||||
self.save_if_needed(document_id, responses);
|
||||
}
|
||||
PortfolioMessage::NextDocument => {
|
||||
@@ -914,6 +952,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(FrontendMessage::UpdateActiveDocument { document_id });
|
||||
responses.add(ToolMessage::InitTools);
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
responses.add(NodeGraphMessage::Init);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
@@ -1162,6 +1201,8 @@ impl PortfolioMessageHandler {
|
||||
persistent_state: Default::default(),
|
||||
fonts: Default::default(),
|
||||
ingest: Default::default(),
|
||||
history: Default::default(),
|
||||
sync: Default::default(),
|
||||
executor,
|
||||
selection_mode: Default::default(),
|
||||
reset_node_definitions_on_open: Default::default(),
|
||||
@@ -1293,12 +1334,33 @@ impl PortfolioMessageHandler {
|
||||
declarations: Declarations,
|
||||
resource_storage: &ResourceStorageMessageHandler,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let (Some(document), Some(gdd)) = (self.documents.get_mut(&document_id), gdd) else { return };
|
||||
document.set_storage(*gdd, declarations);
|
||||
document.require_whole_document_stage();
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
document.retire_storage_interaction();
|
||||
let Some(document) = self.documents.get_mut(&document_id) else { return };
|
||||
// The person at this device authors the working copy, whoever wrote it last
|
||||
let set_user = |gdd: &mut GddV1| {
|
||||
let user = document_graph_storage::UserId(preferences.user_id);
|
||||
if gdd.session().user() != user
|
||||
&& let Err(error) = gdd.set_user(user, document_graph_storage::PeerId(generate_uuid()))
|
||||
{
|
||||
log::error!("Setting the user of {document_id:?} failed: {error}");
|
||||
}
|
||||
};
|
||||
match gdd {
|
||||
Some(mut gdd) => {
|
||||
set_user(&mut gdd);
|
||||
let resources = resource_storage.resources_mut();
|
||||
document.set_storage(*gdd, declarations, resources.storage());
|
||||
document.require_whole_document_stage();
|
||||
document.commit_storage_snapshot(&resources, preferences.validate_storage_round_trip);
|
||||
document.retire_storage_interaction();
|
||||
}
|
||||
None => {
|
||||
let Some(storage) = document.storage_mut() else { return };
|
||||
set_user(storage);
|
||||
}
|
||||
}
|
||||
responses.add(SyncMessage::StorageMounted { document_id });
|
||||
}
|
||||
|
||||
/// The resources of documents that are not loaded yet are unknown, so GC waits for every load and for a successful store listing.
|
||||
@@ -1352,6 +1414,11 @@ impl PortfolioMessageHandler {
|
||||
name: document.name.clone(),
|
||||
path: document.path.clone(),
|
||||
is_saved: document.is_saved(),
|
||||
session: document.storage().and_then(|gdd| match (gdd.role().is_some(), gdd.is_shared()) {
|
||||
(true, _) => Some(SessionStatus::Connected),
|
||||
(false, true) => Some(SessionStatus::Disconnected),
|
||||
(false, false) => None,
|
||||
}),
|
||||
})
|
||||
} else {
|
||||
self.loading_documents.get(&document_id).cloned()
|
||||
@@ -1423,6 +1490,7 @@ mod tests {
|
||||
name: "Elsewhere".into(),
|
||||
path: None,
|
||||
is_saved: true,
|
||||
session: None,
|
||||
};
|
||||
editor.portfolio_message_handler_mut().restoring_documents.push(info);
|
||||
editor
|
||||
@@ -1441,6 +1509,18 @@ mod tests {
|
||||
assert_eq!(editor.active_document().network_interface.document_network().nodes.len(), nodes);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_held_session_is_joined_through_its_manifest_id() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let source = editor.portfolio_message_handler().active_document_id().unwrap();
|
||||
let document_id = editor.active_document().storage().unwrap().manifest().document_id;
|
||||
let token = peer_transport::SessionToken::for_document(document_id).to_string();
|
||||
|
||||
let message = join_stored_session(editor.portfolio_message_handler().document_store(), source).await;
|
||||
assert_eq!(message, SyncMessage::Join { token }.into());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resources_stay_uncollected_while_a_stored_document_is_not_open() {
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! A person's colour and stand-in name. Both derive from the user id, so all peers show the same ones.
|
||||
|
||||
use document_graph_storage::UserId;
|
||||
|
||||
fn scramble(user: UserId) -> u64 {
|
||||
user.0.wrapping_mul(0x9E37_79B9_7F4A_7C15)
|
||||
}
|
||||
|
||||
pub(crate) fn anonymous_name(user: UserId) -> String {
|
||||
let index = (scramble(user) >> 40) as usize % ANONYMOUS_ANIMALS.len();
|
||||
format!("Anonymous {}", ANONYMOUS_ANIMALS[index])
|
||||
}
|
||||
|
||||
const ANONYMOUS_ANIMALS: [&str; 64] = [
|
||||
"Alligator",
|
||||
"Anteater",
|
||||
"Armadillo",
|
||||
"Axolotl",
|
||||
"Badger",
|
||||
"Bat",
|
||||
"Beaver",
|
||||
"Buffalo",
|
||||
"Camel",
|
||||
"Capybara",
|
||||
"Chameleon",
|
||||
"Cheetah",
|
||||
"Chinchilla",
|
||||
"Chipmunk",
|
||||
"Cormorant",
|
||||
"Coyote",
|
||||
"Crow",
|
||||
"Dingo",
|
||||
"Dolphin",
|
||||
"Duck",
|
||||
"Elephant",
|
||||
"Ferret",
|
||||
"Fox",
|
||||
"Frog",
|
||||
"Giraffe",
|
||||
"Gopher",
|
||||
"Grizzly",
|
||||
"Hedgehog",
|
||||
"Heron",
|
||||
"Hippo",
|
||||
"Hyena",
|
||||
"Ibex",
|
||||
"Iguana",
|
||||
"Jackal",
|
||||
"Jaguar",
|
||||
"Kangaroo",
|
||||
"Koala",
|
||||
"Kraken",
|
||||
"Lemur",
|
||||
"Leopard",
|
||||
"Liger",
|
||||
"Llama",
|
||||
"Manatee",
|
||||
"Mink",
|
||||
"Monkey",
|
||||
"Moose",
|
||||
"Narwhal",
|
||||
"Nyan Cat",
|
||||
"Orangutan",
|
||||
"Otter",
|
||||
"Panda",
|
||||
"Penguin",
|
||||
"Platypus",
|
||||
"Python",
|
||||
"Quagga",
|
||||
"Rabbit",
|
||||
"Raccoon",
|
||||
"Rhino",
|
||||
"Sheep",
|
||||
"Shrew",
|
||||
"Skunk",
|
||||
"Squirrel",
|
||||
"Tiger",
|
||||
"Turtle",
|
||||
];
|
||||
|
||||
pub(crate) fn user_color(user: UserId) -> String {
|
||||
let hue = (scramble(user) >> 32) % 360;
|
||||
let (h, s, l): (f64, f64, f64) = (hue as f64 / 60., 0.65, 0.5);
|
||||
let c = (1. - (2. * l - 1.).abs()) * s;
|
||||
let x = c * (1. - (h % 2. - 1.).abs());
|
||||
let m = l - c / 2.;
|
||||
let (r, g, b) = match h as u32 {
|
||||
0 => (c, x, 0.),
|
||||
1 => (x, c, 0.),
|
||||
2 => (0., c, x),
|
||||
3 => (0., x, c),
|
||||
4 => (x, 0., c),
|
||||
_ => (c, 0., x),
|
||||
};
|
||||
let channel = |value: f64| ((value + m) * 255.).round() as u8;
|
||||
format!("#{:02x}{:02x}{:02x}", channel(r), channel(g), channel(b))
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub(crate) mod identity;
|
||||
mod sync_message;
|
||||
mod sync_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
|
||||
pub(crate) use sync_message_handler::now_ms;
|
||||
#[doc(inline)]
|
||||
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
|
||||
@@ -0,0 +1,35 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use peer_transport::TransportPeerId;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, Sync)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SyncMessage {
|
||||
/// Host the active document and give the frontend a link.
|
||||
Share,
|
||||
/// Open a new document that follows the session behind `token`.
|
||||
Join { token: String },
|
||||
/// Disconnect the active document. Editing continues alone.
|
||||
Leave,
|
||||
/// Host the active document as a new session with its own link. The others stay in the old room.
|
||||
Fork,
|
||||
/// Send the Session panel's layout.
|
||||
RefreshPanel,
|
||||
/// Apply what peers sent, once per frame.
|
||||
Poll,
|
||||
/// A packet arrived, so poll now. A stale `generation` is ignored.
|
||||
Wake { document_id: DocumentId, generation: u32 },
|
||||
/// A document's working copy mounted.
|
||||
StorageMounted { document_id: DocumentId },
|
||||
/// A transport loop ended. A stale `generation` is ignored.
|
||||
Disconnected { document_id: DocumentId, generation: u32 },
|
||||
/// `None` when the byte store lacks the declaration.
|
||||
DeclarationLoaded { document_id: DocumentId, hash: ResourceHash, bytes: Option<Vec<u8>> },
|
||||
/// A resource a peer asked for was read from the byte store.
|
||||
ResourceLoaded {
|
||||
document_id: DocumentId,
|
||||
to: TransportPeerId,
|
||||
hash: ResourceHash,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,810 @@
|
||||
use super::identity::{anonymous_name, user_color};
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendRemoteCursor;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use crate::messages::viewport::Position;
|
||||
use document_format::GddV1;
|
||||
use document_graph_storage::{HistoryMetadata, Subject, UserId, user_attr};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::{LoadResource, ResourceHash};
|
||||
use peer_transport::{CursorPosition, CursorSpace, DEFAULT_SIGNALING_SERVER, Event, Incoming, MessageLoopFuture, RemotePeer, Role, Room, SessionToken, SyncTarget, TransportPeerId};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// How long a peer in a hostless room waits before it takes the role.
|
||||
const ROLE_GRACE_MS: f64 = 1_500.;
|
||||
/// The wait before reconnecting a downed transport.
|
||||
const RECONNECT_AFTER_MS: f64 = 3_000.;
|
||||
/// The wait before retrying remote changes.
|
||||
const APPLY_RETRY_MS: f64 = 1_000.;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct SyncMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub tools: &'a ToolMessageHandler,
|
||||
}
|
||||
|
||||
/// Drives every document's session. Connects to rooms, polls them and applies remote changes.
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct SyncMessageHandler {
|
||||
pending_joins: HashMap<DocumentId, SessionToken>,
|
||||
polling: bool,
|
||||
incoming: HashMap<DocumentId, (u32, Incoming)>,
|
||||
connections: u32,
|
||||
dirty: HashSet<DocumentId>,
|
||||
/// Documents whose viewport is fitted once the synced content is applied.
|
||||
fit_after_sync: HashSet<DocumentId>,
|
||||
undecided_since: HashMap<DocumentId, f64>,
|
||||
blocked_reason: HashMap<DocumentId, String>,
|
||||
decoding: HashSet<(DocumentId, ResourceHash)>,
|
||||
last_cursor: HashMap<DocumentId, Option<CursorPosition>>,
|
||||
graph_cursors: Vec<FrontendRemoteCursor>,
|
||||
document_cursors: Vec<FrontendRemoteCursor>,
|
||||
/// When each document next retries, since a try can convert the whole registry.
|
||||
retry_at: HashMap<DocumentId, f64>,
|
||||
reconnect_at: HashMap<DocumentId, f64>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler {
|
||||
fn process_message(&mut self, message: SyncMessage, responses: &mut VecDeque<Message>, context: SyncMessageContext) {
|
||||
let SyncMessageContext {
|
||||
documents,
|
||||
active_document_id,
|
||||
resource_storage,
|
||||
preferences,
|
||||
ipp,
|
||||
viewport,
|
||||
tools,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
SyncMessage::Share => {
|
||||
let Some(document_id) = active_document_id else { return };
|
||||
let Some(document) = documents.get_mut(&document_id) else { return };
|
||||
let Some(gdd) = document.storage() else {
|
||||
log::warn!("Cannot share a document before its working copy is mounted");
|
||||
return;
|
||||
};
|
||||
if gdd.role().is_some() {
|
||||
return;
|
||||
}
|
||||
document.stage_name_attribute();
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
self.host(document_id, gdd, preferences, responses);
|
||||
}
|
||||
SyncMessage::Join { token } => {
|
||||
let token = token.trim();
|
||||
if token.is_empty() {
|
||||
return;
|
||||
}
|
||||
let token = match token.parse::<SessionToken>() {
|
||||
Ok(token) => token,
|
||||
Err(error) => {
|
||||
log::warn!("Ignoring session link: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let document_id = DocumentId(generate_uuid());
|
||||
self.pending_joins.insert(document_id, token);
|
||||
responses.add(PortfolioMessage::NewDocumentWithId {
|
||||
name: "Shared session".into(),
|
||||
document_id,
|
||||
});
|
||||
}
|
||||
SyncMessage::StorageMounted { document_id } => {
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
// Every document polls, shared or not, since retirement runs on the frame tick
|
||||
self.start_polling(responses);
|
||||
if let Some(token) = self.pending_joins.remove(&document_id) {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let incoming = room.incoming();
|
||||
if let Err(error) = gdd.connect(room, UserId(preferences.user_id)) {
|
||||
log::error!("Joining the session failed: {error}");
|
||||
return;
|
||||
}
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
self.attach(document_id, incoming, driver, responses);
|
||||
refresh_session_views(responses);
|
||||
} else if gdd.is_shared() && gdd.role().is_none() {
|
||||
self.connect_document(document_id, gdd, preferences, responses);
|
||||
} else {
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
}
|
||||
SyncMessage::Leave => {
|
||||
let Some(document_id) = active_document_id else { return };
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
gdd.leave();
|
||||
self.detach(document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
SyncMessage::Fork => {
|
||||
let Some(document_id) = active_document_id else { return };
|
||||
let Some(document) = documents.get_mut(&document_id) else { return };
|
||||
document.stage_name_attribute();
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
gdd.leave();
|
||||
self.detach(document_id);
|
||||
// The room derives from the manifest's document id, so a fresh id is a fresh room
|
||||
if let Err(error) = gdd.update_manifest(|manifest| manifest.document_id = generate_uuid()) {
|
||||
log::error!("Forking the session failed: {error}");
|
||||
refresh_session_views(responses);
|
||||
return;
|
||||
}
|
||||
self.host(document_id, gdd, preferences, responses);
|
||||
}
|
||||
SyncMessage::Disconnected { document_id, generation } => {
|
||||
if !self.is_current(document_id, generation) {
|
||||
return;
|
||||
}
|
||||
self.detach(document_id);
|
||||
// The document stays shared, so it reconnects after a pause and on reopen
|
||||
if let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) {
|
||||
gdd.disconnect();
|
||||
self.reconnect_at.insert(document_id, now_ms() + RECONNECT_AFTER_MS);
|
||||
}
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
SyncMessage::RefreshPanel => {
|
||||
let layout = session_panel_layout(documents, active_document_id, preferences);
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout,
|
||||
layout_target: LayoutTarget::SessionPanel,
|
||||
});
|
||||
}
|
||||
SyncMessage::Poll => {
|
||||
let cursor = active_cursor(documents, active_document_id, ipp, viewport, tools);
|
||||
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
|
||||
}
|
||||
SyncMessage::Wake { document_id, generation } => {
|
||||
if !self.is_current(document_id, generation) {
|
||||
return;
|
||||
}
|
||||
let cursor = active_cursor(documents, active_document_id, ipp, viewport, tools);
|
||||
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
|
||||
// The poll drained the inbox, so the next arrival wakes the next poll
|
||||
self.arm(document_id, responses);
|
||||
}
|
||||
SyncMessage::DeclarationLoaded { document_id, hash, bytes } => {
|
||||
let Some(bytes) = bytes else {
|
||||
// Stays in `decoding` so it isn't requested every frame
|
||||
log::warn!("Declaration {hash} is recorded as held but the byte store has no bytes for it");
|
||||
return;
|
||||
};
|
||||
let Some(document) = documents.get_mut(&document_id) else {
|
||||
self.decoding.remove(&(document_id, hash));
|
||||
return;
|
||||
};
|
||||
// A malformed one stays too, and the remote changes wait behind it
|
||||
if document.cache_declaration_bytes(hash, &bytes) {
|
||||
log::debug!("Decoded held declaration {hash} ({} bytes)", bytes.len());
|
||||
self.decoding.remove(&(document_id, hash));
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
}
|
||||
SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => {
|
||||
log::debug!("Sending resource {hash} ({} bytes)", bytes.len());
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = gdd.send_resource(to, hash, bytes) {
|
||||
log::warn!("Failed to send resource {hash} to a peer: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(SyncMessageDiscriminant; Share, Leave);
|
||||
}
|
||||
|
||||
impl SyncMessageHandler {
|
||||
fn host(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
|
||||
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
|
||||
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
|
||||
}
|
||||
|
||||
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
|
||||
let token = SessionToken::for_document(gdd.manifest().document_id);
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let incoming = room.incoming();
|
||||
if let Err(error) = gdd.connect(room, UserId(preferences.user_id)) {
|
||||
log::error!("Connecting to the session failed: {error}");
|
||||
return None;
|
||||
}
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
self.undecided_since.insert(document_id, now_ms());
|
||||
self.reconnect_at.remove(&document_id);
|
||||
self.attach(document_id, incoming, driver, responses);
|
||||
refresh_session_views(responses);
|
||||
Some(token)
|
||||
}
|
||||
|
||||
/// Runs the transport and polls on each packet, since a hidden browser tab gets about one frame a second.
|
||||
fn attach(&mut self, document_id: DocumentId, incoming: Incoming, driver: MessageLoopFuture, responses: &mut VecDeque<Message>) {
|
||||
self.connections += 1;
|
||||
self.incoming.insert(document_id, (self.connections, incoming));
|
||||
self.arm(document_id, responses);
|
||||
responses.add(driver_future(document_id, self.connections, driver));
|
||||
self.start_polling(responses);
|
||||
}
|
||||
|
||||
fn detach(&mut self, document_id: DocumentId) {
|
||||
self.incoming.remove(&document_id);
|
||||
self.last_cursor.remove(&document_id);
|
||||
self.reconnect_at.remove(&document_id);
|
||||
self.retry_at.remove(&document_id);
|
||||
self.undecided_since.remove(&document_id);
|
||||
}
|
||||
|
||||
fn is_current(&self, document_id: DocumentId, generation: u32) -> bool {
|
||||
self.incoming.get(&document_id).is_some_and(|(current, _)| *current == generation)
|
||||
}
|
||||
|
||||
fn arm(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
let Some((generation, incoming)) = self.incoming.get(&document_id).cloned() else { return };
|
||||
let future = async move {
|
||||
match incoming.wait().await {
|
||||
true => SyncMessage::Wake { document_id, generation }.into(),
|
||||
false => Message::NoOp,
|
||||
}
|
||||
};
|
||||
responses.add(future);
|
||||
}
|
||||
|
||||
fn start_polling(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if self.polling {
|
||||
return;
|
||||
}
|
||||
self.polling = true;
|
||||
responses.add(BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send: Box::new(SyncMessage::Poll.into()),
|
||||
});
|
||||
}
|
||||
|
||||
fn poll(
|
||||
&mut self,
|
||||
documents: &mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
active_document_id: Option<DocumentId>,
|
||||
resources: ResourcesHandle,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
active_cursor: Option<CursorPosition>,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
for (&document_id, document) in documents.iter_mut() {
|
||||
let cursor = (Some(document_id) == active_document_id).then(|| active_cursor.clone()).flatten();
|
||||
self.poll_document(document_id, document, &resources, preferences, cursor, responses);
|
||||
}
|
||||
|
||||
let active_document = active_document_id.and_then(|id| documents.get(&id));
|
||||
let graph_cursors = active_document.map(|document| graph_cursors(document, preferences)).unwrap_or_default();
|
||||
if graph_cursors != self.graph_cursors {
|
||||
self.graph_cursors = graph_cursors.clone();
|
||||
responses.add(FrontendMessage::UpdateNodeGraphCursors { cursors: graph_cursors });
|
||||
}
|
||||
let document_cursors = active_document.map(|document| document_cursors(document, preferences)).unwrap_or_default();
|
||||
if document_cursors != self.document_cursors {
|
||||
self.document_cursors = document_cursors.clone();
|
||||
responses.add(FrontendMessage::UpdateDocumentCursors { cursors: document_cursors });
|
||||
}
|
||||
|
||||
self.apply_dirty(documents, active_document_id, &resources, responses);
|
||||
}
|
||||
|
||||
fn poll_document(
|
||||
&mut self,
|
||||
document_id: DocumentId,
|
||||
document: &mut DocumentMessageHandler,
|
||||
resources: &ResourcesHandle,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
cursor: Option<CursorPosition>,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
// A local undo that couldn't apply its changes leaves them here too
|
||||
if !document.pending_remote.is_empty() {
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
let idle = document.network_interface.transaction_status() == TransactionStatus::Finished;
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
if let Err(error) = gdd.retire_due(now_ms(), idle) {
|
||||
log::error!("Retirement failed: {error}");
|
||||
}
|
||||
record_profile(gdd, preferences);
|
||||
if self.reconnect_at.get(&document_id).is_some_and(|&due| now_ms() >= due) {
|
||||
self.reconnect_at.remove(&document_id);
|
||||
if gdd.is_shared() && gdd.role().is_none() {
|
||||
log::info!("Reconnecting {document_id:?} to its session");
|
||||
self.connect_document(document_id, gdd, preferences, responses);
|
||||
}
|
||||
}
|
||||
|
||||
match gdd.role() {
|
||||
None => return,
|
||||
Some(Role::Undecided) => {
|
||||
let since = *self.undecided_since.entry(document_id).or_insert_with(now_ms);
|
||||
if now_ms() - since >= ROLE_GRACE_MS && gdd.decide_role().is_some() {
|
||||
self.undecided_since.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
self.undecided_since.remove(&document_id);
|
||||
}
|
||||
}
|
||||
|
||||
document.stage_pending_edits(resources);
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
if self.last_cursor.get(&document_id) != Some(&cursor) {
|
||||
match gdd.send_cursor(cursor.clone()) {
|
||||
Ok(()) => {
|
||||
self.last_cursor.insert(document_id, cursor);
|
||||
}
|
||||
Err(error) => log::warn!("Sending the pointer position failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
let events = gdd.poll_peers();
|
||||
// Taken on every poll, since a full sync can replace the registry without a change event
|
||||
let changes = gdd.take_remote_changes();
|
||||
if !changes.is_empty() {
|
||||
document.pending_remote.extend(changes);
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
for event in events {
|
||||
match event {
|
||||
Event::Synced => {
|
||||
log::debug!("Synced with the host, applying its state");
|
||||
refresh_session_views(responses);
|
||||
self.dirty.insert(document_id);
|
||||
self.fit_after_sync.insert(document_id);
|
||||
}
|
||||
Event::Changed => {
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
Event::ResourceRequested { from, hash } => {
|
||||
log::debug!("Peer asked for resource {hash}");
|
||||
responses.add(load_resource_future(document_id, from, hash, resources.clone()));
|
||||
}
|
||||
// The replica already stored the bytes. Only the decoded declaration is missing
|
||||
Event::ResourceReceived { hash, bytes } => {
|
||||
log::debug!("Received resource {hash} ({} bytes)", bytes.len());
|
||||
document.cache_declaration_bytes(hash, &bytes);
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
Event::RoleChanged { role } => {
|
||||
log::debug!("Session role is now {role:?}");
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
// A new peer hasn't seen the pointer yet, even if it stayed put
|
||||
Event::PeerJoined { .. } => {
|
||||
self.last_cursor.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses),
|
||||
Event::MetadataChanged => {
|
||||
refresh_session_views(responses);
|
||||
responses.add(HistoryMessage::Refresh);
|
||||
}
|
||||
Event::CursorMoved { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies remote changes once their resources are cached. Never under an open transaction, whose tool state may
|
||||
/// name nodes a peer removed.
|
||||
fn apply_dirty(&mut self, documents: &mut HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, resources: &ResourcesHandle, responses: &mut VecDeque<Message>) {
|
||||
for document_id in self.dirty.clone() {
|
||||
let Some(document) = documents.get_mut(&document_id) else {
|
||||
self.dirty.remove(&document_id);
|
||||
continue;
|
||||
};
|
||||
let Some(gdd) = document.storage() else { continue };
|
||||
let missing = SyncTarget::missing_resources(gdd).len();
|
||||
if self.retry_at.get(&document_id).is_some_and(|&due| now_ms() < due) {
|
||||
continue;
|
||||
}
|
||||
let transaction = document.network_interface.transaction_status();
|
||||
if missing > 0 || transaction != TransactionStatus::Finished {
|
||||
self.wait(document_id, format!("missing {missing} transaction {transaction:?}"));
|
||||
continue;
|
||||
}
|
||||
// A declaration from an earlier session never came from a peer, so read it from the byte store
|
||||
let undecoded = document.undecoded_declaration_hashes();
|
||||
if !undecoded.is_empty() {
|
||||
self.wait(document_id, format!("decoding {} held declarations", undecoded.len()));
|
||||
for hash in undecoded {
|
||||
if self.decoding.insert((document_id, hash)) {
|
||||
responses.add(decode_declaration_future(document_id, hash, resources.clone()));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.blocked_reason.remove(&document_id);
|
||||
|
||||
if !document.apply_remote_changes(responses) {
|
||||
self.retry_at.insert(document_id, now_ms() + APPLY_RETRY_MS);
|
||||
} else {
|
||||
self.retry_at.remove(&document_id);
|
||||
self.dirty.remove(&document_id);
|
||||
// Alone, a tab may be named after its file, and only undo and redo speak for the stored name
|
||||
if document.is_in_session() && document.adopt_name_from_storage() {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
if self.fit_after_sync.remove(&document_id) && Some(document_id) == active_document_id {
|
||||
// The bounds come from the render, so the fit waits for the graph to run
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
}
|
||||
}
|
||||
|
||||
fn wait(&mut self, document_id: DocumentId, reason: String) {
|
||||
if self.blocked_reason.get(&document_id) != Some(&reason) {
|
||||
log::debug!("Applying remote changes to {document_id:?} waits: {reason}");
|
||||
self.blocked_reason.insert(document_id, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn driver_future(document_id: DocumentId, generation: u32, driver: MessageLoopFuture) -> Message {
|
||||
let future = async move {
|
||||
if let Err(error) = driver.await {
|
||||
log::warn!("Session transport for {document_id:?} ended: {error}");
|
||||
}
|
||||
SyncMessage::Disconnected { document_id, generation }.into()
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
fn decode_declaration_future(document_id: DocumentId, hash: ResourceHash, resources: ResourcesHandle) -> Message {
|
||||
let future = async move {
|
||||
let bytes = resources.load(hash).await.map(|resource| resource.as_ref().to_vec());
|
||||
SyncMessage::DeclarationLoaded { document_id, hash, bytes }.into()
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
fn load_resource_future(document_id: DocumentId, to: TransportPeerId, hash: ResourceHash, resources: ResourcesHandle) -> Message {
|
||||
let future = async move {
|
||||
let Some(resource) = resources.load(hash).await else {
|
||||
log::warn!("A peer asked for resource {hash} which is not in the byte store");
|
||||
return Message::NoOp;
|
||||
};
|
||||
SyncMessage::ResourceLoaded {
|
||||
document_id,
|
||||
to,
|
||||
hash,
|
||||
bytes: resource.as_ref().to_vec(),
|
||||
}
|
||||
.into()
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
pub(crate) fn now_ms() -> f64 {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
js_sys::Date::now()
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|elapsed| elapsed.as_secs_f64() * 1000.)
|
||||
.unwrap_or(0.)
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_session_views(responses: &mut VecDeque<Message>) {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
|
||||
fn session_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
|
||||
let heading = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).bold(true).widget_instance()]);
|
||||
let note = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).multiline(true).widget_instance()]);
|
||||
let user_name = preferences.user_name.as_str();
|
||||
let name_row = || {
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new("Your name").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(user_name)
|
||||
.placeholder(anonymous_name(UserId(preferences.user_id)))
|
||||
.on_update(|input: &TextInput| PreferencesMessage::UserName { name: input.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
])
|
||||
};
|
||||
let cursors_row = || {
|
||||
let checkbox_id = CheckboxId::new();
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new("Show cursors")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(90))
|
||||
.for_checkbox(checkbox_id)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.show_remote_cursors)
|
||||
.tooltip_description("Draw the other peers' pointers over the document.")
|
||||
.on_update(|checkbox: &CheckboxInput| PreferencesMessage::ShowRemoteCursors { enabled: checkbox.checked }.into())
|
||||
.for_label(checkbox_id)
|
||||
.widget_instance(),
|
||||
])
|
||||
};
|
||||
|
||||
let Some(document) = active_document_id.and_then(|id| documents.get(&id)) else {
|
||||
return Layout(vec![note("Open a document to share it.")]);
|
||||
};
|
||||
let Some(gdd) = document.storage() else {
|
||||
return Layout(vec![name_row(), cursors_row(), note("The document's working copy is still being mounted.")]);
|
||||
};
|
||||
|
||||
let fork = || {
|
||||
TextButton::new("Fork")
|
||||
.tooltip_label("Fork the session")
|
||||
.tooltip_description("Leave this room and host the document as a new session with its own link. The others keep the room they are in.")
|
||||
.on_commit(|_| SyncMessage::Fork.into())
|
||||
.widget_instance()
|
||||
};
|
||||
let (state, actions, detail) = match gdd.role() {
|
||||
None if gdd.is_shared() => (
|
||||
"Disconnected, reconnecting",
|
||||
vec![
|
||||
TextButton::new("Reconnect").icon("Link").emphasized(true).on_commit(|_| SyncMessage::Share.into()).widget_instance(),
|
||||
TextButton::new("Stop Sharing").on_commit(|_| SyncMessage::Leave.into()).widget_instance(),
|
||||
fork(),
|
||||
],
|
||||
note("The connection to the session was lost. The editor keeps trying to reconnect, and the document stays editable meanwhile."),
|
||||
),
|
||||
None => (
|
||||
"Not shared",
|
||||
vec![
|
||||
TextButton::new("Share Live Session")
|
||||
.icon("Link")
|
||||
.emphasized(true)
|
||||
.on_commit(|_| SyncMessage::Share.into())
|
||||
.widget_instance(),
|
||||
],
|
||||
LayoutGroup::column(vec![
|
||||
TextLabel::new("Share this document to edit it live with others. Everyone who opens the link works on the same document.")
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
),
|
||||
// A connecting guest holds its own id, not the room's, so a link from it would lead elsewhere
|
||||
Some(role) if !(role == Role::Host || (role == Role::Guest && gdd.is_synced())) => (
|
||||
"Connecting",
|
||||
vec![TextButton::new("Disconnect").on_commit(|_| SyncMessage::Leave.into()).widget_instance(), fork()],
|
||||
note("The link appears once the document has arrived."),
|
||||
),
|
||||
Some(_) => {
|
||||
let token = SessionToken::for_document(gdd.manifest().document_id).to_string();
|
||||
let copy_link_token = token.clone();
|
||||
let copy_token = token.clone();
|
||||
(
|
||||
"Live session",
|
||||
vec![
|
||||
TextButton::new("Copy Link")
|
||||
.icon("Copy")
|
||||
.emphasized(true)
|
||||
.on_commit(move |_| FrontendMessage::TriggerSessionLinkCopy { token: copy_link_token.clone() }.into())
|
||||
.widget_instance(),
|
||||
TextButton::new("Disconnect").on_commit(|_| SyncMessage::Leave.into()).widget_instance(),
|
||||
fork(),
|
||||
],
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(token)
|
||||
.monospace(true)
|
||||
.selectable(true)
|
||||
.tooltip_label("Session")
|
||||
.tooltip_description("Opening the editor with this session in the link joins the room.")
|
||||
.widget_instance(),
|
||||
IconButton::new("Copy", 24)
|
||||
.tooltip_label("Copy Session Token")
|
||||
.on_update(move |_| FrontendMessage::TriggerClipboardWrite { content: copy_token.clone() }.into())
|
||||
.widget_instance(),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut groups = vec![name_row(), cursors_row(), heading(state), LayoutGroup::row(actions), detail];
|
||||
if gdd.role().is_none() && !gdd.is_shared() {
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Join a session").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new("")
|
||||
.placeholder("Paste a link")
|
||||
.tooltip_description("Opens the shared document in a new tab, following the session behind the link.")
|
||||
.on_update(|input: &TextInput| SyncMessage::Join { token: input.value.clone() }.into())
|
||||
.widget_instance(),
|
||||
]));
|
||||
}
|
||||
|
||||
if gdd.role().is_some() {
|
||||
let mut peers: Vec<_> = gdd.peers().collect();
|
||||
peers.sort_by_key(|remote| remote.peer);
|
||||
groups.push(heading(&format!("In the session ({})", peers.len() + 1)));
|
||||
let me = match user_name.is_empty() {
|
||||
true => anonymous_name(UserId(preferences.user_id)),
|
||||
false => user_name.to_string(),
|
||||
};
|
||||
groups.push(peer_row(&format!("{me} (you)"), user_name.is_empty()));
|
||||
let metadata = gdd.metadata();
|
||||
groups.extend(peers.iter().map(|remote| peer_row(&display_name(remote, metadata), is_anonymous(remote, metadata))));
|
||||
}
|
||||
Layout(groups)
|
||||
}
|
||||
|
||||
fn peer_row(name: &str, anonymous: bool) -> LayoutGroup {
|
||||
LayoutGroup::row(vec![TextLabel::new(name).italic(anonymous).widget_instance()])
|
||||
}
|
||||
|
||||
/// Records this user's name in the document. An empty name is recorded only to clear one.
|
||||
fn record_profile(gdd: &mut GddV1, preferences: &PreferencesMessageHandler) {
|
||||
let name = preferences.user_name.trim();
|
||||
let user = UserId(preferences.user_id);
|
||||
if gdd.metadata().user_name(user).unwrap_or_default() == name {
|
||||
return;
|
||||
}
|
||||
if let Err(error) = gdd.record(Subject::User(user), user_attr::NAME, serde_json::Value::from(name), now_ms()) {
|
||||
log::warn!("Recording the display name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn announce_name(gdd: &mut GddV1, name: &str) {
|
||||
if let Err(error) = gdd.set_name(name) {
|
||||
log::warn!("Announcing the display name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn active_cursor(
|
||||
documents: &HashMap<DocumentId, DocumentMessageHandler>,
|
||||
active_document_id: Option<DocumentId>,
|
||||
ipp: &InputPreprocessorMessageHandler,
|
||||
viewport: &ViewportMessageHandler,
|
||||
tools: &ToolMessageHandler,
|
||||
) -> Option<CursorPosition> {
|
||||
let document = documents.get(&active_document_id?)?;
|
||||
cursor_position(document, ipp, viewport, tools)
|
||||
}
|
||||
|
||||
/// The pointer over the viewport, in the graph's network or the document. Rounded, so jitter sends nothing.
|
||||
fn cursor_position(document: &DocumentMessageHandler, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler, tools: &ToolMessageHandler) -> Option<CursorPosition> {
|
||||
let mouse = ipp.mouse.position;
|
||||
let size = viewport.size();
|
||||
if mouse.x < 0. || mouse.y < 0. || mouse.x > size.x() || mouse.y > size.y() {
|
||||
return None;
|
||||
}
|
||||
let (to_viewport, space) = match document.is_graph_overlay_open() {
|
||||
true => (graph_to_viewport(document)?, CursorSpace::Graph { network: shown_network(document) }),
|
||||
false => (document.metadata().document_to_viewport, CursorSpace::Document),
|
||||
};
|
||||
let position = to_viewport.inverse().transform_point2(mouse);
|
||||
if !position.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let tool = tools.active_tool_icon();
|
||||
Some(CursorPosition {
|
||||
position: [(position.x * 100.).round() / 100., (position.y * 100.).round() / 100.],
|
||||
space,
|
||||
tool: (!tool.is_empty()).then_some(tool),
|
||||
})
|
||||
}
|
||||
|
||||
fn document_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMessageHandler) -> Vec<FrontendRemoteCursor> {
|
||||
if !preferences.show_remote_cursors || document.is_graph_overlay_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(gdd) = document.storage().filter(|gdd| gdd.role().is_some()) else { return Vec::new() };
|
||||
let to_viewport = document.metadata().document_to_viewport;
|
||||
gdd.peers()
|
||||
.filter_map(|remote| {
|
||||
let cursor = remote.cursor.as_ref().filter(|cursor| matches!(cursor.space, CursorSpace::Document))?;
|
||||
remote_cursor(remote, cursor, to_viewport, gdd.metadata())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn graph_cursors(document: &DocumentMessageHandler, preferences: &PreferencesMessageHandler) -> Vec<FrontendRemoteCursor> {
|
||||
if !preferences.show_remote_cursors || !document.is_graph_overlay_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(gdd) = document.storage().filter(|gdd| gdd.role().is_some()) else { return Vec::new() };
|
||||
let Some(to_viewport) = graph_to_viewport(document) else { return Vec::new() };
|
||||
let shown = shown_network(document);
|
||||
gdd.peers()
|
||||
.filter_map(|remote| {
|
||||
let cursor = remote.cursor.as_ref()?;
|
||||
let CursorSpace::Graph { network } = &cursor.space else { return None };
|
||||
if *network != shown {
|
||||
return None;
|
||||
}
|
||||
remote_cursor(remote, cursor, to_viewport, gdd.metadata())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A peer's pointer in viewport pixels. `None` if not a finite point.
|
||||
fn remote_cursor(remote: &RemotePeer, cursor: &CursorPosition, to_viewport: DAffine2, metadata: &HistoryMetadata) -> Option<FrontendRemoteCursor> {
|
||||
let [x, y] = cursor.position;
|
||||
let point = to_viewport.transform_point2(DVec2::new(x, y));
|
||||
point.is_finite().then(|| FrontendRemoteCursor {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
name: display_name(remote, metadata),
|
||||
anonymous: is_anonymous(remote, metadata),
|
||||
color: user_color(remote.user),
|
||||
tool: cursor.tool.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn graph_to_viewport(document: &DocumentMessageHandler) -> Option<DAffine2> {
|
||||
let metadata = document.network_interface.network_metadata(document.breadcrumb_network_path())?;
|
||||
Some(metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
|
||||
}
|
||||
|
||||
fn shown_network(document: &DocumentMessageHandler) -> Vec<u64> {
|
||||
document.breadcrumb_network_path().iter().map(|id| id.0).collect()
|
||||
}
|
||||
|
||||
/// The document's record of the user, else the announced name, else the stand-in.
|
||||
fn display_name(remote: &RemotePeer, metadata: &HistoryMetadata) -> String {
|
||||
if let Some(name) = metadata.user_name(remote.user) {
|
||||
return name.to_string();
|
||||
}
|
||||
match remote.name.is_empty() {
|
||||
true => anonymous_name(remote.user),
|
||||
false => remote.name.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_anonymous(remote: &RemotePeer, metadata: &HistoryMetadata) -> bool {
|
||||
metadata.user_name(remote.user).is_none() && remote.name.is_empty()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_second_join_does_not_drop_the_first() {
|
||||
let mut sync = SyncMessageHandler::default();
|
||||
let (resource_storage, preferences, ipp, viewport, tools) = Default::default();
|
||||
let mut documents = HashMap::new();
|
||||
for byte in [1, 2] {
|
||||
let context = SyncMessageContext {
|
||||
documents: &mut documents,
|
||||
active_document_id: None,
|
||||
resource_storage: &resource_storage,
|
||||
preferences: &preferences,
|
||||
ipp: &ipp,
|
||||
viewport: &viewport,
|
||||
tools: &tools,
|
||||
};
|
||||
let token = SessionToken([byte; 16]).to_string();
|
||||
sync.process_message(SyncMessage::Join { token }, &mut VecDeque::new(), context);
|
||||
}
|
||||
|
||||
let mut tokens: Vec<_> = sync.pending_joins.values().copied().collect();
|
||||
tokens.sort_by_key(|token| token.0);
|
||||
assert_eq!(tokens, [SessionToken([1; 16]), SessionToken([2; 16])]);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ pub enum PanelType {
|
||||
#[serde(alias = "Properties")]
|
||||
Inspector,
|
||||
Data,
|
||||
Session,
|
||||
History,
|
||||
}
|
||||
|
||||
impl From<String> for PanelType {
|
||||
@@ -22,6 +24,8 @@ impl From<String> for PanelType {
|
||||
"Layers" => PanelType::Layers,
|
||||
"Inspector" | "Properties" => PanelType::Inspector,
|
||||
"Data" => PanelType::Data,
|
||||
"Session" => PanelType::Session,
|
||||
"History" => PanelType::History,
|
||||
_ => panic!("Unknown panel type: {value}"),
|
||||
}
|
||||
}
|
||||
@@ -29,7 +33,7 @@ impl From<String> for PanelType {
|
||||
|
||||
impl PanelType {
|
||||
pub fn non_document_panels() -> &'static [PanelType] {
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data]
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session, PanelType::History]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,6 +256,10 @@ impl WorkspacePanelLayout {
|
||||
});
|
||||
}
|
||||
|
||||
pub fn was_closed(&self, panel_type: PanelType) -> bool {
|
||||
self.saved_positions.iter().any(|saved| saved.panel_type == panel_type)
|
||||
}
|
||||
|
||||
/// Restore a panel to its previous position if available, otherwise to its default position.
|
||||
pub fn restore_panel(&mut self, panel_type: PanelType) {
|
||||
let saved = self.saved_positions.iter().find(|s| s.panel_type == panel_type).copied();
|
||||
@@ -301,7 +309,21 @@ impl WorkspacePanelLayout {
|
||||
/// - Data: below the document in the left column (root child 0)
|
||||
/// - Inspector: top of the right column (root child 1)
|
||||
/// - Layers: bottom of the right column (root child 1)
|
||||
/// - Session, History: a tab beside the Inspector or Layers, otherwise placed like that panel
|
||||
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
|
||||
let beside = match panel_type {
|
||||
PanelType::Session => Some(PanelType::Inspector),
|
||||
PanelType::History => Some(PanelType::Layers),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(beside) = beside
|
||||
&& let Some(group_id) = self.find_panel(beside)
|
||||
&& let Some(group) = self.panel_group_mut(group_id)
|
||||
{
|
||||
group.tabs.push(panel_type);
|
||||
group.active_tab_index = group.tabs.len() - 1;
|
||||
return;
|
||||
}
|
||||
let new_id = self.next_id();
|
||||
let new_group = SplitChild {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
@@ -316,9 +338,9 @@ impl WorkspacePanelLayout {
|
||||
|
||||
// Determine which root child column to insert into and at which position
|
||||
let (root_child_index, insert_at_end) = match panel_type {
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector => (1, false), // Right column, at top
|
||||
PanelType::Layers => (1, true), // Right column, at bottom
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector | PanelType::Session => (1, false), // Right column, at top
|
||||
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
|
||||
_ => (1, true),
|
||||
};
|
||||
|
||||
@@ -403,7 +425,7 @@ impl Default for WorkspacePanelLayout {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
id: PanelGroupId(1),
|
||||
state: PanelGroupState {
|
||||
tabs: vec![PanelType::Inspector],
|
||||
tabs: vec![PanelType::Inspector, PanelType::Session],
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -30,7 +30,12 @@ pub enum WorkspaceMessage {
|
||||
active_tab_index: usize,
|
||||
},
|
||||
ToggleFocusDocument,
|
||||
FocusPanel {
|
||||
panel_type: PanelType,
|
||||
},
|
||||
ToggleDataPanelOpen,
|
||||
ToggleSessionPanelOpen,
|
||||
ToggleHistoryPanelOpen,
|
||||
ToggleInspectorOpen,
|
||||
ToggleLayersPanelOpen,
|
||||
UpdatePanelsLayout,
|
||||
|
||||
@@ -267,6 +267,19 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
|
||||
let panel_type = PanelType::Layers;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::FocusPanel { panel_type } => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
let Some(group) = self.panel_layout.find_panel(panel_type) else {
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
return;
|
||||
};
|
||||
let Some(tab_index) = self.panel_layout.panel_group(group).and_then(|state| state.tabs.iter().position(|&tab| tab == panel_type)) else {
|
||||
return;
|
||||
};
|
||||
responses.add(WorkspaceMessage::SetPanelGroupActiveTab { group, tab_index });
|
||||
}
|
||||
WorkspaceMessage::ToggleDataPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
@@ -275,6 +288,22 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
|
||||
let panel_type = PanelType::Data;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::ToggleSessionPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
|
||||
let panel_type = PanelType::Session;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::ToggleHistoryPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
|
||||
let panel_type = PanelType::History;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::UpdatePanelsLayout => {
|
||||
let panel_layout = match self.panel_layout.focus_document {
|
||||
true => self.panel_layout.document_only_layout(),
|
||||
@@ -390,7 +419,8 @@ impl WorkspaceMessageHandler {
|
||||
PanelType::Inspector => &[LayoutTarget::Inspector],
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
|
||||
PanelType::Data => &[LayoutTarget::DataPanel, LayoutTarget::DataPanelContext, LayoutTarget::DataPanelPath],
|
||||
PanelType::Document | PanelType::Welcome => return,
|
||||
PanelType::Session => &[LayoutTarget::SessionPanel],
|
||||
PanelType::Document | PanelType::Welcome | PanelType::History => return,
|
||||
};
|
||||
|
||||
for &layout_target in targets {
|
||||
@@ -416,6 +446,12 @@ impl WorkspaceMessageHandler {
|
||||
PanelType::Data => {
|
||||
// The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here
|
||||
}
|
||||
PanelType::Session => {
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
PanelType::History => {
|
||||
responses.add(HistoryMessage::Refresh);
|
||||
}
|
||||
PanelType::Document | PanelType::Welcome => {
|
||||
// Re-send the welcome screen buttons layout to repopulate after a remount
|
||||
if has_no_documents {
|
||||
@@ -440,11 +476,11 @@ mod tests {
|
||||
};
|
||||
let group_of = |handler: &WorkspaceMessageHandler, panel_type| handler.panel_layout.find_panel(panel_type).expect("the default layout has this panel");
|
||||
|
||||
// The Layers panel joins the Inspector's group as its active tab
|
||||
// Layers joins the Inspector's group ahead of it, which leaves the Inspector active
|
||||
let join = WorkspaceMessage::MovePanelTab {
|
||||
source_group: group_of(&handler, PanelType::Layers),
|
||||
target_group: group_of(&handler, PanelType::Inspector),
|
||||
insert_index: 1,
|
||||
insert_index: 0,
|
||||
};
|
||||
handler.process_message(join, &mut VecDeque::new(), context());
|
||||
|
||||
|
||||
@@ -40,6 +40,12 @@ pub enum PreferencesMessage {
|
||||
enabled: bool,
|
||||
},
|
||||
ToggleShowStoragePreferences,
|
||||
UserName {
|
||||
name: String,
|
||||
},
|
||||
ShowRemoteCursors {
|
||||
enabled: bool,
|
||||
},
|
||||
#[cfg(target_os = "macos")]
|
||||
VSync {
|
||||
vsync: bool,
|
||||
|
||||
@@ -24,6 +24,12 @@ pub struct PreferencesMessageHandler {
|
||||
pub validate_storage_round_trip: bool,
|
||||
pub save_as_gdd: bool,
|
||||
pub show_storage_preferences: bool,
|
||||
/// This person's id across documents. A decimal string, since the browser's JSON loses 64-bit precision.
|
||||
#[serde(with = "u64_as_string")]
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "string"))]
|
||||
pub user_id: u64,
|
||||
pub user_name: String,
|
||||
pub show_remote_cursors: bool,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub vsync: bool,
|
||||
}
|
||||
@@ -54,12 +60,25 @@ impl Default for PreferencesMessageHandler {
|
||||
validate_storage_round_trip: false,
|
||||
save_as_gdd: false,
|
||||
show_storage_preferences: false,
|
||||
user_id: crate::application::generate_uuid(),
|
||||
user_name: String::new(),
|
||||
show_remote_cursors: true,
|
||||
#[cfg(target_os = "macos")]
|
||||
vsync: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PreferencesMessageHandler {
|
||||
pub fn from_stored(stored: Option<&str>) -> Self {
|
||||
let Some(stored) = stored else { return Self::default() };
|
||||
serde_json::from_str(stored).unwrap_or_else(|error| {
|
||||
log::error!("Failed to deserialize preferences: {error}");
|
||||
Self::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for PreferencesMessageHandler {
|
||||
fn process_message(&mut self, message: PreferencesMessage, responses: &mut VecDeque<Message>, context: PreferencesMessageContext) {
|
||||
@@ -69,6 +88,9 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
// Management messages
|
||||
PreferencesMessage::Load { preferences } => {
|
||||
*self = preferences;
|
||||
if self.user_id == 0 {
|
||||
self.user_id = crate::application::generate_uuid();
|
||||
}
|
||||
|
||||
responses.add(PreferencesMessage::ModifyLayout {
|
||||
zoom_with_scroll: self.zoom_with_scroll,
|
||||
@@ -77,7 +99,11 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
responses.add(ToolMessage::RefreshToolShelf);
|
||||
}
|
||||
PreferencesMessage::ResetToDefaults => {
|
||||
responses.add(PreferencesMessage::Load { preferences: Self::default() });
|
||||
let preferences = Self {
|
||||
user_id: self.user_id,
|
||||
..Self::default()
|
||||
};
|
||||
responses.add(PreferencesMessage::Load { preferences });
|
||||
responses.add(DialogMessage::RequestPreferencesDialog);
|
||||
}
|
||||
|
||||
@@ -125,6 +151,15 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
self.show_storage_preferences = !self.show_storage_preferences;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
}
|
||||
PreferencesMessage::UserName { name } => {
|
||||
self.user_name = name.trim().to_string();
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
PreferencesMessage::ShowRemoteCursors { enabled } => {
|
||||
self.show_remote_cursors = enabled;
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
PreferencesMessage::VSync { vsync } => {
|
||||
self.vsync = vsync;
|
||||
@@ -137,3 +172,89 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
advertise_actions!(PreferencesMessageDiscriminant;
|
||||
);
|
||||
}
|
||||
|
||||
/// A `u64` written as a decimal string, read from a string or a number.
|
||||
mod u64_as_string {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(&value.to_string())
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Stored {
|
||||
Text(String),
|
||||
Number(u64),
|
||||
}
|
||||
match Stored::deserialize(deserializer)? {
|
||||
Stored::Text(text) => text.parse().map_err(serde::de::Error::custom),
|
||||
Stored::Number(number) => Ok(number),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_first_launch_without_stored_preferences_has_a_user_id() {
|
||||
assert_ne!(PreferencesMessageHandler::default().user_id, 0);
|
||||
let stored: PreferencesMessageHandler = serde_json::from_str("{}").unwrap();
|
||||
assert_ne!(stored.user_id, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_unreadable_stored_preferences_load_as_defaults_and_are_persisted() {
|
||||
for stored in [None, Some("not json")] {
|
||||
let mut preferences = PreferencesMessageHandler::default();
|
||||
let loaded = PreferencesMessageHandler::from_stored(stored);
|
||||
assert_ne!(loaded.user_id, 0);
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
let tool_message_handler = ToolMessageHandler::default();
|
||||
let context = PreferencesMessageContext {
|
||||
tool_message_handler: &tool_message_handler,
|
||||
};
|
||||
preferences.process_message(PreferencesMessage::Load { preferences: loaded.clone() }, &mut responses, context);
|
||||
let persisted = responses.iter().find_map(|message| match message {
|
||||
Message::Frontend(FrontendMessage::TriggerUpdatePreferences { preferences }) => Some(preferences),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(persisted.map(|persisted| persisted.user_id), Some(loaded.user_id));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resetting_the_preferences_keeps_the_user_id() {
|
||||
let mut preferences = PreferencesMessageHandler::default();
|
||||
let tool_message_handler = ToolMessageHandler::default();
|
||||
let mut responses = VecDeque::new();
|
||||
preferences.process_message(
|
||||
PreferencesMessage::ResetToDefaults,
|
||||
&mut responses,
|
||||
PreferencesMessageContext {
|
||||
tool_message_handler: &tool_message_handler,
|
||||
},
|
||||
);
|
||||
let reset = responses.iter().find_map(|message| match message {
|
||||
Message::Preferences(PreferencesMessage::Load { preferences }) => Some(preferences),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(reset.map(|reset| reset.user_id), Some(preferences.user_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_user_id_round_trips_as_a_string() {
|
||||
let preferences = PreferencesMessageHandler {
|
||||
user_id: u64::MAX,
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_value(&preferences).unwrap();
|
||||
assert_eq!(json["user_id"], serde_json::Value::from(u64::MAX.to_string()));
|
||||
let read: PreferencesMessageHandler = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(read.user_id, u64::MAX);
|
||||
}
|
||||
}
|
||||
@@ -33,8 +33,10 @@ pub use crate::messages::portfolio::document::resource::{ResourceMessage, Resour
|
||||
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
|
||||
pub use crate::messages::portfolio::failed_documents::{FailedDocumentsMessage, FailedDocumentsMessageContext, FailedDocumentsMessageDiscriminant, FailedDocumentsMessageHandler};
|
||||
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
|
||||
pub use crate::messages::portfolio::history::{HistoryMessage, HistoryMessageContext, HistoryMessageDiscriminant, HistoryMessageHandler};
|
||||
pub use crate::messages::portfolio::ingest::{IngestMessage, IngestMessageContext, IngestMessageDiscriminant, IngestMessageHandler};
|
||||
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
|
||||
pub use crate::messages::portfolio::sync::{SyncMessage, SyncMessageContext, SyncMessageDiscriminant, SyncMessageHandler};
|
||||
pub use crate::messages::portfolio::workspace::{WorkspaceMessage, WorkspaceMessageContext, WorkspaceMessageDiscriminant, WorkspaceMessageHandler};
|
||||
pub use crate::messages::portfolio::{PortfolioMessage, PortfolioMessageContext, PortfolioMessageDiscriminant, PortfolioMessageHandler};
|
||||
pub use crate::messages::preferences::{PreferencesMessage, PreferencesMessageDiscriminant, PreferencesMessageHandler};
|
||||
|
||||
@@ -7,6 +7,16 @@ pub struct ResourcesHandle {
|
||||
inner: Arc<dyn ResourceStorage>,
|
||||
}
|
||||
|
||||
impl ResourcesHandle {
|
||||
pub fn new(inner: Arc<dyn ResourceStorage>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn storage(&self) -> Arc<dyn ResourceStorage> {
|
||||
self.inner.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadResource for ResourcesHandle {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
self.inner.load(hash)
|
||||
|
||||
@@ -460,6 +460,17 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
}
|
||||
|
||||
impl ToolMessageHandler {
|
||||
/// The icon of the active tool, or of the selected shape while the Shape tool is active.
|
||||
pub fn active_tool_icon(&self) -> String {
|
||||
let tool_data = &self.tool_state.tool_data;
|
||||
match tool_data.active_shape_type {
|
||||
Some(ToolType::Line) => Line.icon_name(),
|
||||
Some(ToolType::Rectangle) => Rectangle.icon_name(),
|
||||
Some(ToolType::Ellipse) => Ellipse.icon_name(),
|
||||
_ => tool_data.tools.get(&tool_data.active_tool_type).map(|tool| tool.icon_name()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets go of what the snapping session holds and has woken, so none of it carries over while the tools are off or into another document.
|
||||
fn release_snapping(&mut self, responses: &mut VecDeque<Message>) {
|
||||
self.snap_session.end_gesture();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import Editor from "/src/components/Editor.svelte";
|
||||
import { createSubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageName, SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { loadDemoArtwork } from "/src/utility-functions/network";
|
||||
import { joinSessionFromUrl, loadDemoArtwork } from "/src/utility-functions/network";
|
||||
import { operatingSystem } from "/src/utility-functions/platform";
|
||||
import { initWasm } from "/src/utility-functions/wasm-loader";
|
||||
import { EditorWrapper, receiveNativeMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -29,6 +29,7 @@
|
||||
});
|
||||
|
||||
await loadDemoArtwork(editor);
|
||||
joinSessionFromUrl(editor);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import { createDialogStore, destroyDialogStore } from "/src/stores/dialog";
|
||||
import { createDocumentStore, destroyDocumentStore } from "/src/stores/document";
|
||||
import { createFullscreenStore, destroyFullscreenStore } from "/src/stores/fullscreen";
|
||||
import { createHistoryStore, destroyHistoryStore } from "/src/stores/history";
|
||||
import { createMathExpressionStore, destroyMathExpressionStore } from "/src/stores/math-expression";
|
||||
import { createNodeGraphStore, destroyNodeGraphStore } from "/src/stores/node-graph";
|
||||
import { createPortfolioStore, destroyPortfolioStore } from "/src/stores/portfolio";
|
||||
@@ -31,6 +32,7 @@
|
||||
document: createDocumentStore(subscriptions),
|
||||
fullscreen: createFullscreenStore(subscriptions),
|
||||
nodeGraph: createNodeGraphStore(subscriptions),
|
||||
history: createHistoryStore(subscriptions),
|
||||
portfolio: createPortfolioStore(subscriptions, editor),
|
||||
appWindow: createAppWindowStore(subscriptions),
|
||||
colorPicker: createColorPickerStore(subscriptions),
|
||||
@@ -61,6 +63,7 @@
|
||||
destroyDocumentStore();
|
||||
destroyFullscreenStore();
|
||||
destroyNodeGraphStore();
|
||||
destroyHistoryStore();
|
||||
destroyPortfolioStore();
|
||||
destroyAppWindowStore();
|
||||
destroyColorPickerStore();
|
||||
@@ -104,6 +107,7 @@
|
||||
--color-f-white: #fff;
|
||||
--color-error-red: #d6536e;
|
||||
--color-warning-yellow: #d5aa43;
|
||||
--color-session-green: #4f9a60;
|
||||
|
||||
--color-data-general: #cfcfcf;
|
||||
--color-data-general-dim: #8a8a8a;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import Graph from "/src/components/views/Graph.svelte";
|
||||
import RemoteCursor from "/src/components/views/RemoteCursor.svelte";
|
||||
import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte";
|
||||
import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
@@ -30,6 +31,7 @@
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const appWindow = getContext<AppWindowStore>("appWindow");
|
||||
const document = getContext<DocumentStore>("document");
|
||||
const remoteCursors = document.remoteCursorsStore;
|
||||
|
||||
// Interactive text editing
|
||||
let textInput: undefined | HTMLDivElement = undefined;
|
||||
@@ -713,6 +715,9 @@
|
||||
bind:this={viewport}
|
||||
data-viewport
|
||||
>
|
||||
{#each $remoteCursors as cursor}
|
||||
<RemoteCursor {cursor} />
|
||||
{/each}
|
||||
{#if !$appWindow.viewportHolePunch}
|
||||
<svg class="artboards" style:width={canvasWidthCSS} style:height={canvasHeightCSS}>
|
||||
{@html artworkSvg}
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.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";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import type { HistoryStore } from "/src/stores/history";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const history = getContext<HistoryStore>("history");
|
||||
|
||||
// Relative times age while the panel stays open
|
||||
let now = Date.now();
|
||||
const clock = setInterval(() => (now = Date.now()), 15_000);
|
||||
onDestroy(() => clearInterval(clock));
|
||||
|
||||
// Relative for the past week, a date before that
|
||||
function when(ms: number | undefined, now: number): string {
|
||||
if (ms === undefined) return "";
|
||||
const seconds = Math.max(0, Math.round((now - ms) / 1000));
|
||||
if (seconds < 45) return "just now";
|
||||
const minutes = Math.round(seconds / 60);
|
||||
if (minutes < 60) return `${minutes} min ago`;
|
||||
const hours = Math.round(minutes / 60);
|
||||
if (hours < 24) return `${hours} h ago`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 7) return days === 1 ? "yesterday" : `${days} days ago`;
|
||||
return new Date(ms).toLocaleDateString();
|
||||
}
|
||||
|
||||
function count(n: number, one: string, many: string): string {
|
||||
return `${n} ${n === 1 ? one : many}`;
|
||||
}
|
||||
|
||||
function authorLabel(row: { author: string; mine: boolean }): string {
|
||||
return row.mine ? `${row.author} (you)` : row.author;
|
||||
}
|
||||
|
||||
let renamingId: string | undefined = undefined;
|
||||
let taggingId: string | undefined = undefined;
|
||||
|
||||
function commitName(id: string, label: string) {
|
||||
editor.renameHistoryInteraction(id, label);
|
||||
renamingId = undefined;
|
||||
}
|
||||
|
||||
function commitTag(id: string, tag: string) {
|
||||
if (tag.trim()) editor.tagHistoryInteraction(id, tag, true);
|
||||
taggingId = undefined;
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutCol class="history-panel">
|
||||
{#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}
|
||||
<div class="row progress">
|
||||
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
|
||||
<div class="text">
|
||||
<span class="label">{row.label || (row.open ? "In progress" : "Waiting to enter history")}</span>
|
||||
<span class="meta">
|
||||
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
|
||||
· {count(row.ops, "change", "changes")}
|
||||
· {row.open ? "in progress" : "not yet in history"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#each $history.rows as row (row.id)}
|
||||
<div class="row" class:head={row.head} class:undone={row.undone} class:abandoned={row.abandoned}>
|
||||
<button
|
||||
class="expand"
|
||||
class:expanded={row.expanded}
|
||||
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
|
||||
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
|
||||
></button>
|
||||
<span class="rail"><span class="dot" style:background={row.color}></span></span>
|
||||
<div class="text">
|
||||
{#if renamingId === row.id}
|
||||
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
|
||||
{:else}
|
||||
<span class="label" class:named={row.named}>{row.label}</span>
|
||||
{/if}
|
||||
<span class="meta">
|
||||
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
|
||||
{#if row.time}· {when(row.time, now)}{/if}
|
||||
· {count(row.deltas, "change", "changes")}
|
||||
</span>
|
||||
{#if row.tags.length > 0 || taggingId === row.id}
|
||||
<span class="tags">
|
||||
{#each row.tags as tag (tag)}
|
||||
<span class="tag">{tag}<button class="remove" data-tooltip-label="Remove the tag" on:click={() => editor.tagHistoryInteraction(row.id, tag, false)}>×</button></span>
|
||||
{/each}
|
||||
{#if taggingId === row.id}
|
||||
<TextInput value="" placeholder="Tag name" narrow={true} on:commitText={({ detail }) => commitTag(row.id, detail)} />
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
{#if row.branches.length > 0}
|
||||
<span class="branches">
|
||||
{#each row.branches as branch (branch.id)}
|
||||
<button class="branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button>
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="actions">
|
||||
<button class="small" data-tooltip-label="Name this step" on:click={() => (renamingId = renamingId === row.id ? undefined : row.id)}>Name</button>
|
||||
<button class="small" data-tooltip-label="Tag this step" on:click={() => (taggingId = taggingId === row.id ? undefined : row.id)}>Tag</button>
|
||||
{#if row.undone || row.abandoned}
|
||||
<IconButton
|
||||
icon="HistoryRedo"
|
||||
size={16}
|
||||
tooltipLabel="Bring back"
|
||||
tooltipDescription={row.undone ? "Redo up to and including this step." : "Do this step again on top of the current line."}
|
||||
action={() => editor.bringBackHistoryInteraction(row.id)}
|
||||
/>
|
||||
{:else}
|
||||
{#if !row.head}
|
||||
<IconButton
|
||||
icon="HistoryUndo"
|
||||
size={16}
|
||||
tooltipLabel="Go back to here"
|
||||
tooltipDescription={$history.session ? "Move everyone's document back to this step. The steps since stay as a branch." : "Undo up to this step."}
|
||||
action={() => editor.goBackToHistoryInteraction(row.id)}
|
||||
/>
|
||||
{/if}
|
||||
<IconButton
|
||||
icon="Trash"
|
||||
size={16}
|
||||
tooltipLabel="Remove this step"
|
||||
tooltipDescription="Take this step out and keep the ones after it."
|
||||
action={() => editor.removeHistoryInteraction(row.id)}
|
||||
/>
|
||||
{/if}
|
||||
</span>
|
||||
{#if row.head}<span class="marker">Now</span>{/if}
|
||||
{#if row.undone}<span class="marker">Undone</span>{/if}
|
||||
{#if row.abandoned}<span class="marker">Branch</span>{/if}
|
||||
</div>
|
||||
{#if row.expanded}
|
||||
{#each row.details as delta (delta.id)}
|
||||
<div class="row delta" class:undone={row.undone}>
|
||||
<span class="rail"><span class="tick"></span></span>
|
||||
<div class="text">
|
||||
<span class="label">{delta.label}</span>
|
||||
<span class="meta">
|
||||
<span class="author">{delta.author}</span>
|
||||
{#if delta.time}· {when(delta.time, now)}{/if}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
{/each}
|
||||
{#if $history.more}
|
||||
<div class="more">
|
||||
<TextButton label="Show older" action={() => editor.loadMoreHistory()} />
|
||||
</div>
|
||||
{/if}
|
||||
{#if $history.rows.length === 0 && $history.progress.length === 0}
|
||||
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
|
||||
{/if}
|
||||
</LayoutCol>
|
||||
</LayoutCol>
|
||||
|
||||
<style lang="scss">
|
||||
.history-panel {
|
||||
flex-grow: 1;
|
||||
padding: 4px 0;
|
||||
|
||||
.following {
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 8px 4px 8px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 32px;
|
||||
padding: 2px 8px 2px 4px;
|
||||
gap: 6px;
|
||||
|
||||
&.head {
|
||||
background: var(--color-3-darkgray);
|
||||
}
|
||||
|
||||
&.undone,
|
||||
&.abandoned {
|
||||
.rail,
|
||||
.text {
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
&.delta {
|
||||
min-height: 24px;
|
||||
padding-left: 28px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
visibility: hidden;
|
||||
|
||||
.small {
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
background: var(--color-4-dimgray);
|
||||
color: var(--color-c-brightgray);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--color-5-dullgray);
|
||||
color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .actions {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.expand {
|
||||
flex: 0 0 auto;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 5px;
|
||||
top: 4px;
|
||||
border: 4px solid transparent;
|
||||
border-left: 5px solid var(--color-8-uppergray);
|
||||
}
|
||||
|
||||
&.expanded::after {
|
||||
left: 3px;
|
||||
top: 6px;
|
||||
border: 4px solid transparent;
|
||||
border-top: 5px solid var(--color-8-uppergray);
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
border-left-color: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
&.expanded:hover::after {
|
||||
border-left-color: transparent;
|
||||
border-top-color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
|
||||
.rail {
|
||||
flex: 0 0 12px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
|
||||
&.hollow {
|
||||
background: none;
|
||||
border: 2px solid;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.tick {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-6-lowergray);
|
||||
}
|
||||
}
|
||||
|
||||
.text {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 16px;
|
||||
|
||||
.label {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.meta {
|
||||
color: var(--color-a-softgray);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
.anonymous {
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
|
||||
.label.named {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-top: 2px;
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
padding: 0 2px 0 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--color-accent-hover);
|
||||
color: var(--color-f-white);
|
||||
|
||||
.remove {
|
||||
border: none;
|
||||
background: none;
|
||||
color: inherit;
|
||||
padding: 0 2px;
|
||||
cursor: pointer;
|
||||
line-height: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.branches {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 2px;
|
||||
|
||||
.branch {
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
background: var(--color-4-dimgray);
|
||||
color: var(--color-c-brightgray);
|
||||
cursor: pointer;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
&:hover {
|
||||
background: var(--color-5-dullgray);
|
||||
color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.marker {
|
||||
flex: 0 0 auto;
|
||||
font-size: 10px;
|
||||
line-height: 14px;
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--color-5-dullgray);
|
||||
color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
|
||||
.more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 8px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script lang="ts">
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { sessionPanelLayout } from "/src/stores/portfolio";
|
||||
</script>
|
||||
|
||||
<LayoutCol class="session-panel">
|
||||
<LayoutCol class="body" scrollableY={true}>
|
||||
<WidgetLayout layout={sessionPanelLayout} layoutTarget="SessionPanel" />
|
||||
</LayoutCol>
|
||||
</LayoutCol>
|
||||
|
||||
<style lang="scss">
|
||||
.session-panel {
|
||||
flex-grow: 1;
|
||||
padding: 4px 8px;
|
||||
|
||||
.widget-span:has(.text-label.multiline) {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -6,6 +6,7 @@
|
||||
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import NodeGraphWire from "/src/components/views/NodeGraphWire.svelte";
|
||||
import RemoteCursor from "/src/components/views/RemoteCursor.svelte";
|
||||
import ThumbnailCanvas from "/src/components/views/ThumbnailCanvas.svelte";
|
||||
import ThumbnailImage from "/src/components/views/ThumbnailImage.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
@@ -33,6 +34,7 @@
|
||||
const nodeGraphWires = nodeGraph.wiresStore;
|
||||
const wireInsertionPreview = nodeGraph.wireInsertionPreviewStore;
|
||||
const nodeGlideOffsets = nodeGraph.glideOffsetsStore;
|
||||
const remoteCursors = nodeGraph.remoteCursorsStore;
|
||||
const documentState = getContext<DocumentStore>("document");
|
||||
const subscriptions = getContext<SubscriptionsRouter>("subscriptions");
|
||||
|
||||
@@ -1125,6 +1127,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#each $remoteCursors as cursor}
|
||||
<RemoteCursor {cursor} />
|
||||
{/each}
|
||||
|
||||
<!-- Box selection widget -->
|
||||
{#if $nodeGraph.box}
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<script lang="ts">
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import { ICONS } from "/src/icons";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { FrontendRemoteCursor } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export let cursor: FrontendRemoteCursor;
|
||||
|
||||
// A peer running another build may name a tool icon this build lacks
|
||||
function isIconName(name: string): name is IconName {
|
||||
return Object.hasOwn(ICONS, name);
|
||||
}
|
||||
$: toolIcon = cursor.tool && isIconName(cursor.tool) ? cursor.tool : undefined;
|
||||
|
||||
// White reads well only on darker hues, and black on the rest
|
||||
function labelColor(background: string): string {
|
||||
const [red, green, blue] = [1, 3, 5].map((start) => parseInt(background.slice(start, start + 2), 16));
|
||||
return 0.299 * red + 0.587 * green + 0.114 * blue > 128 ? "#000" : "#fff";
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="remote-cursor" style:left={`${cursor.x}px`} style:top={`${cursor.y}px`}>
|
||||
<svg width="12" height="18" viewBox="0 0 12 18"><path d="M0 0 L0 15 L4 11.5 L7 17.5 L9.5 16.5 L6.5 10.5 L11 10.5 Z" fill={cursor.color} stroke="#fff" stroke-width="1" /></svg>
|
||||
<span class="label" class:anonymous={cursor.anonymous} style:background={cursor.color} style:color={labelColor(cursor.color)}>
|
||||
{#if toolIcon}
|
||||
<IconLabel icon={toolIcon} iconSizeOverride={16} />
|
||||
{/if}
|
||||
{cursor.name}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.remote-cursor {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: 12px;
|
||||
margin-top: -2px;
|
||||
padding: 1px 4px;
|
||||
border-radius: 2px;
|
||||
font-size: 12px;
|
||||
line-height: 16px;
|
||||
white-space: nowrap;
|
||||
|
||||
&.anonymous {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
:global(.icon-label svg) {
|
||||
fill: currentColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,21 +4,25 @@
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import Data from "/src/components/panels/Data.svelte";
|
||||
import Document from "/src/components/panels/Document.svelte";
|
||||
import History from "/src/components/panels/History.svelte";
|
||||
import Inspector from "/src/components/panels/Inspector.svelte";
|
||||
import Layers from "/src/components/panels/Layers.svelte";
|
||||
import Session from "/src/components/panels/Session.svelte";
|
||||
import Welcome from "/src/components/panels/Welcome.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import { panelDrag, startCrossPanelDrag, endCrossPanelDrag, updateCrossPanelHover, updateDockingHover } from "/src/stores/panel-drag";
|
||||
import type { DockingEdge } from "/src/stores/panel-drag";
|
||||
import type { DockingSplitDirection, EditorWrapper, PanelType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { DockingSplitDirection, EditorWrapper, PanelType, SessionStatus } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const PANEL_COMPONENTS = {
|
||||
Welcome,
|
||||
Document,
|
||||
Layers,
|
||||
History,
|
||||
Inspector,
|
||||
Data,
|
||||
Session,
|
||||
};
|
||||
const BUTTON_LEFT = 0;
|
||||
const BUTTON_MIDDLE = 1;
|
||||
@@ -29,7 +33,7 @@
|
||||
|
||||
export let tabMinWidths = false;
|
||||
export let tabCloseButtons = false;
|
||||
export let tabLabels: { name: string; unsaved?: boolean; tooltipLabel?: string; tooltipDescription?: string; tooltipShortcut?: string }[];
|
||||
export let tabLabels: { name: string; unsaved?: boolean; session?: SessionStatus; tooltipLabel?: string; tooltipDescription?: string; tooltipShortcut?: string }[];
|
||||
export let tabActiveIndex: number;
|
||||
export let panelTypes: PanelType[];
|
||||
export let panelId: string;
|
||||
@@ -37,6 +41,7 @@
|
||||
export let closeAction: ((index: number) => void) | undefined = undefined;
|
||||
export let reorderAction: ((oldIndex: number, newIndex: number) => void) | undefined = undefined;
|
||||
export let renameAction: ((index: number, newName: string) => void) | undefined = undefined;
|
||||
export let sessionAction: ((index: number) => void) | undefined = undefined;
|
||||
export let emptySpaceAction: (() => void) | undefined = undefined;
|
||||
export let crossPanelDropAction: ((sourcePanelId: string, targetPanelId: string, insertIndex: number) => void) | undefined = undefined;
|
||||
export let groupDropAction: ((sourcePanelId: string, targetPanelId: string, insertIndex: number) => void) | undefined = undefined;
|
||||
@@ -451,6 +456,17 @@
|
||||
<TextLabel classes={{ hidden: editingNameTabIndex === tabIndex }}>*</TextLabel>
|
||||
{/if}
|
||||
</LayoutRow>
|
||||
{#if tabLabel.session}
|
||||
<button
|
||||
class="session"
|
||||
class:disconnected={tabLabel.session === "Disconnected"}
|
||||
data-tooltip-label={tabLabel.session === "Connected" ? "Live session" : "Disconnected from the session"}
|
||||
data-tooltip-description={tabLabel.session === "Connected" ? "Click to open the Session panel." : "Reconnecting. Click to open the Session panel."}
|
||||
data-session-button
|
||||
on:pointerdown|stopPropagation
|
||||
on:click|stopPropagation={() => sessionAction?.(tabIndex)}
|
||||
></button>
|
||||
{/if}
|
||||
{#if tabCloseButtons}
|
||||
<IconButton
|
||||
action={(e) => {
|
||||
@@ -598,6 +614,31 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.session {
|
||||
flex: 0 0 auto;
|
||||
align-self: center;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
margin-left: 4px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: var(--color-session-green);
|
||||
cursor: pointer;
|
||||
|
||||
&.disconnected {
|
||||
background: var(--color-error-red);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 0 0 2px var(--color-5-dullgray);
|
||||
}
|
||||
|
||||
& + .icon-button {
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
& + .tab {
|
||||
margin-left: 1px;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
}
|
||||
// Reactive array of resolved sizes (merging backend defaults with local overrides)
|
||||
$: resolvedSizes = subdivision && "Split" in subdivision ? subdivision.Split.children.map((child, index) => sizeOverrides[index] ?? child.size) : [];
|
||||
$: documentTabLabels = $portfolio.documents.map((doc: DocumentInfo) => ({ name: doc.name, unsaved: !doc.is_saved }));
|
||||
$: documentTabLabels = $portfolio.documents.map((doc: DocumentInfo) => ({ name: doc.name, unsaved: !doc.is_saved, session: doc.session ?? undefined }));
|
||||
|
||||
onDestroy(() => {
|
||||
activeResizeCleanup?.();
|
||||
@@ -206,6 +206,11 @@
|
||||
editor.selectDocument($portfolio.documents[tabIndex].id);
|
||||
editor.renameDocument(newName);
|
||||
}}
|
||||
sessionAction={(tabIndex) => {
|
||||
// The Session panel shows the active document
|
||||
editor.selectDocument($portfolio.documents[tabIndex].id);
|
||||
editor.focusPanel("Session");
|
||||
}}
|
||||
tabActiveIndex={$portfolio.activeDocumentIndex}
|
||||
groupDropAction={groupDrop}
|
||||
splitDropAction={splitDrop}
|
||||
|
||||
@@ -17,6 +17,13 @@ export function createClipboardManager(subscriptions: SubscriptionsRouter, edito
|
||||
navigator.clipboard?.writeText?.(data.content);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("TriggerSessionLinkCopy", (data) => {
|
||||
const url = new URL(window.location.href);
|
||||
url.hash = "";
|
||||
url.search = new URLSearchParams({ session: data.token }).toString();
|
||||
navigator.clipboard?.writeText?.(url.toString());
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("TriggerSelectionRead", async (data) => {
|
||||
const content = readAtCaret(data.cut);
|
||||
// A text field with nothing selected has nothing to copy, rather than leaving the shortcut to act on the selected layers
|
||||
@@ -35,6 +42,7 @@ export function destroyClipboardManager() {
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerClipboardWrite");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSessionLinkCopy");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSelectionRead");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSelectionWrite");
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Writable } from "svelte/store";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { createLayout } from "/src/utility-functions/layout-state.svelte";
|
||||
import { patchLayout } from "/src/utility-functions/widgets";
|
||||
import type { Layout, RenderStatus } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { FrontendRemoteCursor, Layout, RenderStatus } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type DocumentStore = ReturnType<typeof createDocumentStore>;
|
||||
|
||||
@@ -33,6 +33,10 @@ let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
|
||||
const store: Writable<DocumentStoreState> = import.meta.hot?.data?.store || writable<DocumentStoreState>(initialState);
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
|
||||
// Separate since cursors move every frame and only the overlay draws them
|
||||
const remoteCursorsStore: Writable<FrontendRemoteCursor[]> = import.meta.hot?.data?.remoteCursorsStore || writable<FrontendRemoteCursor[]>([]);
|
||||
if (import.meta.hot) import.meta.hot.data.remoteCursorsStore = remoteCursorsStore;
|
||||
const { subscribe, update } = store;
|
||||
|
||||
export function createDocumentStore(subscriptions: SubscriptionsRouter) {
|
||||
@@ -71,6 +75,9 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) {
|
||||
patchLayout(get(store).nodeGraphControlBarLayout, data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateDocumentCursors", (data) => {
|
||||
remoteCursorsStore.set(data.cursors);
|
||||
});
|
||||
subscriptions.subscribeFrontendMessage("UpdateGraphViewOverlay", (data) => {
|
||||
update((state) => {
|
||||
state.graphViewOverlayOpen = data.open;
|
||||
@@ -85,7 +92,7 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
return { subscribe };
|
||||
return { subscribe, remoteCursorsStore };
|
||||
}
|
||||
|
||||
export function destroyDocumentStore() {
|
||||
@@ -95,6 +102,7 @@ export function destroyDocumentStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateDocumentCursors");
|
||||
subscriptions.unsubscribeLayoutUpdate("ToolOptions");
|
||||
subscriptions.unsubscribeLayoutUpdate("DocumentBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("ToolShelf");
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { writable } from "svelte/store";
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type HistoryStore = ReturnType<typeof createHistoryStore>;
|
||||
|
||||
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, session: 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);
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
|
||||
const { subscribe, set } = store;
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
|
||||
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
destroyHistoryStore();
|
||||
subscriptionsRouter = subscriptions;
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHistoryPanel", (data) => {
|
||||
set(data.state);
|
||||
});
|
||||
|
||||
return { subscribe };
|
||||
}
|
||||
|
||||
export function destroyHistoryStore() {
|
||||
const subscriptions = subscriptionsRouter;
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
|
||||
subscriptionsRouter = undefined;
|
||||
}
|
||||
@@ -3,7 +3,16 @@ import type { Writable } from "svelte/store";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageBody } from "/src/subscriptions-router";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type {
|
||||
NodeGraphErrorDiagnostic,
|
||||
BoxSelection,
|
||||
FrontendClickTargets,
|
||||
ContextMenuInformation,
|
||||
FrontendNode,
|
||||
FrontendNodeType,
|
||||
FrontendRemoteCursor,
|
||||
WirePath,
|
||||
} from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
||||
|
||||
@@ -113,6 +122,10 @@ export type GlideOffsets = { nodes: Map<bigint, [number, number]>; imports: [num
|
||||
const glideOffsetsStore: Writable<GlideOffsets> = import.meta.hot?.data?.glideOffsetsStore || writable<GlideOffsets>({ nodes: new Map(), imports: [0, 0], exports: [0, 0] });
|
||||
if (import.meta.hot) import.meta.hot.data.glideOffsetsStore = glideOffsetsStore;
|
||||
|
||||
// Separate since cursors move every frame and only the overlay draws them
|
||||
const remoteCursorsStore: Writable<FrontendRemoteCursor[]> = import.meta.hot?.data?.remoteCursorsStore || writable<FrontendRemoteCursor[]>([]);
|
||||
if (import.meta.hot) import.meta.hot.data.remoteCursorsStore = remoteCursorsStore;
|
||||
|
||||
export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
destroyNodeGraphStore();
|
||||
|
||||
@@ -134,6 +147,10 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphCursors", (data) => {
|
||||
remoteCursorsStore.set(data.cursors);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
|
||||
update((state) => {
|
||||
state.clickTargets = data.clickTargets;
|
||||
@@ -312,7 +329,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore };
|
||||
return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore, remoteCursorsStore };
|
||||
}
|
||||
|
||||
export function destroyNodeGraphStore() {
|
||||
@@ -321,6 +338,7 @@ export function destroyNodeGraphStore() {
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphCursors");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
||||
|
||||
@@ -42,6 +42,7 @@ export const inspectorLayout = persistedLayout("inspectorLayout");
|
||||
export const dataPanelLayout = persistedLayout("dataPanelLayout");
|
||||
export const dataPanelContextLayout = persistedLayout("dataPanelContextLayout");
|
||||
export const dataPanelPathLayout = persistedLayout("dataPanelPathLayout");
|
||||
export const sessionPanelLayout = persistedLayout("sessionPanelLayout");
|
||||
export const layersPanelControlBarLeftLayout = persistedLayout("layersPanelControlBarLeftLayout");
|
||||
export const layersPanelBottomBarLeftLayout = persistedLayout("layersPanelBottomBarLeftLayout");
|
||||
export const layersPanelBottomBarRightLayout = persistedLayout("layersPanelBottomBarRightLayout");
|
||||
@@ -81,7 +82,7 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
try {
|
||||
const url = new URL(`demo-artwork/${data.filename}`, document.location.href);
|
||||
const response = await fetch(url);
|
||||
editor.ingestPicked(data.filename, "", await response.bytes(), "Open");
|
||||
editor.ingestPicked(data.filename, "", await response.bytes(), "OpenDemo");
|
||||
} catch {
|
||||
// Needs to be delayed until the end of the current call stack so the existing demo artwork dialog can be closed first, otherwise this dialog won't show
|
||||
setTimeout(() => {
|
||||
@@ -146,6 +147,10 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
patchLayout(dataPanelPathLayout, data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeLayoutUpdate("SessionPanel", (data) => {
|
||||
patchLayout(sessionPanelLayout, data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeLayoutUpdate("LayersPanelControlLeftBar", (data) => {
|
||||
patchLayout(layersPanelControlBarLeftLayout, data);
|
||||
});
|
||||
@@ -209,6 +214,7 @@ export function destroyPortfolioStore() {
|
||||
subscriptions.unsubscribeLayoutUpdate("DataPanel");
|
||||
subscriptions.unsubscribeLayoutUpdate("DataPanelContext");
|
||||
subscriptions.unsubscribeLayoutUpdate("DataPanelPath");
|
||||
subscriptions.unsubscribeLayoutUpdate("SessionPanel");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelControlLeftBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomLeftBar");
|
||||
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomRightBar");
|
||||
|
||||
@@ -34,6 +34,18 @@ export function requestWithUploadDownloadProgress(
|
||||
return [promise, xhrValue];
|
||||
}
|
||||
|
||||
// Join the session in the URL's `?session=` token and remove it from the address bar
|
||||
export function joinSessionFromUrl(editor: EditorWrapper) {
|
||||
const token = new URLSearchParams(window.location.search).get("session");
|
||||
if (!token) return;
|
||||
|
||||
editor.joinSession(token);
|
||||
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("session");
|
||||
history.replaceState("", "", `${url.pathname}${url.search}${url.hash}`);
|
||||
}
|
||||
|
||||
// If the URL hash fragment contains a demo artwork path (e.g. #demo/isometric-light), fetch and open it
|
||||
export async function loadDemoArtwork(editor: EditorWrapper) {
|
||||
const demoArtwork = window.location.hash.trim().match(/#demo\/(.*)/)?.[1];
|
||||
@@ -46,7 +58,7 @@ export async function loadDemoArtwork(editor: EditorWrapper) {
|
||||
|
||||
const filename = url.pathname.split("/").pop() || "Untitled.graphite";
|
||||
const content = await response.bytes();
|
||||
editor.ingestPicked(filename, "", content, "Open");
|
||||
editor.ingestPicked(filename, "", content, "OpenDemo");
|
||||
|
||||
history.replaceState("", "", `${window.location.pathname}${window.location.search}`);
|
||||
} catch {
|
||||
|
||||
@@ -187,11 +187,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
fn load_preferences(preferences: Option<String>) -> Message {
|
||||
let Some(preferences) = preferences else { return Message::NoOp };
|
||||
let Ok(preferences) = serde_json::from_str(&preferences) else {
|
||||
log::error!("Failed to deserialize preferences");
|
||||
return Message::NoOp;
|
||||
};
|
||||
let preferences = PreferencesMessageHandler::from_stored(preferences.as_deref());
|
||||
PreferencesMessage::Load { preferences }.into()
|
||||
}
|
||||
|
||||
@@ -208,6 +204,11 @@ mod editor_commands {
|
||||
DialogMessage::RequestNewDocumentDialog.into()
|
||||
}
|
||||
|
||||
/// Join the live session under `token`
|
||||
fn join_session(token: String) -> Message {
|
||||
SyncMessage::Join { token }.into()
|
||||
}
|
||||
|
||||
fn trigger_auto_save(document_id: u64) -> Message {
|
||||
PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into()
|
||||
}
|
||||
@@ -255,6 +256,48 @@ mod editor_commands {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Bring a panel to the front, reopening it if closed
|
||||
fn focus_panel(panel_type: PanelType) -> Message {
|
||||
WorkspaceMessage::FocusPanel { panel_type }.into()
|
||||
}
|
||||
|
||||
/// Show or hide an interaction's deltas
|
||||
fn expand_history_interaction(id: String, expanded: bool) -> Message {
|
||||
HistoryMessage::Expand { id, expanded }.into()
|
||||
}
|
||||
|
||||
fn load_more_history() -> Message {
|
||||
HistoryMessage::LoadMore.into()
|
||||
}
|
||||
|
||||
fn go_back_to_history_interaction(id: String) -> Message {
|
||||
HistoryMessage::GoBack { id }.into()
|
||||
}
|
||||
|
||||
/// Remove one interaction and keep the later ones
|
||||
fn remove_history_interaction(id: String) -> Message {
|
||||
HistoryMessage::RemoveStep { id }.into()
|
||||
}
|
||||
|
||||
/// Redo an undone interaction, or reapply an abandoned one
|
||||
fn bring_back_history_interaction(id: String) -> Message {
|
||||
HistoryMessage::BringBack { id }.into()
|
||||
}
|
||||
|
||||
/// Show a branch's line, or the head's line when `id` is `None`
|
||||
fn follow_history_branch(id: Option<String>) -> Message {
|
||||
HistoryMessage::Follow { id }.into()
|
||||
}
|
||||
|
||||
/// Name an interaction. An empty label removes the name
|
||||
fn rename_history_interaction(id: String, label: String) -> Message {
|
||||
HistoryMessage::Rename { id, label }.into()
|
||||
}
|
||||
|
||||
fn tag_history_interaction(id: String, tag: String, on: bool) -> Message {
|
||||
HistoryMessage::Tag { id, tag, on }.into()
|
||||
}
|
||||
|
||||
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
|
||||
WorkspaceMessage::SplitPanelGroup {
|
||||
target_group: PanelGroupId(target_group),
|
||||
@@ -918,6 +961,7 @@ editor_proxy_types! {
|
||||
IngestAction = editor::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
|
||||
PanelType = editor::messages::portfolio::utility_types::PanelType;
|
||||
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
|
||||
SRGBA8 = graphene_std::color::SRGBA8;
|
||||
}
|
||||
@@ -30,16 +30,20 @@ document-container = { workspace = true, features = ["zip", "xz"] }
|
||||
migration-formats = { workspace = true }
|
||||
migration-compiled = { workspace = true }
|
||||
migration-nodes = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
document-live = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
log = { workspace = true }
|
||||
fern = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tokio = { workspace = true, features = ["io-util", "time"] }
|
||||
winit = { workspace = true }
|
||||
clap = { workspace = true, features = ["cargo", "derive"] }
|
||||
image = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
getrandom = "0.3"
|
||||
wgpu-executor = { workspace = true, optional = true }
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::TokioSpawner;
|
||||
use graph_craft::document::value::{DAffine2, DVec2, RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, Texture, TimingInformation};
|
||||
use graphene_std::core_types::ops::ConvertAsync;
|
||||
use graphene_std::core_types::transform::Footprint;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
@@ -206,6 +206,16 @@ pub(crate) async fn render_frame(
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn render_texture(executor: &DynamicExecutor, render_config: RenderConfig, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Texture, Box<dyn Error>> {
|
||||
match execute_until_settled(executor, runtime, spawner, render_config).await? {
|
||||
TaggedValue::RenderOutput(output) => match output.data {
|
||||
RenderOutputType::Texture(texture) => Ok(texture),
|
||||
other => Err(format!("Expected a GPU render output, got: {other:?}").into()),
|
||||
},
|
||||
other => Err(format!("Expected RenderOutput, got: {other:?}").into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a rendered frame to a file of the export's type.
|
||||
fn write_frame(path: &Path, settings: ExportSettings, frame: RenderedFrame) -> Result<(), Box<dyn Error>> {
|
||||
let contents = match frame {
|
||||
|
||||
@@ -7,13 +7,14 @@ pub mod export;
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use graph_craft::application_io::resource::LoadResource;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
@@ -95,12 +96,12 @@ pub struct CompiledDocument {
|
||||
spawner: Arc<TokioSpawner>,
|
||||
}
|
||||
|
||||
/// Compile `document` against a fresh GPU context, resolving its resources from its `.gdd`.
|
||||
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
|
||||
/// A GPU context and the editor API, resolving resources through `resource_proxy` if given.
|
||||
pub async fn editor_api(resource_proxy: Option<Box<dyn LoadResource>>) -> (Arc<PlatformApplicationIo>, Arc<PlatformEditorApi>) {
|
||||
log::info!("Creating GPU context");
|
||||
let mut application_io = PlatformApplicationIo::new().await;
|
||||
if let Some(gdd) = &document.gdd {
|
||||
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
||||
if let Some(resource_proxy) = resource_proxy {
|
||||
application_io.inject_resource_proxy(resource_proxy);
|
||||
}
|
||||
let application_io = Arc::new(application_io);
|
||||
if let Some(executor) = application_io.gpu_executor() {
|
||||
@@ -111,14 +112,15 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(application_io.clone()),
|
||||
});
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
(application_io, editor_api)
|
||||
}
|
||||
|
||||
let mut network = wrap_network_in_scope(document.network, editor_api, runtime.handle());
|
||||
/// Compile `network`. Only a `.gdd` has a resource store.
|
||||
pub fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
// A `.gdd` resolves resource hashes from its registry, while a legacy `.graphite` has no resource store
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
let preprocessed = match &document.gdd {
|
||||
let preprocessed = match gdd {
|
||||
Some(gdd) => preprocessor.preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|resource| resource.hash)),
|
||||
None => preprocessor.preprocess(&mut network, &|_| None),
|
||||
};
|
||||
@@ -128,9 +130,24 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
for warning in &compiled_network.warnings {
|
||||
eprintln!("{warning:?}");
|
||||
}
|
||||
Ok(compiled_network.network)
|
||||
}
|
||||
|
||||
pub fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
DynamicExecutor::new(proto_network).map_err(|errors| {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
messages.join("\n").into()
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
|
||||
let (application_io, editor_api) = editor_api(document.gdd.as_ref().map(|gdd| Box::new(gdd.resource_proxy()) as Box<dyn LoadResource>)).await;
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let proto_network = compile_graph(document.network, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
Ok(CompiledDocument {
|
||||
proto_network: compiled_network.network,
|
||||
proto_network,
|
||||
application_io,
|
||||
runtime,
|
||||
spawner,
|
||||
@@ -139,10 +156,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
|
||||
impl CompiledDocument {
|
||||
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
|
||||
let executor = DynamicExecutor::new(self.proto_network).map_err(|errors| {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
messages.join("\n")
|
||||
})?;
|
||||
let executor = create_executor(self.proto_network)?;
|
||||
self.runtime.update_sources(executor.sources());
|
||||
|
||||
let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone();
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The `host`, `join` and `watch` subcommands.
|
||||
|
||||
use crate::repl;
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use document_live::{LiveDocument, SessionToken};
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
|
||||
pub use document_live::DEFAULT_SIGNALING_SERVER;
|
||||
|
||||
pub async fn host(signaling: &str, document: Option<&Path>) -> Result<(), Box<dyn Error>> {
|
||||
let (peer, user) = identity()?;
|
||||
let live = match document {
|
||||
Some(path) => {
|
||||
let mut gdd = open_archive(path).await?;
|
||||
// The source document may be open elsewhere under the peer the archive holds
|
||||
gdd.set_user(user, peer)?;
|
||||
let token = SessionToken::for_document(gdd.manifest().document_id);
|
||||
LiveDocument::host_document(gdd, signaling, token, user, spawn_driver)?
|
||||
}
|
||||
// An empty document takes the peer id as its document id
|
||||
None => LiveDocument::host(signaling, SessionToken::for_document(peer.0), peer, user, spawn_driver).await?,
|
||||
};
|
||||
println!("hosting session {}", live.token());
|
||||
drive_from_stdin(live).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn join(signaling: &str, token: SessionToken) -> Result<(), Box<dyn Error>> {
|
||||
let (peer, user) = identity()?;
|
||||
let live = LiveDocument::join(signaling, token, peer, user, spawn_driver).await?;
|
||||
println!("joining session {token}");
|
||||
drive_from_stdin(live).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn watch(signaling: &str, token: SessionToken) -> Result<(), Box<dyn Error>> {
|
||||
let (peer, user) = identity()?;
|
||||
let live = LiveDocument::join(signaling, token, peer, user, spawn_driver).await?;
|
||||
crate::watch::run(live).await
|
||||
}
|
||||
|
||||
async fn open_archive(path: &Path) -> Result<GddV1, Box<dyn Error>> {
|
||||
let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
Ok(GddV1::open_from_archive(&archive, container, GddV1Layout).await?)
|
||||
}
|
||||
|
||||
async fn drive_from_stdin(mut live: LiveDocument) {
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(100));
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tick.tick() => {
|
||||
for event in live.poll().await {
|
||||
repl::report(&event);
|
||||
}
|
||||
}
|
||||
line = lines.next_line() => {
|
||||
let Ok(Some(line)) = line else { break };
|
||||
if !repl::run_command(&mut live, line.trim()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
live.leave();
|
||||
}
|
||||
|
||||
fn spawn_driver(driver: document_live::MessageLoopFuture) {
|
||||
tokio::spawn(driver);
|
||||
}
|
||||
|
||||
fn identity() -> Result<(PeerId, UserId), getrandom::Error> {
|
||||
let peer = PeerId(getrandom::u64()?);
|
||||
Ok((peer, UserId(peer.0)))
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
mod live;
|
||||
mod repl;
|
||||
mod watch;
|
||||
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use document_live::SessionToken;
|
||||
use fern::colors::{Color, ColoredLevelConfig};
|
||||
use graphene_cli::{compile_document, dump, export, open_document, open_gdd};
|
||||
use std::error::Error;
|
||||
@@ -80,6 +85,24 @@ enum Command {
|
||||
ExtractLegacyDoc {
|
||||
document: PathBuf,
|
||||
},
|
||||
/// Host a collaborative session on a .gdd document, or an empty one, driven from stdin.
|
||||
Host {
|
||||
document: Option<PathBuf>,
|
||||
#[clap(long, default_value = live::DEFAULT_SIGNALING_SERVER)]
|
||||
signaling: String,
|
||||
},
|
||||
/// Join a collaborative session and drive it from stdin.
|
||||
Join {
|
||||
token: SessionToken,
|
||||
#[clap(long, default_value = live::DEFAULT_SIGNALING_SERVER)]
|
||||
signaling: String,
|
||||
},
|
||||
/// Join a collaborative session and show the document in a window.
|
||||
Watch {
|
||||
token: SessionToken,
|
||||
#[clap(long, default_value = live::DEFAULT_SIGNALING_SERVER)]
|
||||
signaling: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
@@ -96,6 +119,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
init_logging(app.global_opts.verbose);
|
||||
|
||||
let document_path = match &app.command {
|
||||
Command::Host { document, signaling } => return live::host(signaling, document.as_deref()).await,
|
||||
Command::Join { token, signaling } => return live::join(signaling, *token).await,
|
||||
Command::Watch { token, signaling } => return live::watch(signaling, *token).await,
|
||||
Command::Compile { document, .. } | Command::Export { document, .. } | Command::ExtractLegacyDoc { document } => document,
|
||||
Command::ListNodeIdentifiers => {
|
||||
let mut nodes: Vec<_> = graphene_std::registry::NODE_METADATA.lock().unwrap().keys().cloned().collect();
|
||||
@@ -177,7 +203,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?;
|
||||
}
|
||||
}
|
||||
Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } => unreachable!("Handled before compiling"),
|
||||
Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } | Command::Host { .. } | Command::Join { .. } | Command::Watch { .. } => unreachable!("Handled before compiling"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Line commands that drive a live document from stdin.
|
||||
//!
|
||||
//! ```text
|
||||
//! set <key> <json> stage a document attribute as a hot op
|
||||
//! retire promote pending hot ops (host only)
|
||||
//! show print document attributes and networks
|
||||
//! history print retired deltas
|
||||
//! quit
|
||||
//! ```
|
||||
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Rev};
|
||||
use document_live::{Event, LiveDocument};
|
||||
|
||||
pub fn report(event: &Event) {
|
||||
match event {
|
||||
Event::PeerJoined { peer, user } => println!("peer {peer:?} joined as {user:?}"),
|
||||
Event::PeerLeft { peer } => println!("peer {peer:?} left"),
|
||||
Event::RoleChanged { role } => println!("role is now {role:?}"),
|
||||
Event::ProfileChanged { peer } => println!("peer {peer:?} announced a name"),
|
||||
Event::CursorMoved { .. } => {}
|
||||
Event::MetadataChanged => println!("the record of the document's users changed"),
|
||||
Event::Synced => println!("synced"),
|
||||
Event::Changed => println!("document changed"),
|
||||
Event::ResourceReceived { hash, bytes } => println!("received resource {hash} ({} bytes)", bytes.len()),
|
||||
Event::ResourceRequested { hash, .. } => println!("peer asked for resource {hash}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_command(live: &mut LiveDocument, line: &str) -> bool {
|
||||
match split_command(line) {
|
||||
(Some("set"), Some(key), Some(value)) => {
|
||||
let Ok(value) = serde_json::from_str(value) else {
|
||||
println!("value must be JSON");
|
||||
return true;
|
||||
};
|
||||
let delta = AttributeDelta {
|
||||
key: key.to_string(),
|
||||
value: Some(value),
|
||||
};
|
||||
if let Err(error) = live.document_mut().stage_ops([RegistryDelta::ChangeDocumentAttribute { delta }]) {
|
||||
println!("stage failed: {error}");
|
||||
}
|
||||
}
|
||||
(Some("retire"), ..) => match live.document_mut().retire_pending_interaction() {
|
||||
Ok(revs) => println!("retired {} deltas", revs.len()),
|
||||
Err(error) => println!("retire failed: {error}"),
|
||||
},
|
||||
(Some("show"), ..) => {
|
||||
let registry = live.document().registry();
|
||||
for (key, value) in registry.attributes.live() {
|
||||
println!("{key} = {:?} @{}", value.value, value.timestamp.counter);
|
||||
}
|
||||
for id in registry.networks.keys() {
|
||||
println!("network {id:?}");
|
||||
}
|
||||
println!("{} hot ops pending", live.document().session().hot_log().len());
|
||||
}
|
||||
(Some("history"), ..) => {
|
||||
for delta in live.document().session().history() {
|
||||
println!("{} by {:?} @{} {}", short_rev(delta.id), delta.author, delta.timestamp.counter, describe(&delta.kind));
|
||||
}
|
||||
}
|
||||
(Some("quit"), ..) => return false,
|
||||
_ => println!("commands: set <key> <json>, retire, show, history, quit"),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The command word, the next word and the rest of the line.
|
||||
fn split_command(line: &str) -> (Option<&str>, Option<&str>, Option<&str>) {
|
||||
fn next_word(text: &str) -> (Option<&str>, &str) {
|
||||
let text = text.trim_start();
|
||||
let (word, rest) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
|
||||
((!word.is_empty()).then_some(word), rest)
|
||||
}
|
||||
let (command, rest) = next_word(line);
|
||||
let (argument, rest) = next_word(rest);
|
||||
let rest = rest.trim();
|
||||
(command, argument, (!rest.is_empty()).then_some(rest))
|
||||
}
|
||||
|
||||
fn describe(kind: &RegistryDelta) -> String {
|
||||
match kind {
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => format!("set {} = {:?}", delta.key, delta.value),
|
||||
RegistryDelta::RegisterPeer { peer, user } => format!("register {peer:?} as {user:?}"),
|
||||
RegistryDelta::Merge { extra_parents } => format!("merge {} extra parents", extra_parents.len()),
|
||||
other => format!("{other:?}").chars().take(60).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn short_rev(rev: Rev) -> String {
|
||||
format!("{rev}").chars().take(8).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commands_split_at_any_run_of_whitespace() {
|
||||
assert_eq!(split_command("set name\t\"a b\" "), (Some("set"), Some("name"), Some("\"a b\"")));
|
||||
assert_eq!(split_command("\tretire"), (Some("retire"), None, None));
|
||||
assert_eq!(split_command(" "), (None, None, None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//! A window that follows a live document.
|
||||
|
||||
use document_live::{Event, LiveDocument};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::UVec2;
|
||||
use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export};
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig};
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use wgpu::util::{TextureBlitter, TextureBlitterBuilder};
|
||||
use wgpu_executor::{WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::{StartCause, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::window::{Window, WindowAttributes, WindowId};
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
const BACKGROUND: wgpu::Color = wgpu::Color { r: 0.015, g: 0.015, b: 0.015, a: 1. };
|
||||
|
||||
pub async fn run(live: LiveDocument) -> Result<(), Box<dyn Error>> {
|
||||
let (application_io, editor_api) = editor_api(Some(Box::new(live.resource_proxy()))).await;
|
||||
if application_io.gpu_executor().is_none() {
|
||||
return Err("watching a session needs a usable GPU".into());
|
||||
}
|
||||
let event_loop = EventLoop::new()?;
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
|
||||
let viewer = Viewer {
|
||||
live,
|
||||
application_io,
|
||||
editor_api,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
spawner: spawner.clone(),
|
||||
graph_runtime: AsyncRuntime::new(spawner),
|
||||
window: None,
|
||||
surface: None,
|
||||
blitter: None,
|
||||
executor: None,
|
||||
dirty: false,
|
||||
waiting: Vec::new(),
|
||||
};
|
||||
tokio::task::block_in_place(|| event_loop.run_app(viewer))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Viewer {
|
||||
live: LiveDocument,
|
||||
application_io: Arc<PlatformApplicationIo>,
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
runtime: tokio::runtime::Handle,
|
||||
spawner: Arc<TokioSpawner>,
|
||||
graph_runtime: AsyncRuntime,
|
||||
window: Option<Arc<dyn Window>>,
|
||||
surface: Option<(WgpuSurface, wgpu::SurfaceConfiguration)>,
|
||||
blitter: Option<TextureBlitter>,
|
||||
executor: Option<DynamicExecutor>,
|
||||
dirty: bool,
|
||||
waiting: Vec<ResourceHash>,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
fn wgpu_executor(&self) -> &WgpuExecutor {
|
||||
self.application_io.gpu_executor().expect("`run` checks for a GPU executor")
|
||||
}
|
||||
|
||||
fn create_surface(&mut self, window: &Arc<dyn Window>) {
|
||||
let context = self.wgpu_executor().context();
|
||||
let surface = context.instance.create_surface(window.clone()).expect("create surface");
|
||||
let capabilities = surface.get_capabilities(&context.adapter);
|
||||
// The bytes are already sRGB encoded, so a non-sRGB target passes them through
|
||||
let preferred = [wgpu::TextureFormat::Bgra8Unorm, wgpu::TextureFormat::Rgba8Unorm];
|
||||
let format = preferred.into_iter().find(|format| capabilities.formats.contains(format)).unwrap_or(capabilities.formats[0]);
|
||||
let size = window.surface_size();
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format,
|
||||
width: size.width.max(1),
|
||||
height: size.height.max(1),
|
||||
present_mode: capabilities.present_modes[0],
|
||||
alpha_mode: capabilities.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 1,
|
||||
color_space: wgpu::SurfaceColorSpace::Auto,
|
||||
};
|
||||
surface.configure(&context.device, &config);
|
||||
|
||||
self.blitter = Some(TextureBlitterBuilder::new(&context.device, format).blend_state(wgpu::BlendState::ALPHA_BLENDING).build());
|
||||
self.surface = Some((surface, config));
|
||||
}
|
||||
|
||||
fn resize(&mut self) {
|
||||
let Some(window) = &self.window else { return };
|
||||
let size = window.surface_size();
|
||||
let device = self.wgpu_executor().context().device.clone();
|
||||
if let Some((surface, config)) = &mut self.surface
|
||||
&& size.width > 0
|
||||
&& size.height > 0
|
||||
{
|
||||
config.width = size.width;
|
||||
config.height = size.height;
|
||||
surface.configure(&device, config);
|
||||
}
|
||||
}
|
||||
|
||||
fn log_missing_resources(&mut self) {
|
||||
let missing = self.live.missing_resources();
|
||||
if missing == self.waiting {
|
||||
return;
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
let hashes = missing.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
log::info!("Waiting for {} resources no peer has sent yet: {hashes}", missing.len());
|
||||
}
|
||||
self.waiting = missing;
|
||||
}
|
||||
|
||||
fn recompile(&mut self) {
|
||||
let network = match self.runtime.block_on(self.live.network()) {
|
||||
Ok(network) => network,
|
||||
Err(error) => return log::error!("Failed to build the runtime network: {error}"),
|
||||
};
|
||||
let proto = match compile_graph(network, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
Ok(proto) => proto,
|
||||
Err(error) => return log::error!("Compile failed: {error}"),
|
||||
};
|
||||
match create_executor(proto) {
|
||||
Ok(executor) => {
|
||||
self.graph_runtime.update_sources(executor.sources());
|
||||
log::info!("Document compiled");
|
||||
self.executor = Some(executor);
|
||||
}
|
||||
Err(error) => log::error!("Executor creation failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
let (Some(window), Some((surface, config)), Some(blitter)) = (&self.window, &self.surface, &self.blitter) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Present even without a frame, since Wayland never shows a surface with no committed buffer
|
||||
let frame = match &self.executor {
|
||||
Some(executor) => {
|
||||
let mut render_config = RenderConfig {
|
||||
export_format: ExportFormat::Raster,
|
||||
scale: 1.,
|
||||
..Default::default()
|
||||
};
|
||||
render_config.viewport.resolution = UVec2::new(config.width, config.height);
|
||||
Some(self.runtime.block_on(export::render_texture(executor, render_config, &self.graph_runtime, &self.spawner))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let context = self.wgpu_executor().context();
|
||||
let surface_texture = match surface.get_current_texture(&context.queue) {
|
||||
WgpuCurrentSurfaceTexture::Success(texture) | WgpuCurrentSurfaceTexture::Suboptimal(texture) => texture,
|
||||
WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
|
||||
other => return Err(format!("surface unavailable: {other:?}").into()),
|
||||
};
|
||||
let target = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("live view") });
|
||||
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("live view clear"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &target,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(BACKGROUND),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
if let Some(frame) = &frame {
|
||||
let source = frame.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
blitter.copy(&context.device, &mut encoder, &source, &target);
|
||||
}
|
||||
|
||||
surface_texture.queue.submit([encoder.finish()]);
|
||||
window.pre_present_notify();
|
||||
surface_texture.present();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for Viewer {
|
||||
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||
let attributes = WindowAttributes::default()
|
||||
.with_title(format!("Graphite live view {}", self.live.token()))
|
||||
.with_surface_size(winit::dpi::LogicalSize::new(800, 600));
|
||||
let window: Arc<dyn Window> = event_loop.create_window(attributes).expect("create window").into();
|
||||
self.create_surface(&window);
|
||||
window.request_redraw();
|
||||
self.window = Some(window);
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + POLL_INTERVAL));
|
||||
}
|
||||
|
||||
fn new_events(&mut self, event_loop: &dyn ActiveEventLoop, _cause: StartCause) {
|
||||
for event in self.runtime.block_on(self.live.poll()) {
|
||||
self.dirty |= match event {
|
||||
Event::Synced => {
|
||||
log::info!("Synced with the session");
|
||||
true
|
||||
}
|
||||
Event::ResourceReceived { hash, bytes } => {
|
||||
log::info!("Received resource {hash} ({} bytes)", bytes.len());
|
||||
true
|
||||
}
|
||||
Event::Changed => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
if self.dirty && self.live.is_synced() {
|
||||
self.log_missing_resources();
|
||||
}
|
||||
if self.dirty && self.live.is_ready() {
|
||||
self.dirty = false;
|
||||
self.recompile();
|
||||
if let Some(window) = &self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + POLL_INTERVAL));
|
||||
}
|
||||
|
||||
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
self.live.leave();
|
||||
event_loop.exit();
|
||||
}
|
||||
WindowEvent::SurfaceResized(_) => {
|
||||
self.resize();
|
||||
if let Some(window) = &self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Err(error) = self.draw() {
|
||||
log::error!("Draw failed: {error}");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user