Compare commits

..
Author SHA1 Message Date
Dennis Kobert 96a8e72fcf Fix Vivid Light burning and dodging the source by the backdrop instead of the backdrop by the source 2026-11-05 22:57:24 +00:00
Dennis Kobert 21910d242f Address review comments on the GPU raster kernels 2026-11-05 22:57:24 +00:00
Dennis Kobert c22fb0ec3a Add an Image to Channels GPU node for GPU rasters, since a multi-output struct can't be generic over its raster 2026-11-05 13:30:23 -08:00
Dennis Kobert 312dc1529b Version the nodes that gained GPU rasters and add their migrations 2026-11-05 13:30:23 -08:00
Dennis Kobert ccc32d6104 Test that CPU rasters stay on the CPU without a GPU, Eager opts into it, and a footprint-dependent raster warns at Dehaze 2026-11-05 13:30:22 -08:00
Dennis Kobert ba4b4812e7 Add an Eager node that uploads a raster so the nodes after it run on the GPU 2026-11-05 13:30:22 -08:00
Dennis Kobert 1642bf38ce Report a raster kernel's GPU failures and oversized outputs rather than saying a GPU is required 2026-11-05 13:30:22 -08:00
Dennis Kobert 6684bd279f Mark the Dehaze node as footprint invariant 2026-11-05 13:30:21 -08:00
Dennis Kobert 181c8e461c Fall back to half-float rasters where the GPU can't render full floats 2026-11-05 13:30:20 -08:00
Dennis Kobert 2e57be5aa1 Let list and render nodes carry GPU rasters 2026-11-05 13:30:19 -08:00
Dennis Kobert 7d6718dc67 Embed GPU rasters in SVG output by downloading them first 2026-11-05 13:30:19 -08:00
Dennis Kobert 49ecb3e695 Give GPU rasters an empty default 2026-11-05 13:30:19 -08:00
Dennis Kobert 73aeeee4d6 Run Dehaze and Image Color Palette on GPU rasters 2026-11-05 13:30:16 -08:00
Dennis Kobert 5cfe68dd32 Run raster nodes on GPU rasters through hand-written WGSL kernels 2026-11-05 13:30:15 -08:00
James Lindsay db32addcb0 Update the Tsify dependency (#4600) 2026-11-05 13:29:36 -08:00
Timon 045cdfd5ee Resend only node positions while dragging nodes in the graph (#4921) 2026-11-05 13:29:08 -08:00
Dennis Kobert 1d6b93a6d1 Test all workspace members in CI and remove broken test (#4924) 2026-11-05 13:29:07 -08:00
Dennis Kobert baced334ec Add graphene-cli host, join and watch (#4893)
* Add graphene-cli host, join and watch

* Trim the live CLI to the migrating opener, the graph output it renders and fewer comments

* Log a failed session transport, exit the watcher cleanly, recover a lost surface and clear answered resource requests
2026-11-05 13:29:07 -08:00
Dennis Kobert 4c4e0ba39b Fix clippy warnings (#4923) 2026-11-05 13:29:07 -08:00
Dennis Kobert fbbae5876b Move graph-craft migrations into extra module (#4916) 2026-11-05 13:29:07 -08:00
Dennis Kobert fba33376bc Show other peers' pointers in collaborative editing (#4892) 2026-11-05 13:29:07 -08:00
Dennis Kobert a8104cf230 Add live sessions and the Session panel (#4891)
* Add live sessions and the Session panel

* Move comment

* Address the review findings on joining, guest undo, failed history steps and the panel layout

* Keep the undo note of a failed redo and let a promoted guest undo its unanswered step

* Drop the workspace layout version
2026-11-05 13:28:15 -08:00
Dennis Kobert 778e979c41 Keep in-memory resources when storage mounts after an edit (#4922) 2026-11-05 13:28:15 -08:00
Harshith Jeevan 5ee999b847 Fix a crash when previewing a node with no output (#4899) 2026-11-05 13:28:15 -08:00
Keavon Chambers 9044a9c09a New node: 'Iterate' (#4919) 2026-11-04 18:34:41 -08:00
Keavon Chambers a1ff88ae30 New node: 'Open Ends' (#4918)
* Fix large branching paths freezing the editor

* New node: 'Open Ends' and make 'Vector to Points' keep point attributes
2026-11-04 18:15:57 -08:00
Keavon Chambers d96f03fe90 Rework the 'Math' expression family as 'Math Function' / 'Math Formula', and add 'Math Running' / 'Math Aggregate' (#4917)
* Rename 'Math f(x)' and 'Math f(…)' to 'Math Function' and 'Math Formula'

* Move the lone operator mode of 'Math Formula' into a new 'Math Aggregate' node

* New node: 'Math Running'
2026-11-04 17:18:09 -08:00
Dennis Kobert 708cca339d Move the document and compiler tests into dedicated test modules (#4915) 2026-11-03 19:48:07 +01:00
Timon 6e9208c004 Add save with history preference (#4913)
* Add save with history preference

* Export resources only history names
2026-11-03 15:56:02 +00:00
Dennis Kobert 412979278e Move the compiler passes out of document.rs into a compiler module (#4914) 2026-11-03 16:56:20 +01:00
Dennis Kobert 7f7262c3cd Reconcile the interface with storage, undo hot steps (#4890) 2026-11-03 12:34:58 +01:00
Timon 8206b4cc88 Fix 'Combine Paths' hashing differently across platforms (#4911) 2026-11-02 22:50:39 +00:00
Dennis Kobert b05af55d50 Mint a fresh peer when the user changes (#4889) 2026-11-02 22:53:38 +01:00
Timon 39b8d23a34 Desktop: Confine CEF disk and network more (#4910) 2026-11-02 20:05:09 +00:00
Dennis Kobert 1199d312e4 Compile the definitions table directly instead of inlining it before preprocessing (#4903)
* Compile the definitions table directly instead of inlining it before preprocessing

* Resolve scope inputs against each instance's enclosing scopes, specializing entries whose contexts differ in type
2026-11-02 18:59:22 +01:00
Timon b2cffdfd26 Fix saving leaving the document marked as unsaved on web (#4909) 2026-11-02 17:55:03 +00:00
Timon 6479e0aeba Simplify node graph runtime scheduling (#4907)
* Revert "Limit number of instant graph reevaluations (#4758)"

* Read requests and apply graph updates once per frame
2026-11-02 17:37:00 +00:00
Keavon Chambers bfd85cab6f Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes (#4906)
* Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes

* Resolve the type of Copy to Points content wired from a secondary output
2026-11-02 14:45:28 +00:00
Dennis Kobert 67e5b899d4 Let migrations choose a target per anchor, ask the compiler, and run on whole states 2026-11-02 14:17:49 +00:00
Dennis Kobert 488c992250 Run headless editor tests on a vulkan software GPU (#4880)
* Run headless editor tests on a software GPU

* Update comment
2026-11-02 10:49:00 +00:00
Keavon Chambers 640aded2b2 Add mipmaps to images so they average their pixels when zoomed out (#4908) 2026-11-02 09:55:45 +00:00
260 changed files with 14109 additions and 3347 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
https://github.com/Keavon/graphite-branded-assets/archive/70b260c21afad29140bbc63ddab952fec3dd024c.tar.gz
5b05e7f4449b5f962755542e9b156891bbf2e0a87b7fc90798b8352d9225757d
+6 -29
View File
@@ -174,23 +174,12 @@ jobs:
env:
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: cargo test --all-features
# The plain `cargo test` above only covers the workspace's default members, which leave these out
- name: 🧪 Run document migration tests
env:
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
run: >-
cargo test --all-features
--package migration-core
--package migration-runner
--package migration-formats
--package migration-nodes
--package migration-snapshot
--package document-graph-storage
--package document-format
--package graphene-cli
--package regression
cargo test --workspace --all-features
--exclude 'graphite-desktop*'
--exclude third-party-licenses
&& cargo test --package third-party-licenses
# Render the documents of the regression corpus and compare them with their reference images
regression-corpus:
@@ -237,16 +226,10 @@ jobs:
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
- name: 🖼️ Check the corpus renders against its references
id: corpus
continue-on-error: true
run: cargo run --package regression -- --corpus target/regression-corpus check --output target/regression
- name: ⚠️ Warn about mismatched renders
if: ${{ steps.corpus.outcome == 'failure' }}
run: echo "::warning title=Regression corpus::Some corpus documents render differently from their references. Their renders and diffs are in the regression-mismatches artifact."
- name: 📤 Upload the renders and diffs of mismatches
if: ${{ steps.corpus.outcome == 'failure' }}
if: ${{ failure() }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: regression-mismatches
@@ -279,14 +262,8 @@ jobs:
run: git fetch --depth=1 origin "$BASE_SHA"
- name: 🔬 Check migrations against the base commit
id: migrations
continue-on-error: true
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
- name: ⚠️ Warn about missing migrations
if: ${{ steps.migrations.outcome == 'failure' }}
run: echo "::warning title=Migrations::Some node changes lack a version bump or a migration. The log of the check above lists them."
# Rust format check on GitHub runner
rust-fmt:
needs: skip-check
Generated
+27 -5
View File
@@ -1300,6 +1300,7 @@ dependencies = [
"tinyvec",
"tsify",
"wasm-bindgen",
"web-time",
]
[[package]]
@@ -1776,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"
@@ -2702,7 +2716,10 @@ dependencies = [
"clap",
"document-container",
"document-format",
"document-graph-storage",
"document-live",
"fern",
"getrandom 0.3.3",
"graph-craft",
"graphene-std",
"image",
@@ -2716,6 +2733,7 @@ dependencies = [
"tokio",
"wgpu",
"wgpu-executor",
"winit",
]
[[package]]
@@ -2924,6 +2942,7 @@ dependencies = [
"ash",
"bytemuck",
"cef",
"dirs",
"graphite-desktop-embedded-resources",
"ipc-channel",
"libc",
@@ -2949,7 +2968,6 @@ name = "graphite-desktop-wrapper"
version = "0.0.0"
dependencies = [
"base64 0.22.1",
"dirs",
"graph-craft",
"graphite-editor",
"graphite-wasm-wrapper",
@@ -2996,6 +3014,7 @@ dependencies = [
"node-macro",
"num_enum",
"once_cell",
"peer-transport",
"preprocessor",
"reqwest",
"serde",
@@ -4425,6 +4444,7 @@ dependencies = [
name = "migration-nodes"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"migration-core",
"migration-runner",
"serde",
@@ -5833,6 +5853,7 @@ dependencies = [
"tsify",
"vector-types",
"wasm-bindgen",
"wgpu-executor",
]
[[package]]
@@ -7671,9 +7692,9 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tsify"
version = "0.5.5"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2ec91b85e6c6592ed28636cb1dd1fac377ecbbeb170ff1d79f97aac5e38926d"
checksum = "ea3af6b48c5c5624f7eb3c2f578d1335fadac433321980cae0063e8eb0acaa44"
dependencies = [
"serde",
"serde-wasm-bindgen",
@@ -7683,9 +7704,9 @@ dependencies = [
[[package]]
name = "tsify-macros"
version = "0.5.6"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fc2c44dc9fe4baf55b88e032621b7a11b215a1f0a7de8d0aa04367207d915bc"
checksum = "ef1e2e93369379d0a527c7d6632b58c55d52db7a106d8afbde3b354f3a57a9f1"
dependencies = [
"proc-macro2",
"quote",
@@ -8716,6 +8737,7 @@ dependencies = [
"futures",
"glam",
"graphene-application-io",
"half",
"log",
"node-macro",
"raster-types",
+3
View File
@@ -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" }
@@ -141,6 +143,7 @@ serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
futures = "0.3"
web-time = "1.1"
env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
+35 -26
View File
@@ -4,8 +4,7 @@ use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, SyncSender};
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
@@ -43,14 +42,14 @@ pub(crate) struct App {
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
desktop_wrapper: DesktopWrapper,
runtime_command_sender: Sender<RuntimeCommand>,
ui: UiInstance,
ui_frame_received: bool,
start_render_sender: SyncSender<()>,
ui_initialized: Option<Instant>,
web_communication_startup_buffer: Vec<Vec<u8>>,
ui_frame_received: bool,
ui_startup_buffer: Vec<Vec<u8>>,
preferences: preferences::DesktopPreferences,
launch_documents: Option<Vec<PathBuf>>,
exiting: Arc<AtomicBool>,
exiting: bool,
exit_reason: ExitReason,
}
@@ -74,9 +73,7 @@ impl App {
})
.expect("Error setting Ctrl-C handler");
let exiting = Arc::new(AtomicBool::new(false));
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
let (runtime_command_sender, start_render_receiver) = std::sync::mpsc::channel();
let async_runtime = tokio::runtime::Builder::new_multi_thread()
.thread_name("graphite-async")
@@ -90,9 +87,9 @@ impl App {
let editor_wake = move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
};
let runtime_wake_sender = start_render_sender.clone();
let runtime_wake_sender = runtime_command_sender.clone();
let runtime_wake = move || {
let _ = runtime_wake_sender.try_send(());
let _ = runtime_wake_sender.send(RuntimeCommand::Run);
};
let wgpu_executor = WgpuExecutor::with_context(wgpu_context).expect("Failed to create WgpuExecutor");
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
@@ -106,17 +103,23 @@ impl App {
);
let rendering_app_event_scheduler = app_event_scheduler.clone();
let exiting_clone = exiting.clone();
std::thread::spawn(move || {
let mut update = false;
loop {
if update {
node_runtime.update();
}
let texture = async_runtime.block_on(node_runtime.run());
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
if start_render_receiver.recv_timeout(timeout).is_err() {
node_runtime.begin_frame();
}
if exiting_clone.load(Ordering::Relaxed) {
break;
let first = start_render_receiver.recv_timeout(Duration::from_millis(100)).unwrap_or(RuntimeCommand::Update);
update = false;
for reason in std::iter::once(first).chain(start_render_receiver.try_iter()) {
match reason {
RuntimeCommand::Update => update = true,
RuntimeCommand::Run => {}
RuntimeCommand::Exit => return,
}
}
}
});
@@ -138,12 +141,12 @@ impl App {
desktop_wrapper,
ui,
ui_frame_received: false,
start_render_sender,
runtime_command_sender,
ui_initialized: None,
web_communication_startup_buffer: Vec::new(),
ui_startup_buffer: Vec::new(),
preferences,
launch_documents: Some(launch_documents),
exiting,
exiting: false,
exit_reason: ExitReason::Shutdown,
}
}
@@ -154,10 +157,10 @@ impl App {
}
fn exit(&mut self, reason: Option<ExitReason>) {
if self.exiting.swap(true, Ordering::Relaxed) {
if std::mem::replace(&mut self.exiting, true) {
return;
}
let _ = self.start_render_sender.send(());
let _ = self.runtime_command_sender.send(RuntimeCommand::Exit);
if let Some(reason) = reason {
self.exit_reason = reason;
}
@@ -464,7 +467,7 @@ impl App {
if self.ui_initialized.is_some() {
self.ui.send(UiCommand::Message(message));
} else {
self.web_communication_startup_buffer.push(message);
self.ui_startup_buffer.push(message);
}
}
@@ -473,7 +476,7 @@ impl App {
AppEvent::WebCommunicationInitialized => {
self.ui_initialized = Some(Instant::now());
self.ui_frame_received = false;
for message in self.web_communication_startup_buffer.drain(..) {
for message in self.ui_startup_buffer.drain(..) {
self.ui.send(UiCommand::Message(message));
}
}
@@ -649,7 +652,7 @@ impl ApplicationHandler for App {
}
Err(other) => tracing::error!("Render error: {:?}", other),
}
let _ = self.start_render_sender.try_send(());
let _ = self.runtime_command_sender.send(RuntimeCommand::Update);
}
if !self.ui_frame_received
@@ -759,6 +762,12 @@ impl ApplicationHandler for App {
}
}
enum RuntimeCommand {
Update,
Run,
Exit,
}
pub(crate) enum ExitReason {
Shutdown,
Restart,
-8
View File
@@ -45,11 +45,3 @@ pub(crate) fn app_resources_dir() -> PathBuf {
ensure_dir_exists(&path);
path
}
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
pub(crate) fn delete_old_cef_browser_directory() {
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
if old_browser_dir.is_dir() {
let _ = std::fs::remove_dir_all(&old_browser_dir);
}
}
-3
View File
@@ -74,9 +74,6 @@ pub fn start() -> ExitCode {
dirs::clear_dir(&ui::temp_dir_root());
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory();
// Must be called before event loop initialization or native window integrations will break
App::init();
+1
View File
@@ -28,6 +28,7 @@ wgpu-sync = { workspace = true }
winit = { workspace = true, features = ["serde"] }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
+1 -1
View File
@@ -8,7 +8,7 @@ const APP_DIRECTORY_NAME: &str = "graphite";
const APP_DIRECTORY_NAME: &str = "Graphite";
pub(crate) fn app_tmp_dir() -> PathBuf {
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
let path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join(APP_DIRECTORY_NAME).join("ui");
if let Err(e) = fs::create_dir_all(&path) {
tracing::error!("Failed to create temp directory at {path:?}: {e}");
}
@@ -48,6 +48,10 @@ impl ImplApp for BrowserProcessAppImpl {
cmd.append_switch(Some(&"disable-default-apps".into()));
cmd.append_switch(Some(&"disable-breakpad".into()));
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
cmd.append_switch_with_value(
Some(&"host-resolver-rules".into()),
Some(&"MAP * ~NOTFOUND, EXCLUDE fonts.googleapis.com, EXCLUDE fonts.gstatic.com".into()),
);
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&"disable-features".into());
-1
View File
@@ -27,7 +27,6 @@ wgpu-executor = { workspace = true }
wgpu = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -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);
}
+1 -2
View File
@@ -8,7 +8,6 @@ use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
use std::time::Instant;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
@@ -64,7 +63,7 @@ impl DesktopWrapper {
.with_resource_storage(resource_storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
.with_spawner(spawner)
.with_random_seed(random_seed)
.build();
+4
View File
@@ -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,
}
+13
View File
@@ -181,6 +181,19 @@ impl<L: Layout> Gdd<L> {
}
export_session.embed_resource_sources(links_to_promote)?;
// If the export includes history, also embed every resource referenced by the history.
if options.include_history {
let current: std::collections::HashSet<ResourceHash> = export_session.registry().resources.values().filter_map(|entry| entry.hash).collect();
for hash in export_session.all_referenced_resource_hashes() {
if current.contains(&hash) || working_copy_hashes.contains(&hash) {
continue;
}
if let Some(resource) = byte_store.load(hash).await {
embedded_bytes.push((hash, resource));
}
}
}
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let mut session_state = self.exported_session_state(&export_session);
+31 -5
View File
@@ -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,12 @@ 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,
/// The step a guest asked the host to undo, with the head it asked under. A repeat waits until the head moves.
#[cfg(feature = "network")]
pub(crate) undo_requested: Option<(document_graph_storage::Rev, Option<document_graph_storage::Rev>)>,
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 +146,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 +167,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 +178,11 @@ impl<L: Layout> Gdd<L> {
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
#[cfg(feature = "network")]
undo_requested: None,
interactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
shared: false,
}
}
@@ -186,10 +203,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)
}
}
@@ -220,6 +237,11 @@ impl<L: Layout> Gdd<L> {
Self::open_in_with(working, layout, byte_store, host).await
}
/// 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?)
}
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
@@ -344,18 +366,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 +472,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)
+5
View File
@@ -86,6 +86,7 @@ impl<L: Layout> Gdd<L> {
/// Drop the connection but keep the document shared, so a reopen reconnects. A host first retires every closed
/// interaction with no ops still on their way.
pub fn disconnect(&mut self) {
self.undo_requested = None;
let closed = self.contiguous_interactions();
if let Err(error) = self.retire_interactions(&closed) {
log::error!("Retiring before leaving failed: {error}");
@@ -124,6 +125,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);
+157 -2
View File
@@ -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,138 @@ 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);
};
// A peer promoted to host drops the step itself, so an unanswered request no longer blocks it
let asked = (!self.retires_locally()).then_some((rev, self.session.head_rev()));
if asked.is_some() && self.undo_requested == asked {
return Ok(None);
}
self.drop_step(rev)?;
self.undo_requested = asked;
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(())
}
/// 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 +567,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()
+2 -2
View File
@@ -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.
+127 -53
View File
@@ -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}");
}
});
}
+3 -3
View File
@@ -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 {
+2 -2
View File
@@ -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);
+2 -2
View File
@@ -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> {
+64 -24
View File
@@ -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";
@@ -538,6 +538,46 @@ fn export_materializes_embedded_resource_from_byte_store() {
});
}
/// An export with history carries the bytes of a resource only history still names, so undoing its removal
/// after a reopen finds them, even when they live in the byte store rather than the working copy.
#[test]
fn export_with_history_carries_history_only_resources() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::NoMetadata;
use graph_craft::application_io::resource::ResourceStorage;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
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:?}"));
let payload = b"bytes of a removed resource";
let hash = ResourceHash::from(&payload[..]);
let byte_store = empty_byte_store();
byte_store.store(payload);
let mut resources = ResourceRegistry::new();
let id = ResourceId::new();
resources.push_source_back(&id, DataSource::Embedded);
resources.resolve(&id, hash);
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
gdd.commit_from_runtime(&graph_craft::document::NodeNetwork::default(), &NoMetadata, &ResourceRegistry::new(), &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert!(!gdd.registry().resources.contains_key(&id), "the resource should only be named by history");
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
let archive = gdd
.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &byte_store, None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
.await
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
assert!(reopened.has_resource(&hash).await, "history-only bytes should travel with the export");
});
}
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
@@ -549,7 +589,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 +642,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 +663,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 +705,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 +758,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 +786,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();
+54 -13
View File
@@ -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)]);
});
}
+11 -1
View File
@@ -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));
}
+27 -2
View File
@@ -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)]
+76 -8
View File
@@ -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));
+207 -5
View File
@@ -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(), &registry);
}
#[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));
}
+15
View File
@@ -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)?;
+21
View File
@@ -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
+109
View File
@@ -0,0 +1,109 @@
//! 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};
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, 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 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
}
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 leave(&mut self) {
self.gdd.leave();
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ graph-craft = { workspace = true }
graphene-std = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
preprocessor = { workspace = true }
serde = { workspace = true }
[dev-dependencies]
migration-runner = { workspace = true, features = ["testing"] }
serde = { workspace = true }
+1
View File
@@ -2,5 +2,6 @@
//! Unlike `migration-nodes`, these link the node crates and depend on the build they run in, so a document's peers can't all reach the same result.
mod compiler;
mod vary_nodes_from_copy_to_points;
pub use compiler::CompilerHost;
@@ -0,0 +1,272 @@
use document_graph_storage::attr::node::VISIBLE;
use graphene_std::Color;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Integer(i64),
Bool(bool),
}
fn number(input: &NodeInput) -> Option<f64> {
match literal_of::<Tagged>(input) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
}
}
/// Copy to Points becomes Into Group, Repeat on Points, Vary Rotations, Vary Scales, and a flatten back to the content's element type, ending at the
/// anchor to keep its downstream wires. Grouping makes each copy one row for the vary nodes, and keeps the offsets of its content, whose translation
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
let unset = || literal(Tagged::Bool(false));
let visible = node.attributes().get_or(VISIBLE, true);
if !visible {
target.set(repeat);
replace_inputs(inputs, vec![points, content, unset()]);
return Ok(());
}
let content_type = compiler.and_then(|compiler| compiler.input_type(node, CONTENT));
let fallback = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
let flatten = match &content_type {
Some(content) if content.element_is::<Vector>() => decl!("graphic_nodes::graphic::FlattenVectorNode"@1),
Some(content) if content.element_is::<Raster<CPU>>() => decl!("graphic_nodes::graphic::FlattenRasterNode"@1),
Some(content) if content.element_is::<Color>() => decl!("graphic_nodes::graphic::FlattenColorNode"@1),
Some(content) if content.element_is::<Gradient>() => decl!("graphic_nodes::graphic::FlattenGradientNode"@1),
_ => fallback,
};
// Text has no group to go in, so its rows are repeated as they are
let groups = !content_type.as_ref().is_some_and(|content| content.element_is::<String>());
let group = groups.then(|| {
upstream.add_node(NewNode {
declaration: decl!("graphic_nodes::graphic::IntoGroupNode"@1),
inputs: vec![content.clone()],
})
});
let repeated_content = group.map_or(content, |group| NodeInput::Node { id: group, index: 0 });
let mut stages = vec![(repeat, vec![points, repeated_content, unset()])];
// The rotation range was centered on zero, so a wired one is halved to each side by Multiply nodes
if number(&rotation) != Some(0.) {
let mut half = |factor: f64, key: &str| match number(&rotation) {
Some(rotation) => literal(Tagged::Number(rotation * factor)),
None => {
let multiply = upstream.add_node_keyed(
NewNode {
declaration: decl!("math_nodes::MultiplyNode"@1),
inputs: vec![rotation.clone(), literal(Tagged::Number(factor))],
},
key,
);
NodeInput::Node { id: multiply, index: 0 }
}
};
let (min, max) = (half(-0.5, "min"), half(0.5, "max"));
stages.push((
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
vec![
unset(),
min,
max,
literal(Tagged::Number(0.5)),
unset(),
literal(Tagged::Bool(true)),
rotation_seed,
literal(Tagged::Integer(0)),
],
));
}
// A wired bias can't be converted, so it is left at the default
if number(&scale_min) != Some(1.) || number(&scale_max) != Some(1.) {
let bias = number(&scale_bias).map_or(0.5, bias_keeping_average_scale);
stages.push((
decl!("transform_nodes::transform_nodes::VaryScalesNode"@1),
vec![
unset(),
scale_min,
scale_max,
literal(Tagged::Number(bias)),
unset(),
literal(Tagged::Bool(true)),
scale_seed,
literal(Tagged::Integer(0)),
],
));
}
if groups {
let fully_flatten = (flatten == fallback).then(unset);
stages.push((flatten, std::iter::once(unset()).chain(fully_flatten).collect()));
}
// Each stage reads the one before it, up to the last, which is the anchor
let Some((last_declaration, mut last_inputs)) = stages.pop() else { return Ok(()) };
let mut previous = None;
for (declaration, mut stage_inputs) in stages {
if let Some(id) = previous {
stage_inputs[0] = NodeInput::Node { id, index: 0 };
}
previous = Some(upstream.add_node(NewNode { declaration, inputs: stage_inputs }));
}
if let Some(id) = previous {
last_inputs[0] = NodeInput::Node { id, index: 0 };
}
target.set(last_declaration);
replace_inputs(inputs, last_inputs);
Ok(())
}
fn replace_inputs(inputs: &mut Inputs, replacement: Vec<NodeInput>) {
inputs.truncate(0);
for input in replacement {
inputs.push(input);
}
}
/// The Vary Scales bias giving the same average scale, as a fraction of its range, that Copy to Points' random scale distribution had for its bias.
fn bias_keeping_average_scale(bias: f64) -> f64 {
if bias.abs() < 1e-6 {
return 0.5;
}
// Its bias curve `log2(1 + r (2^b - 1)) / b` averages `2^b / (2^b - 1) - 1 / (b ln 2)`, written with `x = b ln 2` to stay finite for a large bias
let x = bias * std::f64::consts::LN_2;
let average = -1. / (-x).exp_m1() - 1. / x;
// The new curve averages `k / (k + 1)` for `1 - (1 - t)^k` below a bias of 0.5, where `k = -log2(1 - bias)`, and `1 / (p + 1)` for `t^p` above it, where `p = -log2(bias)`
if average < 0.5 {
let k = average / (1. - average);
1. - (-k).exp2()
} else {
let p = 1. / average - 1.;
(-p).exp2()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::CompilerHost;
use migration_core::Declaration;
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
const STAR: Declaration = decl!("vector_nodes::generator_nodes::StarNode"@1);
const FLATTEN_VECTOR: Declaration = decl!("graphic_nodes::graphic::FlattenVectorNode"@1);
const FLATTEN_GRAPHIC: Declaration = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
const VARY_ROTATIONS: Declaration = decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2);
fn host() -> CompilerHost {
CompilerHost::default()
}
fn contract() -> SourceContract {
SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
}
fn star_inputs() -> Vec<NodeInput> {
vec![literal(Tagged::None), literal(Tagged::Integer(5)), literal(Tagged::Number(50.)), literal(Tagged::Number(25.))]
}
fn inputs(content: NodeInput, scale: f64, rotation: f64) -> Vec<NodeInput> {
let number = |number| literal(Tagged::Number(number));
let integer = |integer| literal(Tagged::Integer(integer));
vec![literal(Tagged::Integer(0)), content, number(scale), number(scale), number(0.), integer(1), number(rotation), integer(2)]
}
#[test]
fn rewrites_history() {
let host = host();
check_commutation_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
check_undo_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
}
#[test]
fn typed_content_ends_in_the_flatten_of_its_element() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 0.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_VECTOR));
assert_eq!(fixture.inputs(&migrated, copies).len(), 1);
}
#[test]
fn content_that_does_not_compile_keeps_flatten_graphic() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let unknown = fixture.add(decl!("migration_testing::unknown"@1), vec![]);
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: unknown, index: 0 }, 2., 0.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_GRAPHIC));
assert_eq!(fixture.inputs(&migrated, copies).len(), 2);
}
#[test]
fn text_is_repeated_without_a_group() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let text = fixture.add(decl!("text_nodes::AsStringNode"@1), vec![literal(Tagged::Number(1.))]);
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: text, index: 0 }, 1., 90.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(VARY_ROTATIONS));
let NodeInput::Node { id: repeat, .. } = fixture.inputs(&migrated, copies)[0] else {
panic!("the rotations read the repeat")
};
assert_eq!(fixture.inputs(&migrated, repeat)[1], NodeInput::Node { id: text, index: 0 });
}
#[test]
fn rotation_range_is_centered() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 90.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
let NodeInput::Node { id: rotations, .. } = fixture.inputs(&migrated, copies)[0] else {
panic!("the flatten reads the last stage")
};
assert_eq!(fixture.declaration_of(&migrated, rotations), Some(VARY_ROTATIONS));
assert_eq!(number(&fixture.inputs(&migrated, rotations)[1]), Some(-45.));
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
}
#[test]
fn bias_keeps_its_average() {
assert_eq!(bias_keeping_average_scale(0.), 0.5);
assert!(bias_keeping_average_scale(-10.) < 0.5);
assert!(bias_keeping_average_scale(10.) > 0.5);
assert!(bias_keeping_average_scale(100.).is_finite());
}
}
+1 -4
View File
@@ -12,8 +12,5 @@ migration-core = { workspace = true, features = ["typed"] }
serde = { workspace = true }
[dev-dependencies]
document-graph-storage = { workspace = true, default-features = false }
migration-runner = { workspace = true, features = ["testing"] }
[package.metadata.cargo-shear]
# Frozen mirrors of stored values, once a node migration needs one
ignored = ["serde"]
@@ -2,3 +2,4 @@
mod passthrough_from_upload_texture_node;
mod renames;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,131 @@
use migration_core::{Declaration, Downstream, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Target, decl, literal_of, migration};
use serde::{Deserialize, Serialize};
const FILL: u32 = 1;
const STROKE: u32 = 2;
/// Frozen mirror of the `TaggedValue` variant this migration reads.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// Assign Colors splits by its Fill and Stroke toggles into Vary Fill Colors, Vary Stroke Colors, or both in a row, with the same parameters.
/// A wired toggle counts as enabled, and with both off it only ever passed its content through, which a Passthrough still does. With both on,
/// the stroke goes downstream of the anchor so toggling never rewires the content, since a wire written to a removed node would revive it.
#[migration("graphene_core::vector::AssignColorsNode"@1 => "graphene_core::vector::VaryFillColorsNode"@2)]
pub fn vary_colors_from_assign_colors(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, target: &mut Target) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
if slots.len() != 8 {
return Err(MigrationError::invariant("Assign Colors has eight inputs"));
}
let enabled = |slot: u32| !matches!(literal_of::<Tagged>(&slots[slot as usize]), Some(Tagged::Bool(false)));
let (fill, stroke) = (enabled(FILL), enabled(STROKE));
let vary_fill: Declaration = decl!("graphene_core::vector::VaryFillColorsNode"@2);
let vary_stroke: Declaration = decl!("graphene_core::vector::VaryStrokeColorsNode"@1);
if !fill && !stroke {
target.set(decl!("graphene_core::ops::PassthroughNode"@2));
inputs.truncate(1);
return Ok(());
}
inputs.remove(STROKE);
inputs.remove(FILL);
if !fill {
target.set(vary_stroke);
return Ok(());
}
target.set(vary_fill);
if stroke {
let consumers = downstream.consumers(0);
let mut stroke_inputs = vec![NodeInput::Node { id: node.id(), index: 0 }];
stroke_inputs.extend(slots[3..].iter().cloned());
let strokes = downstream.add_node(NewNode {
declaration: vary_stroke,
inputs: stroke_inputs,
});
for consumer in consumers {
downstream.connect(OutputConnector { node: strokes, output: 0 }, consumer);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const ASSIGN_COLORS: Declaration = decl!("graphene_core::vector::AssignColorsNode"@1);
fn contract() -> SourceContract {
// Only the content can read another Assign Colors, since the other inputs don't take its output type
SourceContract {
reads_own_output: |slot| slot == 0,
..SourceContract::new(8, |random, slot| match slot {
1 | 2 => literal(Tagged::Bool(random.below(2) == 0)),
_ => literal(random.below(4) as f64),
})
}
}
fn node(fill: bool, stroke: bool) -> Vec<NodeInput> {
let parameter = |number: u32| literal(f64::from(number));
vec![
parameter(0),
literal(Tagged::Bool(fill)),
literal(Tagged::Bool(stroke)),
parameter(3),
parameter(4),
parameter(5),
parameter(6),
parameter(7),
]
}
fn migrated_declaration(fill: bool, stroke: bool) -> (Option<Declaration>, usize) {
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
let anchor = fixture.add(ASSIGN_COLORS, node(fill, stroke));
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
(fixture.declaration_of(&migrated, anchor), fixture.inputs(&migrated, anchor).len())
}
#[test]
fn rewrites_history() {
check_commutation(&VaryColorsFromAssignColors, &contract());
check_undo(&VaryColorsFromAssignColors, &contract());
}
#[test]
fn each_toggle_chooses_its_node() {
assert_eq!(migrated_declaration(true, false), (Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)), 6));
assert_eq!(migrated_declaration(false, true), (Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)), 6));
assert_eq!(migrated_declaration(false, false), (Some(decl!("graphene_core::ops::PassthroughNode"@2)), 1));
}
#[test]
fn both_toggles_chain_fill_into_stroke() {
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
let anchor = fixture.add(ASSIGN_COLORS, node(true, true));
fixture.export(NodeInput::Node { id: anchor, index: 0 });
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)));
assert_eq!(fixture.inputs(&migrated, anchor)[0], literal(0.));
let export = migrated.networks[&document_graph_storage::ROOT_NETWORK].exports[0].target.clone();
let Some(NodeInput::Node { id: strokes, .. }) = export else {
panic!("the export reads the stroke")
};
assert_eq!(fixture.declaration_of(&migrated, strokes), Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)));
assert_eq!(fixture.inputs(&migrated, strokes)[0], NodeInput::Node { id: anchor, index: 0 });
}
}
+6
View File
@@ -2,4 +2,10 @@
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod graphene_core;
mod math_nodes;
mod raster_nodes;
/// The scope input of nodes that came to take the GPU pipeline, the identifier frozen as it was when they did.
fn raster_kernel_pipeline() -> migration_core::NodeInput {
migration_core::NodeInput::Scope("raster_nodes::raster_kernel::RasterKernelPipelineNode".into())
}
@@ -0,0 +1,107 @@
use migration_core::{Node, Target, decl, literal_of, migration};
use serde::{Deserialize, Serialize};
const EXPRESSION: usize = 1;
/// Frozen mirror of the `TaggedValue` variant this migration reads.
#[derive(Serialize, Deserialize)]
enum Tagged {
String(String),
}
/// The lone operators 'Math f(…)' applied across its items, in every spelling its classifier read when the node was split.
const OPERATORS: &[&str] = &["+", "-", "*", "/", "^", "&&", "∧", "||", "∨", "<", "<=", "≤", ">", ">=", "≥", "==", "!=", "≠"];
/// The variadic functions 'Math f(…)' called with all its items when given a lone name, also spelled with a leading `\`.
const FUNCTIONS: &[&str] = &[
"hypot",
"min",
"max",
"mean",
"median",
"variance",
"variancepop",
"stdev",
"stdevpop",
"geomean",
"harmmean",
"rms",
"mode",
"count",
"xor",
"gcd",
"lcm",
];
/// 'Math f(…)' split by the kind of string it held: a lone operator or function name, which it applied across its items, moves to
/// 'Math Aggregate', and an expression stays as 'Math Formula'. A wired string can't be read before it runs, so it stays an expression.
#[migration("math_nodes::MathFNode"@1 => "math_nodes::MathFormulaNode"@2)]
pub fn math_formula_from_math_f(node: &Node, target: &mut Target) {
let Some(slot) = node.inputs().get(EXPRESSION) else { return };
let Some(Tagged::String(expression)) = literal_of::<Tagged>(&slot.input) else { return };
let token = expression.trim();
let function = token.strip_prefix('\\').unwrap_or(token);
if OPERATORS.contains(&token) || FUNCTIONS.contains(&function) {
target.set(decl!("math_nodes::MathAggregateNode"@1));
}
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{Declaration, NodeInput, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const MATH_F: Declaration = decl!("math_nodes::MathFNode"@1);
fn contract() -> SourceContract {
// Only the items can read another 'Math f(…)', since the expression and output type don't take its number
SourceContract {
reads_own_output: |slot| slot == 0,
..SourceContract::new(3, |random, slot| match slot {
EXPRESSION => literal(Tagged::String(["+", "a * b", "\\max", " ≤ ", "min(a, b)"][random.below(5)].to_string())),
_ => literal(random.below(4) as f64),
})
}
}
fn migrated_declaration(expression: NodeInput) -> Option<Declaration> {
let mut fixture = Fixture::new(&MathFormulaFromMathF);
let anchor = fixture.add(MATH_F, vec![literal(1.), expression, literal(0.)]);
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
fixture.declaration_of(&migrated, anchor)
}
#[test]
fn rewrites_history() {
check_commutation(&MathFormulaFromMathF, &contract());
check_undo(&MathFormulaFromMathF, &contract());
}
#[test]
fn lone_operators_and_functions_become_aggregates() {
let aggregate = Some(decl!("math_nodes::MathAggregateNode"@1));
let formula = Some(decl!("math_nodes::MathFormulaNode"@2));
let expression = |text: &str| literal(Tagged::String(text.to_string()));
assert_eq!(migrated_declaration(expression("+")), aggregate);
assert_eq!(migrated_declaration(expression(" ≠ ")), aggregate);
assert_eq!(migrated_declaration(expression("max")), aggregate);
assert_eq!(migrated_declaration(expression("\\mean")), aggregate);
assert_eq!(migrated_declaration(expression("a + b")), formula);
assert_eq!(migrated_declaration(expression("max(a, b)")), formula);
assert_eq!(migrated_declaration(expression("")), formula);
}
#[test]
fn a_wired_expression_becomes_a_formula() {
let mut fixture = Fixture::new(&MathFormulaFromMathF);
let source = fixture.add(MATH_F, vec![literal(1.), literal(Tagged::String("+".to_string())), literal(0.)]);
let anchor = fixture.add(MATH_F, vec![literal(1.), NodeInput::Node { id: source, index: 0 }, literal(0.)]);
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("math_nodes::MathFormulaNode"@2)));
assert_eq!(fixture.declaration_of(&migrated, source), Some(decl!("math_nodes::MathAggregateNode"@1)));
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f;
mod renames;
@@ -0,0 +1,5 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::BlackAndWhiteNode"@1 => @2)]
pub fn black_and_white_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlackAndWhiteV1, &contract());
check_undo(&BlackAndWhiteV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::filter::BlurNode"@1 => @2)]
pub fn blur_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlurV1, &contract());
check_undo(&BlurV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::BrightnessContrastNode"@1 => @2)]
pub fn brightness_contrast_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BrightnessContrastV1, &contract());
check_undo(&BrightnessContrastV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ChannelMixerNode"@1 => @2)]
pub fn channel_mixer_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(19, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ChannelMixerV1, &contract());
check_undo(&ChannelMixerV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::ChannelsToImageNode"@1 => @2)]
pub fn channels_to_image_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ChannelsToImageV1, &contract());
check_undo(&ChannelsToImageV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ColorBalanceNode"@1 => @2)]
pub fn color_balance_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(12, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorBalanceV1, &contract());
check_undo(&ColorBalanceV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ColorLookupNode"@1 => @2)]
pub fn color_lookup_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorLookupV1, &contract());
check_undo(&ColorLookupV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => @2)]
pub fn color_overlay_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorOverlayV1, &contract());
check_undo(&ColorOverlayV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::CurvesNode"@1 => @2)]
pub fn curves_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&CurvesV1, &contract());
check_undo(&CurvesV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::dehaze::DehazeNode"@1 => @2)]
pub fn dehaze_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DehazeV1, &contract());
check_undo(&DehazeV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::DesaturateNode"@1 => @2)]
pub fn desaturate_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DesaturateV1, &contract());
check_undo(&DesaturateV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ExposureNode"@1 => @2)]
pub fn exposure_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ExposureV1, &contract());
check_undo(&ExposureV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => @2)]
pub fn extend_image_to_bounds_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ExtendImageToBoundsV1, &contract());
check_undo(&ExtendImageToBoundsV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::GammaCorrectionNode"@1 => @2)]
pub fn gamma_correction_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&GammaCorrectionV1, &contract());
check_undo(&GammaCorrectionV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::GradientMapNode"@1 => @2)]
pub fn gradient_map_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&GradientMapV1, &contract());
check_undo(&GradientMapV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::HueSaturationNode"@1 => @2)]
pub fn hue_saturation_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(51, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&HueSaturationV1, &contract());
check_undo(&HueSaturationV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::image_color_palette::ImageColorPaletteNode"@1 => @2)]
pub fn image_color_palette_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ImageColorPaletteV1, &contract());
check_undo(&ImageColorPaletteV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::InvertNode"@1 => @2)]
pub fn invert_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InvertV1, &contract());
check_undo(&InvertV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::LevelsNode"@1 => @2)]
pub fn levels_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(27, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&LevelsV1, &contract());
check_undo(&LevelsV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
pub fn make_opaque_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MakeOpaqueV1, &contract());
check_undo(&MakeOpaqueV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::MaskNode"@1 => @2)]
pub fn mask_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MaskV1, &contract());
check_undo(&MaskV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
pub fn median_filter_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MedianFilterV1, &contract());
check_undo(&MedianFilterV1, &contract());
}
}
@@ -1,4 +1,31 @@
//! Migrations of the nodes in `raster_nodes`.
mod black_and_white_v1;
mod blur_v1;
mod brightness_contrast_v1;
mod channel_mixer_v1;
mod channels_to_image_v1;
mod color_balance_v1;
mod color_lookup_v1;
mod color_overlay_v1;
mod curves_v1;
mod dehaze_v1;
mod desaturate_v1;
mod exposure_v1;
mod extend_image_to_bounds_v1;
mod gamma_correction_v1;
mod gradient_map_v1;
mod hue_saturation_v1;
mod image_color_palette_v1;
mod invert_v1;
mod levels_v1;
mod make_opaque_v1;
mod mask_v1;
mod median_filter_v1;
mod mix_colors_from_mix_node;
mod photo_filter_v1;
mod posterize_v1;
mod renames;
mod selective_color_v1;
mod threshold_v1;
mod vibrance_v1;
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::PhotoFilterNode"@1 => @2)]
pub fn photo_filter_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PhotoFilterV1, &contract());
check_undo(&PhotoFilterV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::PosterizeNode"@1 => @2)]
pub fn posterize_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PosterizeV1, &contract());
check_undo(&PosterizeV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::SelectiveColorNode"@1 => @2)]
pub fn selective_color_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(39, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&SelectiveColorV1, &contract());
check_undo(&SelectiveColorV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ThresholdNode"@1 => @2)]
pub fn threshold_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ThresholdV1, &contract());
check_undo(&ThresholdV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::VibranceNode"@1 => @2)]
pub fn vibrance_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&VibranceV1, &contract());
check_undo(&VibranceV1, &contract());
}
}
+24
View File
@@ -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)> {
@@ -401,6 +405,12 @@ impl Replica {
}
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
if let Some(recipients) = self.owed_resources.get_mut(&hash) {
recipients.remove(&to);
if recipients.is_empty() {
self.owed_resources.remove(&hash);
}
}
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
}
@@ -1122,4 +1132,18 @@ mod tests {
host.poll(&mut session);
assert!(host.owed_resources.is_empty(), "nothing is owed to a link that closed");
}
#[test]
fn an_answered_request_is_owed_no_more() {
let (mut network, mut host, host_link, mut session) = hosted_room();
let mut bare = connect_bare_peer(&mut network, &mut host, &mut session);
let hash = ResourceHash::from(b"bytes".as_slice());
bare.send(host_link, &hello(0)).unwrap();
bare.send(host_link, &SyncPacket::ResourceRequest(vec![hash])).unwrap();
network.deliver_all();
host.poll(&mut session);
host.send_resource(bare.id(), hash, b"bytes".to_vec()).unwrap();
assert!(host.owed_resources.is_empty());
}
}
+2 -1
View File
@@ -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 }
+11 -28
View File
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
use crate::task::{Clock, Scheduling, Spawn, Spawner};
use crate::task::{Spawn, Spawner};
use document_container::store::DocumentStore;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
@@ -96,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
let RuntimeBuilder {
wake: runtime_wake,
mut application_io,
scheduling,
clock,
} = runtime;
graphene_std::uuid::set_uuid_seed(random_seed);
@@ -109,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
node_runtime.replace_application_io(application_io);
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
node_runtime.set_scheduling(scheduling);
node_runtime.replace_task_executor(spawner, runtime_wake);
(Editor { dispatcher }, node_runtime)
}
@@ -187,18 +184,17 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
pub struct RuntimeBuilder<W = (), A = ()> {
wake: W,
application_io: A,
clock: Arc<dyn Clock>,
scheduling: Scheduling,
}
impl RuntimeBuilder {
pub fn new(clock: Arc<dyn Clock>) -> Self {
Self {
wake: (),
application_io: (),
clock,
scheduling: Scheduling::default(),
}
pub fn new() -> Self {
Self { wake: (), application_io: () }
}
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
}
}
@@ -208,25 +204,12 @@ impl<A> RuntimeBuilder<(), A> {
RuntimeBuilder {
wake: Arc::new(wake),
application_io: self.application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W> RuntimeBuilder<W, ()> {
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
RuntimeBuilder {
wake: self.wake,
application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W, A> RuntimeBuilder<W, A> {
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
Self { scheduling, ..self }
RuntimeBuilder { wake: self.wake, application_io }
}
}
+2
View File
@@ -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,7 @@ 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.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;
@@ -330,6 +330,29 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
let save_with_history_description = "
Include the document's edit history in saved files. Only applies with \"Save as .gdd\" enabled.\n\
\n\
*Default: Off.*
"
.trim();
let save_with_history_checkbox_id = CheckboxId::new();
let save_with_history = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.save_with_history)
.tooltip_label("Save with History")
.tooltip_description(save_with_history_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveWithHistory { enabled: checkbox_input.checked }.into())
.for_label(save_with_history_checkbox_id)
.widget_instance(),
TextLabel::new("Save with History")
.tooltip_label("Save with History")
.tooltip_description(save_with_history_description)
.for_checkbox(save_with_history_checkbox_id)
.widget_instance(),
];
let validate_description = "
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
\n\
@@ -353,7 +376,7 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
rows.extend_from_slice(&[header, save_as_gdd, save_with_history, validate_storage_round_trip]);
}
// =============
@@ -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,22 +25,26 @@ 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)| {
let label = TextLabel::new(name.clone()).widget_instance();
let button = TextButton::new("Open a Copy")
.on_update(move |_| {
DialogMessage::CloseAndThen {
followups: vec![PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }.into()],
}
.into()
})
.widget_instance();
LayoutGroup::row(vec![label, Separator::new(SeparatorStyle::Unrelated).widget_instance(), button])
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
let button = |label: &str, followup: Box<dyn Fn() -> PortfolioMessage + Send + Sync>| {
TextButton::new(label)
.on_update(move |_| DialogMessage::CloseAndThen { followups: vec![followup().into()] }.into())
.widget_instance()
};
let mut widgets = vec![TextLabel::new(name.clone()).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance()];
// A copy stays possible, since joining needs the other tab to be connected
if shared {
widgets.push(button("Join in This Tab", Box::new(move || PortfolioMessage::JoinStoredSession { source })));
}
widgets.push(button("Open a Copy", Box::new(move || PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() })));
LayoutGroup::row(widgets)
}));
Layout(rows)
@@ -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,12 @@ pub enum FrontendMessage {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateDocumentCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateNodeGraphCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateContextMenuInformation {
#[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>,
+13 -2
View File
@@ -12,9 +12,20 @@ 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), tsify(large_number_types_as_bigints, from_wasm_abi))]
#[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))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PersistedState {
pub documents: Vec<DocumentInfo>,
@@ -51,7 +62,7 @@ pub enum RenderStatus {
Panic,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum FileType {
#[default]
@@ -118,7 +118,7 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
};
// The reply carries the source it read, so the frontend can drop one that a later keystroke has outdated
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.operator_only);
let completions = caret.map(|caret| math_expression_completions(&source, caret, asked));
responses.add(FrontendMessage::UpdateMathExpressionAnalysis {
widget_id,
@@ -371,9 +371,9 @@ impl LayoutMessageHandler {
};
// The widget is resent as stored, so its tokens and errors must be for its new value rather than its old one
let accepts_reducers = math_expression_input.accepts_reducers;
let error = math_expression_error(update_value, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, accepts_reducers);
let operator_only = math_expression_input.operator_only;
let error = math_expression_error(update_value, operator_only);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, operator_only);
math_expression_input.tokens = tokens;
math_expression_input.tooltips = tooltips;
math_expression_input.errors = math_expression_error_ranges(update_value, error.as_ref());
@@ -24,7 +24,7 @@ impl core::fmt::Display for WidgetId {
macro_rules! define_layout_target {
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LayoutTarget {
@@ -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.
@@ -16,13 +16,16 @@ fn utf16_offsets(source: &str) -> Vec<u32> {
units
}
/// Why a math expression fails to parse, or `None` when it parses. Where the node applies a lone operator or function name like
/// `+` or `min` across its items, that counts as valid too.
pub fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<ParseError> {
/// Why a math expression fails to parse, or `None` when it parses. Where the node takes only a lone operator or function name like
/// `+` or `min` to apply across its items, anything else is the error instead.
pub fn math_expression_error(expression: &str, operator_only: bool) -> Option<ParseError> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
if expression.trim().is_empty() {
return None;
}
if operator_only {
return math_parser::reducer::reducer_error(expression);
}
math_parser::ast::Node::try_parse_from_str(expression).err()
}
@@ -143,11 +146,11 @@ pub struct MathExpressionTokens {
}
/// The tokens of a math expression for the frontend to color and typeset, with the parser's byte offsets converted to code units.
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
pub fn math_expression_tokens(source: &str, operator_only: bool) -> MathExpressionTokens {
let units = utf16_offsets(source);
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
let tokens = math_parser::highlight::highlight(source, accepts_reducers).into_iter().map(|token| {
let tokens = math_parser::highlight::highlight(source, operator_only).into_iter().map(|token| {
let tooltip = token.tooltip.map(|tooltip| MathExpressionTooltip {
label: tooltip.label,
form: tooltip.form,
@@ -502,9 +502,9 @@ pub struct MathExpressionInput {
pub tooltips: Vec<MathExpressionTooltip>,
/// The stretches of the value its parse errors point at, which the frontend underlines.
pub errors: Vec<MathExpressionRange>,
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
/// Whether the value is a lone operator or function name like `+` or `max`, applied across a list, rather than an expression.
#[serde(skip)]
pub accepts_reducers: bool,
pub operator_only: bool,
pub disabled: bool,
// Tooltips
@@ -24,6 +24,7 @@ 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 layers_panel_open: bool,
pub inspector_open: bool,
pub focus_document: bool,
@@ -687,6 +688,11 @@ 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),
],
])
.widget_instance(),
@@ -18,7 +18,7 @@ use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -944,9 +944,15 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({} x {})", self.data().width(), self.data().height())
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
if self.is_empty() {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
@@ -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,112 @@ 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;
}
// A failed retract may already have taken the step back, so no older step is undone after it
let retracted = match self.retract_storage_interaction() {
Ok(retracted) => retracted,
Err(error) => {
log::error!("Taking the storage interaction back failed: {error}");
return false;
}
};
let note = if let Some(ops) = retracted {
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;
};
let redone = match &note {
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
UndoNote::Dropped(rev) => self.redo_retired_step(*rev),
UndoNote::Cursor => true,
};
if !redone {
// The note stays paired with its redo snapshot
self.undo_notes.push(note);
return false;
}
if let Some(snapshot) = self.pop_redo() {
self.push_undo(snapshot);
}
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) -> Result<Option<Vec<document_graph_storage::RegistryDelta>>, document_format::Error> {
match self.storage.as_mut() {
Some(storage) => storage.retract_interaction(),
None => Ok(None),
}
}
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) -> bool {
let Some(storage) = self.storage.as_mut() else { return false };
storage.restage_ops(ops).inspect_err(|error| log::error!("Staging the redone step failed: {error}")).is_ok()
}
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 {
let Some(storage) = self.storage.as_mut() else { return false };
storage.redo_retired_step(rev).inspect_err(|error| log::error!("Redoing the dropped step failed: {error}")).is_ok()
}
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 +244,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 +277,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 +363,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`
@@ -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,
@@ -1147,6 +1155,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);
@@ -1245,6 +1254,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
let save_as_gdd = preferences.save_as_gdd;
let include_history = preferences.save_with_history;
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
let name = format!("{}.{}", self.name.clone(), extension);
@@ -1253,7 +1263,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocumentAs => None,
_ => self.path.clone().map(|path| path.with_extension(extension)),
};
if path.is_some() {
if path.is_some() || environment.is_web() {
responses.add(DocumentMessage::MarkAsSaved);
}
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
@@ -1280,7 +1290,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportOptions {
include_history: false,
include_history,
..Default::default()
},
export_load_handle.as_ref(),
@@ -1659,7 +1669,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 +2187,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 +2203,8 @@ 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.refresh_resource_registry();
document
}
@@ -2373,6 +2387,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,10 +2438,15 @@ 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);
}
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.
pub(crate) fn retire_storage_interaction(&mut self) {
self.history.retire_storage_interaction();
@@ -2420,7 +2473,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 +2549,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 +2647,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 +2973,47 @@ 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);
}
/// 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 +3048,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 +4300,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);
@@ -4695,6 +4888,7 @@ mod document_message_handler_tests {
.executor
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
let frontend_messages = editor.editor.handle_message(Message::Wake);
@@ -5115,4 +5309,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");
}
}
@@ -1394,8 +1394,8 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
"math_expression_or_reducer".to_string(),
// Like `math_expression`, but taking only a lone operator or function name like `+` or `min` to apply across the node's items
"math_operator".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_inspector::math_expression_widget(info, true))])
@@ -208,6 +208,7 @@ pub enum NodeGraphMessage {
SendWires,
UpdateVisibleNodes,
SendGraph,
SendNodePositions,
SetInputValue {
node_id: NodeId,
input_index: usize,
@@ -131,9 +131,9 @@ pub struct NodeGraphMessageHandler {
reordering_export: Option<usize>,
/// The end index of the moved connector
end_index: Option<usize>,
/// Used to keep track of what nodes are sent to the front end so that only visible ones are sent to the frontend
frontend_nodes: Vec<NodeId>,
/// Used to keep track of what wires are sent to the front end so the old ones can be removed
/// The nodes the frontend currently knows about
frontend_nodes: Vec<FrontendNode>,
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
frontend_wires: HashSet<(NodeId, usize)>,
evaluation_errors: Vec<NodeEvaluationError>,
}
@@ -2017,7 +2017,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let document_bbox: [DVec2; 2] = viewport_bbox.map(|p| network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(p));
let mut nodes = Vec::new();
for node_id in &self.frontend_nodes {
for node_id in self.frontend_nodes.iter().map(|node| &node.id) {
let Some(node_bbox) = network_interface.node_bounding_box(node_id, breadcrumb_network_path) else {
log::error!("Could not get bbox for node: {node_id:?}");
continue;
@@ -2052,9 +2052,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(InspectorMessage::Refresh);
responses.add(EventMessage::GraphChanged);
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes });
self.frontend_nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
@@ -2071,6 +2070,36 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.update_node_graph_hints(responses);
}
}
NodeGraphMessage::SendNodePositions => {
if breadcrumb_network_path != selection_network_path || !graph_view_overlay_open {
return;
}
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { return };
let same_nodes = network.nodes.len() == self.frontend_nodes.len() && self.frontend_nodes.iter().all(|node| network.nodes.contains_key(&node.id));
if !same_nodes {
responses.add(NodeGraphMessage::SendGraph);
return;
}
for node in &mut self.frontend_nodes {
if let Some(position) = network_interface.position(&node.id, breadcrumb_network_path) {
node.position = position.into();
}
}
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateLayerWidths {
layer_widths,
chain_widths,
has_left_input_wire,
});
responses.add(NodeGraphMessage::UpdateImportsExports);
}
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
@@ -2134,12 +2163,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
if graph_view_overlay_open {
responses.add(NodeGraphMessage::SendGraph);
if !rubber_band {
responses.add(NodeGraphMessage::SendGraph);
}
responses.add(DocumentMessage::RenderRulers);
responses.add(DocumentMessage::RenderScrollbars);
}
}
NodeGraphMessage::ShiftSelectedNodesByAmount { mut graph_delta, rubber_band, glide } => {
let moved = graph_delta != IVec2::ZERO;
while graph_delta != IVec2::ZERO {
match graph_delta.x.cmp(&0) {
Ordering::Greater => {
@@ -2183,6 +2215,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
responses.add(NodeGraphMessage::SendWires);
if rubber_band && moved {
responses.add(NodeGraphMessage::SendNodePositions);
}
}
NodeGraphMessage::ToggleSelectedAsLayersOrNodes => {
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
@@ -3410,7 +3445,8 @@ impl NodeGraphMessageHandler {
.exports
.iter()
.any(|export| matches!(export, NodeInput::Node { node_id: export_node_id, .. } if *export_node_id == node_id));
if selection_is_not_already_the_output && no_other_selections {
let has_outputs = network_interface.number_of_outputs(&node_id, breadcrumb_network_path) > 0;
if selection_is_not_already_the_output && no_other_selections && has_outputs {
let button = TextButton::new("Preview")
.icon("FrameAll")
.tooltip_label("Preview")
@@ -481,16 +481,16 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
}
/// A math expression's typeset text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, operator_only: bool) -> Vec<WidgetInstance> {
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return text_widget(parameter_widgets_info);
};
let error = math_expression_error(expression, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
let error = math_expression_error(expression, operator_only);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, operator_only);
let input = MathExpressionInput::new(expression.clone())
.tokens(tokens)
.tooltips(tooltips)
.accepts_reducers(accepts_reducers)
.operator_only(operator_only)
.errors(math_expression_error_ranges(expression, error.as_ref()))
.on_update(parameter_widgets_info.update_value(|x: &MathExpressionInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
@@ -500,7 +500,7 @@ pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo,
// padded to a checkbox's 16px so the field lines up with the rows around it
let icon = match &error {
Some(error) => IconLabel::new("Warning")
.tooltip_label("Invalid Math Expression")
.tooltip_label(if operator_only { "Invalid Operator" } else { "Invalid Math Expression" })
.tooltip_description(math_expression_error_description(error)),
None => IconLabel::new("Empty12px"),
};
@@ -3942,12 +3942,13 @@ mod tests {
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
assert!(math_expression_error(expression, accepts_reducers).is_none(), "`{expression}`");
for (expression, operator_only) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true), (" ≤ ", true)] {
assert!(math_expression_error(expression, operator_only).is_none(), "`{expression}`");
}
assert!(math_expression_error("2 +", false).is_some());
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert!(math_expression_error("+", false).is_some(), "a lone operator is an error where the node takes an expression");
assert!(math_expression_error("a + b", true).is_some(), "an expression is an error where the node takes a lone operator");
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
}
@@ -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);
@@ -662,12 +664,46 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
}
}
#[tokio::test]
async fn pasted_image_resource_survives_inserting_a_node() {
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.handle_message(paste_named_image()).await;
editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER)).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let document = editor.active_document();
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
}
#[tokio::test]
async fn pasted_image_resource_survives_storage_mounting_after_the_paste() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(paste_named_image()).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let document = editor.active_document();
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
}
/// 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 +737,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 +972,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);
@@ -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));
}
@@ -3532,3 +3532,18 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
"The evaluated network should fall back to the document's own export"
);
}
#[tokio::test]
async fn cannot_preview_node_without_outputs() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
// Attempting to toggle preview on a node without outputs should not enable previewing
network_interface.toggle_preview(custom_node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
}
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff. Show more