mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
80
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4bddbd067 | ||
|
|
e061fbc9f0 | ||
|
|
bbe33f34fc | ||
|
|
53c54333fe | ||
|
|
089efc9d27 | ||
|
|
701d68d067 | ||
|
|
4f9657a4a1 | ||
|
|
815f9e9dba | ||
|
|
b7c77560d2 | ||
|
|
af9c5dd65d | ||
|
|
a835005d3c | ||
|
|
3a2ecdc501 | ||
|
|
72fe9269a3 | ||
|
|
db70c1981d | ||
|
|
04f8aa0237 | ||
|
|
8ebc85746e | ||
|
|
9526a4e726 | ||
|
|
857eb26cbd | ||
|
|
e3ea0dcf68 | ||
|
|
1d4d0544cc | ||
|
|
6ae878d86a | ||
|
|
6ed938f62b | ||
|
|
6d23f7c2f4 | ||
|
|
53a0c1548d | ||
|
|
e2fec54ced | ||
|
|
e92ca26fd2 | ||
|
|
5d70619c4c | ||
|
|
69398a6703 | ||
|
|
d7ae6029e0 | ||
|
|
343710b623 | ||
|
|
f872c5cd57 | ||
|
|
626956c950 | ||
|
|
b22bbf6d95 | ||
|
|
75117e8d6b | ||
|
|
95672018b0 | ||
|
|
d0fb9a1efc | ||
|
|
f0622d62b6 | ||
|
|
2da22f2458 | ||
|
|
849e08829d | ||
|
|
679421ec80 | ||
|
|
9a925d16e5 | ||
|
|
e49c707524 | ||
|
|
506690d109 | ||
|
|
4813fe39b0 | ||
|
|
6e44a74254 | ||
|
|
3d13dc379b | ||
|
|
aee07b052a | ||
|
|
2ed5e775e5 | ||
|
|
23e6b0f11d | ||
|
|
97d8452a1d | ||
|
|
ab32a60476 | ||
|
|
7d1303f695 | ||
|
|
f90bef159c | ||
|
|
cb30348215 | ||
|
|
3f1351e3b9 | ||
|
|
eb4a122322 | ||
|
|
358eb317d2 | ||
|
|
04a401c1b8 | ||
|
|
6f06f030d6 | ||
|
|
fac555ab3b | ||
|
|
8d111e37f5 | ||
|
|
fdf6cfe296 | ||
|
|
c6d6f9f8be | ||
|
|
68d2a06c80 | ||
|
|
0bede7969c | ||
|
|
e38926004f | ||
|
|
e8f7366a43 | ||
|
|
5e705aaa04 | ||
|
|
cc444da637 | ||
|
|
1940e430dc | ||
|
|
eaadea6593 | ||
|
|
ecd2007e63 | ||
|
|
fea741cdef | ||
|
|
98550f6f25 | ||
|
|
89b797f4c1 | ||
|
|
21cceeb7ba | ||
|
|
96024d6c2c | ||
|
|
645d346565 | ||
|
|
3e51b757db | ||
|
|
944d00cac5 |
No files matched your search
Generated
+1975
-409
File diff suppressed because it is too large.
Load diff
+15
@@ -11,10 +11,13 @@ members = [
|
||||
"document/format",
|
||||
"document/graph-storage",
|
||||
"document/container",
|
||||
"document/peer-transport",
|
||||
"document/live",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"libraries/wgpu-sync",
|
||||
"node-graph/libraries/graphene-hash",
|
||||
"node-graph/libraries/*",
|
||||
@@ -40,6 +43,7 @@ default-members = [
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
"libraries/math-parser",
|
||||
"libraries/ipsum",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/interpreted-executor",
|
||||
"node-graph/node-macro",
|
||||
@@ -96,6 +100,8 @@ graph-craft = { path = "node-graph/graph-craft" }
|
||||
document-format = { path = "document/format" }
|
||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-container = { path = "document/container" }
|
||||
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" }
|
||||
@@ -105,6 +111,7 @@ wgpu-sync = { path = "libraries/wgpu-sync" }
|
||||
graphite-proc-macros = { path = "proc-macros" }
|
||||
graphite-editor = { path = "editor" }
|
||||
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
|
||||
ipsum = { path = "libraries/ipsum" }
|
||||
|
||||
# Workspace dependencies
|
||||
rustc-hash = "2.0"
|
||||
@@ -192,6 +199,13 @@ image = { version = "0.25", default-features = false, features = [
|
||||
"jpeg",
|
||||
"bmp",
|
||||
"gif",
|
||||
"webp",
|
||||
"tiff",
|
||||
"ico",
|
||||
"tga",
|
||||
"hdr",
|
||||
"exr",
|
||||
"serde",
|
||||
] }
|
||||
pretty_assertions = "1.4"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
@@ -260,6 +274,7 @@ lto = "thin"
|
||||
debug = true
|
||||
|
||||
[patch.crates-io]
|
||||
winit = { git = "https://github.com/timon-schelling/winit", branch = "graphite" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
@@ -18,6 +18,7 @@ accepted = [
|
||||
"NCSA", # Keep this list in sync with those in `/deny.toml`
|
||||
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
|
||||
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
|
||||
"Unlicense", # Keep this list in sync with those in `/deny.toml`
|
||||
]
|
||||
workarounds = ["ring"]
|
||||
ignore-build-dependencies = true
|
||||
|
||||
@@ -82,6 +82,7 @@ allow = [
|
||||
"NCSA", # Keep this list in sync with those in `/about.toml`
|
||||
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
|
||||
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
|
||||
"Unlicense", # Keep this list in sync with those in `/about.toml`
|
||||
]
|
||||
# The confidence threshold for detecting a license from license text.
|
||||
# The higher the value, the more closely the license text must be to the
|
||||
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
@@ -44,12 +44,12 @@ rfd = { workspace = true }
|
||||
open = { workspace = true }
|
||||
lzma-rust2 = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
url = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
interprocess = "2.4.2"
|
||||
fd-lock = "4.0.4"
|
||||
ctrlc = "3.5.1"
|
||||
window_clipboard = "0.5"
|
||||
|
||||
# Windows-specific dependencies
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-bundle"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Bundle"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
cef-dll-sys = { workspace = true }
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-embedded-resources"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop Embedded Resources"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
include_dir = { workspace = true }
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-linux"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Linux"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-mac"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Mac"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
main = ["dep:graphite-desktop"]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-win"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Windows"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "graphite"
|
||||
|
||||
+96
-28
@@ -9,10 +9,11 @@ use std::sync::mpsc::{Receiver, SyncSender};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::data_transfer::{DataTransferSendBuilder, TypeHint};
|
||||
use winit::dpi::PhysicalSize;
|
||||
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::dirs;
|
||||
@@ -23,7 +24,7 @@ use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Preferences};
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
@@ -35,6 +36,8 @@ pub(crate) struct App {
|
||||
window_maximized: bool,
|
||||
window_fullscreen: bool,
|
||||
window_pending_drag: bool,
|
||||
pending_dnd_fetch: Option<AsyncRequestSerial>,
|
||||
pending_clipboard_fetch: Option<AsyncRequestSerial>,
|
||||
input_state: InputState,
|
||||
ui_scale: f64,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
@@ -107,6 +110,8 @@ impl App {
|
||||
window_maximized: false,
|
||||
window_fullscreen: false,
|
||||
window_pending_drag: false,
|
||||
pending_dnd_fetch: None,
|
||||
pending_clipboard_fetch: None,
|
||||
input_state: InputState::new(),
|
||||
ui_scale: 1.,
|
||||
app_event_receiver,
|
||||
@@ -200,15 +205,15 @@ impl App {
|
||||
};
|
||||
self.send_or_queue_web_message(bytes);
|
||||
}
|
||||
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
|
||||
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let _ = thread::spawn(move || {
|
||||
let mut dialog = AsyncFileDialog::new().set_title(title);
|
||||
for filter in filters {
|
||||
for filter in options.filters {
|
||||
dialog = dialog.add_filter(filter.name, &filter.extensions);
|
||||
}
|
||||
|
||||
let handles = if multiple {
|
||||
let handles = if options.multiple {
|
||||
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
|
||||
} else {
|
||||
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
|
||||
@@ -218,7 +223,8 @@ impl App {
|
||||
let path = handle.path().to_path_buf();
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
|
||||
let action = action.clone();
|
||||
let message = DesktopWrapperMessage::IngestFile { path, content, action };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
|
||||
@@ -335,16 +341,10 @@ impl App {
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::ClipboardRead => {
|
||||
if let Some(window) = &self.window {
|
||||
let content = window.clipboard_read();
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
self.app_event_scheduler.schedule(AppEvent::ClipboardRead);
|
||||
}
|
||||
DesktopFrontendMessage::ClipboardWrite { content } => {
|
||||
if let Some(window) = &mut self.window {
|
||||
window.clipboard_write(content);
|
||||
}
|
||||
self.app_event_scheduler.schedule(AppEvent::ClipboardWrite { content });
|
||||
}
|
||||
DesktopFrontendMessage::PointerLock => {
|
||||
self.input_state.lock_pointer();
|
||||
@@ -467,6 +467,32 @@ impl App {
|
||||
self.ui_frame_received = true;
|
||||
}
|
||||
}
|
||||
AppEvent::ClipboardRead => {
|
||||
let result = event_loop.clipboard().and_then(|id| {
|
||||
let Some(id) = id else { return Ok(None) };
|
||||
let data_transfer = event_loop.data_transfer(id)?;
|
||||
if !data_transfer.has_type(&TypeHint::Plaintext) {
|
||||
return Ok(None);
|
||||
}
|
||||
event_loop.fetch_data_transfer(id, &TypeHint::Plaintext).map(Some)
|
||||
});
|
||||
match result {
|
||||
Ok(Some(serial)) => self.pending_clipboard_fetch = Some(serial),
|
||||
Ok(None) => self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None }),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
AppEvent::ClipboardWrite { content } => {
|
||||
let send_data = DataTransferSendBuilder::new(content)
|
||||
.with_type(TypeHint::Plaintext, |content: &String, _| Some(content.clone()))
|
||||
.build();
|
||||
if let Err(e) = event_loop.set_clipboard(send_data) {
|
||||
tracing::error!("Failed to write to clipboard: {e}");
|
||||
}
|
||||
}
|
||||
AppEvent::CursorChange(cursor) => {
|
||||
if let Some(window) = &mut self.window {
|
||||
window.set_cursor(event_loop, cursor);
|
||||
@@ -495,7 +521,11 @@ impl App {
|
||||
for path in paths {
|
||||
tracing::info!("Opening file: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
let message = DesktopWrapperMessage::IngestFile {
|
||||
path,
|
||||
content,
|
||||
action: IngestAction::Open,
|
||||
};
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
@@ -538,7 +568,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
// Handle pointer lock release
|
||||
if let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
@@ -601,20 +631,58 @@ impl ApplicationHandler for App {
|
||||
self.exit(Some(ExitReason::UiAccelerationFailure));
|
||||
}
|
||||
}
|
||||
WindowEvent::DragDropped { paths, .. } => {
|
||||
for path in paths {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::ImportFile { path, content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
WindowEvent::DragEntered { id, .. } => {
|
||||
let accepts = event_loop.data_transfer(id).is_ok_and(|data_transfer| data_transfer.has_type(&TypeHint::UriList));
|
||||
let actions: &[DndAction] = if accepts { &[DndAction::Copy] } else { &[] };
|
||||
if let Err(e) = event_loop.set_valid_dnd_actions(id, actions) {
|
||||
tracing::error!("Failed to set valid drag and drop actions: {e}");
|
||||
}
|
||||
}
|
||||
WindowEvent::DragDropped { id, .. } => match event_loop.fetch_data_transfer(id, &TypeHint::UriList) {
|
||||
Ok(serial) => self.pending_dnd_fetch = Some(serial),
|
||||
Err(e) => tracing::error!("Failed to fetch dropped data: {e}"),
|
||||
},
|
||||
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_clipboard_fetch == Some(serial) => match value.try_as_string() {
|
||||
Ok(content) => {
|
||||
self.pending_clipboard_fetch = None;
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content: Some(content) };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||
Err(e) => {
|
||||
self.pending_clipboard_fetch = None;
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
let message = DesktopWrapperMessage::ClipboardReadResult { content: None };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
},
|
||||
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_dnd_fetch == Some(serial) => match value.try_as_uris() {
|
||||
Ok(uris) => {
|
||||
self.pending_dnd_fetch = None;
|
||||
let paths = uris.iter().filter_map(|uri| url::Url::parse(uri).ok()?.to_file_path().ok());
|
||||
for path in paths {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::IngestFile {
|
||||
path,
|
||||
content,
|
||||
action: IngestAction::Import,
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||
Err(e) => {
|
||||
self.pending_dnd_fetch = None;
|
||||
tracing::error!("Failed to read dropped data: {e}");
|
||||
}
|
||||
},
|
||||
|
||||
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
|
||||
if !self.input_state.pointer_locked() && self.window_pending_drag =>
|
||||
|
||||
@@ -8,6 +8,10 @@ pub(crate) enum AppEvent {
|
||||
WebCommunicationInitialized,
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
ClipboardRead,
|
||||
ClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
Exit,
|
||||
UiCrashed,
|
||||
OpenFiles(Vec<std::path::PathBuf>),
|
||||
|
||||
@@ -221,6 +221,7 @@ impl InputState {
|
||||
let input = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => InputEvent::pointer().scrolled_lines(f64::from(*x), f64::from(*y)),
|
||||
MouseScrollDelta::PixelDelta(position) => InputEvent::pointer().scrolled_pixels(position.x, position.y),
|
||||
_ => return,
|
||||
};
|
||||
ui_callback(input.modifiers(self.modifiers).build());
|
||||
return;
|
||||
@@ -229,6 +230,7 @@ impl InputState {
|
||||
let (x, y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
|
||||
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
|
||||
_ => return,
|
||||
};
|
||||
|
||||
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
|
||||
|
||||
@@ -43,13 +43,6 @@ pub(crate) struct Window {
|
||||
#[allow(dead_code)]
|
||||
native_handle: native::NativeWindowImpl,
|
||||
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
|
||||
clipboard: Option<window_clipboard::Clipboard>,
|
||||
}
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
// Clipboard must be dropped before `winit_window`
|
||||
drop(self.clipboard.take());
|
||||
}
|
||||
}
|
||||
|
||||
impl Window {
|
||||
@@ -70,12 +63,10 @@ impl Window {
|
||||
|
||||
let winit_window = event_loop.create_window(attributes).unwrap();
|
||||
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
|
||||
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.ok();
|
||||
Self {
|
||||
winit_window: winit_window.into(),
|
||||
native_handle,
|
||||
custom_cursors: HashMap::new(),
|
||||
clipboard,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,28 +199,4 @@ impl Window {
|
||||
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
|
||||
self.native_handle.update_menu(entries);
|
||||
}
|
||||
|
||||
pub(crate) fn clipboard_read(&self) -> Option<String> {
|
||||
let Some(clipboard) = &self.clipboard else {
|
||||
tracing::error!("Clipboard not available");
|
||||
return None;
|
||||
};
|
||||
match clipboard.read() {
|
||||
Ok(data) => Some(data),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read from clipboard: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clipboard_write(&mut self, data: String) {
|
||||
let Some(clipboard) = &mut self.clipboard else {
|
||||
tracing::error!("Clipboard not available");
|
||||
return;
|
||||
};
|
||||
if let Err(e) = clipboard.write(data) {
|
||||
tracing::error!("Failed to write to clipboard: {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@
|
||||
name = "graphite-desktop-ui"
|
||||
description = "Renders the Graphite editor frontend UI into wgpu textures"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-wrapper"
|
||||
version = "0.1.0"
|
||||
description = "Graphite Desktop Wrapper"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
||||
|
||||
@@ -2,7 +2,7 @@ use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use graphite_editor::messages::prelude::*;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
|
||||
match message {
|
||||
@@ -15,14 +15,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
DesktopWrapperMessage::Input(message) => {
|
||||
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
|
||||
}
|
||||
DesktopWrapperMessage::FileDialogResult { path, content, context } => match context {
|
||||
OpenFileDialogContext::Open => {
|
||||
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenFile { path, content });
|
||||
}
|
||||
OpenFileDialogContext::Import => {
|
||||
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::IngestFile { path, content, action } => {
|
||||
dispatcher.queue_editor_message(IngestMessage::Ingest {
|
||||
data: content,
|
||||
action,
|
||||
mime_type: String::new(),
|
||||
path: Some(path),
|
||||
});
|
||||
}
|
||||
DesktopWrapperMessage::SaveFileDialogResult { path, context } => match context {
|
||||
SaveFileDialogContext::Document { document_id, content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: path.clone(), content });
|
||||
@@ -35,14 +35,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::OpenFile { path, content } => {
|
||||
let message = PortfolioMessage::OpenFile { path, content };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::ImportFile { path, content } => {
|
||||
let message = PortfolioMessage::ImportFile { path, content };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
|
||||
DesktopWrapperMessage::UpdateMaximized { maximized } => {
|
||||
let message = FrontendMessage::UpdateMaximized { maximized };
|
||||
|
||||
@@ -3,27 +3,23 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, OpenFileDialogContext, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, IngestAction, SaveFileDialogContext};
|
||||
|
||||
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
|
||||
match message {
|
||||
FrontendMessage::RenderOverlays { context } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
|
||||
}
|
||||
FrontendMessage::TriggerOpen { filters } => {
|
||||
FrontendMessage::TriggerBrowse { options, action } => {
|
||||
let title = match action {
|
||||
IngestAction::Open => "Open Document",
|
||||
IngestAction::Import => "Import File",
|
||||
_ => "Select File",
|
||||
};
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Open Document".to_string(),
|
||||
filters,
|
||||
multiple: true,
|
||||
context: OpenFileDialogContext::Open,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerImport { filters } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
|
||||
title: "Import File".to_string(),
|
||||
filters,
|
||||
multiple: false,
|
||||
context: OpenFileDialogContext::Import,
|
||||
title: title.to_string(),
|
||||
options,
|
||||
action,
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerSaveDocument {
|
||||
|
||||
@@ -3,9 +3,10 @@ use std::path::PathBuf;
|
||||
|
||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileFilter, PersistedState};
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileDialogOptions, FileFilter, PersistedState};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ScrollDelta};
|
||||
pub use graphite_editor::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
pub use graphite_editor::messages::prelude::DocumentId;
|
||||
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
|
||||
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
||||
@@ -15,9 +16,8 @@ pub enum DesktopFrontendMessage {
|
||||
OpenLaunchDocuments,
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
filters: Vec<FileFilter>,
|
||||
multiple: bool,
|
||||
context: OpenFileDialogContext,
|
||||
options: FileDialogOptions,
|
||||
action: IngestAction,
|
||||
},
|
||||
SaveFileDialog {
|
||||
title: String,
|
||||
@@ -87,10 +87,8 @@ pub enum DesktopWrapperMessage {
|
||||
FromWeb(Box<EditorMessage>),
|
||||
Wake,
|
||||
Input(InputMessage),
|
||||
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
|
||||
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
|
||||
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
|
||||
OpenFile { path: PathBuf, content: Vec<u8> },
|
||||
ImportFile { path: PathBuf, content: Vec<u8> },
|
||||
PollNodeGraphEvaluation,
|
||||
UpdateMaximized { maximized: bool },
|
||||
UpdateFullscreen { fullscreen: bool },
|
||||
@@ -103,12 +101,6 @@ pub enum DesktopWrapperMessage {
|
||||
LoadThirdPartyLicenses { text: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum OpenFileDialogContext {
|
||||
Open,
|
||||
Import,
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
Document { document_id: DocumentId, content: Vec<u8> },
|
||||
File { content: Vec<u8> },
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
[package]
|
||||
name = "document-container"
|
||||
description = "Container abstraction for the on-disk side of the .gdd document format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
[package]
|
||||
name = "document-format"
|
||||
description = "Typed handle for the .gdd document format, sitting over document-graph-storage and document-container"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
|
||||
@@ -15,11 +17,14 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
|
||||
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
|
||||
zip = ["document-container/zip"]
|
||||
xz = ["document-container/xz"]
|
||||
default = ["conversion", "zip", "xz"]
|
||||
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
|
||||
network = ["dep:peer-transport"]
|
||||
default = ["conversion", "zip", "xz", "network"]
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-graph-storage = { workspace = true, default-features = false }
|
||||
peer-transport = { workspace = true, optional = true }
|
||||
graph-craft = { workspace = true, optional = true }
|
||||
graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
|
||||
@@ -47,4 +47,8 @@ pub enum Error {
|
||||
/// An export marked a resource for embedding but its bytes were absent from the byte store.
|
||||
#[error("embedded resource {0} missing from the byte store")]
|
||||
MissingResource(ResourceHash),
|
||||
/// A packet for the collaboration session failed to encode.
|
||||
#[cfg(feature = "network")]
|
||||
#[error("network error: {0}")]
|
||||
Network(#[from] peer_transport::PacketError),
|
||||
}
|
||||
@@ -150,6 +150,7 @@ impl<L: Layout> Gdd<L> {
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
next_hot_sequence: self.session.next_hot_sequence(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
|
||||
+67
-19
@@ -20,7 +20,7 @@ use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
use graphene_resource::{ResourceHash, ResourceStorage};
|
||||
|
||||
pub mod codec;
|
||||
pub mod error;
|
||||
@@ -28,6 +28,8 @@ pub mod export;
|
||||
pub mod io;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
#[cfg(feature = "network")]
|
||||
pub mod network;
|
||||
pub mod persist;
|
||||
pub mod resource;
|
||||
pub mod session_state;
|
||||
@@ -68,8 +70,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
|
||||
/// read.
|
||||
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
|
||||
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared.
|
||||
#[derive(Clone)]
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
|
||||
/// not carried over, so a clone is a read-only copy for asynchronous writes.
|
||||
pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) session: Session,
|
||||
pub(crate) working: Arc<AnyContainer>,
|
||||
@@ -84,6 +86,42 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
|
||||
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
|
||||
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
|
||||
/// Where this document's resource bytes live. `None` means the working copy's own content-addressed
|
||||
/// store, which is what a standalone handle uses. The editor points this at its application-wide
|
||||
/// cache, the single store resources are kept in there.
|
||||
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) network: Option<peer_transport::Replica>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) pending_persist: PendingPersist,
|
||||
}
|
||||
|
||||
/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs
|
||||
/// one rewrite of each file rather than one per packet.
|
||||
#[cfg(feature = "network")]
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub(crate) struct PendingPersist {
|
||||
pub(crate) history: bool,
|
||||
pub(crate) hot_log: bool,
|
||||
pub(crate) snapshot: bool,
|
||||
}
|
||||
|
||||
impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
session: self.session.clone(),
|
||||
working: self.working.clone(),
|
||||
layout: self.layout.clone(),
|
||||
manifest: self.manifest.clone(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
byte_store: self.byte_store.clone(),
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||
@@ -144,7 +182,15 @@ impl<L: Layout> Gdd<L> {
|
||||
(true, true) => {
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
let history = load_history(&working, &layout, codecs.history).await?;
|
||||
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
Session::load(
|
||||
peer,
|
||||
registry,
|
||||
history,
|
||||
session_state.head_rev,
|
||||
session_state.redo_stack,
|
||||
session_state.next_node_counter,
|
||||
session_state.next_hot_sequence,
|
||||
)
|
||||
}
|
||||
(true, false) => {
|
||||
// Registry-only export: synthesize a history that reproduces this state.
|
||||
@@ -168,6 +214,11 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
byte_store: None,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -190,6 +241,11 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
byte_store: None,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -292,24 +348,16 @@ impl<L: Layout> Gdd<L> {
|
||||
(working, self.layout)
|
||||
}
|
||||
|
||||
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
|
||||
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
|
||||
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
|
||||
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
|
||||
/// because resource loads are.
|
||||
/// Resolve every proto-node declaration referenced by the registry or its history into a
|
||||
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
|
||||
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
|
||||
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
|
||||
use document_graph_storage::Implementation;
|
||||
|
||||
let registry = self.session.registry();
|
||||
let mut declarations = document_graph_storage::Declarations::new();
|
||||
|
||||
for node in registry.node_instances.values() {
|
||||
let Implementation::ProtoNode(id) = node.implementation() else { continue };
|
||||
if declarations.contains_key(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
|
||||
for (id, hash) in self.session.all_declaration_resources() {
|
||||
let Some(hash) = hash else {
|
||||
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
||||
continue;
|
||||
};
|
||||
@@ -319,7 +367,7 @@ impl<L: Layout> Gdd<L> {
|
||||
};
|
||||
match document_graph_storage::decode_declaration(resource.as_ref()) {
|
||||
Ok(proto) => {
|
||||
declarations.insert(*id, proto);
|
||||
declarations.insert(id, proto);
|
||||
}
|
||||
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
|
||||
//! then broadcasts staged hot ops and (as host) retired deltas, and `poll_peers` applies what peers
|
||||
//! send through the [`SyncTarget`] impl below, which persists inbound state the same way local
|
||||
//! edits are.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session, UserId};
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::{Gdd, PendingPersist};
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
|
||||
self.network = Some(Replica::host(transport, self.session.peer(), user));
|
||||
}
|
||||
|
||||
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
|
||||
self.network = Some(Replica::guest(transport, self.session.peer(), user));
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
if let Some(mut replica) = self.network.take() {
|
||||
replica.leave();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.network.as_ref().map(Replica::role)
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.network.as_ref().is_none_or(Replica::is_synced)
|
||||
}
|
||||
|
||||
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
|
||||
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);
|
||||
self.network = Some(replica);
|
||||
events
|
||||
}
|
||||
|
||||
/// Answer an [`Event::ResourceRequested`].
|
||||
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_resource(to, hash, bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
fn peer(&self) -> PeerId {
|
||||
self.session.peer()
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
self.session.head_rev()
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
self.session.retired_registry().clone()
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
self.session.hot_log().to_vec()
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
self.session.known_revs()
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
self.session.delta(rev).is_some()
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
|
||||
<Session as SyncTarget>::deltas_unknown_to(&self.session, known)
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
self.session.load(registry, history, head)?;
|
||||
self.pending_persist = PendingPersist {
|
||||
history: true,
|
||||
hot_log: true,
|
||||
snapshot: true,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
// An op naming an entity that has not arrived here yet is handed back for a later retry, so only
|
||||
// what actually applied reaches the hot frame log.
|
||||
let mut deferred = Vec::new();
|
||||
for hot_op in ops {
|
||||
if self.session.replay_hot_op(hot_op.clone()).is_err() {
|
||||
deferred.push(hot_op);
|
||||
continue;
|
||||
}
|
||||
self.append_hot_frame(&hot_op)?;
|
||||
}
|
||||
|
||||
Ok(deferred)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
|
||||
self.session.merge_remote(deltas, retires)?;
|
||||
|
||||
// Whatever a peer sent is shared by definition, so it sits behind the published frontier too: a
|
||||
// guest must no more silently rewind the host's history than the host may rewind its own.
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.hot_log |= !retires.is_empty();
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
SyncTarget::retired_marks(&self.session)
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
SyncTarget::absorb_retired_marks(&mut self.session, remote)?;
|
||||
self.pending_persist.hot_log = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
let pending = std::mem::take(&mut self.pending_persist);
|
||||
|
||||
if pending.history {
|
||||
self.rewrite_history()?;
|
||||
}
|
||||
if pending.hot_log {
|
||||
self.rewrite_hot_log()?;
|
||||
}
|
||||
if pending.snapshot {
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
self.unstored_resources().into_iter().collect()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
self.hold_resource(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp};
|
||||
use document_graph_storage::{HotOp, RegistryDelta, Rev, TimeStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -47,7 +47,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
|
||||
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
|
||||
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
|
||||
/// interaction.
|
||||
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
|
||||
@@ -60,19 +60,34 @@ impl<L: Layout> Gdd<L> {
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
// identical bytes on every commit is an idempotent no-op.
|
||||
for bytes in declaration_bytes.values() {
|
||||
for bytes in conversion.declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(conversion.declarations)
|
||||
}
|
||||
|
||||
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
|
||||
let hot_ops = self.session.stage_ops(ops)?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -159,7 +174,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
|
||||
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
|
||||
fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for delta in self.session.history() {
|
||||
self.manifest.codecs.history.append(&mut buffer, delta)?;
|
||||
@@ -168,13 +183,14 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
next_hot_sequence: self.session.next_hot_sequence(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
@@ -186,7 +202,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
|
||||
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
|
||||
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
pub(crate) fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -215,7 +231,7 @@ impl<L: Layout> Gdd<L> {
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
@@ -232,6 +248,12 @@ impl<L: Layout> Gdd<L> {
|
||||
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
|
||||
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
|
||||
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
|
||||
let new_revs = self.session.retire(up_to)?;
|
||||
|
||||
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
|
||||
@@ -239,21 +261,51 @@ impl<L: Layout> Gdd<L> {
|
||||
self.session.mark_interaction_end(last);
|
||||
}
|
||||
|
||||
// In a session these deltas are about to reach peers, so the published frontier moves with them.
|
||||
// Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire
|
||||
// to tell them, so undo past this point has to go through forward inverse ops instead. Set before
|
||||
// the persists below so the frontier survives a reopen.
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
&& let Some(&last) = new_revs.last()
|
||||
{
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
|
||||
if !new_revs.is_empty() {
|
||||
self.append_history_deltas(&new_revs)?;
|
||||
}
|
||||
|
||||
// Rewrite hot log with whatever survived retirement.
|
||||
let mut hot_buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
|
||||
}
|
||||
self.working
|
||||
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
|
||||
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
replica.broadcast_retired(&deltas, &retired_hot_ops)?;
|
||||
}
|
||||
|
||||
Ok(new_revs)
|
||||
}
|
||||
|
||||
/// Guests leave retirement to the session host and keep their hot ops until the host's retired
|
||||
/// deltas arrive.
|
||||
fn retires_locally(&self) -> bool {
|
||||
#[cfg(feature = "network")]
|
||||
{
|
||||
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
|
||||
}
|
||||
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,36 @@ impl<L: Layout> Gdd<L> {
|
||||
{
|
||||
ResourceProxy(self.working.clone(), self.layout.clone())
|
||||
}
|
||||
|
||||
/// Point resource lookups at an external store instead of the working copy, for an embedder that
|
||||
/// already keeps one cache for every open document.
|
||||
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
|
||||
self.byte_store = Some(byte_store);
|
||||
}
|
||||
|
||||
/// Whether this document's resource bytes are on hand, in whichever store backs it.
|
||||
pub fn holds_resource(&self, hash: &ResourceHash) -> bool {
|
||||
match &self.byte_store {
|
||||
Some(byte_store) => byte_store.contains(hash),
|
||||
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put resource bytes into whichever store backs this document.
|
||||
pub fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
|
||||
match &self.byte_store {
|
||||
Some(byte_store) => {
|
||||
byte_store.store(bytes);
|
||||
Ok(())
|
||||
}
|
||||
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resources the registry or its history names whose bytes are not on hand.
|
||||
pub fn unstored_resources(&self) -> Vec<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
@@ -104,6 +134,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
|
||||
|
||||
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
|
||||
@@ -31,6 +31,10 @@ pub struct SessionState {
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// How many hot ops this peer has authored, feeding `HotOp::sequence`. Persisted so a reopen
|
||||
/// continues the run: a reused sequence would look like one already retired and be dropped.
|
||||
#[serde(default)]
|
||||
pub next_hot_sequence: u64,
|
||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
|
||||
@@ -128,6 +128,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: 1,
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -154,6 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: 1,
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -161,6 +163,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
sequence: 2,
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
@@ -200,6 +203,7 @@ fn last_broadcast_rev_persists_across_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: 1,
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
@@ -655,6 +659,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: 1,
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
[package]
|
||||
name = "document-graph-storage"
|
||||
description = "Provides a delta based graph representation used in the Graphite file format"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
conversion = ["dep:graph-craft", "dep:core-types"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
|
||||
apply_attribute_delta, reverse_attribute_delta,
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, RetiredMarks, Rev,
|
||||
SourceValue, TimeStamp, apply_attribute_delta, reverse_attribute_delta,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -11,6 +11,10 @@ pub struct Document {
|
||||
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
||||
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// Which hot ops history already covers, so one that arrives after its own retirement is recognized
|
||||
/// and dropped rather than re-entering the hot log for good. Retirement discards the link from a
|
||||
/// delta back to the hot op it came from, so this is the only record of it. See [`RetiredMarks`].
|
||||
pub(crate) retired: RetiredMarks,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
|
||||
@@ -36,6 +40,8 @@ pub struct Document {
|
||||
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||
/// reading the same counter still produce distinct IDs.
|
||||
pub(crate) next_node_counter: u64,
|
||||
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
|
||||
pub(crate) next_hot_sequence: u64,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -66,24 +72,16 @@ impl Document {
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
/// Search every delta reachable from `head` (following all parents, including a merge's
|
||||
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
|
||||
/// ancestry reachability, so a node added only on a merged-in branch is still found.
|
||||
/// The last delta in canonical history order matching `predicate`, among those reachable from `head`
|
||||
/// or any history tip (following all parents, including a merge's `extra_parents`). Tips cover deltas
|
||||
/// absorbed mid-merge that `head` doesn't reach yet.
|
||||
///
|
||||
/// Resurrection reads the removed entity out of the match, so every peer has to pick the same one.
|
||||
/// Canonical order is agreed; a walk from `head` is not, since peers sit on different merge revs.
|
||||
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
|
||||
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
|
||||
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
|
||||
while let Some(rev) = queue.pop_front() {
|
||||
let Some(delta) = self.history.get(rev) else { continue };
|
||||
if predicate(delta) {
|
||||
return Some(delta.clone());
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
if seen.insert(parent) {
|
||||
queue.push_back(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
let reachable = self.history.ancestors(self.head.into_iter().chain(self.history.tips()));
|
||||
|
||||
self.history.iter().filter(|delta| reachable.contains(&delta.id) && predicate(delta)).last().cloned()
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
@@ -111,11 +109,55 @@ impl Document {
|
||||
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
|
||||
/// than an error.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
// Its effect is already in retired history, and re-adding it would leave an entry no retirement
|
||||
// list will ever name.
|
||||
if self.is_retired(hot_op.id()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// A hot op is identified by its timestamp, so a re-announcement of one already held is a no-op
|
||||
// rather than a second copy that replays and re-broadcasts as though it were new work.
|
||||
if self.hot_log.iter().any(|held| held.timestamp == hot_op.timestamp) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Replaying our own persisted ops after a reload is what restores the sequence counter.
|
||||
if hot_op.timestamp.peer == self.peer {
|
||||
self.next_hot_sequence = self.next_hot_sequence.max(hot_op.sequence);
|
||||
}
|
||||
|
||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether this hot op has already been promoted into history.
|
||||
pub(crate) fn is_retired(&self, id: HotOpId) -> bool {
|
||||
self.retired.covers(id)
|
||||
}
|
||||
|
||||
/// Record newly retired hot ops, dropping any the hot log still holds.
|
||||
pub(crate) fn mark_retired(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
self.retired.extend(retired);
|
||||
|
||||
self.drop_retired_hot_ops();
|
||||
}
|
||||
|
||||
/// Take on another peer's retirement marks as well as this peer's.
|
||||
pub(crate) fn absorb_retired(&mut self, remote: &RetiredMarks) {
|
||||
self.retired.absorb(remote);
|
||||
|
||||
self.drop_retired_hot_ops();
|
||||
}
|
||||
|
||||
/// Drop hot ops history already covers, so a retired op never sits in the hot log whatever path
|
||||
/// put it there.
|
||||
fn drop_retired_hot_ops(&mut self) {
|
||||
let retired = std::mem::take(&mut self.retired);
|
||||
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
|
||||
self.retired = retired;
|
||||
}
|
||||
|
||||
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
|
||||
/// targets, Remove on missing ones) since hot ops already produced the structural state.
|
||||
/// The point is to bump field timestamps to T_retire via the LWW arms.
|
||||
@@ -296,7 +338,7 @@ impl Document {
|
||||
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
|
||||
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
|
||||
/// before the node. No-op for ops that reference nothing absent.
|
||||
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||
pub(crate) fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||
match op {
|
||||
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
@@ -321,17 +363,50 @@ impl Document {
|
||||
}
|
||||
|
||||
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
self.restore_node_from_history(target, node_id)?;
|
||||
if self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
return Ok(());
|
||||
}
|
||||
Ok(())
|
||||
let removal = self.hot_log_node_removal(target, node_id);
|
||||
match removal {
|
||||
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
|
||||
None => self.restore_node_from_history(target, node_id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The most recent hot removal of a network, for reviving it in the working zone. Returns `None`
|
||||
/// for the snapshot, which must stay a function of history alone.
|
||||
fn hot_log_removal(&self, target: RegistryTarget, network_id: NetworkId) -> Option<(RegistryDelta, TimeStamp)> {
|
||||
if target != RegistryTarget::Working {
|
||||
return None;
|
||||
}
|
||||
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } if *id == network_id => Some((RegistryDelta::AddNetwork { id: *id, network: snapshot.clone() }, hot_op.timestamp)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The node equivalent of [`hot_log_removal`](Self::hot_log_removal).
|
||||
fn hot_log_node_removal(&self, target: RegistryTarget, node_id: NodeId) -> Option<(RegistryDelta, TimeStamp)> {
|
||||
if target != RegistryTarget::Working {
|
||||
return None;
|
||||
}
|
||||
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
|
||||
RegistryDelta::RemoveNode { id, snapshot } if *id == node_id => Some((RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, hot_op.timestamp)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
self.restore_network_from_history(target, network_id)?;
|
||||
if self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
return Ok(());
|
||||
}
|
||||
// The hot log is this peer's own, so reviving the snapshot zone from it would make the retired
|
||||
// state depend on which hot ops happened to be here. Only history is shared.
|
||||
let removal = self.hot_log_removal(target, network_id);
|
||||
match removal {
|
||||
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
|
||||
None => self.restore_network_from_history(target, network_id),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
|
||||
@@ -89,33 +89,17 @@ impl TryFrom<&NodeNetwork> for Registry {
|
||||
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
|
||||
|
||||
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
|
||||
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
|
||||
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
|
||||
/// the `ResourceId`/`ResourceHash` references.
|
||||
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
|
||||
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
|
||||
pub struct RuntimeConversion {
|
||||
pub registry: Registry,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
pub declarations: crate::Declarations,
|
||||
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
|
||||
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
|
||||
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||
}
|
||||
|
||||
impl RuntimeConversion {
|
||||
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
|
||||
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
|
||||
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
|
||||
/// their byte store instead.
|
||||
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
|
||||
self.declaration_bytes
|
||||
.iter()
|
||||
.map(|(hash, bytes)| {
|
||||
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
|
||||
Ok((ResourceId::from_hash(hash), proto))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
|
||||
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
|
||||
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
|
||||
@@ -149,6 +133,7 @@ impl Registry {
|
||||
let mut ctx = ConversionContext {
|
||||
declaration_ids: HashMap::new(),
|
||||
declaration_bytes: HashMap::new(),
|
||||
declarations: HashMap::new(),
|
||||
network_ids: HashMap::new(),
|
||||
metadata,
|
||||
peer,
|
||||
@@ -167,6 +152,7 @@ impl Registry {
|
||||
Ok(RuntimeConversion {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
@@ -254,6 +240,8 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
|
||||
declaration_ids: HashMap<String, ResourceId>,
|
||||
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
|
||||
declaration_bytes: DeclarationBytes,
|
||||
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
|
||||
declarations: crate::Declarations,
|
||||
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
|
||||
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
|
||||
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
|
||||
@@ -555,6 +543,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
|
||||
register_declaration_resource(registry, id, hash, ctx.peer);
|
||||
ctx.declaration_bytes.insert(hash, bytes);
|
||||
ctx.declarations.insert(id, proto);
|
||||
ctx.declaration_ids.insert(identifier_str, id);
|
||||
|
||||
Implementation::ProtoNode(id)
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
|
||||
//! which re-sorts the combined set into the canonical order to restore the invariant.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
|
||||
|
||||
@@ -64,22 +64,13 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
fn canonical_sort(&mut self) {
|
||||
///
|
||||
/// The sort is deterministic, so two peers that absorb the same delta set produce byte-identical
|
||||
/// history, not merely two different valid orderings. This is the history-convergence mechanism:
|
||||
/// arrival order is erased.
|
||||
pub fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
@@ -119,6 +110,51 @@ impl History {
|
||||
}
|
||||
}
|
||||
|
||||
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
|
||||
pub fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
|
||||
while let Some(rev) = stack.pop() {
|
||||
if !seen.insert(rev) {
|
||||
continue;
|
||||
}
|
||||
if let Some(delta) = self.get(rev) {
|
||||
stack.extend(delta.all_parents());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
pub fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
|
||||
self.ancestors([descendant]).contains(&ancestor)
|
||||
}
|
||||
|
||||
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
|
||||
/// so it can locate the divergence point within a factor of two of the true distance.
|
||||
pub fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
|
||||
let mut samples = vec![tip];
|
||||
let mut current = tip;
|
||||
let mut distance = 0;
|
||||
let mut next_sample_distance = 1;
|
||||
|
||||
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
|
||||
current = parent;
|
||||
distance += 1;
|
||||
if distance == next_sample_distance {
|
||||
samples.push(current);
|
||||
next_sample_distance *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
samples
|
||||
}
|
||||
|
||||
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
|
||||
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
|
||||
let known = self.ancestors(known);
|
||||
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
|
||||
@@ -43,6 +43,27 @@ impl Node {
|
||||
attributes_value_equal(&self.attributes, &other.attributes)
|
||||
}
|
||||
|
||||
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
|
||||
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
|
||||
/// slot by position.
|
||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
||||
let slot = InputSlot {
|
||||
input: NodeInput::Value {
|
||||
value: serde_json::Value::Null,
|
||||
exposed: false,
|
||||
},
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Attributes::new(),
|
||||
};
|
||||
|
||||
Self {
|
||||
implementation,
|
||||
inputs: vec![slot; inputs],
|
||||
attributes: Attributes::new(),
|
||||
network,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dummy() -> Self {
|
||||
Self {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use crate::{ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -16,6 +16,9 @@ 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 registry the runtime was last built from or staged to. Local diffs are taken against it,
|
||||
/// so edits peers applied to the working registry in the meantime are not diffed away.
|
||||
runtime_base: Option<Registry>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -36,14 +39,17 @@ impl Session {
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
retired: RetiredMarks::default(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
next_hot_sequence: 0,
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,8 +70,7 @@ impl Session {
|
||||
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
|
||||
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
|
||||
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
|
||||
/// proto-node declaration bytes the conversion extracted, keyed by content hash, for the caller
|
||||
/// to persist into its byte store (`document-graph-storage` itself is byte-unaware).
|
||||
/// conversion, whose extracted declarations the caller persists and caches.
|
||||
///
|
||||
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
|
||||
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
||||
@@ -76,11 +81,18 @@ impl Session {
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::DeclarationBytes), CommitError> {
|
||||
) -> 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 base = self.runtime_base.as_ref().unwrap_or(&self.document.working_registry);
|
||||
let ops = crate::delta::compute_deltas(base, &conversion.registry);
|
||||
self.runtime_base = Some(conversion.registry.clone());
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
Ok((hot_ops, conversion.declaration_bytes))
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
/// Record that the runtime now reflects the working registry, after the caller rebuilt it from there.
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.runtime_base = Some(self.document.working_registry.clone());
|
||||
}
|
||||
|
||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
||||
@@ -136,7 +148,7 @@ impl Session {
|
||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||
/// `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 — registration rides a real edit.
|
||||
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -149,9 +161,11 @@ impl Session {
|
||||
|
||||
let mut staged = Vec::with_capacity(pending.len());
|
||||
for op in pending {
|
||||
self.document.next_hot_sequence += 1;
|
||||
let hot_op = HotOp {
|
||||
op,
|
||||
timestamp: self.document.clock.tick(),
|
||||
sequence: self.document.next_hot_sequence,
|
||||
};
|
||||
self.document.apply_hot_op(hot_op.clone())?;
|
||||
staged.push(hot_op);
|
||||
@@ -181,6 +195,8 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
// The reverse must read the pre-op value of a target that may have been concurrently removed.
|
||||
self.document.ensure_referenced_exist(target, &op)?;
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let timestamp = self.document.clock.tick();
|
||||
let parent = self.document.head;
|
||||
@@ -208,7 +224,7 @@ impl Session {
|
||||
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
||||
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
||||
/// (topological) order.
|
||||
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64, next_hot_sequence: u64) -> Self {
|
||||
let mut clock = LamportClock::new(peer);
|
||||
for delta in &history {
|
||||
clock.observe(delta.timestamp);
|
||||
@@ -222,14 +238,17 @@ impl Session {
|
||||
working_registry: registry,
|
||||
history: History::from_ordered(history),
|
||||
hot_log: Vec::new(),
|
||||
retired: RetiredMarks::default(),
|
||||
head,
|
||||
redo_stack,
|
||||
clock,
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter,
|
||||
next_hot_sequence,
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,47 +270,124 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Apply a hot op without going through the broadcast stream.
|
||||
/// Apply a hot op received from another peer.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.apply_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// The hot ops a `retire(up_to)` call would drain. Broadcast alongside the retired deltas so guests
|
||||
/// drop exactly these; a cutoff alone doesn't transfer, since a lagging peer's op can carry a
|
||||
/// timestamp below the cutoff yet reach the host only after that retirement.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
}
|
||||
|
||||
/// Drop hot ops another peer has retired without retiring them locally.
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) {
|
||||
self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id()));
|
||||
// How a peer that did not retire these learns they are in history now.
|
||||
self.document.mark_retired(retired.iter().copied());
|
||||
}
|
||||
|
||||
/// Which hot ops history already covers, for a peer catching up. See [`RetiredMarks`].
|
||||
pub fn retired_marks(&self) -> &RetiredMarks {
|
||||
&self.document.retired
|
||||
}
|
||||
|
||||
/// Take on another peer's retirement marks as well as this peer's.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
|
||||
self.document.absorb_retired(remote);
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
/// where the registry may already reflect the op's effect from a prior retired snapshot.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
/// Rebuild both registries by refolding canonically sorted history, then re-layering the hot tail.
|
||||
/// Every peer sorts history the same way, so the result no longer depends on the order deltas
|
||||
/// happened to arrive in. Costs a full replay, so callers check that it is needed first.
|
||||
fn refold_registries(&mut self) -> Result<(), CrdtError> {
|
||||
let replay: Vec<(RegistryDelta, TimeStamp)> = self.document.history.iter().map(|delta| (delta.kind.clone(), delta.timestamp)).collect();
|
||||
|
||||
self.document.retired_snapshot = Registry::default();
|
||||
for (kind, timestamp) in replay {
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, kind, timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
|
||||
// A hot op the refold left unapplicable is kept rather than dropped, since a later delta or hot
|
||||
// op can still supply the referent it names.
|
||||
self.document.working_registry = self.document.retired_snapshot.clone();
|
||||
let mut failure = None;
|
||||
for hot_op in std::mem::take(&mut self.document.hot_log) {
|
||||
if let Err(error) = self.document.replay_hot_op(hot_op.clone()) {
|
||||
self.document.hot_log.push(hot_op);
|
||||
failure = failure.or(Some(error));
|
||||
}
|
||||
}
|
||||
|
||||
match failure {
|
||||
Some(error) => Err(error),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
|
||||
/// without a new delta when the incoming history extends it, otherwise joins `head` and the
|
||||
/// incoming tips with a [`RegistryDelta::Merge`].
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
|
||||
let length_before = self.document.history.len();
|
||||
|
||||
// Each delta enters history before the next is applied, so a later delta in the batch that
|
||||
// targets something an earlier one removed can resurrect it.
|
||||
let mut absorbed_ids = HashSet::new();
|
||||
let mut arrival_order = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
arrival_order.push(delta.id);
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
// The working registry is the snapshot plus the hot tail, so a retired delta lands on both
|
||||
// rather than cloning one over the other, which would promote unretired hot ops.
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
absorbed_ids.insert(delta.id);
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
if absorbed_ids.is_empty() {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
|
||||
// The registries were folded in arrival order, and concurrent ops do not all commute: a remove
|
||||
// and a change to the same target resolve by whichever lands second. Refold unless the sort
|
||||
// happened to leave the batch appended in the order it was applied.
|
||||
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
|
||||
if !folded_in_canonical_order {
|
||||
self.refold_registries()?;
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
let history = &self.document.history;
|
||||
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
|
||||
candidates.extend(self.document.head);
|
||||
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
|
||||
let parents: Vec<Rev> = candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect();
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
let outcome = match parents.as_slice() {
|
||||
[tip] => MergeOutcome::FastForward(*tip),
|
||||
_ => {
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(parents, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
|
||||
self.document.history.push(merge);
|
||||
MergeOutcome::Merged(merge_rev)
|
||||
}
|
||||
};
|
||||
self.document.head = outcome.head();
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
|
||||
@@ -299,6 +395,8 @@ impl Session {
|
||||
///
|
||||
/// Today: one retired delta per hot op. Coarsening is a future step.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
// Drained in hot-log order, which is causal, so the deltas commit in an order their references
|
||||
// survive.
|
||||
let mut drained = Vec::new();
|
||||
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
|
||||
for hot_op in self.document.hot_log.drain(..) {
|
||||
@@ -309,6 +407,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
self.document.hot_log = remaining;
|
||||
self.document.mark_retired(drained.iter().map(HotOp::id));
|
||||
|
||||
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
|
||||
}
|
||||
@@ -374,6 +473,8 @@ impl Session {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
// The caller rebuilds the runtime from the rewound registry; until then diff against it directly.
|
||||
self.runtime_base = None;
|
||||
|
||||
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
|
||||
// interaction's boundary (its `interaction_end` delta) or the root.
|
||||
@@ -382,7 +483,11 @@ impl Session {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
let parent = delta.parent;
|
||||
|
||||
self.document.revert_delta(RegistryTarget::Working, delta)?;
|
||||
self.document.revert_delta(RegistryTarget::Working, delta.clone())?;
|
||||
// The working registry is the snapshot plus the hot tail, so rewind both rather than copying
|
||||
// one over the other, which would promote unretired hot ops into retired state.
|
||||
self.document.revert_delta(RegistryTarget::Snapshot, delta)?;
|
||||
|
||||
self.document.head = parent;
|
||||
|
||||
match parent {
|
||||
@@ -392,9 +497,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
|
||||
// working registry (the next interaction's reverses are computed against it).
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -404,6 +506,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);
|
||||
@@ -418,11 +521,11 @@ impl Session {
|
||||
// at the same timestamp. Symmetric with `revert_delta`.
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
// Both zones move together, for the same reason `undo` rewinds both.
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Force)?;
|
||||
}
|
||||
self.document.head = Some(checkpoint);
|
||||
|
||||
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
@@ -442,6 +545,17 @@ impl Session {
|
||||
self.document.history.iter()
|
||||
}
|
||||
|
||||
/// Revs sampled at exponentially growing distances behind `head`, for a remote peer to locate what
|
||||
/// this session is missing (see [`History::sample_chain`]).
|
||||
pub fn known_revs(&self) -> Vec<Rev> {
|
||||
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Retired deltas not reachable from `known`, in replay order.
|
||||
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
|
||||
self.document.history.deltas_unknown_to(known)
|
||||
}
|
||||
|
||||
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
|
||||
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
|
||||
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -473,6 +587,40 @@ impl Session {
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Every proto-node declaration resource referenced by the current registry or anywhere in history,
|
||||
/// with its content hash, or `None` where the hash never resolved.
|
||||
pub fn all_declaration_resources(&self) -> HashMap<ResourceId, Option<ResourceHash>> {
|
||||
let registry = &self.document.working_registry;
|
||||
|
||||
let mut hashes: HashMap<ResourceId, ResourceHash> = registry.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect();
|
||||
for delta in self.document.history.iter() {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { id, entry } => hashes.extend(entry.hash.map(|hash| (*id, hash))),
|
||||
RegistryDelta::RemoveResource { id, snapshot } => hashes.extend(snapshot.hash.map(|hash| (*id, hash))),
|
||||
RegistryDelta::SetResourceHash { id, hash: Some(hash) } => {
|
||||
hashes.insert(*id, *hash);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let current_nodes = registry.node_instances.values();
|
||||
let historic_nodes = self.document.history.iter().filter_map(|delta| match &delta.kind {
|
||||
RegistryDelta::AddNode { node, .. } => Some(node),
|
||||
RegistryDelta::RemoveNode { snapshot, .. } => Some(snapshot),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
current_nodes
|
||||
.chain(historic_nodes)
|
||||
.filter_map(|node| match node.implementation() {
|
||||
Implementation::ProtoNode(id) => Some(*id),
|
||||
Implementation::Network(_) => None,
|
||||
})
|
||||
.map(|id| (id, hashes.get(&id).copied()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn hot_log(&self) -> &[HotOp] {
|
||||
&self.document.hot_log
|
||||
}
|
||||
@@ -514,6 +662,12 @@ impl Session {
|
||||
pub fn next_node_counter(&self) -> u64 {
|
||||
self.document.next_node_counter
|
||||
}
|
||||
|
||||
/// How many hot ops this peer has authored. Persisted and carried across a reload so a fresh op
|
||||
/// never reuses a sequence an earlier one already spent. See [`HotOp::sequence`].
|
||||
pub fn next_hot_sequence(&self) -> u64 {
|
||||
self.document.next_hot_sequence
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors from `Session::commit_from_runtime`.
|
||||
@@ -533,12 +687,109 @@ impl Default for Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MergeOutcome {
|
||||
NoOp,
|
||||
FastForward(Rev),
|
||||
Merged(Rev),
|
||||
}
|
||||
|
||||
impl MergeOutcome {
|
||||
/// The head after the merge, or `None` when nothing changed.
|
||||
pub fn head(self) -> Option<Rev> {
|
||||
match self {
|
||||
Self::NoOp => None,
|
||||
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
|
||||
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct HotOp {
|
||||
pub op: RegistryDelta,
|
||||
pub timestamp: TimeStamp,
|
||||
/// Position in its author's own run of hot ops, counting from 1 with no gaps. The Lamport counter
|
||||
/// skips whenever a higher remote timestamp is observed, so it cannot tell a missing op from a
|
||||
/// skipped tick; this can, which is what lets a watermark stand for a contiguous prefix.
|
||||
pub sequence: u64,
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Identifies the op for retirement, which tracks a contiguous prefix per author.
|
||||
pub fn id(&self) -> HotOpId {
|
||||
HotOpId {
|
||||
peer: self.timestamp.peer,
|
||||
sequence: self.sequence,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One hot op's author and position in that author's run. Retirement names the ops it promoted with
|
||||
/// these rather than with timestamps, so a receiver can tell which prefix history now covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct HotOpId {
|
||||
pub peer: PeerId,
|
||||
pub sequence: u64,
|
||||
}
|
||||
|
||||
/// Which hot ops history already covers. `through` is how far each author's run has retired without a
|
||||
/// gap, and `above` names the retired ops past that point, which is where an op lands when it retires
|
||||
/// before an earlier one from the same author has arrived. Replicated so a peer catching up can tell
|
||||
/// an op already in the history it was handed from one still owed to it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RetiredMarks {
|
||||
pub through: HashMap<PeerId, u64>,
|
||||
pub above: HashSet<HotOpId>,
|
||||
}
|
||||
|
||||
impl RetiredMarks {
|
||||
/// Whether history already holds this hot op.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
self.through.get(&id.peer).is_some_and(|&through| id.sequence <= through) || self.above.contains(&id)
|
||||
}
|
||||
|
||||
/// Take on `remote`'s coverage as well as this one's.
|
||||
pub fn absorb(&mut self, remote: &Self) {
|
||||
for (&peer, &remote_through) in &remote.through {
|
||||
let through = self.through.entry(peer).or_default();
|
||||
*through = (*through).max(remote_through);
|
||||
}
|
||||
self.above.extend(remote.above.iter().copied());
|
||||
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Record newly retired ops.
|
||||
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
self.above.extend(retired);
|
||||
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Fold every exception that continues its author's prefix into `through`, so the set only ever
|
||||
/// holds ops still separated from the prefix by a gap.
|
||||
fn compact(&mut self) {
|
||||
let mut by_author: HashMap<PeerId, Vec<u64>> = HashMap::new();
|
||||
for id in &self.above {
|
||||
by_author.entry(id.peer).or_default().push(id.sequence);
|
||||
}
|
||||
|
||||
for (peer, mut sequences) in by_author {
|
||||
sequences.sort_unstable();
|
||||
let through = self.through.entry(peer).or_default();
|
||||
for sequence in sequences {
|
||||
if sequence == *through + 1 {
|
||||
*through = sequence;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let through = std::mem::take(&mut self.through);
|
||||
self.above.retain(|id| through.get(&id.peer).is_none_or(|&covered| id.sequence > covered));
|
||||
self.through = through;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -40,6 +40,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
let hot_op = HotOp {
|
||||
op: remove_node_op(NodeId(99)),
|
||||
timestamp: observed,
|
||||
sequence: 1,
|
||||
};
|
||||
|
||||
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
|
||||
@@ -182,9 +183,10 @@ fn merge_converges_to_identical_history() {
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
|
||||
|
||||
assert!(matches!(merge_a, crate::MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
@@ -193,6 +195,29 @@ fn merge_converges_to_identical_history() {
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// A peer whose history is a prefix of the incoming one moves its head forward without minting a
|
||||
/// merge delta, and the negotiated transfer sends only the deltas past the sampled known revs.
|
||||
#[test]
|
||||
fn merge_fast_forwards_a_prefix_history() {
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
for value in 1..=5 {
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", value)).expect("B edit");
|
||||
}
|
||||
|
||||
let known = session_a.known_revs();
|
||||
let missing: Vec<_> = session_b.deltas_unknown_to(known).into_iter().cloned().collect();
|
||||
assert_eq!(missing.len(), 5, "only B's new commits are unknown to A");
|
||||
|
||||
let outcome = session_a.merge(missing).expect("merge failed");
|
||||
assert_eq!(outcome, crate::MergeOutcome::FastForward(session_b.head_rev().unwrap()));
|
||||
assert_eq!(session_a.history().count(), session_b.history().count(), "no merge delta was added");
|
||||
|
||||
assert_eq!(session_b.merge(session_a.cloned_deltas()).expect("merge failed"), crate::MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
@@ -879,3 +904,192 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
|
||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry, which sits at
|
||||
/// `retired_snapshot + hot tail`. `commit_op_for_test` alone only advances the snapshot zone.
|
||||
fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
for delta in session.cloned_deltas().into_iter().skip(before) {
|
||||
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge `deltas` into a copy of `base` in the given order and report whether node 7 survived,
|
||||
/// with the stamp on its `tint` attribute.
|
||||
fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> Option<(serde_json::Value, TimeStamp)> {
|
||||
let mut session = base.clone();
|
||||
let ordered: Vec<Delta> = order.iter().map(|&index| deltas[index].clone()).collect();
|
||||
session.merge(ordered).expect("merge failed");
|
||||
|
||||
session
|
||||
.retired_registry()
|
||||
.node_instances
|
||||
.get(&NodeId(7))
|
||||
.and_then(|node| node.attributes.get("tint"))
|
||||
.map(|value| (value.value.clone(), value.timestamp))
|
||||
}
|
||||
|
||||
/// Retired deltas reach the registries in arrival order while only `history` is canonically sorted,
|
||||
/// so concurrent deltas must commute. A remove concurrent with an attribute change does not: applied
|
||||
/// change-then-remove the node is gone, while remove-then-change resurrects it from the removal's
|
||||
/// embedded snapshot and reapplies the change on top.
|
||||
#[test]
|
||||
fn a_concurrent_remove_and_attribute_change_commute() {
|
||||
let network_id = NetworkId(5);
|
||||
let node = Node::new(network_id, crate::Implementation::Network(network_id), 0);
|
||||
|
||||
// Shared base holding node 7, then the two peers diverge.
|
||||
let mut base = Session::with_peer(PeerId(1));
|
||||
commit_retired(
|
||||
&mut base,
|
||||
RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
},
|
||||
);
|
||||
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
|
||||
|
||||
let mut remover = base.clone();
|
||||
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
|
||||
|
||||
let mut changer = Session::with_peer(PeerId(2));
|
||||
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
|
||||
commit_retired(
|
||||
&mut changer,
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id: NodeId(7),
|
||||
delta: crate::AttributeDelta {
|
||||
key: "tint".to_string(),
|
||||
value: Some(serde_json::json!(75)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// One delta from each branch, neither an ancestor of the other.
|
||||
let removal = remover.cloned_deltas().into_iter().last().expect("removal delta");
|
||||
let change = changer.cloned_deltas().into_iter().last().expect("change delta");
|
||||
let deltas = [removal, change];
|
||||
|
||||
let removal_first = merge_order_outcome(&base, &deltas, [0, 1]);
|
||||
let change_first = merge_order_outcome(&base, &deltas, [1, 0]);
|
||||
|
||||
assert_eq!(removal_first, change_first, "the retired registry must not depend on delta arrival order");
|
||||
}
|
||||
|
||||
/// A hot op can retire before an earlier one from the same author has arrived, so the marks have to
|
||||
/// cover it out of order. The prefix absorbs it once the gap fills, which is what keeps the exception
|
||||
/// set from growing.
|
||||
#[test]
|
||||
fn retired_marks_cover_a_gap_and_compact_once_it_fills() {
|
||||
let author = PeerId(1);
|
||||
let id = |sequence| crate::HotOpId { peer: author, sequence };
|
||||
|
||||
let mut marks = crate::RetiredMarks::default();
|
||||
marks.extend([id(1), id(2)]);
|
||||
assert_eq!(marks.through.get(&author), Some(&2), "a contiguous run folds straight into the prefix");
|
||||
assert!(marks.above.is_empty());
|
||||
|
||||
// Sequence 3 never arrived, so 4 retires above the prefix rather than extending it.
|
||||
marks.extend([id(4)]);
|
||||
assert_eq!(marks.through.get(&author), Some(&2));
|
||||
assert!(marks.covers(id(4)), "an op past the gap is still recognized as retired");
|
||||
assert!(!marks.covers(id(3)), "the missing op is not claimed");
|
||||
|
||||
// The gap fills, so the prefix swallows both it and the exception behind it.
|
||||
marks.extend([id(3)]);
|
||||
assert_eq!(marks.through.get(&author), Some(&4));
|
||||
assert!(marks.above.is_empty(), "the exception set empties once the prefix reaches it");
|
||||
}
|
||||
|
||||
/// Marks merge by union, and a peer adopting another's wholesale must not lose its own coverage.
|
||||
#[test]
|
||||
fn absorbing_marks_keeps_both_sides_coverage() {
|
||||
let author = PeerId(1);
|
||||
let id = |sequence| crate::HotOpId { peer: author, sequence };
|
||||
|
||||
let mut local = crate::RetiredMarks::default();
|
||||
local.extend([id(1), id(4)]);
|
||||
|
||||
let mut remote = crate::RetiredMarks::default();
|
||||
remote.extend([id(1), id(2), id(3), id(5)]);
|
||||
|
||||
local.absorb(&remote);
|
||||
|
||||
// The union is 1..=5 contiguous, so it all collapses into the prefix.
|
||||
assert_eq!(local.through.get(&author), Some(&5));
|
||||
assert!(local.above.is_empty());
|
||||
for sequence in 1..=5 {
|
||||
assert!(local.covers(id(sequence)), "sequence {sequence} must stay covered");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo rewinds retired history, so it must leave the hot tail alone. The retired snapshot is the
|
||||
/// state history alone produces; copying the working registry onto it promotes live work nobody has
|
||||
/// retired, which is the same mistake `Session::merge` used to make.
|
||||
#[test]
|
||||
fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
// Two retired interactions, so the second is undoable.
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
// Unretired live work sitting on top, on a key no retired delta touches.
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
assert!(session.registry().attributes.contains_key("hot"), "the hot op must be in the working registry");
|
||||
assert!(!session.retired_registry().attributes.contains_key("hot"), "and must not be in the snapshot");
|
||||
|
||||
session.undo().expect("undo");
|
||||
|
||||
assert!(!session.retired_registry().attributes.contains_key("second"), "undo must rewind the retired snapshot");
|
||||
assert!(
|
||||
!session.retired_registry().attributes.contains_key("hot"),
|
||||
"undo promoted an unretired hot op into the retired snapshot"
|
||||
);
|
||||
}
|
||||
|
||||
/// Redo puts the interaction back on both zones, so the pair stays `snapshot + hot tail` rather than
|
||||
/// drifting apart in the other direction.
|
||||
#[test]
|
||||
fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
session.undo().expect("undo");
|
||||
session.redo().expect("redo");
|
||||
|
||||
assert!(session.retired_registry().attributes.contains_key("second"), "redo must restore the retired delta");
|
||||
assert!(
|
||||
!session.retired_registry().attributes.contains_key("hot"),
|
||||
"redo promoted an unretired hot op into the retired snapshot"
|
||||
);
|
||||
assert!(session.registry().attributes.contains_key("hot"), "the hot op must survive an undo/redo round trip");
|
||||
}
|
||||
|
||||
/// Silent undo rewrites the local registries without emitting anything, so it is only legal while a
|
||||
/// commit is still unpublished. Once peers hold it, a rewind would diverge from them for good.
|
||||
#[test]
|
||||
fn publishing_a_commit_disables_silent_undo() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
let head = session.head_rev().expect("a head");
|
||||
assert!(session.can_undo(), "an unpublished interaction is undoable");
|
||||
|
||||
session.publish_up_to(head);
|
||||
|
||||
assert!(!session.can_undo(), "a published interaction must not be silently rewound");
|
||||
}
|
||||
@@ -20,12 +20,10 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
|
||||
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
||||
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
||||
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
|
||||
/// `Declarations` map for the back-conversion.
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
|
||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
|
||||
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
(conversion.registry, declarations)
|
||||
(conversion.registry, conversion.declarations)
|
||||
}
|
||||
|
||||
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
|
||||
@@ -477,7 +475,7 @@ fn test_ui_metadata_round_trip() {
|
||||
);
|
||||
|
||||
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
||||
|
||||
@@ -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 }
|
||||
document-graph-storage = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,116 @@
|
||||
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
|
||||
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
|
||||
//! async runtime: the caller spawns the transport driver and decides how to render.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout, ResourceProxy};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
pub use document_graph_storage::to_runtime::ConversionError;
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LiveError {
|
||||
#[error(transparent)]
|
||||
Format(#[from] FormatError),
|
||||
#[error(transparent)]
|
||||
Conversion(#[from] ConversionError),
|
||||
}
|
||||
|
||||
pub struct LiveDocument {
|
||||
gdd: GddV1,
|
||||
token: SessionToken,
|
||||
}
|
||||
|
||||
impl LiveDocument {
|
||||
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
|
||||
/// future for as long as the session lives.
|
||||
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).await?;
|
||||
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
|
||||
}
|
||||
|
||||
/// Host a session on an already opened document.
|
||||
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
gdd.share(room, user);
|
||||
Self { gdd, token }
|
||||
}
|
||||
|
||||
/// Join the session under `token`; the document fills in once the host's sync arrives.
|
||||
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).await?;
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
gdd.join(room, user);
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, peer.0, version.clone(), version).await
|
||||
}
|
||||
|
||||
pub fn token(&self) -> SessionToken {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.gdd.role()
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
|
||||
/// Synced and holding every resource the document references, so `network` can be built and run.
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
|
||||
}
|
||||
|
||||
/// Apply whatever peers sent since the last call and answer their resource 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
|
||||
}
|
||||
|
||||
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
/// Byte store for resources received from peers, for an executor to load from.
|
||||
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
|
||||
self.gdd.resource_proxy()
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "peer-transport"
|
||||
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
matchbox_socket = "0.14.0"
|
||||
futures = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_bytes = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
uuid = "1"
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,19 @@
|
||||
pub mod mock;
|
||||
mod packet;
|
||||
mod replica;
|
||||
mod room;
|
||||
mod target;
|
||||
mod token;
|
||||
mod transport;
|
||||
|
||||
pub use packet::{PacketError, Role, SyncPacket, SyncPayload};
|
||||
pub use replica::{Event, Replica, ReplicaError};
|
||||
pub use room::Room;
|
||||
pub use target::{SyncTarget, TargetError};
|
||||
pub use token::{InvalidSessionToken, SessionToken};
|
||||
pub use transport::{Transport, TransportEvent, TransportPeerId};
|
||||
|
||||
pub use matchbox_socket::MessageLoopFuture;
|
||||
|
||||
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
|
||||
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
|
||||
@@ -0,0 +1,175 @@
|
||||
//! In-process transport for deterministic simulation. Every packet sits in a per-(sender, receiver)
|
||||
//! queue until `step` delivers it, so interleavings across peers are driven by the seed while each
|
||||
//! pair stays ordered like a reliable channel.
|
||||
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
connected: Vec<TransportPeerId>,
|
||||
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
|
||||
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
|
||||
next_peer: u128,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn disconnect(&mut self, id: TransportPeerId) {
|
||||
self.connected.retain(|&other| other != id);
|
||||
self.in_flight.retain(|&(from, to), _| from != id && to != id);
|
||||
for &other in &self.connected.clone() {
|
||||
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
|
||||
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MockNetwork {
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl MockNetwork {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self {
|
||||
shared: Arc::new(Mutex::new(Shared::default())),
|
||||
rng: SplitMix64(seed),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, not yet connected peer.
|
||||
pub fn endpoint(&mut self) -> MockEndpoint {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
shared.next_peer += 1;
|
||||
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
|
||||
shared.inboxes.insert(id, VecDeque::new());
|
||||
MockEndpoint {
|
||||
id,
|
||||
shared: self.shared.clone(),
|
||||
known_peers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, id: TransportPeerId) {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
if shared.connected.contains(&id) {
|
||||
return;
|
||||
}
|
||||
for &other in &shared.connected.clone() {
|
||||
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
|
||||
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
|
||||
}
|
||||
shared.connected.push(id);
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self, id: TransportPeerId) {
|
||||
self.shared.lock().unwrap().disconnect(id);
|
||||
}
|
||||
|
||||
pub fn pending(&self) -> usize {
|
||||
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
|
||||
}
|
||||
|
||||
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
|
||||
pub fn step(&mut self) -> bool {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
|
||||
if queues.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (from, to) = queues[self.rng.below(queues.len())];
|
||||
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
|
||||
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
|
||||
true
|
||||
}
|
||||
|
||||
pub fn deliver_all(&mut self) {
|
||||
while self.step() {}
|
||||
}
|
||||
|
||||
/// Deliver everything in flight to one peer, leaving every other peer's queues untouched. Random
|
||||
/// stepping cannot target a receiver, so this is how a test puts a packet in one peer's hands and
|
||||
/// not another's.
|
||||
pub fn deliver_to(&mut self, to: TransportPeerId) {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
|
||||
|
||||
for key in queues {
|
||||
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
|
||||
for packet in packets {
|
||||
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn random_below(&mut self, bound: usize) -> usize {
|
||||
self.rng.below(bound)
|
||||
}
|
||||
}
|
||||
|
||||
/// Like a real socket, an endpoint only knows the peers whose connect events it has polled, so it
|
||||
/// can't send to a peer before it had the chance to greet it.
|
||||
pub struct MockEndpoint {
|
||||
id: TransportPeerId,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
known_peers: Vec<TransportPeerId>,
|
||||
}
|
||||
|
||||
impl MockEndpoint {
|
||||
pub fn id(&self) -> TransportPeerId {
|
||||
self.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for MockEndpoint {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
if self.known_peers.contains(&to) {
|
||||
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
for to in self.known_peers.clone() {
|
||||
if Some(to) != excluded {
|
||||
self.send(to, packet)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
|
||||
for event in &events {
|
||||
match event {
|
||||
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
|
||||
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.shared.lock().unwrap().disconnect(self.id);
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
(self.next() % bound as u64) as usize
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The host is the single peer that retires hot ops.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Role {
|
||||
Host,
|
||||
Guest,
|
||||
}
|
||||
|
||||
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts
|
||||
/// `seq`, so `epoch` names the incarnation that produced it and counters from different epochs are
|
||||
/// never compared.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerSeq {
|
||||
pub peer: PeerId,
|
||||
pub epoch: u64,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
/// MessagePack-encoded on the wire.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum SyncPacket {
|
||||
/// Sent first on every new connection. `epoch` and `seq` anchor the receiver's counter for this
|
||||
/// sender, since broadcasts made before the connection were never sent to it.
|
||||
Hello {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
role: Role,
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
},
|
||||
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
|
||||
SyncRequest {
|
||||
known_revs: Vec<Rev>,
|
||||
},
|
||||
Sync(Box<SyncPayload>),
|
||||
Broadcast(Broadcast),
|
||||
ResourceRequest(Vec<ResourceHash>),
|
||||
Resource {
|
||||
hash: ResourceHash,
|
||||
#[serde(with = "serde_bytes")]
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The host's answer to a `SyncRequest`. `registry` is only sent when the host recognized none of
|
||||
/// the requester's revs; otherwise `deltas` extend the requester's history. `seen` is the host's
|
||||
/// delivery vector at snapshot time, which the guest adopts so later broadcasts line up.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SyncPayload {
|
||||
pub registry: Option<Registry>,
|
||||
pub deltas: Vec<Delta>,
|
||||
pub head: Option<Rev>,
|
||||
pub hot_log: Vec<HotOp>,
|
||||
pub known_revs: Vec<Rev>,
|
||||
pub seen: Vec<PeerSeq>,
|
||||
/// Which hot ops the history being handed over already covers, so the requester can recognize one
|
||||
/// it is holding rather than re-entering it as live work.
|
||||
pub retired: RetiredMarks,
|
||||
}
|
||||
|
||||
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen`
|
||||
/// is the sender's delivery vector; a receiver holds the packet until it has delivered everything in
|
||||
/// `seen`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Broadcast {
|
||||
pub epoch: u64,
|
||||
pub seq: u64,
|
||||
pub seen: Vec<PeerSeq>,
|
||||
pub body: BroadcastBody,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum BroadcastBody {
|
||||
HotOps(Vec<HotOp>),
|
||||
/// `deltas` are in causal order. `retires` names the hot ops they replace (empty for a plain history transfer).
|
||||
Deltas {
|
||||
deltas: Vec<Delta>,
|
||||
retires: Vec<HotOpId>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PacketError {
|
||||
#[error("failed to encode packet: {0}")]
|
||||
Encode(#[from] rmp_serde::encode::Error),
|
||||
#[error("failed to decode packet: {0}")]
|
||||
Decode(#[from] rmp_serde::decode::Error),
|
||||
}
|
||||
|
||||
impl SyncPacket {
|
||||
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
|
||||
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
|
||||
Ok(rmp_serde::from_slice(bytes)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
use crate::packet::{Broadcast, BroadcastBody, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
|
||||
use crate::target::{SyncTarget, TargetError};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, ResourceHash, UserId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub enum Event {
|
||||
PeerJoined {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
},
|
||||
PeerLeft {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// The guest has applied the host's state.
|
||||
Synced,
|
||||
/// Remote ops changed the target.
|
||||
Changed,
|
||||
ResourceReceived {
|
||||
hash: ResourceHash,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
/// The target couldn't serve this synchronously; answer with `send_resource`.
|
||||
ResourceRequested {
|
||||
from: TransportPeerId,
|
||||
hash: ResourceHash,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReplicaError {
|
||||
#[error(transparent)]
|
||||
Packet(#[from] PacketError),
|
||||
#[error(transparent)]
|
||||
Target(#[from] TargetError),
|
||||
}
|
||||
|
||||
struct RemotePeer {
|
||||
peer: PeerId,
|
||||
#[expect(dead_code, reason = "Read once peers are surfaced in the UI")]
|
||||
user: UserId,
|
||||
#[expect(dead_code, reason = "Read once host handover is implemented")]
|
||||
role: Role,
|
||||
}
|
||||
|
||||
/// How far one peer's broadcasts have been delivered here.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PeerProgress {
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
/// Broadcasts that arrive before the host's `Sync` are held back, since they target state the guest
|
||||
/// doesn't have yet.
|
||||
enum SyncState {
|
||||
Synced,
|
||||
AwaitingSync { pending: Vec<(PeerId, Broadcast)> },
|
||||
}
|
||||
|
||||
/// Protocol state for one peer in a room. Owns no document; `poll` applies into a `SyncTarget`.
|
||||
///
|
||||
/// Broadcasts are delivered in causal order: each carries the sender's sequence number and delivery
|
||||
/// vector, and is held until everything the sender had delivered has been delivered here too.
|
||||
pub struct Replica {
|
||||
transport: Box<dyn Transport>,
|
||||
role: Role,
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
peers: HashMap<TransportPeerId, RemotePeer>,
|
||||
sync: SyncState,
|
||||
/// This incarnation, drawn fresh so a reconnect or a reload never reuses one. See [`PeerSeq`].
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
delivered: HashMap<PeerId, PeerProgress>,
|
||||
held: Vec<(PeerId, Broadcast)>,
|
||||
/// Hot ops whose referents had not arrived when they did, retried as later ops fill the gaps.
|
||||
/// A missing entity is not distinguishable from one that was concurrently removed, so the op is
|
||||
/// kept rather than applied against state it does not fit.
|
||||
deferred: Vec<HotOp>,
|
||||
/// Broadcasts that arrived before their sender's hello, parked rather than dropped so a reordering
|
||||
/// on a fresh link cannot lose ops.
|
||||
ungreeted: HashMap<TransportPeerId, Vec<Broadcast>>,
|
||||
/// Resources asked for and not yet received, so a standing request is not resent every poll.
|
||||
requested_resources: HashSet<ResourceHash>,
|
||||
/// Requests that arrived before the bytes did, answered once they turn up here.
|
||||
owed_resources: HashMap<ResourceHash, HashSet<TransportPeerId>>,
|
||||
/// Whether the target's resource references may have moved since they were last examined.
|
||||
resources_stale: bool,
|
||||
}
|
||||
|
||||
impl Replica {
|
||||
pub fn host(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::new(Box::new(transport), Role::Host, peer, user, SyncState::Synced)
|
||||
}
|
||||
|
||||
pub fn guest(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::new(Box::new(transport), Role::Guest, peer, user, SyncState::AwaitingSync { pending: Vec::new() })
|
||||
}
|
||||
|
||||
fn new(transport: Box<dyn Transport>, role: Role, peer: PeerId, user: UserId, sync: SyncState) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
role,
|
||||
peer,
|
||||
user,
|
||||
peers: HashMap::new(),
|
||||
sync,
|
||||
epoch: core_types::uuid::generate_uuid(),
|
||||
seq: 0,
|
||||
delivered: HashMap::new(),
|
||||
held: Vec::new(),
|
||||
deferred: Vec::new(),
|
||||
ungreeted: HashMap::new(),
|
||||
requested_resources: HashSet::new(),
|
||||
owed_resources: HashMap::new(),
|
||||
resources_stale: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Role {
|
||||
self.role
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
matches!(self.sync, SyncState::Synced)
|
||||
}
|
||||
|
||||
/// Broadcasts waiting on causal dependencies. Non-zero in an idle room means a stuck delivery.
|
||||
pub fn held_broadcasts(&self) -> usize {
|
||||
self.held.len()
|
||||
}
|
||||
|
||||
/// Ops held back for a referent that had not arrived. Non-zero in an idle room means one never did.
|
||||
pub fn deferred_ops(&self) -> usize {
|
||||
self.deferred.len()
|
||||
}
|
||||
|
||||
/// Resources asked for whose bytes have not come back yet.
|
||||
pub fn pending_resource_requests(&self) -> impl Iterator<Item = ResourceHash> + '_ {
|
||||
self.requested_resources.iter().copied()
|
||||
}
|
||||
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// A local edit can name a resource whose bytes are not here, a pasted node referencing a font for
|
||||
// instance, so the references are worth re-examining even though nothing arrived from the wire.
|
||||
self.resources_stale = true;
|
||||
|
||||
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
|
||||
}
|
||||
|
||||
/// Host only.
|
||||
pub fn broadcast_retired(&mut self, deltas: &[Delta], retires: &[HotOpId]) -> Result<(), PacketError> {
|
||||
debug_assert_eq!(self.role, Role::Host);
|
||||
if deltas.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Retirement moves ops into history, which referenced resources are read from as well as from the
|
||||
// registry, so a hash the registry has since overwritten becomes referenced again from here.
|
||||
self.resources_stale = true;
|
||||
|
||||
self.broadcast(BroadcastBody::Deltas {
|
||||
deltas: deltas.to_vec(),
|
||||
retires: retires.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn broadcast(&mut self, body: BroadcastBody) -> Result<(), PacketError> {
|
||||
self.seq += 1;
|
||||
let broadcast = Broadcast {
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
seen: self.seen_vector(),
|
||||
body,
|
||||
};
|
||||
self.transport.broadcast(&SyncPacket::Broadcast(broadcast))
|
||||
}
|
||||
|
||||
/// Everything delivered here, including this peer's own broadcasts.
|
||||
fn seen_vector(&self) -> Vec<PeerSeq> {
|
||||
let delivered = self.delivered.iter().map(|(&peer, progress)| PeerSeq {
|
||||
peer,
|
||||
epoch: progress.epoch,
|
||||
seq: progress.seq,
|
||||
});
|
||||
delivered
|
||||
.chain([PeerSeq {
|
||||
peer: self.peer,
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
}])
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.transport.close();
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, target: &mut dyn SyncTarget) -> Vec<Event> {
|
||||
let mut events = Vec::new();
|
||||
let transport_events = self.transport.poll();
|
||||
|
||||
// Greet every new peer before handling anything else in the batch. A transport adds them to its
|
||||
// send set for the whole batch up front, so a broadcast made while handling an earlier event
|
||||
// would reach a peer that has not been greeted; the hello that followed would then carry a
|
||||
// sequence number covering it, and the receiver would rightly treat those ops as unneeded.
|
||||
for transport_event in &transport_events {
|
||||
if let TransportEvent::PeerConnected(transport_peer) = transport_event
|
||||
&& let Err(error) = self.send_hello(*transport_peer)
|
||||
{
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
for transport_event in transport_events {
|
||||
let result = match transport_event {
|
||||
TransportEvent::PeerConnected(_) => Ok(()),
|
||||
TransportEvent::PeerDisconnected(transport_peer) => {
|
||||
let departed = self.peers.remove(&transport_peer);
|
||||
if let Some(remote) = &departed {
|
||||
events.push(Event::PeerLeft { peer: remote.peer });
|
||||
}
|
||||
// A peer that left may have been the one still owing bytes, so let the rest be asked again.
|
||||
self.requested_resources.clear();
|
||||
self.resources_stale = true;
|
||||
// The hello those were waiting on is never coming now.
|
||||
self.ungreeted.remove(&transport_peer);
|
||||
|
||||
match departed {
|
||||
Some(remote) => self.close_epoch(remote.peer, target, &mut events),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
TransportEvent::Packet(transport_peer, packet) => self.handle_packet(transport_peer, packet, target, &mut events),
|
||||
TransportEvent::Malformed(transport_peer, error) => {
|
||||
log::warn!("Dropping malformed packet from {transport_peer}: {error}");
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(error) = result {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
self.retry_deferred(target, &mut events);
|
||||
|
||||
if let Err(error) = target.flush() {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
if let Err(error) = self.request_missing_resources(target) {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
if let Err(error) = self.serve_owed_resources(target) {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
/// Re-announce every hot op held here that history does not yet cover, whoever wrote it. A peer can
|
||||
/// hold the only copy of another's op, so replaying only our own would leave that one to die with the
|
||||
/// connection it arrived on. Ops the watermark covers replay as no-ops on every receiver.
|
||||
fn reannounce_hot_ops(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
let retired = target.retired_marks();
|
||||
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
|
||||
|
||||
self.broadcast_hot_ops(&unretired)
|
||||
}
|
||||
|
||||
/// Retry ops held back for a missing referent. A later op can supply the entity an earlier one
|
||||
/// named, so this runs once per poll rather than only where the op arrived.
|
||||
fn retry_deferred(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) {
|
||||
if self.deferred.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let pending = std::mem::take(&mut self.deferred);
|
||||
let waiting = pending.len();
|
||||
match target.apply_remote_hot_ops(pending) {
|
||||
Ok(deferred) => {
|
||||
// One that finally applied can name a resource nobody here has seen, and leaves the target
|
||||
// changed, neither of which anything else in the poll would notice.
|
||||
if deferred.len() < waiting {
|
||||
self.resources_stale = true;
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
self.deferred = deferred;
|
||||
}
|
||||
Err(error) => log::error!("Retrying deferred hot ops: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the room for referenced bytes nobody here has yet. Runs after every batch of packets rather
|
||||
/// than once at sync, since an op delivered later can reference a resource this peer has never seen.
|
||||
/// Only the hashes without a standing request go out, so a slow transfer is not re-requested.
|
||||
fn request_missing_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if !self.resources_stale {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = false;
|
||||
|
||||
let missing = target.missing_resources();
|
||||
// A resource that turned up some other way, staged here for instance, leaves its request behind.
|
||||
// Clearing those keeps a later ask for the same hash from being suppressed.
|
||||
self.requested_resources.retain(|hash| missing.contains(hash));
|
||||
|
||||
let unasked: Vec<ResourceHash> = missing.into_iter().filter(|hash| !self.requested_resources.contains(hash)).collect();
|
||||
if unasked.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.requested_resources.extend(unasked.iter().copied());
|
||||
self.transport.broadcast(&SyncPacket::ResourceRequest(unasked))
|
||||
}
|
||||
|
||||
/// Answer requests that arrived before their bytes did. A resource can turn up locally rather than
|
||||
/// over the wire, so this runs every poll; a requester never asks twice, so nothing else would.
|
||||
fn serve_owed_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.owed_resources.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let ready: Vec<(ResourceHash, Vec<u8>)> = self.owed_resources.keys().filter_map(|&hash| target.resource_bytes(hash).map(|bytes| (hash, bytes))).collect();
|
||||
for (hash, bytes) in ready {
|
||||
for to in self.owed_resources.remove(&hash).unwrap_or_default() {
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes: bytes.clone() })?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_hello(&mut self, transport_peer: TransportPeerId) -> Result<(), ReplicaError> {
|
||||
let hello = SyncPacket::Hello {
|
||||
peer: self.peer,
|
||||
user: self.user,
|
||||
role: self.role,
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
};
|
||||
self.transport.send(transport_peer, &hello)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_packet(&mut self, from: TransportPeerId, packet: SyncPacket, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
match packet {
|
||||
SyncPacket::Hello { peer, user, role, epoch, seq } => {
|
||||
self.peers.insert(from, RemotePeer { peer, user, role });
|
||||
self.anchor_delivered(peer, epoch, seq);
|
||||
// Now that the sender is known, whatever arrived ahead of its hello can be handled.
|
||||
for broadcast in self.ungreeted.remove(&from).unwrap_or_default() {
|
||||
self.handle_packet(from, SyncPacket::Broadcast(broadcast), target, events)?;
|
||||
}
|
||||
|
||||
// The anchor can unblock broadcasts held against the counter an earlier link reached.
|
||||
self.deliver_held(target, events)?;
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
events.push(Event::PeerJoined { peer, user });
|
||||
// A fresh peer may hold bytes nobody else here could serve.
|
||||
self.requested_resources.clear();
|
||||
self.resources_stale = true;
|
||||
|
||||
if role == Role::Host && !self.is_synced() {
|
||||
self.transport.send(from, &SyncPacket::SyncRequest { known_revs: target.known_revs() })?;
|
||||
}
|
||||
}
|
||||
SyncPacket::SyncRequest { known_revs } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
let shares_history = known_revs.iter().any(|&rev| target.contains_rev(rev));
|
||||
let sync = SyncPayload {
|
||||
registry: (!shares_history).then(|| target.retired_registry()),
|
||||
deltas: target.deltas_unknown_to(&known_revs),
|
||||
head: target.head(),
|
||||
hot_log: target.hot_log(),
|
||||
known_revs: target.known_revs(),
|
||||
seen: self.seen_vector(),
|
||||
retired: target.retired_marks(),
|
||||
};
|
||||
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
|
||||
}
|
||||
SyncPacket::Sync(sync) => {
|
||||
let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) else {
|
||||
return Ok(());
|
||||
};
|
||||
match sync.registry {
|
||||
Some(registry) => target.load(registry, sync.deltas, sync.head)?,
|
||||
None => target.merge_remote(sync.deltas, &[])?,
|
||||
}
|
||||
target.absorb_retired_marks(&sync.retired)?;
|
||||
|
||||
self.deferred.extend(target.apply_remote_hot_ops(sync.hot_log)?);
|
||||
self.resources_stale = true;
|
||||
|
||||
// The host's hot log is not a superset of the room's: this peer may hold the only copy of an
|
||||
// op that never reached the host, and history is the only way it survives.
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
|
||||
// Broadcasts the host had delivered before answering are already reflected in the snapshot.
|
||||
for mark in sync.seen {
|
||||
self.observe_delivered(mark);
|
||||
}
|
||||
// An earlier seq is baked into the snapshot already.
|
||||
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
|
||||
self.held.extend(worth_holding);
|
||||
self.deliver_held(target, events)?;
|
||||
|
||||
let host_is_missing = target.deltas_unknown_to(&sync.known_revs);
|
||||
if !host_is_missing.is_empty() {
|
||||
self.broadcast(BroadcastBody::Deltas {
|
||||
deltas: host_is_missing,
|
||||
retires: Vec::new(),
|
||||
})?;
|
||||
}
|
||||
|
||||
// Hot ops only ever existed in flight, so a drop loses them where retired work survives in
|
||||
// history. Re-announce the ones authored here.
|
||||
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
|
||||
self.broadcast_hot_ops(&own_hot_ops)?;
|
||||
|
||||
events.push(Event::Synced);
|
||||
}
|
||||
SyncPacket::Broadcast(broadcast) => {
|
||||
// Its sender is only known from a hello, so park it rather than drop it.
|
||||
let Some(remote) = self.peers.get(&from) else {
|
||||
self.ungreeted.entry(from).or_default().push(broadcast);
|
||||
return Ok(());
|
||||
};
|
||||
let sender = remote.peer;
|
||||
match &mut self.sync {
|
||||
SyncState::AwaitingSync { pending } => pending.push((sender, broadcast)),
|
||||
SyncState::Synced => {
|
||||
if self.worth_holding(sender, &broadcast) {
|
||||
self.held.push((sender, broadcast));
|
||||
self.deliver_held(target, events)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SyncPacket::ResourceRequest(hashes) => {
|
||||
for hash in hashes {
|
||||
match target.resource_bytes(hash) {
|
||||
Some(bytes) => self.transport.send(from, &SyncPacket::Resource { hash, bytes })?,
|
||||
None => {
|
||||
self.owed_resources.entry(hash).or_default().insert(from);
|
||||
events.push(Event::ResourceRequested { from, hash });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SyncPacket::Resource { hash, bytes } => {
|
||||
if ResourceHash::from(bytes.as_slice()) != hash {
|
||||
log::warn!("Resource from {from} does not match its hash; dropping");
|
||||
return Ok(());
|
||||
}
|
||||
target.store_resource(hash, &bytes)?;
|
||||
self.requested_resources.remove(&hash);
|
||||
events.push(Event::ResourceReceived { hash, bytes });
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record that a peer's broadcasts up to `mark` need not be waited for. Monotonic, since a hello
|
||||
/// and a host's `seen` vector can carry the same fact in either order.
|
||||
fn observe_delivered(&mut self, mark: PeerSeq) {
|
||||
if mark.peer == self.peer {
|
||||
return;
|
||||
}
|
||||
match self.delivered.get_mut(&mark.peer) {
|
||||
Some(progress) if progress.epoch == mark.epoch => progress.seq = progress.seq.max(mark.seq),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
self.delivered.insert(mark.peer, PeerProgress { epoch: mark.epoch, seq: mark.seq });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set where a peer's broadcasts resume on a newly opened link. Nothing before its hello was ever
|
||||
/// sent here, so this replaces rather than raises.
|
||||
fn anchor_delivered(&mut self, peer: PeerId, epoch: u64, seq: u64) {
|
||||
if peer == self.peer {
|
||||
return;
|
||||
}
|
||||
self.delivered.insert(peer, PeerProgress { epoch, seq });
|
||||
|
||||
// Held broadcasts from an earlier incarnation can never be delivered in order, and the sender
|
||||
// re-announces what is still hot once it resyncs.
|
||||
self.held.retain(|(sender, broadcast)| *sender != peer || broadcast.epoch == epoch);
|
||||
}
|
||||
|
||||
/// Settle up after a peer leaves: its own held broadcasts can never fill their gaps, and anything
|
||||
/// waiting on it is now free to go.
|
||||
fn close_epoch(&mut self, peer: PeerId, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
// Buffered broadcasts go too, in both queues. Applying them after their author left would mint a
|
||||
// fresh orphan with no departure left to clean it up, and nothing has been applied yet, so
|
||||
// dropping them breaks no dependency. Anything else waiting on this peer is released instead.
|
||||
if let SyncState::AwaitingSync { pending } = &mut self.sync {
|
||||
pending.retain(|(sender, _)| *sender != peer);
|
||||
}
|
||||
self.held.retain(|(sender, _)| *sender != peer);
|
||||
|
||||
// Its ops waiting on a referent have nobody left to supply one, so they stop being held open.
|
||||
// Retirement drains the rest: an op the watermark covers replays as a no-op and leaves the queue.
|
||||
self.deferred.retain(|hot_op| hot_op.timestamp.peer != peer);
|
||||
|
||||
self.deliver_held(target, events)?;
|
||||
|
||||
// The departed peer's unretired work reached some peers and not others, and it can no longer
|
||||
// re-announce the difference itself. Passing on the whole hot tail covers it along with anything
|
||||
// that depends on it, so the host can retire the lot into history.
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a link to this peer is open, meaning more of its broadcasts may still turn up.
|
||||
fn is_connected(&self, peer: PeerId) -> bool {
|
||||
self.peers.values().any(|remote| remote.peer == peer)
|
||||
}
|
||||
|
||||
/// Deliver every held broadcast whose causal dependencies are met, repeating since each delivery
|
||||
/// can unblock others.
|
||||
fn deliver_held(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
while let Some(index) = self.held.iter().position(|(sender, broadcast)| self.is_deliverable(*sender, broadcast)) {
|
||||
let (sender, broadcast) = self.held.remove(index);
|
||||
self.delivered.insert(
|
||||
sender,
|
||||
PeerProgress {
|
||||
epoch: broadcast.epoch,
|
||||
seq: broadcast.seq,
|
||||
},
|
||||
);
|
||||
|
||||
// Applying is best effort: the ops that did land still have to be accounted for, so a failure
|
||||
// is reported rather than abandoning the bookkeeping and the rest of the queue.
|
||||
let applied = match broadcast.body {
|
||||
BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
|
||||
BroadcastBody::Deltas { deltas, retires } => target.merge_remote(deltas, &retires),
|
||||
};
|
||||
if let Err(error) = applied {
|
||||
log::error!("Applying a delivered broadcast: {error}");
|
||||
}
|
||||
|
||||
self.resources_stale = true;
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_deliverable(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
|
||||
let Some(progress) = self.delivered.get(&sender) else { return false };
|
||||
if progress.epoch != broadcast.epoch || broadcast.seq != progress.seq + 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
broadcast.seen.iter().all(|&mark| mark.peer == sender || self.has_delivered(mark))
|
||||
}
|
||||
|
||||
/// Whether a broadcast can still come up for delivery. A stale epoch or an already-delivered seq
|
||||
/// never will, so holding one would park it for good.
|
||||
fn worth_holding(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
|
||||
self.delivered.get(&sender).is_none_or(|progress| progress.epoch == broadcast.epoch && broadcast.seq > progress.seq)
|
||||
}
|
||||
|
||||
/// Whether one of a broadcast's dependencies is met. Dependencies that can never be met count as
|
||||
/// met, rather than stalling their sender for good.
|
||||
fn has_delivered(&self, mark: PeerSeq) -> bool {
|
||||
if mark.peer == self.peer {
|
||||
return mark.epoch != self.epoch || mark.seq <= self.seq;
|
||||
}
|
||||
match self.delivered.get(&mark.peer) {
|
||||
Some(progress) if progress.epoch != mark.epoch => true,
|
||||
Some(progress) if progress.seq >= mark.seq => true,
|
||||
// A peer with no open link sends nothing more, including one whose hello never arrived.
|
||||
_ => !self.is_connected(mark.peer),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use matchbox_socket::{MessageLoopFuture, PeerState, WebRtcSocket};
|
||||
use std::collections::HashMap;
|
||||
|
||||
const CHANNEL: usize = 0;
|
||||
/// Largest SCTP message every browser accepts.
|
||||
const CHUNK_BYTES: usize = 16 * 1024;
|
||||
const FRAME_FINAL: u8 = 1;
|
||||
const FRAME_MORE: u8 = 0;
|
||||
|
||||
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so a receiver finds
|
||||
/// the packet boundary without a length prefix.
|
||||
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
|
||||
// An empty packet still gets one frame. Chunking it would yield none at all, and the packet would
|
||||
// leave no trace on the wire rather than arriving empty.
|
||||
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
|
||||
|
||||
chunks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, chunk)| {
|
||||
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
|
||||
std::iter::once(flag).chain(chunk.iter().copied()).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Per-peer reassembly of framed packets. The channel is reliable and ordered per peer, so chunks
|
||||
/// arrive in the order they were sent and a packet ends at the first [`FRAME_FINAL`].
|
||||
#[derive(Default)]
|
||||
struct Reassembler {
|
||||
partial: HashMap<TransportPeerId, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Reassembler {
|
||||
/// The packet's bytes once its final chunk lands, or `None` while more are still to come.
|
||||
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
|
||||
let (&flag, chunk) = frame.split_first()?;
|
||||
let buffer = self.partial.entry(peer).or_default();
|
||||
buffer.extend_from_slice(chunk);
|
||||
|
||||
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
|
||||
}
|
||||
|
||||
/// Drop a peer's half-received packet, which nothing will ever complete.
|
||||
fn forget(&mut self, peer: TransportPeerId) {
|
||||
self.partial.remove(&peer);
|
||||
}
|
||||
}
|
||||
|
||||
/// One matchbox room over WebRTC. Packets are split into `[flag][bytes]` chunks; the reliable
|
||||
/// channel is ordered per peer, so the receiver reassembles by appending until the final flag.
|
||||
/// The returned future must be polled continuously by the caller.
|
||||
pub struct Room {
|
||||
socket: WebRtcSocket,
|
||||
incoming: Reassembler,
|
||||
}
|
||||
|
||||
impl Room {
|
||||
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
|
||||
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
|
||||
let (socket, driver) = WebRtcSocket::new_reliable(signaling_url);
|
||||
(
|
||||
Self {
|
||||
socket,
|
||||
incoming: Reassembler::default(),
|
||||
},
|
||||
driver,
|
||||
)
|
||||
}
|
||||
|
||||
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
|
||||
let channel = self.socket.channel_mut(CHANNEL);
|
||||
|
||||
for frame in frames(bytes) {
|
||||
for &peer in peers {
|
||||
channel.send(frame.clone(), peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Room {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
let bytes = packet.encode()?;
|
||||
self.send_chunks(&bytes, &[to]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
let bytes = packet.encode()?;
|
||||
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
|
||||
self.send_chunks(&bytes, &peers);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
for (peer, state) in self.socket.update_peers() {
|
||||
events.push(match state {
|
||||
PeerState::Connected => TransportEvent::PeerConnected(peer),
|
||||
PeerState::Disconnected => {
|
||||
self.incoming.forget(peer);
|
||||
TransportEvent::PeerDisconnected(peer)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let received: Vec<_> = self.socket.channel_mut(CHANNEL).receive();
|
||||
for (peer, frame) in received {
|
||||
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
|
||||
|
||||
events.push(match SyncPacket::decode(&bytes) {
|
||||
Ok(packet) => TransportEvent::Packet(peer, packet),
|
||||
Err(error) => TransportEvent::Malformed(peer, error),
|
||||
});
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn peer(byte: u128) -> TransportPeerId {
|
||||
TransportPeerId(uuid::Uuid::from_u128(byte))
|
||||
}
|
||||
|
||||
/// Push every frame at a reassembler and collect whatever packets come back out.
|
||||
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
|
||||
}
|
||||
|
||||
/// A packet within one chunk travels as a single final frame.
|
||||
#[test]
|
||||
fn a_small_packet_is_one_frame() {
|
||||
let bytes = b"hello".to_vec();
|
||||
let framed = frames(&bytes);
|
||||
|
||||
assert_eq!(framed.len(), 1);
|
||||
assert_eq!(framed[0][0], FRAME_FINAL);
|
||||
assert_eq!(round_trip(&bytes), vec![bytes]);
|
||||
}
|
||||
|
||||
/// Chunking an empty packet yields no chunks at all, so it needs a frame of its own or it would
|
||||
/// leave no trace on the wire.
|
||||
#[test]
|
||||
fn an_empty_packet_still_produces_one_frame() {
|
||||
let framed = frames(&[]);
|
||||
|
||||
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
|
||||
assert_eq!(framed[0][0], FRAME_FINAL);
|
||||
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
|
||||
}
|
||||
|
||||
/// The boundary either side of the SCTP limit: exactly one chunk stays one frame, one byte more
|
||||
/// splits, and both rebuild byte for byte.
|
||||
#[test]
|
||||
fn packets_around_the_chunk_boundary_round_trip() {
|
||||
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
|
||||
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
|
||||
let framed = frames(&bytes);
|
||||
|
||||
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
|
||||
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
|
||||
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
|
||||
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
|
||||
|
||||
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet would be
|
||||
/// spliced into the other.
|
||||
#[test]
|
||||
fn interleaved_peers_reassemble_separately() {
|
||||
let (first, second) = (peer(1), peer(2));
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
|
||||
let short = b"short".to_vec();
|
||||
|
||||
let long_frames = frames(&long);
|
||||
let short_frames = frames(&short);
|
||||
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
|
||||
|
||||
// The short packet arrives whole between the long packet's two chunks.
|
||||
assert_eq!(incoming.accept(first, &long_frames[0]), None);
|
||||
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
|
||||
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
|
||||
}
|
||||
|
||||
/// A peer that drops mid-packet leaves a partial buffer, which must not be prepended to whatever
|
||||
/// the next peer to reuse that id sends.
|
||||
#[test]
|
||||
fn forgetting_a_peer_discards_its_partial_packet() {
|
||||
let sender = peer(1);
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
|
||||
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
|
||||
|
||||
incoming.forget(sender);
|
||||
|
||||
let fresh = b"fresh".to_vec();
|
||||
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
|
||||
}
|
||||
|
||||
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
|
||||
#[test]
|
||||
fn an_empty_frame_is_ignored() {
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
assert_eq!(incoming.accept(peer(1), &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
use document_graph_storage::{Delta, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub type TargetError = Box<dyn std::error::Error>;
|
||||
|
||||
/// The document state a `Replica` reads from and applies remote changes to.
|
||||
pub trait SyncTarget {
|
||||
fn peer(&self) -> PeerId;
|
||||
fn head(&self) -> Option<Rev>;
|
||||
fn retired_registry(&self) -> Registry;
|
||||
fn hot_log(&self) -> Vec<HotOp>;
|
||||
fn known_revs(&self) -> Vec<Rev>;
|
||||
fn contains_rev(&self, rev: Rev) -> bool;
|
||||
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta>;
|
||||
|
||||
/// Highest hot-op counter retired per author.
|
||||
fn retired_marks(&self) -> RetiredMarks;
|
||||
/// Take on a peer's retirement watermark, dropping any hot op it shows as already retired.
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError>;
|
||||
|
||||
/// Replace all state with the given retired state.
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
|
||||
/// Must be idempotent on structural ops: a buffered op may already be reflected by the sync.
|
||||
/// Returns the ops it could not apply, whose referents have not arrived yet; the caller retries
|
||||
/// them as later ops fill the gaps.
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError>;
|
||||
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll),
|
||||
/// so a target that rewrites whole files can do it once for a batch rather than once per packet.
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Referenced resources whose bytes are not available locally.
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
HashSet::new()
|
||||
}
|
||||
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
let _ = hash;
|
||||
None
|
||||
}
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let _ = (hash, bytes);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for Session {
|
||||
fn peer(&self) -> PeerId {
|
||||
Session::peer(self)
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
self.head_rev()
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
Session::retired_registry(self).clone()
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
Session::hot_log(self).to_vec()
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
Session::known_revs(self)
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
self.delta(rev).is_some()
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
|
||||
Session::deltas_unknown_to(self, known.iter().copied()).into_iter().cloned().collect()
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
// Kept across the replace: a sequence this peer already spent must not come round again, or an
|
||||
// op of its own would be taken for one already retired.
|
||||
*self = Session::load(self.peer(), registry, history, head, Vec::new(), self.next_node_counter(), self.next_hot_sequence());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
// Every op gets its turn even if one fails, since the broadcast that carried them is consumed by
|
||||
// the time this runs. A failure usually means the entity the op names has not arrived here yet,
|
||||
// so it is handed back to be retried rather than dropped.
|
||||
let mut deferred = Vec::new();
|
||||
for hot_op in ops {
|
||||
if self.replay_hot_op(hot_op.clone()).is_err() {
|
||||
deferred.push(hot_op);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(deferred)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
|
||||
// Hot ops stay until after the merge: a delta may target something a still-hot removal took away.
|
||||
self.merge(deltas)?;
|
||||
self.discard_hot_ops(retires);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
Session::retired_marks(self).clone()
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
Session::absorb_retired_marks(self, remote);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
|
||||
const PREFIX: &str = "graphite-";
|
||||
|
||||
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SessionToken(pub [u8; 16]);
|
||||
|
||||
impl SessionToken {
|
||||
pub fn signaling_url(&self, signaling_server: &str) -> String {
|
||||
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SessionToken {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("invalid session token")]
|
||||
pub struct InvalidSessionToken;
|
||||
|
||||
impl FromStr for SessionToken {
|
||||
type Err = InvalidSessionToken;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
|
||||
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_string() {
|
||||
let token = SessionToken([7; 16]);
|
||||
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_length_or_missing_prefix() {
|
||||
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
|
||||
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
|
||||
pub use matchbox_socket::PeerId as TransportPeerId;
|
||||
|
||||
pub enum TransportEvent {
|
||||
PeerConnected(TransportPeerId),
|
||||
PeerDisconnected(TransportPeerId),
|
||||
Packet(TransportPeerId, SyncPacket),
|
||||
Malformed(TransportPeerId, PacketError),
|
||||
}
|
||||
|
||||
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
|
||||
/// sender, which is what lets the `Replica` skip acknowledgements and buffering.
|
||||
pub trait Transport: Send + Sync {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
|
||||
fn poll(&mut self) -> Vec<TransportEvent>;
|
||||
fn close(&mut self);
|
||||
|
||||
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
self.broadcast_except(None, packet)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,735 @@
|
||||
//! Deterministic simulation over the mock transport: random edits on every peer, random delivery
|
||||
//! order, random host retirement. After quiescence every peer must hold the same retired state.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> GUESTS=<n> cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use document_graph_storage::{
|
||||
AttributeDelta, Delta, HotOp, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId, RetiredMarks, Rev,
|
||||
Session, SourceKey, TimeStamp, UserId,
|
||||
};
|
||||
use peer_transport::mock::{MockEndpoint, MockNetwork};
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static TOTAL_NODES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_WIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_EXPORTS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_INPUT_ATTRIBUTES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_SOURCES: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A peer's document plus the byte store the editor keeps application-wide. Bare `Session` takes the
|
||||
/// trait's no-op resource defaults, which would leave the whole request path unexercised.
|
||||
struct SimTarget {
|
||||
session: Session,
|
||||
resources: HashMap<ResourceHash, Vec<u8>>,
|
||||
/// History as of the last `flush`, to check the sync path never leaves applied state undurable.
|
||||
durable_history: Vec<Rev>,
|
||||
flushes: usize,
|
||||
/// Every rev this peer has ever held, to check none is later dropped. See [`SimTarget::flush`].
|
||||
seen_revs: HashSet<Rev>,
|
||||
seed: u64,
|
||||
}
|
||||
|
||||
impl SimTarget {
|
||||
fn new(peer: PeerId, seed: u64) -> Self {
|
||||
Self {
|
||||
session: Session::with_peer(peer),
|
||||
resources: HashMap::new(),
|
||||
durable_history: Vec::new(),
|
||||
flushes: 0,
|
||||
seen_revs: HashSet::new(),
|
||||
seed,
|
||||
}
|
||||
}
|
||||
|
||||
fn history_revs(&self) -> Vec<Rev> {
|
||||
self.session.history().map(|delta| delta.id).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for SimTarget {
|
||||
fn peer(&self) -> PeerId {
|
||||
SyncTarget::peer(&self.session)
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
SyncTarget::head(&self.session)
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
SyncTarget::retired_registry(&self.session)
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
SyncTarget::hot_log(&self.session)
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
SyncTarget::known_revs(&self.session)
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
SyncTarget::contains_rev(&self.session, rev)
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
|
||||
SyncTarget::deltas_unknown_to(&self.session, known)
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
SyncTarget::load(&mut self.session, registry, history, head)
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
SyncTarget::apply_remote_hot_ops(&mut self.session, ops)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<(), TargetError> {
|
||||
SyncTarget::merge_remote(&mut self.session, deltas, retires)
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
SyncTarget::retired_marks(&self.session)
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
SyncTarget::absorb_retired_marks(&mut self.session, remote)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
// History is append-only. Hot ops are explicitly transient and a rejoin may drop the lot, but a
|
||||
// retired delta is the durable record, so losing one is data loss no convergence check would see.
|
||||
let current: HashSet<Rev> = self.history_revs().into_iter().collect();
|
||||
if let Some(dropped) = self.seen_revs.iter().find(|rev| !current.contains(rev)) {
|
||||
panic!("seed {}: peer {:?} dropped retired delta {dropped:?} from history", self.seed, self.session.peer());
|
||||
}
|
||||
self.seen_revs.extend(current);
|
||||
|
||||
self.durable_history = self.history_revs();
|
||||
self.flushes += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash)).collect()
|
||||
}
|
||||
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
self.resources.get(&hash).cloned()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
self.resources.insert(hash, bytes.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Peer {
|
||||
target: SimTarget,
|
||||
replica: Replica,
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
transport: TransportPeerId,
|
||||
/// Gone for good, unlike a rejoin. Its document stops taking part and stops being asserted on.
|
||||
departed: bool,
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
fn new(endpoint: MockEndpoint, role: Role, index: u64, seed: u64) -> Self {
|
||||
let (peer, user) = (PeerId(index), UserId(index));
|
||||
let transport = endpoint.id();
|
||||
let replica = match role {
|
||||
Role::Host => Replica::host(endpoint, peer, user),
|
||||
Role::Guest => Replica::guest(endpoint, peer, user),
|
||||
};
|
||||
Self {
|
||||
target: SimTarget::new(peer, seed),
|
||||
replica,
|
||||
peer,
|
||||
user,
|
||||
transport,
|
||||
departed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop off the room, keeping the document. The editor rebuilds the `Replica` on a reconnect but
|
||||
/// reuses the `Gdd`'s persisted `PeerId`, so protocol state resets while document state does not.
|
||||
fn rejoin(&mut self, network: &mut MockNetwork) {
|
||||
network.disconnect(self.transport);
|
||||
|
||||
let endpoint = network.endpoint();
|
||||
self.transport = endpoint.id();
|
||||
self.replica = Replica::guest(endpoint, self.peer, self.user);
|
||||
network.connect(self.transport);
|
||||
}
|
||||
|
||||
/// Close the tab. The peer is never heard from again, so the room has to settle without whatever
|
||||
/// it alone knew.
|
||||
fn depart(&mut self, network: &mut MockNetwork) {
|
||||
network.disconnect(self.transport);
|
||||
self.departed = true;
|
||||
}
|
||||
|
||||
fn session(&self) -> &Session {
|
||||
&self.target.session
|
||||
}
|
||||
|
||||
fn stage(&mut self, op: RegistryDelta) {
|
||||
let hot_ops = self.target.session.stage_ops([op]).expect("stage");
|
||||
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
}
|
||||
|
||||
/// Introduce a resource only this peer holds the bytes for, so every other peer has to fetch them.
|
||||
fn stage_resource(&mut self, bytes: Vec<u8>) {
|
||||
let hash = ResourceHash::from(bytes.as_slice());
|
||||
self.target.resources.insert(hash, bytes);
|
||||
|
||||
// Each peer names its resources itself, the way live resources get a fresh `ResourceId`. Deriving
|
||||
// the id from the content instead would collide across peers, which `AddResource` resolves by
|
||||
// replay order rather than by merging.
|
||||
let id = ResourceId::from(u64::from(ResourceId::from_hash(&hash)) ^ self.peer.0);
|
||||
let hot_ops = self.target.session.stage_embedded_resource(id, hash).expect("stage resource");
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
}
|
||||
|
||||
fn retire(&mut self) {
|
||||
let Some(up_to) = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
|
||||
return;
|
||||
};
|
||||
self.retire_up_to(up_to);
|
||||
}
|
||||
|
||||
/// Retire only part of the hot log, leaving newer ops live. A later op of one author can then retire
|
||||
/// while an earlier one is still in flight, which is what puts entries above the retired prefix.
|
||||
fn retire_prefix(&mut self, nth: usize) {
|
||||
let mut timestamps: Vec<TimeStamp> = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).collect();
|
||||
if timestamps.is_empty() {
|
||||
return;
|
||||
}
|
||||
timestamps.sort();
|
||||
|
||||
self.retire_up_to(timestamps[nth.min(timestamps.len() - 1)]);
|
||||
}
|
||||
|
||||
fn retire_up_to(&mut self, up_to: TimeStamp) {
|
||||
let retired_hot_ops = self.target.session.hot_ops_up_to(up_to);
|
||||
|
||||
let revs = self.target.session.retire(up_to).expect("retire");
|
||||
let deltas: Vec<_> = revs.iter().filter_map(|&rev| self.target.session.delta(rev).cloned()).collect();
|
||||
self.replica.broadcast_retired(&deltas, &retired_hot_ops).expect("broadcast retired");
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<Event> {
|
||||
let flushes_before = self.target.flushes;
|
||||
let events = self.replica.poll(&mut self.target);
|
||||
assert_eq!(self.target.flushes, flushes_before + 1, "poll must flush the target exactly once");
|
||||
events
|
||||
}
|
||||
}
|
||||
|
||||
/// Node-level ops, which reach the input-slot LWW arms and the resurrection path a concurrent remove
|
||||
/// triggers. `None` when the registry holds nothing the drawn op could target.
|
||||
fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<RegistryDelta> {
|
||||
let registry = session.registry();
|
||||
let node_id = NodeId(1 + network.random_below(4) as u64);
|
||||
let live_nodes: Vec<NodeId> = registry.node_instances.keys().copied().collect();
|
||||
let live_networks: Vec<NetworkId> = registry.networks.keys().copied().collect();
|
||||
|
||||
match network.random_below(8) {
|
||||
// Per-slot attributes, the one place `InputSlot.attributes` is written.
|
||||
6 => {
|
||||
let node = registry.node_instances.get(&node_id)?;
|
||||
let index = network.random_below(node.inputs().len().max(1)) as u32;
|
||||
|
||||
Some(RegistryDelta::ChangeNodeInputAttribute {
|
||||
id: node_id,
|
||||
index,
|
||||
delta: AttributeDelta {
|
||||
key: "label".into(),
|
||||
value: Some(serde_json::json!(network.random_below(100))),
|
||||
},
|
||||
})
|
||||
}
|
||||
// A node needs a live network to sit in, and `AddNode` errors on one that already exists.
|
||||
0 | 1 if !registry.node_instances.contains_key(&node_id) => {
|
||||
let network_id = *pick(network, &live_networks)?;
|
||||
Some(RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 2),
|
||||
})
|
||||
}
|
||||
2 => registry.node_instances.get(&node_id).map(|node| RegistryDelta::RemoveNode { id: node_id, snapshot: node.clone() }),
|
||||
3 | 4 => {
|
||||
let node = registry.node_instances.get(&node_id)?;
|
||||
let index = network.random_below(node.inputs().len().max(1)) as u32;
|
||||
|
||||
// Wiring to a node that is live here can still land on a peer that concurrently removed it,
|
||||
// which is what drives the resurrection path.
|
||||
let wire_to = pick(network, &live_nodes).copied();
|
||||
let new_input = match wire_to {
|
||||
Some(target) if network.random_below(3) > 0 => NodeInput::Node { id: target, index: 0 },
|
||||
_ => NodeInput::Value {
|
||||
value: serde_json::json!(network.random_below(100)),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
Some(RegistryDelta::ChangeNodeInput { id: node_id, index, new_input })
|
||||
}
|
||||
_ => pick(network, &live_nodes).copied().map(|node_id| RegistryDelta::ChangeNodeAttribute {
|
||||
id: node_id,
|
||||
delta: AttributeDelta {
|
||||
key: "name".into(),
|
||||
value: Some(serde_json::json!(network.random_below(100))),
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resource-lifecycle ops past creation. `AddResource` already rides the staged-resource path, so
|
||||
/// these cover the rest of the chain: the resolved hash, the source fallback list, and removal.
|
||||
/// `None` when the registry holds no resource to target.
|
||||
fn random_resource_op(network: &mut MockNetwork, target: &SimTarget) -> Option<RegistryDelta> {
|
||||
let session = &target.session;
|
||||
let registry = session.registry();
|
||||
let live: Vec<ResourceId> = registry.resources.keys().copied().collect();
|
||||
let id = *pick(network, &live)?;
|
||||
|
||||
// A small pool of priorities, so concurrent adds sometimes collide on a key and sometimes stack up
|
||||
// as distinct entries in the same chain.
|
||||
let key = SourceKey {
|
||||
priority: Priority::new(network.random_below(3) as f64).expect("a whole number is finite"),
|
||||
peer: session.peer(),
|
||||
};
|
||||
|
||||
Some(match network.random_below(5) {
|
||||
// Only a hash this peer holds the bytes for: a resolved hash is content derived, so in the editor
|
||||
// the peer that resolves a resource is the one that fetched it.
|
||||
0 => {
|
||||
let held: Vec<ResourceHash> = target.resources.keys().copied().collect();
|
||||
RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: Some(*pick(network, &held)?),
|
||||
}
|
||||
}
|
||||
1 => RegistryDelta::SetResourceHash { id, hash: None },
|
||||
2 => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: serde_json::json!("Embedded"),
|
||||
},
|
||||
3 => RegistryDelta::RemoveSource { id, key },
|
||||
_ => RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: registry.resources.get(&id)?.clone(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// One element at random, or `None` when there is nothing to choose from.
|
||||
fn pick<'a, T>(network: &mut MockNetwork, options: &'a [T]) -> Option<&'a T> {
|
||||
(!options.is_empty()).then(|| &options[network.random_below(options.len())])
|
||||
}
|
||||
|
||||
fn random_op(network: &mut MockNetwork, target: &SimTarget) -> RegistryDelta {
|
||||
let session = &target.session;
|
||||
let network_id = NetworkId(1 + network.random_below(3) as u64);
|
||||
|
||||
// Half the ops are node-level, falling through to the network-level ones when nothing fits.
|
||||
if network.random_below(2) == 0
|
||||
&& let Some(op) = random_node_op(network, session)
|
||||
{
|
||||
return op;
|
||||
}
|
||||
|
||||
// Resources exist only once a peer has staged one, so this yields nothing early in a run.
|
||||
if network.random_below(5) == 0
|
||||
&& let Some(op) = random_resource_op(network, target)
|
||||
{
|
||||
return op;
|
||||
}
|
||||
|
||||
match network.random_below(6) {
|
||||
// Export slots resize on demand and LWW per slot, and clearing one leaves a tombstone that must
|
||||
// still compare equal to the slot being absent.
|
||||
4 | 5 if session.registry().networks.contains_key(&network_id) => {
|
||||
let live_nodes: Vec<NodeId> = session.registry().node_instances.keys().copied().collect();
|
||||
let export = match pick(network, &live_nodes).copied() {
|
||||
Some(id) if network.random_below(4) > 0 => Some(NodeInput::Node { id, index: 0 }),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: network.random_below(3) as u32,
|
||||
export,
|
||||
}
|
||||
}
|
||||
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: format!("key{}", network.random_below(3)),
|
||||
value: Some(serde_json::json!(network.random_below(100))),
|
||||
},
|
||||
},
|
||||
2 if let Some(network) = session.registry().networks.get(&network_id) => RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: network.clone(),
|
||||
},
|
||||
_ if session.registry().networks.contains_key(&network_id) => RegistryDelta::ChangeNetworkAttribute {
|
||||
id: network_id,
|
||||
delta: AttributeDelta {
|
||||
key: "name".into(),
|
||||
value: Some(serde_json::json!(network.random_below(100))),
|
||||
},
|
||||
},
|
||||
_ => RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn present_guests(peers: &[Peer]) -> usize {
|
||||
peers.iter().skip(1).filter(|peer| !peer.departed).count()
|
||||
}
|
||||
|
||||
/// Run until nothing is in flight and no peer reports progress. Resource transfers need several
|
||||
/// rounds (request out, bytes back), so this is not a fixed number of passes.
|
||||
fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) {
|
||||
for _ in 0..1000 {
|
||||
network.deliver_all();
|
||||
let events: usize = peers.iter_mut().filter(|peer| !peer.departed).map(|peer| peer.poll().len()).sum();
|
||||
if events == 0 && network.pending() == 0 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("the room never went idle");
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Peer>) {
|
||||
let mut network = MockNetwork::new(seed);
|
||||
|
||||
let mut peers: Vec<Peer> = (0..=guest_count)
|
||||
.map(|index| {
|
||||
let endpoint = network.endpoint();
|
||||
let id = endpoint.id();
|
||||
let role = if index == 0 { Role::Host } else { Role::Guest };
|
||||
let peer = Peer::new(endpoint, role, index as u64 + 1, seed);
|
||||
network.connect(id);
|
||||
peer
|
||||
})
|
||||
.collect();
|
||||
|
||||
for _ in 0..steps {
|
||||
let index = network.random_below(peers.len());
|
||||
if peers[index].departed {
|
||||
continue;
|
||||
}
|
||||
|
||||
match network.random_below(16) {
|
||||
// A guest edits only once synced; anything staged earlier would be invisible to its peers.
|
||||
0..=2 if peers[index].replica.is_synced() => {
|
||||
let op = random_op(&mut network, &peers[index].target);
|
||||
peers[index].stage(op);
|
||||
}
|
||||
// A small pool of distinct payloads, so peers sometimes introduce the same resource
|
||||
// concurrently and sometimes one nobody else can serve.
|
||||
8 if peers[index].replica.is_synced() => {
|
||||
let bytes = format!("resource-{}", network.random_below(5)).into_bytes();
|
||||
peers[index].stage_resource(bytes);
|
||||
}
|
||||
0..=2 | 8 => {}
|
||||
// Mostly a partial retire, so the host's history lags its hot log the way a real one does.
|
||||
3 => {
|
||||
let nth = network.random_below(4);
|
||||
peers[0].retire_prefix(nth);
|
||||
}
|
||||
4..=7 => {
|
||||
network.step();
|
||||
}
|
||||
// The host cannot hand over, so only guests drop and come back.
|
||||
9 if index > 0 => peers[index].rejoin(&mut network),
|
||||
9 => {
|
||||
let endpoint = network.endpoint();
|
||||
let id = endpoint.id();
|
||||
peers.push(Peer::new(endpoint, Role::Guest, peers.len() as u64 + 1, seed));
|
||||
network.connect(id);
|
||||
}
|
||||
// Keep one guest around, so the room stays a room.
|
||||
10 if index > 0 && present_guests(&peers) > 1 => peers[index].depart(&mut network),
|
||||
_ => {
|
||||
peers[index].poll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
quiesce(&mut network, &mut peers);
|
||||
peers[0].retire();
|
||||
quiesce(&mut network, &mut peers);
|
||||
|
||||
(network, peers)
|
||||
}
|
||||
|
||||
/// Dump every peer's state for one seed: `SIM_DUMP=<seed> cargo test ... -- --nocapture`.
|
||||
fn dump_if_requested(seed: u64, peers: &[Peer]) {
|
||||
if std::env::var("SIM_DUMP").ok().and_then(|value| value.parse::<u64>().ok()) != Some(seed) {
|
||||
return;
|
||||
}
|
||||
for (index, peer) in peers.iter().enumerate() {
|
||||
eprintln!(
|
||||
"DUMP {index} {:?} departed {} synced {} held {} pending_resources {} history {} hot {:?} watermark {:?}",
|
||||
peer.peer,
|
||||
peer.departed,
|
||||
peer.replica.is_synced(),
|
||||
peer.replica.held_broadcasts(),
|
||||
peer.replica.pending_resource_requests().count(),
|
||||
peer.session().history().count(),
|
||||
peer.session()
|
||||
.hot_log()
|
||||
.iter()
|
||||
.map(|h| format!("{}:{}#{}", h.timestamp.peer.0, h.timestamp.counter, h.sequence))
|
||||
.collect::<Vec<_>>(),
|
||||
{
|
||||
let retired = peer.session().retired_marks();
|
||||
let mut through: Vec<_> = retired.through.iter().map(|(p, c)| (p.0, *c)).collect();
|
||||
through.sort();
|
||||
let mut above: Vec<_> = retired.above.iter().map(|id| (id.peer.0, id.sequence)).collect();
|
||||
above.sort();
|
||||
format!("{through:?} above {above:?}")
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every `AddNode` in history names a network that history itself creates. Retirement promotes
|
||||
/// whatever the host managed to apply, so a referent that only ever existed as an unretired hot op
|
||||
/// could in principle leave a durable hole here.
|
||||
fn assert_history_self_contained(seed: u64, peers: &[Peer]) {
|
||||
for (index, peer) in peers.iter().enumerate().filter(|(_, peer)| !peer.departed) {
|
||||
let created: HashSet<NetworkId> = peer
|
||||
.session()
|
||||
.history()
|
||||
.filter_map(|delta| match delta.kind {
|
||||
RegistryDelta::AddNetwork { id, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.chain(peer.session().history().filter_map(|delta| match delta.reverse {
|
||||
RegistryDelta::AddNetwork { id, .. } => Some(id),
|
||||
_ => None,
|
||||
}))
|
||||
.collect();
|
||||
for delta in peer.session().history() {
|
||||
if let RegistryDelta::AddNode { node, .. } = &delta.kind {
|
||||
assert!(
|
||||
created.contains(&node.network()),
|
||||
"seed {seed}: peer {index} history has AddNode into {:?} that nothing in history creates",
|
||||
node.network()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hot op is identified by its timestamp, so holding one twice means some path appended a copy of
|
||||
/// something already there, which then replays and re-broadcasts as if it were new work.
|
||||
fn assert_no_duplicate_hot_ops(seed: u64, peers: &[Peer]) {
|
||||
for (index, peer) in peers.iter().enumerate() {
|
||||
let mut seen = HashSet::new();
|
||||
for hot_op in peer.session().hot_log() {
|
||||
assert!(seen.insert(hot_op.timestamp), "seed {seed}: peer {index} holds {:?} twice", hot_op.timestamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_converged(seed: u64, peers: &[Peer]) {
|
||||
dump_if_requested(seed, peers);
|
||||
assert_no_duplicate_hot_ops(seed, peers);
|
||||
assert_history_self_contained(seed, peers);
|
||||
|
||||
let present = || peers.iter().enumerate().filter(|(_, peer)| !peer.departed);
|
||||
|
||||
// A sparse `known_revs` sample only describes a peer's state if history is parent-complete, so a
|
||||
// hole makes the host under-send on the next resync.
|
||||
for (index, peer) in present() {
|
||||
let present_revs: HashSet<Rev> = peer.session().history().map(|delta| delta.id).collect();
|
||||
for delta in peer.session().history() {
|
||||
for parent in delta.all_parents() {
|
||||
assert!(present_revs.contains(&parent), "seed {seed}: peer {index} has {:?} without its parent {parent:?}", delta.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let host = &peers[0];
|
||||
let host_history: Vec<_> = host.session().history().map(|delta| delta.id).collect();
|
||||
for (index, guest) in present().skip(1) {
|
||||
let guest_history: Vec<_> = guest.session().history().map(|delta| delta.id).collect();
|
||||
assert_eq!(guest_history, host_history, "seed {seed}: guest {index} history diverged");
|
||||
assert_eq!(guest.session().head_rev(), host.session().head_rev(), "seed {seed}: guest {index} head diverged");
|
||||
assert_eq!(guest.session().retired_registry(), host.session().retired_registry(), "seed {seed}: guest {index} registry diverged");
|
||||
assert!(guest.session().hot_log().is_empty(), "seed {seed}: guest {index} still holds hot ops");
|
||||
}
|
||||
|
||||
// Bytes that left with a departed peer are gone for good, so the room is only answerable for the
|
||||
// resources someone still in it could have served.
|
||||
let servable: HashSet<ResourceHash> = present().flat_map(|(_, peer)| peer.target.resources.keys().copied()).collect();
|
||||
|
||||
// An idle room with anything outstanding is stuck, which convergence of content alone can miss:
|
||||
// a broadcast held forever behind a dependency that will never arrive changes nothing observable.
|
||||
for (index, peer) in present() {
|
||||
assert_eq!(peer.replica.held_broadcasts(), 0, "seed {seed}: peer {index} still holds undelivered broadcasts");
|
||||
assert_eq!(peer.replica.deferred_ops(), 0, "seed {seed}: peer {index} still holds ops waiting on a referent");
|
||||
assert_eq!(peer.target.durable_history, peer.target.history_revs(), "seed {seed}: peer {index} has unflushed history");
|
||||
|
||||
let unserved: Vec<_> = SyncTarget::missing_resources(&peer.target).into_iter().filter(|hash| servable.contains(hash)).collect();
|
||||
assert!(unserved.is_empty(), "seed {seed}: peer {index} is missing resource bytes another peer holds: {unserved:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peers_converge_under_random_interleavings() {
|
||||
// The committed corpus is the first 1000 seeds; `SIM_SEEDS` pushes the frontier further by hand.
|
||||
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(1000);
|
||||
|
||||
for seed in 0..seeds {
|
||||
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200);
|
||||
{
|
||||
let registry = peers[0].session().retired_registry();
|
||||
TOTAL_NODES.fetch_add(registry.node_instances.len(), Ordering::Relaxed);
|
||||
let wired = registry
|
||||
.node_instances
|
||||
.values()
|
||||
.flat_map(|node| node.inputs())
|
||||
.filter(|slot| matches!(slot.input, NodeInput::Node { .. }))
|
||||
.count();
|
||||
TOTAL_WIRED.fetch_add(wired, Ordering::Relaxed);
|
||||
|
||||
let exports = registry.networks.values().flat_map(|net| &net.exports).filter(|slot| slot.target.is_some()).count();
|
||||
TOTAL_EXPORTS.fetch_add(exports, Ordering::Relaxed);
|
||||
|
||||
let input_attributes = registry.node_instances.values().flat_map(|node| node.inputs()).filter(|slot| !slot.attributes.is_empty()).count();
|
||||
TOTAL_INPUT_ATTRIBUTES.fetch_add(input_attributes, Ordering::Relaxed);
|
||||
|
||||
// More than one source on a resource can only come from `AddSource`, which the staging path
|
||||
// never emits, so this is what proves the resource-chain ops reach the registry.
|
||||
let stacked_sources = registry.resources.values().filter(|entry| entry.sources.len() > 1).count();
|
||||
TOTAL_SOURCES.fetch_add(stacked_sources, Ordering::Relaxed);
|
||||
}
|
||||
assert_converged(seed, &peers);
|
||||
}
|
||||
// The node ops are guarded on what the registry holds, so a generator change can quietly stop
|
||||
// producing them. Without nodes wired to other nodes nothing reaches the resurrection path.
|
||||
assert!(TOTAL_NODES.load(Ordering::Relaxed) > 0, "the corpus produced no nodes");
|
||||
assert!(TOTAL_WIRED.load(Ordering::Relaxed) > 0, "the corpus produced no node-to-node inputs");
|
||||
assert!(TOTAL_EXPORTS.load(Ordering::Relaxed) > 0, "the corpus set no network exports");
|
||||
assert!(TOTAL_INPUT_ATTRIBUTES.load(Ordering::Relaxed) > 0, "the corpus wrote no input-slot attributes");
|
||||
assert!(TOTAL_SOURCES.load(Ordering::Relaxed) > 0, "the corpus never stacked a second source on a resource");
|
||||
}
|
||||
|
||||
/// A guest that drops and comes back keeps its `PeerId` but gets a fresh `Replica`, so its broadcast
|
||||
/// sequence restarts. The room must follow the restart rather than keep waiting on the sequence the
|
||||
/// old connection had reached.
|
||||
#[test]
|
||||
fn a_rejoining_guest_is_still_heard() {
|
||||
let mut network = MockNetwork::new(0);
|
||||
|
||||
let mut peers: Vec<Peer> = (0..2)
|
||||
.map(|index| {
|
||||
let endpoint = network.endpoint();
|
||||
let id = endpoint.id();
|
||||
let role = if index == 0 { Role::Host } else { Role::Guest };
|
||||
let peer = Peer::new(endpoint, role, index as u64 + 1, 0);
|
||||
network.connect(id);
|
||||
peer
|
||||
})
|
||||
.collect();
|
||||
|
||||
quiesce(&mut network, &mut peers);
|
||||
|
||||
peers[1].stage(RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: Network::default(),
|
||||
});
|
||||
quiesce(&mut network, &mut peers);
|
||||
assert!(peers[0].session().registry().networks.contains_key(&NetworkId(1)), "the host missed the first edit");
|
||||
|
||||
peers[1].rejoin(&mut network);
|
||||
quiesce(&mut network, &mut peers);
|
||||
|
||||
peers[1].stage(RegistryDelta::AddNetwork {
|
||||
id: NetworkId(2),
|
||||
network: Network::default(),
|
||||
});
|
||||
quiesce(&mut network, &mut peers);
|
||||
|
||||
assert_eq!(peers[0].replica.held_broadcasts(), 0, "the host is holding the rejoined guest's broadcast");
|
||||
assert!(peers[0].session().registry().networks.contains_key(&NetworkId(2)), "the host missed the edit made after the rejoin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual inspection of one seed"]
|
||||
fn inspect_seed() {
|
||||
let _ = env_logger::builder().is_test(true).try_init();
|
||||
let seed = std::env::var("SEED").ok().and_then(|value| value.parse().ok()).unwrap_or(0);
|
||||
let guests = std::env::var("GUESTS").ok().and_then(|value| value.parse().ok()).unwrap_or(1);
|
||||
|
||||
let (_, peers) = simulate(seed, guests, 200);
|
||||
for (index, peer) in peers.iter().enumerate() {
|
||||
eprintln!("=== peer {index} head {:?}", peer.session().head_rev());
|
||||
eprintln!("registry {}", serde_json::to_string(peer.session().retired_registry()).unwrap());
|
||||
eprintln!("hot log {:?}", peer.session().hot_log());
|
||||
eprintln!("resources {:?}", peer.target.resources.keys().collect::<Vec<_>>());
|
||||
for delta in peer.session().history() {
|
||||
eprintln!("{:?} parent {:?} author {:?} ts {} {:?}", delta.id, delta.parent, delta.author, delta.timestamp.counter, delta.kind);
|
||||
}
|
||||
}
|
||||
assert_converged(seed, &peers);
|
||||
}
|
||||
|
||||
/// A hot op can reach one guest and not the host, and its author can then leave for good. The guest
|
||||
/// holds the only copy, so unless it passes the op on the work is lost with the peer that made it.
|
||||
/// Random delivery reaches this only by luck, so it is built by hand.
|
||||
#[test]
|
||||
fn a_guest_holding_the_only_copy_gets_it_retired() {
|
||||
let mut network = MockNetwork::new(0);
|
||||
|
||||
let mut peers: Vec<Peer> = (0..3)
|
||||
.map(|index| {
|
||||
let endpoint = network.endpoint();
|
||||
let id = endpoint.id();
|
||||
let role = if index == 0 { Role::Host } else { Role::Guest };
|
||||
let peer = Peer::new(endpoint, role, index as u64 + 1, 0);
|
||||
network.connect(id);
|
||||
peer
|
||||
})
|
||||
.collect();
|
||||
|
||||
quiesce(&mut network, &mut peers);
|
||||
|
||||
// The author stages one op, and only the other guest is allowed to receive it.
|
||||
let author_transport = peers[1].transport;
|
||||
peers[1].stage(RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
});
|
||||
let witness_transport = peers[2].transport;
|
||||
network.deliver_to(witness_transport);
|
||||
peers[2].poll();
|
||||
|
||||
assert!(peers[2].session().registry().networks.contains_key(&NetworkId(9)), "the witness must have received the op");
|
||||
assert!(peers[0].session().hot_log().is_empty(), "the host must not have received it yet");
|
||||
|
||||
// The author leaves for good, taking its own copy and its undelivered packets with it.
|
||||
network.disconnect(author_transport);
|
||||
peers[1].departed = true;
|
||||
|
||||
quiesce(&mut network, &mut peers);
|
||||
peers[0].retire();
|
||||
quiesce(&mut network, &mut peers);
|
||||
|
||||
assert!(
|
||||
peers[0].session().retired_registry().networks.contains_key(&NetworkId(9)),
|
||||
"the op the witness alone held never reached history"
|
||||
);
|
||||
assert_converged(0, &peers);
|
||||
}
|
||||
+7
-9
@@ -1,14 +1,11 @@
|
||||
[package]
|
||||
name = "graphite-editor"
|
||||
publish = false
|
||||
version = "0.0.0"
|
||||
rust-version = "1.88"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
edition = "2024"
|
||||
readme = "../README.md"
|
||||
homepage = "https://graphite.art"
|
||||
repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "MIT OR Apache-2.0"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["gpu"]
|
||||
@@ -22,6 +19,7 @@ graph-craft = { workspace = true }
|
||||
document-format = { workspace = true }
|
||||
document-graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-container = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||
|
||||
@@ -266,8 +266,8 @@ impl Dispatcher {
|
||||
Message::MenuBar(message) => {
|
||||
let menu_bar_message_handler = &mut self.message_handlers.menu_bar_message_handler;
|
||||
|
||||
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.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.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
|
||||
@@ -427,6 +427,7 @@ impl Dispatcher {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -478,9 +479,11 @@ mod test {
|
||||
"Demo artwork '{document_name}' has more than 1 line (remember to open and re-save it in Graphite)",
|
||||
);
|
||||
|
||||
let responses = editor.editor.handle_message(PortfolioMessage::OpenFile {
|
||||
path: file_name.into(),
|
||||
content: document_serialized_content.bytes().collect(),
|
||||
let responses = editor.editor.handle_message(IngestMessage::Ingest {
|
||||
data: document_serialized_content.into_bytes(),
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some(file_name.into()),
|
||||
});
|
||||
|
||||
// Check if the graph renders
|
||||
|
||||
@@ -11,7 +11,6 @@ use crate::messages::tool::utility_types::ToolType;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
use graphite_proc_macros::{ExtractField, message_handler_data};
|
||||
@@ -51,22 +50,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
responses.add(FrontendMessage::TriggerSelectionWrite { content: text });
|
||||
}
|
||||
}
|
||||
ClipboardContentRaw::Svg(svg) => {
|
||||
responses.add(PortfolioMessage::InsertSvg {
|
||||
svg,
|
||||
name: None,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
});
|
||||
}
|
||||
ClipboardContentRaw::Image { data, width, height } => {
|
||||
responses.add(PortfolioMessage::InsertImage {
|
||||
image: Image::from_image_data(&data, width, height),
|
||||
name: None,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
});
|
||||
}
|
||||
},
|
||||
ClipboardMessage::ReadSelection { content, cut } => {
|
||||
if let Some(text) = content {
|
||||
|
||||
@@ -10,8 +10,6 @@ use graphene_std::vector::Vector;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardContentRaw {
|
||||
Text(String),
|
||||
Svg(String),
|
||||
Image { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{SpectrumInputUpdate, VisualColorPickersInputUpdate};
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{SliderInputUpdate, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::vector::style::{FillChoice, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
|
||||
|
||||
@@ -45,8 +45,8 @@ pub enum ColorPickerMessage {
|
||||
/// Swap the current "new" color with the captured "old" color.
|
||||
SwapNewWithOld,
|
||||
|
||||
/// `SpectrumInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
|
||||
GradientUpdate { update: SpectrumInputUpdate },
|
||||
/// `SliderInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
|
||||
GradientUpdate { update: SliderInputUpdate },
|
||||
/// Gradient spread choice from the gradient "Ends" selection.
|
||||
SetGradientSpread { gradient_spread: GradientSpread },
|
||||
/// Gradient cyclic choice: whether the stops wrap as a cycle, from the "Cyclic" checkbox.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SliderInputUpdate, SliderMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -377,10 +377,10 @@ impl ColorPickerMessageHandler {
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply an incoming `SpectrumInput` intent to the gradient state and broadcast the result.
|
||||
fn apply_gradient_update(&mut self, update: SpectrumInputUpdate, responses: &mut VecDeque<Message>) {
|
||||
/// Apply an incoming `SliderInput` intent to the gradient state and broadcast the result.
|
||||
fn apply_gradient_update(&mut self, update: SliderInputUpdate, responses: &mut VecDeque<Message>) {
|
||||
// Active marker selection is the one update that doesn't mutate the gradient
|
||||
if let SpectrumInputUpdate::ActiveMarker {
|
||||
if let SliderInputUpdate::ActiveMarker {
|
||||
active_marker_index,
|
||||
active_marker_is_midpoint,
|
||||
} = update
|
||||
@@ -401,19 +401,19 @@ impl ColorPickerMessageHandler {
|
||||
let Some(mut gradient) = self.gradient.clone() else { return };
|
||||
|
||||
match update {
|
||||
SpectrumInputUpdate::MoveMarker { index, position } => {
|
||||
SliderInputUpdate::MoveMarker { index, position } => {
|
||||
let new_index = gradient.move_stop(index as usize, position, self.gradient_cyclic);
|
||||
if Some(index) == self.active_marker_index {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::MoveMidpoint { index, position } => {
|
||||
SliderInputUpdate::MoveMidpoint { index, position } => {
|
||||
if (index as usize) >= gradient.len() {
|
||||
return;
|
||||
}
|
||||
gradient.set_midpoint(index as usize, position.clamp(MIN_MIDPOINT, MAX_MIDPOINT));
|
||||
}
|
||||
SpectrumInputUpdate::InsertMarker { position } => {
|
||||
SliderInputUpdate::InsertMarker { position } => {
|
||||
let new_index = gradient.insert_stop(position, self.gradient_settings());
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
@@ -422,7 +422,7 @@ impl ColorPickerMessageHandler {
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::InsertDuplicate { index, position } => {
|
||||
SliderInputUpdate::InsertDuplicate { index, position } => {
|
||||
let source = index as usize;
|
||||
let Some(insert_index) = gradient.duplicate_stop(source, position, self.gradient_cyclic) else {
|
||||
return;
|
||||
@@ -432,7 +432,7 @@ impl ColorPickerMessageHandler {
|
||||
self.active_marker_index = Some(dragged_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
}
|
||||
SpectrumInputUpdate::RemoveDuplicate { index } => {
|
||||
SliderInputUpdate::RemoveDuplicate { index } => {
|
||||
let anchor = index as usize;
|
||||
if anchor >= gradient.len() || gradient.len() <= 2 {
|
||||
return;
|
||||
@@ -449,7 +449,7 @@ impl ColorPickerMessageHandler {
|
||||
self.active_marker_index = Some(active - 1);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::DeleteMarker { index } => {
|
||||
SliderInputUpdate::DeleteMarker { index } => {
|
||||
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
|
||||
if gradient.len() <= 2 || (index as usize) >= gradient.len() {
|
||||
return;
|
||||
@@ -463,10 +463,10 @@ impl ColorPickerMessageHandler {
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::ResetMidpoint { index } => {
|
||||
SliderInputUpdate::ResetMidpoint { index } => {
|
||||
gradient.reset_midpoint(index as usize);
|
||||
}
|
||||
SpectrumInputUpdate::ResetMarker { index } => {
|
||||
SliderInputUpdate::ResetMarker { index } => {
|
||||
let i = index as usize;
|
||||
let count = gradient.len();
|
||||
if i >= count {
|
||||
@@ -483,7 +483,7 @@ impl ColorPickerMessageHandler {
|
||||
self.active_marker_index = Some(new_index as u32);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
|
||||
SliderInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
|
||||
}
|
||||
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
@@ -514,10 +514,10 @@ impl ColorPickerMessageHandler {
|
||||
if let Some(gradient) = &self.gradient {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = (0..gradient.len())
|
||||
.filter_map(|i| Some(SpectrumMarker::new(gradient.position(i, self.gradient_cyclic), gradient.midpoint(i), gradient.color(i)?)))
|
||||
.filter_map(|i| Some(SliderMarker::new(gradient.position(i, self.gradient_cyclic), gradient.midpoint(i), gradient.color(i)?)))
|
||||
.collect();
|
||||
let mut row_widgets = vec![
|
||||
SpectrumInput::new(GradientStops::from(gradient))
|
||||
SliderInput::new(GradientStops::from(gradient))
|
||||
.track_space(self.gradient_space)
|
||||
.track_cyclic(self.gradient_cyclic)
|
||||
.track_hue_direction(self.gradient_hue_direction)
|
||||
@@ -529,8 +529,9 @@ impl ColorPickerMessageHandler {
|
||||
.allow_insert(!self.disabled)
|
||||
.allow_delete(!self.disabled)
|
||||
.allow_reorder(true)
|
||||
.allow_select(true)
|
||||
.disabled(self.disabled)
|
||||
.on_update(|update: &SpectrumInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
|
||||
.on_update(|update: &SliderInputUpdate| ColorPickerMessage::GradientUpdate { update: update.clone() }.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
@@ -555,12 +556,12 @@ impl ColorPickerMessageHandler {
|
||||
return Message::NoOp;
|
||||
};
|
||||
let update = if is_midpoint {
|
||||
SpectrumInputUpdate::MoveMidpoint {
|
||||
SliderInputUpdate::MoveMidpoint {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
} else {
|
||||
SpectrumInputUpdate::MoveMarker {
|
||||
SliderInputUpdate::MoveMarker {
|
||||
index: captured_index,
|
||||
position: new_value / 100.,
|
||||
}
|
||||
|
||||
@@ -94,19 +94,38 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
let entries = [(FileType::Png, "PNG"), (FileType::Jpg, "JPG"), (FileType::Svg, "SVG")]
|
||||
// The vector type, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
(FileType::Webp, "WEBP"),
|
||||
(FileType::Tiff, "TIFF"),
|
||||
(FileType::Bmp, "BMP"),
|
||||
(FileType::Tga, "TGA"),
|
||||
(FileType::Ico, "ICO"),
|
||||
],
|
||||
];
|
||||
let selected_index = file_types.iter().flatten().position(|(file_type, _)| *file_type == self.file_type);
|
||||
let entries = file_types
|
||||
.into_iter()
|
||||
.map(|(file_type, name)| {
|
||||
RadioEntryData::new(format!("{file_type:?}"))
|
||||
.label(name)
|
||||
.on_update(move |_| ExportDialogMessage::FileType { file_type }.into())
|
||||
.map(|section| {
|
||||
section
|
||||
.into_iter()
|
||||
.map(|(file_type, name)| {
|
||||
MenuListEntry::new(format!("{file_type:?}"))
|
||||
.label(name)
|
||||
.on_commit(move |_| ExportDialogMessage::FileType { file_type }.into())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
|
||||
let export_type = vec![
|
||||
TextLabel::new("File Type").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
RadioInput::new(entries).selected_index(Some(self.file_type as u32)).widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(selected_index.map(|index| index as u32)).min_width(200).widget_instance(),
|
||||
];
|
||||
|
||||
let resolution = vec![
|
||||
|
||||
@@ -18,7 +18,7 @@ impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
|
||||
.tooltip_description("Save the raw document data to disk so it can be recovered later.")
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![PortfolioMessage::DownloadFailedToLoadDocuments.into()],
|
||||
followups: vec![FailedDocumentsMessage::DownloadFailedToLoadDocuments.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
@@ -27,7 +27,7 @@ impl DialogLayoutHolder for FailedToLoadDocumentsDialog {
|
||||
.tooltip_description("Permanently delete the autosaved data for these documents.")
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![PortfolioMessage::DiscardFailedToLoadDocuments.into()],
|
||||
followups: vec![FailedDocumentsMessage::DiscardFailedToLoadDocuments.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileFilter, RasterizedImage};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
@@ -9,6 +9,7 @@ use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||
@@ -87,11 +88,9 @@ pub enum FrontendMessage {
|
||||
commit_date: String,
|
||||
},
|
||||
TriggerDisplayThirdPartyLicensesDialog,
|
||||
TriggerOpen {
|
||||
filters: Vec<FileFilter>,
|
||||
},
|
||||
TriggerImport {
|
||||
filters: Vec<FileFilter>,
|
||||
TriggerBrowse {
|
||||
options: FileDialogOptions,
|
||||
action: IngestAction,
|
||||
},
|
||||
TriggerSaveDocument {
|
||||
document_id: DocumentId,
|
||||
@@ -110,7 +109,8 @@ pub enum FrontendMessage {
|
||||
TriggerExportImage {
|
||||
svg: String,
|
||||
name: String,
|
||||
mime: String,
|
||||
#[serde(rename = "fileType")]
|
||||
file_type: FileType,
|
||||
size: (f64, f64),
|
||||
},
|
||||
TriggerFetchAndOpenDocument {
|
||||
@@ -150,6 +150,10 @@ pub enum FrontendMessage {
|
||||
url: String,
|
||||
},
|
||||
TriggerClipboardRead,
|
||||
/// Copy a link to join the live session behind `token`, built from the page's own origin.
|
||||
TriggerSessionLinkCopy {
|
||||
token: String,
|
||||
},
|
||||
TriggerClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
|
||||
@@ -47,28 +47,30 @@ pub enum MouseCursorIcon {
|
||||
Rotate,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FileType {
|
||||
#[default]
|
||||
Png,
|
||||
Jpg,
|
||||
Webp,
|
||||
Tiff,
|
||||
Bmp,
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
pub fn to_mime(self) -> &'static str {
|
||||
match self {
|
||||
FileType::Png => "image/png",
|
||||
FileType::Jpg => "image/jpeg",
|
||||
FileType::Svg => "image/svg+xml",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self {
|
||||
FileType::Png => "png",
|
||||
FileType::Jpg => "jpg",
|
||||
FileType::Webp => "webp",
|
||||
FileType::Tiff => "tiff",
|
||||
FileType::Bmp => "bmp",
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
}
|
||||
}
|
||||
@@ -77,13 +79,64 @@ impl FileType {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
FileType::Jpg => "JPEG Image",
|
||||
FileType::Webp => "WEBP Image",
|
||||
FileType::Tiff => "TIFF Image",
|
||||
FileType::Bmp => "BMP Image",
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
extensions: vec![self.extension().into()],
|
||||
mime_types: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 8-bit RGBA pixels with straight alpha as a file of this raster type.
|
||||
pub fn encode(self, width: u32, height: u32, rgba: Vec<u8>) -> Result<Vec<u8>, String> {
|
||||
use image::buffer::ConvertBuffer;
|
||||
use image::{ImageFormat, RgbImage, RgbaImage};
|
||||
|
||||
let Some(mut image) = RgbaImage::from_raw(width, height, rgba) else {
|
||||
return Err("Failed to create image buffer for export".to_string());
|
||||
};
|
||||
|
||||
let format = match self {
|
||||
FileType::Png => ImageFormat::Png,
|
||||
FileType::Jpg => ImageFormat::Jpeg,
|
||||
FileType::Webp => ImageFormat::WebP,
|
||||
FileType::Tiff => ImageFormat::Tiff,
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
}
|
||||
|
||||
let mut encoded = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(&mut encoded);
|
||||
|
||||
let result = if self == FileType::Jpg {
|
||||
// Composite onto a white background since JPG doesn't support transparency
|
||||
for pixel in image.pixels_mut() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
let alpha = a as f32 / 255.;
|
||||
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
|
||||
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
|
||||
}
|
||||
|
||||
let image: RgbImage = image.convert();
|
||||
image.write_to(&mut cursor, format)
|
||||
} else {
|
||||
image.write_to(&mut cursor, format)
|
||||
};
|
||||
result.map_err(|error| format!("Failed to encode {self:?}: {error}"))?;
|
||||
|
||||
Ok(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -117,4 +170,49 @@ pub struct RasterizedImage {
|
||||
pub struct FileFilter {
|
||||
pub name: String,
|
||||
pub extensions: Vec<String>,
|
||||
#[serde(rename = "mimeTypes")]
|
||||
pub mime_types: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FileDialogOptions {
|
||||
pub filters: Vec<FileFilter>,
|
||||
pub multiple: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graphene_std::raster::Image;
|
||||
|
||||
#[test]
|
||||
fn every_raster_file_type_encodes_an_image_that_reads_back() {
|
||||
// Opaque red, then fully transparent
|
||||
let pixels = vec![255, 0, 0, 255, 0, 0, 0, 0];
|
||||
|
||||
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
|
||||
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
|
||||
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
|
||||
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
|
||||
|
||||
// Only JPG lacks transparency, so it lands on white
|
||||
let transparent = decoded.to_flat_u8().0[4..8].to_vec();
|
||||
if file_type == FileType::Jpg {
|
||||
assert!(transparent.iter().all(|&channel| channel > 250), "{transparent:?}");
|
||||
} else {
|
||||
assert_eq!(transparent[3], 0, "{file_type:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
assert!(too_large.contains("256 pixels"), "{too_large}");
|
||||
assert!(FileType::Ico.encode(256, 1, vec![0; 256 * 4]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -444,11 +444,11 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Tab); modifiers=[Control, Shift], action_dispatch=PortfolioMessage::PrevDocument),
|
||||
entry!(KeyDown(KeyW); modifiers=[Accel], action_dispatch=PortfolioMessage::CloseActiveDocumentWithConfirmation),
|
||||
entry!(KeyDown(KeyW); modifiers=[Accel, Alt], action_dispatch=PortfolioMessage::CloseAllDocumentsWithConfirmation),
|
||||
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=PortfolioMessage::Open),
|
||||
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=PortfolioMessage::Import),
|
||||
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=IngestMessage::Open),
|
||||
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=IngestMessage::Import),
|
||||
entry!(KeyDown(KeyR); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleRulers),
|
||||
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleDataPanelOpen),
|
||||
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleFocusDocument),
|
||||
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=WorkspaceMessage::ToggleDataPanelOpen),
|
||||
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=WorkspaceMessage::ToggleFocusDocument),
|
||||
//
|
||||
// DialogMessage
|
||||
entry!(KeyDown(KeyE); modifiers=[Accel], action_dispatch=DialogMessage::RequestExportDialog),
|
||||
|
||||
@@ -30,4 +30,9 @@ pub enum LayoutMessage {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
},
|
||||
WidgetValueFileDrop {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
file: DroppedFile,
|
||||
},
|
||||
}
|
||||
@@ -76,6 +76,21 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
responses.add((icon_button.on_drag_drop.callback)(icon_button));
|
||||
}
|
||||
}
|
||||
LayoutMessage::WidgetValueFileDrop { layout_target, widget_id, file } => {
|
||||
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
|
||||
warn!("WidgetValueFileDrop referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
|
||||
warn!("WidgetValueFileDrop referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
if let Widget::DropdownInput(dropdown_input) = &*widget_instance.widget
|
||||
&& dropdown_input.takes_file_drop
|
||||
{
|
||||
responses.add((dropdown_input.on_file_drop.callback)(&file));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,20 +270,34 @@ impl LayoutMessageHandler {
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
Widget::SliderInput(slider_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (spectrum_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Commit => (slider_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<SpectrumInputUpdate>(value) else {
|
||||
warn!("SpectrumInput update was not able to be parsed as SpectrumInputUpdate");
|
||||
let Ok(update) = serde_json::from_value::<SliderInputUpdate>(value) else {
|
||||
warn!("SliderInput update was not able to be parsed as SliderInputUpdate");
|
||||
return;
|
||||
};
|
||||
// Don't mutate the stored widget here: leaving its old values lets the layout diff detect a change
|
||||
// when the new layout is rebuilt with the updated state. Otherwise the frontend's stored layout
|
||||
// keeps stale values for `activeMarkerIndex`, etc., and any other widget's diff (e.g. the position
|
||||
// NumberInput) will trigger Svelte to re-spread those stale props onto SpectrumInput, clobbering
|
||||
// NumberInput) will trigger Svelte to re-spread those stale props onto SliderInput, clobbering
|
||||
// its local `activeMarkerIndex` and making subsequent drags target the wrong stop.
|
||||
(spectrum_input.on_update.callback)(&update)
|
||||
(slider_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(callback_message);
|
||||
}
|
||||
Widget::TransferCurveInput(curve_input) => {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (curve_input.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(update) = serde_json::from_value::<TransferCurveInputUpdate>(value) else {
|
||||
warn!("TransferCurveInput update was not able to be parsed as TransferCurveInputUpdate");
|
||||
return;
|
||||
};
|
||||
(curve_input.on_update.callback)(&update)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -532,22 +561,47 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
for instance in layout.iter_mut() {
|
||||
match &mut *instance.widget {
|
||||
Widget::ColorInput(color_input) => {
|
||||
color_input.chosen_gradient = color_input.value.to_css_background_image();
|
||||
color_input.swatch_samples = match &color_input.value {
|
||||
FillChoice::None => Vec::new(),
|
||||
FillChoice::Solid(color) => vec![GradientSample::new(0., graphene_std::Color::from(*color))],
|
||||
FillChoice::Gradient(ramp) => graphene_std::vector::style::Gradient::from(&ramp.stops)
|
||||
.interpolated_samples_or_black(ramp.into())
|
||||
.into_iter()
|
||||
.map(|(position, color, _)| GradientSample::new(position, color))
|
||||
.collect(),
|
||||
};
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
Widget::TransferCurveInput(curve_input) => {
|
||||
const SAMPLE_COUNT: usize = 128;
|
||||
let curve = graphene_std::transfer_curve::TransferCurve::new(curve_input.points.iter().map(|&(x, y)| glam::DVec2::new(x, y)).collect());
|
||||
let evaluator = curve.evaluator();
|
||||
let [x_min, x_max] = curve_input.domain;
|
||||
let [y_min, y_max] = curve_input.range;
|
||||
let (x_span, y_span) = ((x_max - x_min).max(f64::EPSILON), (y_max - y_min).max(f64::EPSILON));
|
||||
// A spline overshooting the range rides its edge as a flat line, as the clamped adjustment it depicts does
|
||||
let clamp_to_range = curve_input.clamp_to_range;
|
||||
curve_input.samples = (0..=SAMPLE_COUNT)
|
||||
.map(|i| {
|
||||
let t = i as f64 / SAMPLE_COUNT as f64;
|
||||
let y = (evaluator.evaluate(x_min + t * x_span) - y_min) / y_span;
|
||||
(t, if clamp_to_range { y.clamp(0., 1.) } else { y })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
Widget::SliderInput(slider_input) => {
|
||||
// The track strip spans exactly 0 to 1, which no spread affects, so the widget carries no spread of its own
|
||||
let settings = graphene_std::vector::style::GradientSettings {
|
||||
spread: Default::default(),
|
||||
cyclic: spectrum_input.track_cyclic,
|
||||
space: spectrum_input.track_space,
|
||||
hue_direction: spectrum_input.track_hue_direction,
|
||||
interpolation: spectrum_input.track_interpolation,
|
||||
cyclic: slider_input.track_cyclic,
|
||||
space: slider_input.track_space,
|
||||
hue_direction: slider_input.track_hue_direction,
|
||||
interpolation: slider_input.track_interpolation,
|
||||
};
|
||||
let track_gradient = graphene_std::vector::style::Gradient::from(&spectrum_input.track);
|
||||
spectrum_input.track_samples = track_gradient
|
||||
let track_gradient = graphene_std::vector::style::Gradient::from(&slider_input.track);
|
||||
slider_input.track_samples = track_gradient
|
||||
.interpolated_samples_or_black(settings)
|
||||
.into_iter()
|
||||
.map(|(position, color, _)| SpectrumSample::new(position, color))
|
||||
.map(|(position, color, _)| GradientSample::new(position, color))
|
||||
.collect();
|
||||
// The end caps sample the track's boundary colors, which a cyclic wrap makes the wrapped interval's boundary-crossing color rather than the outermost stops'
|
||||
let track_evaluator = track_gradient.evaluator(settings);
|
||||
@@ -555,8 +609,8 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
let color = track_evaluator.evaluate(t);
|
||||
SRGBA8::from(color).to_css_hex()
|
||||
};
|
||||
spectrum_input.track_start_css = cap(0.);
|
||||
spectrum_input.track_end_css = cap(1.);
|
||||
slider_input.track_start_css = cap(0.);
|
||||
slider_input.track_end_css = cap(1.);
|
||||
}
|
||||
Widget::ColorComparisonInput(comparison) => {
|
||||
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
|
||||
|
||||
@@ -470,7 +470,8 @@ impl LayoutGroup {
|
||||
| Widget::ParameterExposeButton(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::SliderInput(_)
|
||||
| Widget::TransferCurveInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => continue,
|
||||
};
|
||||
if val.is_empty() {
|
||||
@@ -808,6 +809,7 @@ pub enum Widget {
|
||||
ColorComparisonInput(ColorComparisonInput),
|
||||
ColorInput(ColorInput),
|
||||
ColorPresetsInput(ColorPresetsInput),
|
||||
TransferCurveInput(TransferCurveInput),
|
||||
DropdownInput(DropdownInput),
|
||||
IconButton(IconButton),
|
||||
IconLabel(IconLabel),
|
||||
@@ -821,7 +823,7 @@ pub enum Widget {
|
||||
PopoverButton(PopoverButton),
|
||||
RadioInput(RadioInput),
|
||||
Separator(Separator),
|
||||
SpectrumInput(SpectrumInput),
|
||||
SliderInput(SliderInput),
|
||||
TextAreaInput(TextAreaInput),
|
||||
TextButton(TextButton),
|
||||
TextInput(TextInput),
|
||||
@@ -886,7 +888,8 @@ impl DiffUpdate {
|
||||
| Widget::WorkingColorsInput(_)
|
||||
| Widget::ColorComparisonInput(_)
|
||||
| Widget::ColorPresetsInput(_)
|
||||
| Widget::SpectrumInput(_)
|
||||
| Widget::SliderInput(_)
|
||||
| Widget::TransferCurveInput(_)
|
||||
| Widget::VisualColorPickersInput(_) => None,
|
||||
};
|
||||
|
||||
|
||||
@@ -193,11 +193,11 @@ pub struct ColorInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub value: FillChoice<SRGBA8>,
|
||||
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
|
||||
/// `None` when `value` is `FillChoice::<SRGBA8>::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "chosenGradient")]
|
||||
/// Straight-alpha color samples drawn by the frontend as the stops of an SVG gradient filling the swatch. Auto-populated from `value` at layout-send time.
|
||||
/// Empty when `value` is `FillChoice::<SRGBA8>::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "swatchSamples")]
|
||||
#[widget_builder(skip)]
|
||||
pub chosen_gradient: Option<String>,
|
||||
pub swatch_samples: Vec<GradientSample>,
|
||||
#[serde(rename = "allowNone")]
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub allow_none: bool,
|
||||
|
||||
@@ -83,6 +83,10 @@ pub struct DropdownInput {
|
||||
pub virtual_scrolling: bool,
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub interactive: bool,
|
||||
// Set along with the `on_file_drop` callback
|
||||
#[serde(rename = "takesFileDrop")]
|
||||
#[widget_builder(skip)]
|
||||
pub takes_file_drop: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
@@ -97,8 +101,28 @@ pub struct DropdownInput {
|
||||
pub tooltip_description: String,
|
||||
#[serde(rename = "tooltipShortcut")]
|
||||
pub tooltip_shortcut: Option<ActionShortcut>,
|
||||
//
|
||||
// Callbacks exists on the `MenuListEntry` children, not this parent `DropdownInput`
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
#[widget_builder(skip)]
|
||||
pub on_file_drop: WidgetCallback<DroppedFile>,
|
||||
}
|
||||
|
||||
impl DropdownInput {
|
||||
/// Makes the widget take a file dropped on it, which is handed to the callback.
|
||||
pub fn on_file_drop(mut self, callback: impl Fn(&DroppedFile) -> Message + 'static + Send + Sync) -> Self {
|
||||
self.takes_file_drop = true;
|
||||
self.on_file_drop = WidgetCallback::new(callback);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DroppedFile {
|
||||
pub name: String,
|
||||
pub mime_type: String,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
pub type MenuListEntrySections = Vec<Vec<MenuListEntry>>;
|
||||
@@ -581,7 +605,50 @@ pub enum ColorPresetsInputUpdate {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct SpectrumInput {
|
||||
pub struct TransferCurveInput {
|
||||
// Content
|
||||
/// The control points in the units of `domain` and `range`, in any x order, since sampling sorts them.
|
||||
#[widget_builder(constructor)]
|
||||
pub points: Vec<(f64, f64)>,
|
||||
/// The x extent the box spans, left to right.
|
||||
pub domain: [f64; 2],
|
||||
/// The y extent the box spans, bottom to top.
|
||||
pub range: [f64; 2],
|
||||
/// Whether the drawn curve and a dragged point's y stay inside `range`. A point's x always stays inside `domain`.
|
||||
#[serde(rename = "clampToRange")]
|
||||
pub clamp_to_range: bool,
|
||||
/// Polyline of the curve in box-normalized 0..1 coordinates with y upward. Auto-populated from `points` at layout-send time.
|
||||
#[widget_builder(skip)]
|
||||
pub samples: Vec<(f64, f64)>,
|
||||
/// Whether clicking empty space inserts a point.
|
||||
#[serde(rename = "allowInsert")]
|
||||
pub allow_insert: bool,
|
||||
/// Whether double-click or right-click removes a point. The handler still has the final say (e.g., enforcing a minimum count).
|
||||
#[serde(rename = "allowDelete")]
|
||||
pub allow_delete: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<TransferCurveInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransferCurveInputUpdate {
|
||||
MovePoint { index: u32, x: f64, y: f64 },
|
||||
InsertPoint { x: f64, y: f64 },
|
||||
DeletePoint { index: u32 },
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct SliderInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
@@ -598,10 +665,10 @@ pub struct SpectrumInput {
|
||||
/// The path the track's stops interpolate along, used to bake `track_samples` and by the frontend to suppress the midpoint diamonds when stepped.
|
||||
#[serde(rename = "trackInterpolation")]
|
||||
pub track_interpolation: GradientInterpolation,
|
||||
/// Straight-alpha samples the frontend draws as the stops of an SVG gradient filling the track strip. Auto-populated from `track` at layout-send time.
|
||||
/// Straight-alpha color samples drawn by the frontend as the stops of an SVG gradient filling the track strip. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackSamples")]
|
||||
#[widget_builder(skip)]
|
||||
pub track_samples: Vec<SpectrumSample>,
|
||||
pub track_samples: Vec<GradientSample>,
|
||||
/// Hex string for the track strip's leftmost solid-color end-cap. Auto-populated by evaluating `track` at position 0.
|
||||
#[serde(rename = "trackStartCSS")]
|
||||
#[widget_builder(skip)]
|
||||
@@ -611,7 +678,7 @@ pub struct SpectrumInput {
|
||||
#[widget_builder(skip)]
|
||||
pub track_end_css: String,
|
||||
/// The handles the user can drag along the track. Their handle colors are caller-owned (e.g., for a gradient editor they follow the stop colors, for a "Shadows/Midpoints/Highlights" widget they're hardcoded).
|
||||
pub markers: Vec<SpectrumMarker>,
|
||||
pub markers: Vec<SliderMarker>,
|
||||
#[serde(rename = "activeMarkerIndex")]
|
||||
pub active_marker_index: Option<u32>,
|
||||
#[serde(rename = "activeMarkerIsMidpoint")]
|
||||
@@ -619,24 +686,34 @@ pub struct SpectrumInput {
|
||||
/// Whether to render midpoint diamonds between adjacent markers (only meaningful for gradient-like uses).
|
||||
#[serde(rename = "showMidpoints")]
|
||||
pub show_midpoints: bool,
|
||||
/// Whether clicking the track inserts a new marker at the click position.
|
||||
/// Whether clicking the track inserts a new marker at the click position. Otherwise the click picks up the nearest marker.
|
||||
#[serde(rename = "allowInsert")]
|
||||
pub allow_insert: bool,
|
||||
/// Whether right-click or pressing Delete removes a marker. The handler still has the final say on whether the deletion goes through (e.g., enforcing a minimum count).
|
||||
#[serde(rename = "allowDelete")]
|
||||
pub allow_delete: bool,
|
||||
/// Whether dragging a marker past another reorders them. If false, the dragged marker is clamped between its neighbors.
|
||||
/// Whether dragging a marker past another reorders them, which also needs `allow_select`. Otherwise the dragged marker is clamped between its neighbors.
|
||||
#[serde(rename = "allowReorder")]
|
||||
pub allow_reorder: bool,
|
||||
/// Whether the track's ends meet, as on a hue wheel: a run dragged by its strip or dashed link wraps past them, a lone marker stops.
|
||||
#[serde(rename = "allowWrap")]
|
||||
pub allow_wrap: bool,
|
||||
/// Whether clicking a marker selects it, keeping it highlighted and reported as the active marker until another is chosen,
|
||||
/// as a gradient editor needs for the stop being edited. Otherwise the highlight only follows the pointer and the drag.
|
||||
#[serde(rename = "allowSelect")]
|
||||
pub allow_select: bool,
|
||||
/// Compact mode: 8px track height with 8px top padding, for use in rows alongside other widgets.
|
||||
pub narrow: bool,
|
||||
/// Plain range-slider mode, for a number beside its number input: a flat 4px track is drawn in place of the gradient, so `track` is never shown.
|
||||
#[serde(rename = "rangeSlider")]
|
||||
pub range_slider: bool,
|
||||
/// Whether the input is disabled (dimmed and read-only).
|
||||
pub disabled: bool,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_update: WidgetCallback<SpectrumInputUpdate>,
|
||||
pub on_update: WidgetCallback<SliderInputUpdate>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
@@ -644,30 +721,59 @@ pub struct SpectrumInput {
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SpectrumMarker {
|
||||
/// Position of the marker along the spectrum track, normally from 0 to 1. A shifted or stretched non-cyclic ramp can
|
||||
/// place it outside that range, where the track draws only the markers falling within its visible span.
|
||||
pub struct SliderMarker {
|
||||
/// Position along the track, normally 0..1. A shifted or stretched non-cyclic ramp can push it outside, where it is not drawn.
|
||||
position: f64,
|
||||
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true.
|
||||
/// The last marker's value controls the wrapped interval when `track_cyclic` is set, and is otherwise ignored.
|
||||
/// Midpoint (0..1) of the interval to the next marker, used only with `show_midpoints`. The last marker's midpoint spans the wrap of a cyclic track, or is otherwise ignored.
|
||||
midpoint: f64,
|
||||
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`],
|
||||
/// CSS color string for the marker handle's fill. Set via `SliderMarker::new` from a linear [`Color`],
|
||||
/// discarding any transparency so the handle always shows the RGB that steers the interpolation.
|
||||
#[serde(rename = "handleColorCSS")]
|
||||
handle_color_css: String,
|
||||
/// Whether this marker and the next form a split handle: one marker split down the middle while they coincide, two halves joined by a strip once apart.
|
||||
#[serde(rename = "pairedWithNext")]
|
||||
paired_with_next: bool,
|
||||
/// Whether a dashed line runs from this marker to the next through the lane below the track. Dragging it carries both markers, along with any split-handle halves attached to them.
|
||||
#[serde(rename = "dashedToNext")]
|
||||
dashed_to_next: bool,
|
||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||
#[serde(rename = "betweenNeighbors")]
|
||||
between_neighbors: bool,
|
||||
}
|
||||
|
||||
impl SpectrumMarker {
|
||||
impl SliderMarker {
|
||||
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
|
||||
let handle_color_css = format!("#{}", SRGBA8::from(handle_color).to_rgb_hex());
|
||||
Self { position, midpoint, handle_color_css }
|
||||
Self {
|
||||
position,
|
||||
midpoint,
|
||||
handle_color_css,
|
||||
paired_with_next: false,
|
||||
dashed_to_next: false,
|
||||
between_neighbors: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn between_neighbors(mut self) -> Self {
|
||||
self.between_neighbors = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pair_with_next(mut self) -> Self {
|
||||
self.paired_with_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dash_to_next(mut self) -> Self {
|
||||
self.dashed_to_next = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SpectrumSample {
|
||||
/// Position (0..1) of the sample along the spectrum track, drawn as the SVG stop's `offset`.
|
||||
pub struct GradientSample {
|
||||
/// Position (0..1) of the sample along the gradient, drawn as the SVG stop's `offset`.
|
||||
position: f64,
|
||||
/// `#rrggbb` hex of the sample's color, drawn as the SVG stop's `stop-color`.
|
||||
color: String,
|
||||
@@ -675,7 +781,7 @@ pub struct SpectrumSample {
|
||||
alpha: f32,
|
||||
}
|
||||
|
||||
impl SpectrumSample {
|
||||
impl GradientSample {
|
||||
pub fn new(position: f64, color: Color) -> Self {
|
||||
Self {
|
||||
position,
|
||||
@@ -687,7 +793,7 @@ impl SpectrumSample {
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SpectrumInputUpdate {
|
||||
pub enum SliderInputUpdate {
|
||||
MoveMarker {
|
||||
index: u32,
|
||||
position: f64,
|
||||
|
||||
@@ -123,8 +123,8 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Open…")
|
||||
.label("Open…")
|
||||
.icon("Folder")
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Open))
|
||||
.on_commit(|_| PortfolioMessage::Open.into()),
|
||||
.tooltip_shortcut(action_shortcut!(IngestMessageDiscriminant::Open))
|
||||
.on_commit(|_| IngestMessage::Open.into()),
|
||||
MenuListEntry::new("Open Demo Artwork…")
|
||||
.label("Open Demo Artwork…")
|
||||
.icon("Image")
|
||||
@@ -163,8 +163,8 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Import…")
|
||||
.label("Import…")
|
||||
.icon("FileImport")
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::Import))
|
||||
.on_commit(|_| PortfolioMessage::Import.into())
|
||||
.tooltip_shortcut(action_shortcut!(IngestMessageDiscriminant::Import))
|
||||
.on_commit(|_| IngestMessage::Import.into())
|
||||
.disabled(no_active_document),
|
||||
MenuListEntry::new("Export…")
|
||||
.label("Export…")
|
||||
@@ -173,6 +173,17 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
||||
.disabled(no_active_document),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Share Live Session")
|
||||
.label("Share Live Session")
|
||||
.icon("Link")
|
||||
.on_commit(|_| SyncMessage::Share.into())
|
||||
.disabled(no_active_document),
|
||||
MenuListEntry::new("Leave Live Session")
|
||||
.label("Leave Live Session")
|
||||
.on_commit(|_| SyncMessage::Leave.into())
|
||||
.disabled(no_active_document),
|
||||
],
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
vec![preferences],
|
||||
])
|
||||
@@ -651,33 +662,33 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
MenuListEntry::new("Focus Document")
|
||||
.label("Focus Document")
|
||||
.icon(if self.focus_document { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleFocusDocument))
|
||||
.on_commit(|_| PortfolioMessage::ToggleFocusDocument.into()),
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleFocusDocument))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleFocusDocument.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Reset Workspace")
|
||||
.label("Reset Workspace")
|
||||
.icon("Reset")
|
||||
.on_commit(|_| PortfolioMessage::ResetWorkspaceLayout.into()),
|
||||
.on_commit(|_| WorkspaceMessage::ResetWorkspaceLayout.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Properties")
|
||||
.label("Properties")
|
||||
.icon(if self.properties_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::TogglePropertiesPanelOpen))
|
||||
.on_commit(|_| PortfolioMessage::TogglePropertiesPanelOpen.into())
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::TogglePropertiesPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::TogglePropertiesPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Layers")
|
||||
.label("Layers")
|
||||
.icon(if self.layers_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleLayersPanelOpen))
|
||||
.on_commit(|_| PortfolioMessage::ToggleLayersPanelOpen.into())
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleLayersPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleLayersPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Data")
|
||||
.label("Data")
|
||||
.icon(if self.data_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.tooltip_shortcut(action_shortcut!(PortfolioMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| PortfolioMessage::ToggleDataPanelOpen.into())
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
],
|
||||
])
|
||||
|
||||
@@ -10,17 +10,20 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::text::TextAlign;
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
|
||||
@@ -228,6 +231,7 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<GradientInterpolation>,
|
||||
List<DashPattern>,
|
||||
List<BoxCorners>,
|
||||
List<TransferCurve>,
|
||||
List<StrokeJoin>,
|
||||
List<StrokeAlign>,
|
||||
List<StrokeCap>,
|
||||
@@ -235,11 +239,15 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<ExtrudeJoiningAlgorithm>,
|
||||
List<PointSpacingType>,
|
||||
List<StringCapitalization>,
|
||||
List<LuminanceCalculation>,
|
||||
List<TextDenomination>,
|
||||
List<DesaturateMethod>,
|
||||
List<RedGreenBlue>,
|
||||
List<RedGreenBlueAlpha>,
|
||||
List<RelativeAbsolute>,
|
||||
List<SelectiveColorChoice>,
|
||||
List<TonalRange>,
|
||||
List<AdjustmentChannel>,
|
||||
List<HueSaturationRange>,
|
||||
List<XY>,
|
||||
List<ScaleType>,
|
||||
List<ReferencePoint>,
|
||||
@@ -283,6 +291,7 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<GradientInterpolation>,
|
||||
Item<DashPattern>,
|
||||
Item<BoxCorners>,
|
||||
Item<TransferCurve>,
|
||||
Item<StrokeJoin>,
|
||||
Item<StrokeAlign>,
|
||||
Item<StrokeCap>,
|
||||
@@ -290,11 +299,15 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<ExtrudeJoiningAlgorithm>,
|
||||
Item<PointSpacingType>,
|
||||
Item<StringCapitalization>,
|
||||
Item<LuminanceCalculation>,
|
||||
Item<TextDenomination>,
|
||||
Item<DesaturateMethod>,
|
||||
Item<RedGreenBlue>,
|
||||
Item<RedGreenBlueAlpha>,
|
||||
Item<RelativeAbsolute>,
|
||||
Item<SelectiveColorChoice>,
|
||||
Item<TonalRange>,
|
||||
Item<AdjustmentChannel>,
|
||||
Item<HueSaturationRange>,
|
||||
Item<XY>,
|
||||
Item<ScaleType>,
|
||||
Item<ReferencePoint>,
|
||||
@@ -562,6 +575,26 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"Transfer Curve"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
let points = self.points().len();
|
||||
format!("Transfer Curve ({points} {})", if points == 1 { "point" } else { "points" })
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for BoxCorners {
|
||||
fn type_name() -> &'static str {
|
||||
"BoxCorners"
|
||||
@@ -827,20 +860,32 @@ macro_rules! impl_table_item_layout_for_number {
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_number!(
|
||||
f32 => "Number (f32)",
|
||||
u32 => "Number (u32)",
|
||||
i32 => "Number (i32)",
|
||||
u64 => "Number (u64)",
|
||||
i64 => "Number (i64)",
|
||||
);
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
|
||||
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
// Denoised so 0.1 + 0.2 reads as 0.3 rather than 0.30000000000000004. We don't do this for f32 because it lacks precision to reliably distinguish between intentional digits and noise.
|
||||
impl TableItemLayout for f64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{}", round_away_float_noise(*self))
|
||||
format_f64(round_away_float_noise(*self))
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
@@ -932,7 +977,7 @@ impl TableItemLayout for Option<f64> {
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let text = match self {
|
||||
Some(value) => format!("Some({})", round_away_float_noise(*value)),
|
||||
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
|
||||
@@ -1039,11 +1084,15 @@ impl_table_item_layout_for_choice_enum!(
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
CentroidType,
|
||||
@@ -1243,6 +1292,7 @@ macro_rules! known_item_types {
|
||||
Cover,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
@@ -1256,11 +1306,15 @@ macro_rules! known_item_types {
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
LuminanceCalculation,
|
||||
TextDenomination,
|
||||
DesaturateMethod,
|
||||
RedGreenBlue,
|
||||
RedGreenBlueAlpha,
|
||||
RelativeAbsolute,
|
||||
SelectiveColorChoice,
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
XY,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::Registry;
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
use document_graph_storage::{Declarations, Registry};
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
|
||||
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
|
||||
@@ -24,6 +24,19 @@ pub struct DocumentHistory {
|
||||
/// future built by `load_document` resolves.
|
||||
#[derivative(Debug = "ignore")]
|
||||
storage: Option<document_format::GddV1>,
|
||||
/// Decoded proto-node declarations for every registry state the cursor can reach, filled at mount
|
||||
/// and extended on each staging, so a cursor rebuild never touches the byte store.
|
||||
#[derivative(Debug = "ignore")]
|
||||
declarations: Declarations,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CursorMoveError {
|
||||
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
|
||||
NotMoved,
|
||||
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
|
||||
RebuildFailed,
|
||||
}
|
||||
|
||||
impl DocumentHistory {
|
||||
@@ -79,9 +92,10 @@ impl DocumentHistory {
|
||||
self.storage.as_mut()
|
||||
}
|
||||
|
||||
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
|
||||
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
|
||||
self.storage = storage;
|
||||
/// 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.storage = Some(storage);
|
||||
self.declarations = declarations;
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
|
||||
@@ -119,9 +133,12 @@ impl DocumentHistory {
|
||||
|
||||
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
|
||||
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
match storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
|
||||
Ok(declarations) => self.declarations.extend(declarations),
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(error) = storage.set_view_settings(view_settings) {
|
||||
@@ -142,31 +159,81 @@ impl DocumentHistory {
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
|
||||
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
|
||||
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
|
||||
/// unmounted, or the move failed.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
|
||||
/// first, and rebuild the interface from the rewound registry using the declaration cache.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
|
||||
self.retire_storage_interaction();
|
||||
|
||||
let storage = self.storage.as_mut()?;
|
||||
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return None;
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.undo().map(|_| ())
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return None;
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.redo().map(|_| ())
|
||||
};
|
||||
if let Err(error) = moved {
|
||||
log::error!("Storage undo/redo cursor move failed: {error}");
|
||||
return None;
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
|
||||
Some(storage.clone())
|
||||
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
|
||||
}
|
||||
|
||||
/// Build a fresh interface from the working registry, using the declaration cache so no resource load
|
||||
/// is needed. `None` (logged) when the registry does not convert.
|
||||
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
|
||||
let storage = self.storage.as_ref()?;
|
||||
|
||||
let rebuilt = 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()));
|
||||
|
||||
match rebuilt {
|
||||
Ok(interface) => Some(interface),
|
||||
Err(error) => {
|
||||
log::error!("Storage interface rebuild failed: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache a resource that arrived from a peer as a proto-node declaration, under every declaration
|
||||
/// resource referencing its hash. Ignores resources no declaration refers to (images, fonts).
|
||||
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) {
|
||||
let Some(storage) = self.storage.as_ref() else { return };
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
match document_graph_storage::decode_declaration(bytes) {
|
||||
Ok(declaration) => self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone()))),
|
||||
Err(error) => log::error!("Failed to deserialize a received ProtoNode declaration: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
|
||||
/// direction whose rebuild failed.
|
||||
pub fn revert_cursor(&mut self, undo: bool) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let reverted = if undo { storage.redo() } else { storage.undo() };
|
||||
if let Err(error) = reverted {
|
||||
log::error!("Storage undo/redo cursor revert failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
|
||||
@@ -193,13 +260,7 @@ impl DocumentHistory {
|
||||
}
|
||||
};
|
||||
let target = &conversion.registry;
|
||||
let declarations = match conversion.declarations() {
|
||||
Ok(declarations) => declarations,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: declaration rebuild failed: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let declarations = &conversion.declarations;
|
||||
|
||||
let stored = storage.registry();
|
||||
if !stored.value_equal(target) {
|
||||
@@ -213,7 +274,7 @@ impl DocumentHistory {
|
||||
panic!("storage round-trip: timestamp order inconsistent between stored and target");
|
||||
}
|
||||
|
||||
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(&declarations) {
|
||||
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: to_runtime failed: {error}");
|
||||
|
||||
@@ -9,12 +9,10 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, GridSnapping};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2};
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::click_target::ClickTarget;
|
||||
@@ -117,7 +115,8 @@ pub enum DocumentMessage {
|
||||
},
|
||||
InsertImage {
|
||||
name: Option<String>,
|
||||
image: Image<Color>,
|
||||
data: Arc<[u8]>,
|
||||
size: UVec2,
|
||||
mouse: Option<(f64, f64)>,
|
||||
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
|
||||
/// When true (file-open flow), place the image at the document origin so `WrapContentInArtboard`
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::DocumentHistory;
|
||||
use super::document_diff::diff_networks;
|
||||
use super::node_graph::document_node_definitions;
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
|
||||
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
|
||||
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
|
||||
use super::{CursorMoveError, DocumentHistory};
|
||||
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
|
||||
@@ -32,8 +32,9 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use document_graph_storage::Declarations;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceStorage};
|
||||
use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
@@ -148,6 +149,10 @@ pub struct DocumentMessageHandler {
|
||||
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
|
||||
#[serde(skip)]
|
||||
history: DocumentHistory,
|
||||
/// Peers changed the registry and the interface hasn't been rebuilt from it yet, so a staged diff
|
||||
/// would read as reverting their edits.
|
||||
#[serde(skip)]
|
||||
pub(crate) runtime_stale: bool,
|
||||
/// Hash of the document snapshot that was most recently saved to disk by the user.
|
||||
#[serde(skip)]
|
||||
saved_hash: Option<u64>,
|
||||
@@ -199,6 +204,7 @@ impl Default for DocumentMessageHandler {
|
||||
breadcrumb_network_path: Vec::new(),
|
||||
selection_network_path: Vec::new(),
|
||||
history: DocumentHistory::default(),
|
||||
runtime_stale: false,
|
||||
saved_hash: None,
|
||||
auto_saved_hash: None,
|
||||
layer_range_selection_reference: None,
|
||||
@@ -249,6 +255,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::PropertiesPanel(message) => {
|
||||
let context = PropertiesPanelMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
network_interface: &mut self.network_interface,
|
||||
resources: &self.resources,
|
||||
selection_network_path: &self.selection_network_path,
|
||||
@@ -405,8 +412,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
|
||||
self.layer_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, resource_storage, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, resource_storage, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -797,15 +804,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
DocumentMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
data,
|
||||
size,
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
place_at_origin,
|
||||
} => {
|
||||
// All the image's pixels have been converted to 0..=1, linear, and premultiplied by `Color::from_rgba8_srgb`
|
||||
|
||||
let layer_parent = self.new_layer_parent(true);
|
||||
let image_size = DVec2::new(image.width as f64, image.height as f64);
|
||||
let image_size = size.as_dvec2();
|
||||
|
||||
let mut transform = if place_at_origin {
|
||||
// File-open flow: place at document origin without centering so `WrapContentInArtboard` can wrap it
|
||||
@@ -813,7 +819,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} else {
|
||||
// Clipboard paste or drag-drop: center at cursor or viewport center.
|
||||
// Convert the document-space cursor to the parent's local coordinate space so that
|
||||
// an artboard at a non-zero position does not offset the placement.
|
||||
// an artboard at a nonzero position does not offset the placement.
|
||||
let parent_to_document = {
|
||||
let metadata = self.metadata();
|
||||
metadata.document_to_viewport.inverse() * metadata.transform_to_viewport(layer_parent)
|
||||
@@ -828,7 +834,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(image, layer_node_id, layer_parent, responses);
|
||||
let layer = graph_modification_utils::new_image_layer(data, layer_node_id, layer_parent, responses);
|
||||
|
||||
if let Some(name) = name {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
@@ -876,7 +882,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} else {
|
||||
// Clipboard paste or drag-drop: center at cursor or viewport center.
|
||||
// Convert the document-space cursor to the parent's local coordinate space so that
|
||||
// an artboard at a non-zero position does not offset the placement.
|
||||
// an artboard at a nonzero position does not offset the placement.
|
||||
let parent_to_document = {
|
||||
let metadata = self.metadata();
|
||||
metadata.document_to_viewport.inverse() * metadata.transform_to_viewport(layer_parent)
|
||||
@@ -1100,6 +1106,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".into(),
|
||||
extensions: vec![extension.into()],
|
||||
mime_types: Vec::new(),
|
||||
}],
|
||||
content: content.into(),
|
||||
})
|
||||
@@ -1807,7 +1814,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, 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,
|
||||
@@ -1816,11 +1830,7 @@ impl DocumentMessageHandler {
|
||||
};
|
||||
|
||||
document.apply_stored_document_settings(storage.view_settings());
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => document.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
|
||||
}
|
||||
document.history.set_storage(Some(storage));
|
||||
document.set_storage(storage, declarations, byte_store);
|
||||
|
||||
document
|
||||
}
|
||||
@@ -2015,9 +2025,11 @@ impl DocumentMessageHandler {
|
||||
self.history.storage_mut()
|
||||
}
|
||||
|
||||
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
|
||||
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
|
||||
self.history.set_storage(storage);
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
|
||||
storage.set_byte_store(byte_store);
|
||||
self.history.set_storage(storage, declarations);
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
|
||||
@@ -2029,7 +2041,7 @@ impl DocumentMessageHandler {
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
|
||||
if self.history.storage().is_none() {
|
||||
if self.history.storage().is_none() || self.runtime_stale {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2081,24 +2093,46 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor and spawn the async future that rebuilds the
|
||||
/// interface from the cursor and swaps it in. `had_oracle` records whether the legacy snapshot already
|
||||
/// applied, so the completion can compare; it travels with the spawned message. Returns whether the
|
||||
/// cursor moved, so callers know a rebuild is pending.
|
||||
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
|
||||
let Some(gdd) = self.history.move_cursor(undo) else { return false };
|
||||
/// Move the `Gdd` undo/redo cursor and swap in the interface rebuilt from it. `had_oracle` records
|
||||
/// whether the legacy snapshot already applied, so the rebuild can be compared against it.
|
||||
fn drive_storage_undo_redo(&mut self, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
match self.history.move_cursor(undo) {
|
||||
Ok(rebuilt) => self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses),
|
||||
Err(CursorMoveError::NotMoved) => {}
|
||||
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
|
||||
Err(CursorMoveError::RebuildFailed) => {
|
||||
if !had_oracle {
|
||||
self.history.revert_cursor(undo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(crate::messages::portfolio::document_storage_io::rebuild_gdd_cursor(
|
||||
gdd,
|
||||
resource_storage.resources_mut(),
|
||||
document_id,
|
||||
had_oracle,
|
||||
));
|
||||
true
|
||||
/// Rebuild the runtime resource registry from storage, which holds each resource's id, content hash
|
||||
/// and sources. The preprocessor resolves a node's `Resource` input through it, so an interface
|
||||
/// swapped in from storage needs it refreshed alongside. Keeps the current registry on failure.
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap in an interface rebuilt from the registry a peer's changes left behind.
|
||||
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let Some(rebuilt) = self.history.rebuild_interface() else { return };
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
|
||||
}
|
||||
|
||||
/// Cache a resource received from a peer as a proto-node declaration, so a rebuild can resolve it.
|
||||
pub(crate) fn cache_declaration_bytes(&mut self, hash: graph_craft::application_io::resource::ResourceHash, bytes: &[u8]) {
|
||||
self.history.cache_declaration_bytes(hash, bytes);
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
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);
|
||||
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
|
||||
rebuilt.load_structure();
|
||||
@@ -2108,6 +2142,11 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
self.runtime_stale = false;
|
||||
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();
|
||||
@@ -2409,7 +2448,7 @@ impl DocumentMessageHandler {
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
true
|
||||
@@ -2417,7 +2456,21 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
|
||||
if self.is_in_session() {
|
||||
self.stage_session_undo(resource_storage);
|
||||
return;
|
||||
}
|
||||
self.drive_storage_undo_redo(legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
fn is_in_session(&self) -> bool {
|
||||
self.storage().is_some_and(|gdd| gdd.role().is_some())
|
||||
}
|
||||
|
||||
/// In a session every op is already public, so an undo is a new forward edit: the restored snapshot
|
||||
/// diffs against the last staged state into the inverse ops, broadcast like any other change.
|
||||
fn stage_session_undo(&mut self, resource_storage: &ResourceStorageMessageHandler) {
|
||||
self.commit_storage_snapshot(&resource_storage.resources_mut(), false);
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
@@ -2451,7 +2504,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
true
|
||||
@@ -2459,7 +2512,11 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
|
||||
if self.is_in_session() {
|
||||
self.stage_session_undo(resource_storage);
|
||||
return;
|
||||
}
|
||||
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
@@ -2777,7 +2834,7 @@ impl DocumentMessageHandler {
|
||||
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer);
|
||||
|
||||
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
|
||||
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
|
||||
// A visible stroke needs both renderable geometry (nonzero weight) and paint that draws something
|
||||
let has_stroke = appearance.is_some_and(|appearance| {
|
||||
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke())
|
||||
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_guaranteed_fully_transparent())
|
||||
@@ -3539,7 +3596,7 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.on_commit(|_| DocumentMessage::AddTransaction.into())
|
||||
.max_width(100)
|
||||
.tooltip_label("Fill")
|
||||
.tooltip_label("Fill Opacity")
|
||||
.widget_instance(),
|
||||
];
|
||||
let layers_panel_control_bar_left = Layout(vec![LayoutGroup::row(widgets)]);
|
||||
@@ -3750,7 +3807,7 @@ impl DocumentMessageHandler {
|
||||
let first_or_last_selected_layer = match relative_index_offset.signum() {
|
||||
-1 => selected_layers.next(),
|
||||
1 => selected_layers.last(),
|
||||
_ => panic!("selected_layers_reorder() must be given a non-zero value"),
|
||||
_ => panic!("selected_layers_reorder() must be given a nonzero value"),
|
||||
};
|
||||
|
||||
let Some(pivot_layer) = first_or_last_selected_layer else {
|
||||
|
||||
@@ -6,10 +6,10 @@ use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -141,7 +141,7 @@ pub enum GraphOperationMessage {
|
||||
},
|
||||
NewBitmapLayer {
|
||||
id: NodeId,
|
||||
image: Image<Color>,
|
||||
data: Arc<[u8]>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
|
||||
+2
-2
@@ -267,10 +267,10 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewBitmapLayer { id, image, parent, insert_index } => {
|
||||
GraphOperationMessage::NewBitmapLayer { id, data, parent, insert_index } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_image_data(image, layer);
|
||||
modify_inputs.insert_image_data(data, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
@@ -14,12 +14,12 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransformIn {
|
||||
@@ -270,20 +270,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.set_chain_position(node_id, &[]);
|
||||
}
|
||||
|
||||
pub fn insert_image_data(&mut self, image: Image<Color>, layer: LayerNodeIdentifier) {
|
||||
pub fn insert_image_data(&mut self, data: Arc<[u8]>, layer: LayerNodeIdentifier) {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
let resource_id = ResourceId::new();
|
||||
self.responses.add(ResourceMessage::StoreEmbedded {
|
||||
resource_id,
|
||||
data: image.to_png().into(),
|
||||
});
|
||||
self.responses.add(ResourceMessage::StoreEmbedded { resource_id, data });
|
||||
|
||||
let image_node = resolve_proto_node_type(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER)
|
||||
.expect("Image node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
|
||||
|
||||
let image_node_id = NodeId::new();
|
||||
self.network_interface.insert_node(image_node_id, image_node, &[]);
|
||||
@@ -664,7 +661,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.nodes
|
||||
.get(&node_id)
|
||||
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput));
|
||||
if !current_input.is_some_and(|input| input.as_value().is_some()) {
|
||||
if current_input.is_none_or(|input| input.as_value().is_none()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -688,7 +685,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.nodes
|
||||
.get(&node_id)
|
||||
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput));
|
||||
if !current_input.is_some_and(|input| input.as_value().is_some()) {
|
||||
if current_input.is_none_or(|input| input.as_value().is_none()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
pub(crate) use document_diff::diff_networks;
|
||||
pub(crate) use document_history::DocumentHistory;
|
||||
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
mod document_node_derive;
|
||||
|
||||
use super::node_properties::choice::enum_choice;
|
||||
use super::node_properties::{self, ParameterWidgetsInfo};
|
||||
use super::node_properties::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::prelude::{FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
@@ -26,6 +27,7 @@ use std::collections::{HashMap, VecDeque};
|
||||
pub struct NodePropertiesContext<'a> {
|
||||
pub responses: &'a mut VecDeque<Message>,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub document_id: DocumentId,
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub resources: &'a ResourceMessageHandler,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
@@ -480,7 +482,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(list!(Vector), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "TODO").into(),
|
||||
@@ -914,10 +916,12 @@ fn static_node_properties() -> NodeProperties {
|
||||
map.insert("brightness_contrast_properties".to_string(), Box::new(node_properties::brightness_contrast_properties));
|
||||
map.insert("channel_mixer_properties".to_string(), Box::new(node_properties::channel_mixer_properties));
|
||||
map.insert("levels_properties".to_string(), Box::new(node_properties::levels_properties));
|
||||
map.insert("transfer_curves_properties".to_string(), Box::new(node_properties::transfer_curves_properties));
|
||||
map.insert("hue_saturation_properties".to_string(), Box::new(node_properties::hue_saturation_properties));
|
||||
map.insert("black_and_white_properties".to_string(), Box::new(node_properties::black_and_white_properties));
|
||||
map.insert("threshold_properties".to_string(), Box::new(node_properties::threshold_properties));
|
||||
map.insert("vibrance_properties".to_string(), Box::new(node_properties::vibrance_properties));
|
||||
map.insert("color_balance_properties".to_string(), Box::new(node_properties::color_balance_properties));
|
||||
map.insert("fill_properties".to_string(), Box::new(node_properties::fill_properties));
|
||||
map.insert("stroke_properties".to_string(), Box::new(node_properties::stroke_properties));
|
||||
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
|
||||
@@ -1071,19 +1075,26 @@ fn static_input_properties() -> InputProperties {
|
||||
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
||||
index - 1,
|
||||
number_input,
|
||||
None,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// Like `optional_f64`, but the number input is configured as a percentage with a 0-100 range.
|
||||
// Like `optional_f64`, but with a 0-100% range slider beside the number input, double-click restoring the full 100%.
|
||||
// As with `optional_f64`, the bool input must be at the input index directly before the f64 input.
|
||||
"optional_percentage".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let number_input = NumberInput::default().percentage().min(0.).max(100.);
|
||||
let number_input = NumberInput::default().mode_increment().unit("%").min(0.).max(100.);
|
||||
let slider = SliderRange {
|
||||
min: 0.,
|
||||
max: 100.,
|
||||
default: Some(100.),
|
||||
};
|
||||
Ok(vec![LayoutGroup::row(node_properties::optional_f64_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
||||
index - 1,
|
||||
number_input,
|
||||
Some(slider),
|
||||
))])
|
||||
}),
|
||||
);
|
||||
@@ -1239,13 +1250,13 @@ fn static_input_properties() -> InputProperties {
|
||||
"noise_properties_fractal_weighted_strength".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_properties::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_weighted_strength = node_properties::number_widget(
|
||||
let fractal_weighted_strength = node_properties::range_slider_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.mode_range()
|
||||
.min(0.)
|
||||
.max(1.) // Defined for the 0-1 range
|
||||
.max(1.)
|
||||
.disabled(!coherent_noise_active || !fractal_active || domain_warp_only_fractal_type_wrongly_active),
|
||||
SliderRange { min: 0., max: 1., default: Some(0.) },
|
||||
);
|
||||
Ok(vec![fractal_weighted_strength.into()])
|
||||
}),
|
||||
@@ -1452,6 +1463,20 @@ fn static_input_properties() -> InputProperties {
|
||||
Ok(result)
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"image_file".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let widgets = node_properties::resource_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), vec![TypeFilter::raster()]);
|
||||
Ok(vec![LayoutGroup::row(widgets)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"lut_file".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let widgets = node_properties::resource_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), vec![TypeFilter::lut()]);
|
||||
Ok(vec![LayoutGroup::row(widgets)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"artboard_background".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1524,6 +1549,26 @@ impl InputTypeConstraint {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a type reaches the constraint through an `input_adapter`, the per-connector node which the preprocessor places ahead of
|
||||
/// every ranked connector to convert or embed a convertible element, such as a color literal feeding a `Graphic` paint wire.
|
||||
#[must_use]
|
||||
fn satisfies_through_input_adapter(&self, ty: &Type) -> bool {
|
||||
let provided = Self::type_name(ty);
|
||||
|
||||
interpreted_executor::node_registry::NODE_REGISTRY
|
||||
.iter()
|
||||
.filter(|(identifier, _)| identifier.as_str().starts_with("input_adapter<"))
|
||||
.flat_map(|(_, implementations)| implementations.keys())
|
||||
.any(|node_io| node_io.inputs.first().is_some_and(|from| Self::type_name(from) == provided) && self.satisfies(&node_io.return_value))
|
||||
}
|
||||
|
||||
/// Check if a default value of this type is valid for the constraint.
|
||||
#[must_use]
|
||||
fn accepts_default_value(&self, ty: &Type) -> bool {
|
||||
// Empty types are used when the input must come from the graph so they can be skipped
|
||||
ty.nested_type() == &concrete!(()) || self.satisfies(ty) || self.satisfies_through_input_adapter(ty)
|
||||
}
|
||||
|
||||
/// Compute the type constraint for one input. Note that this cannot use the infrastructure in the node network interface as the node is not placed in a network.
|
||||
#[must_use]
|
||||
fn compute_constraint_for_input(template_document_node: &NodeTemplate, name: &str, input_index: usize) -> Self {
|
||||
@@ -1580,9 +1625,7 @@ impl InputTypeConstraint {
|
||||
for (index, (constraint, input)) in all_input_constraints.iter().zip(&template_document_node.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value() {
|
||||
let input_ty = value.ty();
|
||||
|
||||
// Empty types are used when the input must come from the graph so they can be skipped.
|
||||
if input_ty.nested_type() != &concrete!(()) && !constraint.satisfies(&input_ty) {
|
||||
if !constraint.accepts_default_value(&input_ty) {
|
||||
warn!("The default value for input index {index} node {name} is {input_ty}, but does not satisfy {constraint:?}");
|
||||
}
|
||||
}
|
||||
@@ -1678,6 +1721,27 @@ mod test {
|
||||
|
||||
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
|
||||
}
|
||||
|
||||
// Guards the unconnected Path input, whose default must match the rank of the Morph connector it feeds
|
||||
#[tokio::test]
|
||||
async fn blend_resolves_and_evaluates_with_default_inputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = NodeId::new();
|
||||
let node_template = resolve_network_node_type("Blend").expect("the Blend definition should exist").default_node_template();
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(node_template),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
editor.eval_graph().await.expect("the Blend network should type-resolve and evaluate");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1698,6 +1762,25 @@ mod test_type_constraints {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passthrough() {
|
||||
let node_type = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).expect("passthrough node");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+3
@@ -9,6 +9,7 @@ use crate::node_graph_executor::NodeGraphExecutor;
|
||||
#[derive(ExtractField)]
|
||||
pub struct PropertiesPanelMessageContext<'a> {
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub document_id: DocumentId,
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub resources: &'a ResourceMessageHandler,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
@@ -26,6 +27,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
fn process_message(&mut self, message: PropertiesPanelMessage, responses: &mut VecDeque<Message>, context: PropertiesPanelMessageContext) {
|
||||
let PropertiesPanelMessageContext {
|
||||
executor,
|
||||
document_id,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
@@ -51,6 +53,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
let mut node_properties_context = NodePropertiesContext {
|
||||
responses,
|
||||
executor,
|
||||
document_id,
|
||||
network_interface,
|
||||
resources,
|
||||
selection_network_path,
|
||||
|
||||
@@ -28,7 +28,7 @@ fn editor_metadata_round_trip_against_demo() {
|
||||
let network = interface.document_network().clone();
|
||||
|
||||
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
|
||||
@@ -153,7 +153,7 @@ fn editor_interface_rebuild_round_trip() {
|
||||
|
||||
let network = original.document_network().clone();
|
||||
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let declarations = conversion.declarations;
|
||||
let registry = conversion.registry;
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
|
||||
|
||||
|
||||
@@ -4,17 +4,20 @@
|
||||
//! MessagePack 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};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage};
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
@@ -155,7 +158,7 @@ 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())
|
||||
.await
|
||||
@@ -175,7 +178,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.set_storage(Some(reopened));
|
||||
document.set_storage(reopened, declarations, byte_store.storage());
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
@@ -490,6 +493,15 @@ async fn live_undo_new_document_draw_rect() {
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &before_rect, "undo should restore the pre-rect network");
|
||||
}
|
||||
|
||||
fn paste_named_image() -> IngestMessage {
|
||||
IngestMessage::Ingest {
|
||||
data: Image::new(2, 2, Color::WHITE).to_png(),
|
||||
action: IngestAction::Paste,
|
||||
mime_type: String::new(),
|
||||
path: Some("pasted.png".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pasting an image is one user action and must be one undo step: the paste handler brackets the layer add,
|
||||
/// name set, reparent, and transform in a single transaction. Were the name set to open its own nested
|
||||
/// transaction (a historical wart), the first undo would revert only the name and leave the layer behind, so
|
||||
@@ -503,15 +515,7 @@ async fn paste_image_with_name_is_one_undo_step() {
|
||||
|
||||
// Paste with a name so the handler emits the `SetDisplayName` sub-step that historically opened its
|
||||
// own transaction. `create_raster_image` passes `name: None` and so wouldn't exercise this path.
|
||||
let image = Image::new(2, 2, Color::WHITE);
|
||||
editor
|
||||
.handle_message(PortfolioMessage::InsertImage {
|
||||
name: Some("pasted".into()),
|
||||
image,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
assert_eq!(
|
||||
editor.active_document().metadata().all_layers().count(),
|
||||
layers_before + 1,
|
||||
@@ -526,6 +530,38 @@ async fn paste_image_with_name_is_one_undo_step() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Choosing "None" in the Image node's file picker leaves the empty-resource placeholder, which must still render.
|
||||
#[tokio::test]
|
||||
async fn image_node_with_no_file_still_evaluates() {
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graph_craft::document::DocumentNodeImplementation;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::item;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.create_raster_image(Image::new(2, 2, Color::WHITE), None).await;
|
||||
|
||||
let image_node_id = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: image_node_id,
|
||||
input_index: graphene_std::raster_nodes::std_nodes::image::ResourceInput::INDEX,
|
||||
value: TaggedValue::TypeDefault(item!(Resource)).into(),
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.eval_graph().await.expect("an Image node with no file chosen should still evaluate");
|
||||
}
|
||||
|
||||
/// Undoing an image paste reverts the interaction's `AddResource` in the `Gdd` cursor while the runtime keeps
|
||||
/// the resource alive for legacy redo, so the cursor legitimately holds fewer resources than a fresh
|
||||
/// `from_runtime`. Drives the relaxed comparison: every resource the current network references must be in
|
||||
@@ -538,15 +574,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let image = Image::new(2, 2, Color::WHITE);
|
||||
editor
|
||||
.handle_message(PortfolioMessage::InsertImage {
|
||||
name: Some("pasted".into()),
|
||||
image,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
|
||||
@@ -582,15 +610,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let after_rect = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
let image = Image::new(2, 2, Color::WHITE);
|
||||
editor
|
||||
.handle_message(PortfolioMessage::InsertImage {
|
||||
name: Some("pasted".into()),
|
||||
image,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
|
||||
// First undo: removes the paste, back to the post-rectangle network. Cursor and legacy must agree.
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
@@ -656,12 +676,13 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
|
||||
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
|
||||
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
|
||||
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
|
||||
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
editor.active_document_mut().set_storage(Some(gdd));
|
||||
HashMapResourceStorage::new()
|
||||
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
|
||||
@@ -675,9 +696,11 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
// Open a real demo artwork through the normal open path and let it render.
|
||||
let content = std::fs::read_to_string("../demo-artwork/changing-seasons.graphite").expect("read demo artwork");
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenFile {
|
||||
path: "changing-seasons.graphite".into(),
|
||||
content: content.bytes().collect(),
|
||||
.handle_message(IngestMessage::Ingest {
|
||||
data: content.into_bytes(),
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some("changing-seasons.graphite".into()),
|
||||
})
|
||||
.await;
|
||||
|
||||
|
||||
@@ -311,7 +311,15 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn collect_used_resources(&self, target: &mut HashSet<ResourceId>) {
|
||||
collect_network_resources(self.document_network(), target);
|
||||
visit_network_resources(self.document_network(), &mut |id| {
|
||||
target.insert(id);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn collect_resources_use_counts(&self) -> HashMap<ResourceId, usize> {
|
||||
let mut counts = HashMap::new();
|
||||
visit_network_resources(self.document_network(), &mut |id| *counts.entry(id).or_insert(0) += 1);
|
||||
counts
|
||||
}
|
||||
|
||||
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
|
||||
|
||||
@@ -283,12 +283,16 @@ impl NodeTemplateImplementation {
|
||||
/// Collects resource IDs referenced by a template and its nested networks.
|
||||
pub fn collect_template_resources(template: &NodeTemplate, out: &mut HashSet<ResourceId>) {
|
||||
for input in &template.inputs {
|
||||
collect_input_resource(input, out);
|
||||
visit_input_resource(input, &mut |id| {
|
||||
out.insert(id);
|
||||
});
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network_template) = &template.implementation {
|
||||
for export in &network_template.exports {
|
||||
collect_input_resource(export, out);
|
||||
visit_input_resource(export, &mut |id| {
|
||||
out.insert(id);
|
||||
});
|
||||
}
|
||||
for nested_template in network_template.nodes.values() {
|
||||
collect_template_resources(nested_template, out);
|
||||
|
||||
@@ -865,31 +865,29 @@ pub(crate) enum SoleDependentStep {
|
||||
Escape,
|
||||
}
|
||||
|
||||
pub(crate) fn collect_network_resources(network: &NodeNetwork, out: &mut HashSet<ResourceId>) {
|
||||
pub(crate) fn visit_network_resources(network: &NodeNetwork, visit: &mut impl FnMut(ResourceId)) {
|
||||
for export in &network.exports {
|
||||
collect_input_resource(export, out);
|
||||
visit_input_resource(export, visit);
|
||||
}
|
||||
for node in network.nodes.values() {
|
||||
collect_node_resources(node, out);
|
||||
visit_node_resources(node, visit);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects resource IDs referenced by a node and its nested networks.
|
||||
pub fn collect_node_resources(node: &DocumentNode, out: &mut HashSet<ResourceId>) {
|
||||
pub(crate) fn visit_node_resources(node: &DocumentNode, visit: &mut impl FnMut(ResourceId)) {
|
||||
for input in &node.inputs {
|
||||
collect_input_resource(input, out);
|
||||
visit_input_resource(input, visit);
|
||||
}
|
||||
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
|
||||
collect_network_resources(nested, out);
|
||||
visit_network_resources(nested, visit);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the resource ID held by a value input, covering node inputs and export slots alike.
|
||||
pub(crate) fn collect_input_resource(input: &NodeInput, out: &mut HashSet<ResourceId>) {
|
||||
pub(crate) fn visit_input_resource(input: &NodeInput, visit: &mut impl FnMut(ResourceId)) {
|
||||
if let NodeInput::Value { tagged_value, .. } = input
|
||||
&& let TaggedValue::Resource(id) = &**tagged_value
|
||||
{
|
||||
out.insert(*id);
|
||||
visit(*id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -897,6 +895,38 @@ pub(crate) fn collect_input_resource(input: &NodeInput, out: &mut HashSet<Resour
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_visits_reach_nested_networks_and_exports() {
|
||||
let shared = ResourceId::from(1);
|
||||
let uses = |id: ResourceId| NodeInput::value(TaggedValue::Resource(id), false);
|
||||
let node = |inputs: Vec<NodeInput>| DocumentNode { inputs, ..Default::default() };
|
||||
let inner = NodeNetwork {
|
||||
exports: vec![uses(shared)],
|
||||
nodes: [(NodeId(2), node(vec![uses(shared)]))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let outer = NodeNetwork {
|
||||
nodes: [
|
||||
(NodeId(1), node(vec![uses(shared), uses(ResourceId::from(2))])),
|
||||
(
|
||||
NodeId(3),
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(inner),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut visits = Vec::new();
|
||||
visit_network_resources(&outer, &mut |id| visits.push(id));
|
||||
assert_eq!(visits.iter().filter(|id| **id == shared).count(), 3);
|
||||
assert_eq!(visits.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_click_targets_are_clickable_at_their_center() {
|
||||
let center = DVec2::new(100., 50.);
|
||||
|
||||
@@ -10,7 +10,7 @@ use glam::{DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
use graph_craft::{Type, item, list};
|
||||
use graph_craft::{Type, concrete, item, list};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
@@ -399,6 +399,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::sine_inverse::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::SineInverseNode", "graphene_core::ops::SineInverseNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::string_to_color::IDENTIFIER,
|
||||
aliases: &["math_nodes::HexToColorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::subtract::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::SubtractNode", "graphene_core::ops::SubtractNode"],
|
||||
@@ -412,8 +416,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_math_nodes::TangentInverseNode", "graphene_core::ops::TangentInverseNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::as_f_64::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::ToF64Node", "graphene_core::ops::ToF64Node", "math_nodes::ToF64Node"],
|
||||
node: graphene_std::math_nodes::as_number::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::ToF64Node", "graphene_core::ops::ToF64Node", "math_nodes::ToF64Node", "math_nodes::AsF64Node"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::as_u_32::IDENTIFIER,
|
||||
@@ -473,12 +477,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::BrightnessContrastNode",
|
||||
"graphene_core::raster::adjustments::BrightnessContrastNode",
|
||||
"graphene_raster_nodes::adjustments::brightness_contrast_classic",
|
||||
"graphene_raster_nodes::adjustments::BrightnessContrastClassicNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast_classic::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::BrightnessContrastClassicNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::channel_mixer::IDENTIFIER,
|
||||
aliases: &[
|
||||
@@ -535,7 +537,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::gradient_map::gradient_map::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::adjustments::gradient_map::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::gradient_map::GradientMapNode",
|
||||
"graphene_raster_nodes::adjustments::GradientMapNode",
|
||||
@@ -587,8 +589,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::luminance::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::adjustments::desaturate::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::adjustments::LuminanceNode",
|
||||
"graphene_raster_nodes::adjustments::LuminanceNode",
|
||||
"graphene_core::raster::adjustments::LuminanceNode",
|
||||
"graphene_core::raster::LuminanceNode",
|
||||
@@ -2123,7 +2126,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
_ => None,
|
||||
});
|
||||
|
||||
if let Some(image) = image {
|
||||
if let Some(mut image) = image {
|
||||
// Legacy embedded pixel data is premultiplied, so restore straight alpha before encoding it
|
||||
image.data.iter_mut().for_each(|pixel| *pixel = pixel.to_unassociated_alpha());
|
||||
let hash = document.resources.embedded.store(Resource::new(image.to_png()));
|
||||
|
||||
let resource_id = ResourceId::new();
|
||||
@@ -2135,10 +2140,21 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let _ = document.network_interface.replace_inputs(node_id, network_path, &mut node_template);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::Resource(resource_id), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Resource(resource_id), false), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Move the Image node's resource, whether a stored value or a wire, from the primary input to the first secondary input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER)
|
||||
&& inputs_count == 1
|
||||
&& !matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::ImageData(_)))
|
||||
{
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[0].clone(), network_path);
|
||||
}
|
||||
|
||||
// Convert text nodes from the old `editor-api` scope + `Font` input to a single font `Resource` input.
|
||||
// The chosen typeface is recorded as a `DataSource::Font` in the document's resource registry and loaded on open.
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 13 && matches!(node.inputs.first(), Some(NodeInput::Scope(_))) {
|
||||
@@ -2176,6 +2192,107 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (i, input) in old_inputs.iter().enumerate().take(3) {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i), input.clone(), network_path);
|
||||
}
|
||||
inputs_count = 3;
|
||||
}
|
||||
|
||||
// Vibrance gained a Saturation input after its Vibrance input, whose default of 0 leaves old documents unchanged
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::vibrance::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
for (index, input) in old_inputs.iter().take(2).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
inputs_count = 3;
|
||||
}
|
||||
|
||||
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
for (index, input) in old_inputs.iter().take(3).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 3), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
inputs_count = 4;
|
||||
}
|
||||
|
||||
// Brightness/Contrast gained the classic algorithm's pivot, whose default of 127 matches what PSD adjustment layers store
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
for (index, input) in old_inputs.iter().take(4).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
inputs_count = 5;
|
||||
}
|
||||
|
||||
// Levels' Midtones became the gamma value it encoded, and each channel gained its own record after the composite one
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::levels::IDENTIFIER) && inputs_count == 6 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
let output_level = |index: usize, default: f32| match old_inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::F32(percent)) => percent / 100.,
|
||||
_ => default,
|
||||
};
|
||||
let (output_minimums, output_maximums) = (output_level(4, 0.), output_level(5, 1.));
|
||||
for (index, input) in old_inputs.iter().take(6).enumerate() {
|
||||
let input = match (index, input.as_value()) {
|
||||
(2, Some(TaggedValue::F32(percent))) => {
|
||||
// The old node's midtones-to-gamma mapping, from https://stackoverflow.com/questions/39510072/algorithm-for-adjustment-of-image-levels
|
||||
let midtones = output_minimums + (output_maximums - output_minimums) * percent / 100.;
|
||||
let gamma = if midtones < 0.5 { 1. + 9. * (1. - midtones * 2.) } else { ((1. - midtones) * 2.).max(0.01) };
|
||||
NodeInput::value(TaggedValue::F32(gamma.clamp(0.01, 9.99)), input.is_exposed())
|
||||
}
|
||||
_ => input.clone(),
|
||||
};
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
inputs_count = 27;
|
||||
}
|
||||
|
||||
// Hue/Saturation gained colorize and the six hue ranges after its three master sliders
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::hue_saturation::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
for (index, input) in old_inputs.iter().take(4).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
inputs_count = 51;
|
||||
}
|
||||
|
||||
// Black & White gained a Use Tint toggle ahead of its tint color; a non-black tint used to be the only way to tint
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::black_and_white::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
for (index, input) in old_inputs.iter().enumerate().skip(1).take(7) {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index + 1), input.clone(), network_path);
|
||||
}
|
||||
let use_tint = !matches!(old_inputs[1].as_value(), Some(TaggedValue::Color(color)) if *color == Color::BLACK);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Bool(use_tint), false), network_path);
|
||||
inputs_count = 9;
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::repeat::repeat_on_points::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
@@ -2760,6 +2877,24 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// A `Resource` input disconnected before `Resource` became an item-ranked type default stored the bare `TypeDefault(Resource)`, which no longer unwraps to an `Item<Resource>` default
|
||||
if let Some(current_node) = document.network_interface.document_node(node_id, network_path) {
|
||||
let bare_resource_inputs: Vec<(usize, bool)> = current_node
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, input)| match input {
|
||||
NodeInput::Value { tagged_value, exposed } if matches!(&**tagged_value, TaggedValue::TypeDefault(stored_type) if *stored_type == concrete!(Resource)) => Some((index, *exposed)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for (index, exposed) in bare_resource_inputs {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::type_default(item!(Resource), exposed), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// PUT ALL MIGRATIONS ABOVE THIS LINE
|
||||
// ==================================
|
||||
@@ -3005,6 +3140,68 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_legacy_image_shape_stores_its_resource_as_secondary_input() {
|
||||
use graphene_std::raster::Image;
|
||||
|
||||
let resource_id = ResourceId::new();
|
||||
let upstream_id = NodeId(2);
|
||||
let legacy_inputs = [
|
||||
NodeInput::value(TaggedValue::ImageData(Image::new(2, 2, Color::WHITE)), false),
|
||||
NodeInput::value(TaggedValue::Resource(resource_id), false),
|
||||
NodeInput::node(upstream_id, 0),
|
||||
];
|
||||
|
||||
for legacy_input in legacy_inputs {
|
||||
let image_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let image_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(upstream_id, NodeTemplate::default(), &[]);
|
||||
document.network_interface.insert_node(image_id, image_template, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(image_id, 0), legacy_input.clone(), &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
let image_node = &document.network_interface.document_network().nodes[&image_id];
|
||||
assert_eq!(image_node.inputs.len(), 2, "the image node should gain its placeholder primary input");
|
||||
let migrated = &image_node.inputs[1];
|
||||
match legacy_input.as_value() {
|
||||
None => assert_eq!(migrated.as_node(), Some(upstream_id), "the wire should sit at input 1"),
|
||||
Some(legacy_value) => {
|
||||
let Some(TaggedValue::Resource(stored)) = migrated.as_value() else {
|
||||
panic!("the file should sit at input 1")
|
||||
};
|
||||
match legacy_value {
|
||||
TaggedValue::Resource(legacy) => assert_eq!(stored, legacy, "the stored resource should be kept"),
|
||||
_ => assert!(document.resources.registry.contains(stored), "the embedded pixels should be stored as a new resource"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_resource_type_defaults_become_item_defaults() {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let image_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::TypeDefault(concrete!(Resource)), true)],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(node_id, image_template, &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
let migrated = &document.network_interface.document_network().nodes[&node_id].inputs[1];
|
||||
assert_eq!(migrated.as_value(), Some(&TaggedValue::TypeDefault(item!(Resource))), "the bare default should become the item default");
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Asynchronous `.gdd` working-copy IO, spawned by `PortfolioMessageHandler` as `FutureMessage`s:
|
||||
//! building/opening containers, opening `.gdd` archives into documents, and rebuilding the interface
|
||||
//! from the undo/redo cursor. The `validate` flag is the `validate_storage_round_trip` preference; when
|
||||
//! building/opening containers and opening `.gdd` archives into documents.
|
||||
//! The `validate` flag is the `validate_storage_round_trip` preference; when
|
||||
//! set, the registry build is compared against the legacy oracle (logged, not fatal) for the soak.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout};
|
||||
use graph_craft::application_io::resource::{LoadResource, ResourceStorage};
|
||||
use document_graph_storage::Declarations;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
|
||||
use super::document::DocumentMessageHandler;
|
||||
@@ -86,31 +87,10 @@ pub(super) async fn open_gdd_document(
|
||||
})
|
||||
}
|
||||
|
||||
/// `FutureMessage` that rebuilds a document's interface from a post-move `Gdd` cursor snapshot and
|
||||
/// delivers it via [`PortfolioMessage::GddUndoRedoRebuilt`] (`None` interface on failure, logged here).
|
||||
pub(crate) async fn rebuild_gdd_cursor(gdd: GddV1, store_handle: ResourcesHandle, document_id: DocumentId, had_oracle: bool) -> Message {
|
||||
let declarations = gdd.declarations(&store_handle).await;
|
||||
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
|
||||
Ok((network, node_entries, network_entries)) => match build_interface_from_storage(network, node_entries, network_entries) {
|
||||
Ok(interface) => Some(Box::new(interface)),
|
||||
Err(error) => {
|
||||
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to build interface: {error}");
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to convert registry to runtime: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
Message::Portfolio(PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface })
|
||||
}
|
||||
|
||||
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is
|
||||
/// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails.
|
||||
/// Returns `None` only if neither the build nor the legacy fallback worked.
|
||||
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
|
||||
async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &ResourcesHandle, document_id: DocumentId, validate: bool) -> Option<DocumentMessageHandler> {
|
||||
let (container, _exists) = match build_per_document_container(path).await {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
@@ -184,7 +164,7 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
|
||||
);
|
||||
}
|
||||
}
|
||||
return Some(DocumentMessageHandler::from_storage(interface, gdd, String::new(), None));
|
||||
return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, store_handle.storage(), String::new(), None));
|
||||
}
|
||||
|
||||
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
|
||||
@@ -196,9 +176,8 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8],
|
||||
|
||||
/// Soak check that the reopened `.gdd`'s stored registry, converted back to a runtime network, matches
|
||||
/// the legacy load. Logs divergence only (legacy stays authoritative); runs once per open.
|
||||
pub(super) async fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, byte_store: &dyn LoadResource, document_id: DocumentId) {
|
||||
let declarations = gdd.declarations(byte_store).await;
|
||||
let mut candidate = match gdd.registry().to_runtime_with_metadata(&declarations) {
|
||||
pub(super) fn compare_storage_against_runtime(gdd: &GddV1, legacy_network: &NodeNetwork, declarations: &Declarations, document_id: DocumentId) {
|
||||
let mut candidate = match gdd.registry().to_runtime_with_metadata(declarations) {
|
||||
Ok((network, _entries)) => network,
|
||||
Err(error) => {
|
||||
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, FailedDocuments)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FailedDocumentsMessage {
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
ShowFailedToLoadDocumentsDialog,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
DiscardFailedToLoadDocuments,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
DownloadFailedToLoadDocuments,
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
use crate::consts::FILE_EXTENSION;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, FileFilter};
|
||||
use crate::messages::layout::utility_types::layout_widget::DialogLayoutHolder;
|
||||
use crate::messages::portfolio::persistent_state::PersistentStateMessage;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FailedDocumentsMessageContext<'a> {
|
||||
pub document_ids: &'a mut VecDeque<DocumentId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct FailedDocumentsMessageHandler {
|
||||
/// Pairs of `(info, raw serialized content)` for autosaved documents that failed to deserialize.
|
||||
/// The info entries are folded back into `persisted_state_snapshot` so their on-disk autosave files survive garbage collection.
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
failed_to_load_documents: HashMap<DocumentId, (DocumentInfo, String)>,
|
||||
/// In-flight count of autosaved-document loads from the initial startup batch; the batched failure dialog fires when this hits 0.
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
pending_initial_autosave_loads: usize,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<FailedDocumentsMessage, FailedDocumentsMessageContext<'_>> for FailedDocumentsMessageHandler {
|
||||
fn process_message(&mut self, message: FailedDocumentsMessage, responses: &mut VecDeque<Message>, context: FailedDocumentsMessageContext) {
|
||||
let FailedDocumentsMessageContext { document_ids } = context;
|
||||
|
||||
match message {
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
FailedDocumentsMessage::ShowFailedToLoadDocumentsDialog => {
|
||||
if self.failed_to_load_documents.is_empty() {
|
||||
return;
|
||||
}
|
||||
let failed_document_names = self.failed_to_load_documents.values().map(|(info, _)| display_name_with_fallback(info)).collect();
|
||||
let dialog = simple_dialogs::FailedToLoadDocumentsDialog { failed_document_names };
|
||||
dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
FailedDocumentsMessage::DiscardFailedToLoadDocuments => {
|
||||
let failed = std::mem::take(&mut self.failed_to_load_documents);
|
||||
for document_id in failed.keys() {
|
||||
document_ids.retain(|id| id != document_id);
|
||||
responses.add(PersistentStateMessage::DeleteDocument { document_id: *document_id });
|
||||
}
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(PersistentStateMessage::WriteState);
|
||||
}
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
FailedDocumentsMessage::DownloadFailedToLoadDocuments => {
|
||||
if self.failed_to_load_documents.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut used_names = HashSet::new();
|
||||
let files: Vec<(String, Vec<u8>)> = self
|
||||
.failed_to_load_documents
|
||||
.values()
|
||||
.map(|(info, content)| {
|
||||
let stem = sanitize_filename_stem(&info.name).unwrap_or_else(|| format!("document-{:x}", info.id.0));
|
||||
|
||||
// A name that was already given out, even as another document's numbered copy, takes the next free number
|
||||
let mut unique = format!("{stem}.{FILE_EXTENSION}");
|
||||
let mut copy_number = 1;
|
||||
while !used_names.insert(unique.clone()) {
|
||||
unique = format!("{stem} ({copy_number}).{FILE_EXTENSION}");
|
||||
copy_number += 1;
|
||||
}
|
||||
|
||||
(unique, content.as_bytes().to_vec())
|
||||
})
|
||||
.collect();
|
||||
|
||||
const FOLDER_NAME: &str = "Graphite Recovered Documents";
|
||||
|
||||
if files.len() == 1 {
|
||||
let (filename, content) = files.into_iter().next().expect("just checked there's one entry");
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name: filename,
|
||||
folder: None,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".into(),
|
||||
extensions: vec![FILE_EXTENSION.into()],
|
||||
mime_types: Vec::new(),
|
||||
}],
|
||||
content: serde_bytes::ByteBuf::from(content),
|
||||
});
|
||||
} else {
|
||||
match build_recovery_zip(&files) {
|
||||
Ok(zip_bytes) => responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name: format!("{FOLDER_NAME}.zip"),
|
||||
folder: None,
|
||||
filters: vec![FileFilter {
|
||||
name: "Zip Archive".into(),
|
||||
extensions: vec!["zip".into()],
|
||||
mime_types: Vec::new(),
|
||||
}],
|
||||
content: serde_bytes::ByteBuf::from(zip_bytes),
|
||||
}),
|
||||
Err(e) => {
|
||||
log::error!("Failed to build recovery zip: {e}");
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Failed to download".to_string(),
|
||||
description: format!("Could not bundle the failed documents for download.\n\n{e}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(FailedDocumentsMessageDiscriminant;);
|
||||
}
|
||||
|
||||
impl FailedDocumentsMessageHandler {
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Keeps a document that failed to load, with its raw serialized content, so it can be offered for download.
|
||||
pub(crate) fn record_failure(&mut self, document_id: DocumentId, info: DocumentInfo, serialized_content: String) {
|
||||
self.failed_to_load_documents.insert(document_id, (info, serialized_content));
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Counts more autosaved documents of the startup batch whose loads the batched failure dialog waits for.
|
||||
pub(crate) fn expect_autosave_loads(&mut self, count: usize) {
|
||||
self.pending_initial_autosave_loads = self.pending_initial_autosave_loads.saturating_add(count);
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether documents failed to load and none of the startup batch is still loading, so the failure dialog is due.
|
||||
pub(crate) fn has_failures_to_report(&self) -> bool {
|
||||
self.pending_initial_autosave_loads == 0 && !self.failed_to_load_documents.is_empty()
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The info of each document that failed to load.
|
||||
pub(crate) fn failed_document_infos(&self) -> impl Iterator<Item = &DocumentInfo> {
|
||||
self.failed_to_load_documents.values().map(|(info, _)| info)
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
pub(crate) fn tick_autosave_load_progress(&mut self, responses: &mut VecDeque<Message>, failed: bool) {
|
||||
if self.pending_initial_autosave_loads > 0 {
|
||||
self.pending_initial_autosave_loads -= 1;
|
||||
if self.has_failures_to_report() {
|
||||
responses.add(FailedDocumentsMessage::ShowFailedToLoadDocumentsDialog);
|
||||
}
|
||||
} else if failed {
|
||||
responses.add(FailedDocumentsMessage::ShowFailedToLoadDocumentsDialog);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
fn display_name_with_fallback(info: &DocumentInfo) -> String {
|
||||
if info.name.trim().is_empty() {
|
||||
format!("Untitled Document ({:x})", info.id.0)
|
||||
} else {
|
||||
info.name.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `None` if the name has no safe filename characters left or matches a Windows reserved device name, so callers fall back to an ID-based stem.
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
fn sanitize_filename_stem(name: &str) -> Option<String> {
|
||||
let replaced: String = name
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() {
|
||||
'_'
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Trim dots to avoid `.` / `..` resolving against the parent directory, and to dodge Windows' trailing-dot/space quirks
|
||||
let trimmed = replaced.trim().trim_matches('.').trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Windows rejects these regardless of extension; superscript digits are normalized equivalently by some path APIs
|
||||
let first_segment = trimmed.split('.').next().unwrap_or("").to_ascii_uppercase();
|
||||
if matches!(
|
||||
first_segment.as_str(),
|
||||
"CON"
|
||||
| "PRN" | "AUX"
|
||||
| "NUL" | "COM1"
|
||||
| "COM2" | "COM3"
|
||||
| "COM4" | "COM5"
|
||||
| "COM6" | "COM7"
|
||||
| "COM8" | "COM9"
|
||||
| "COM¹" | "COM²"
|
||||
| "COM³" | "LPT1"
|
||||
| "LPT2" | "LPT3"
|
||||
| "LPT4" | "LPT5"
|
||||
| "LPT6" | "LPT7"
|
||||
| "LPT8" | "LPT9"
|
||||
| "LPT¹" | "LPT²"
|
||||
| "LPT³"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
fn build_recovery_zip(entries: &[(String, Vec<u8>)]) -> Result<Vec<u8>, String> {
|
||||
use std::io::{Cursor, Write};
|
||||
use zip::write::{SimpleFileOptions, ZipWriter};
|
||||
|
||||
let mut buffer = Cursor::new(Vec::<u8>::new());
|
||||
let mut writer = ZipWriter::new(&mut buffer);
|
||||
let options: SimpleFileOptions = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o644);
|
||||
|
||||
for (filename, content) in entries {
|
||||
writer.start_file(filename, options).map_err(|e| format!("start_file: {e}"))?;
|
||||
writer.write_all(content).map_err(|e| format!("write_all: {e}"))?;
|
||||
}
|
||||
|
||||
writer.finish().map_err(|e| format!("finish: {e}"))?;
|
||||
Ok(buffer.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recovered_documents_sharing_a_name_with_a_numbered_copy_still_download() {
|
||||
let mut handler = FailedDocumentsMessageHandler::default();
|
||||
for (id, name) in [(1, "Art"), (2, "Art"), (3, "Art (1)")] {
|
||||
let info = DocumentInfo {
|
||||
id: DocumentId(id),
|
||||
name: name.to_string(),
|
||||
resources: None,
|
||||
path: None,
|
||||
is_saved: true,
|
||||
};
|
||||
handler.record_failure(DocumentId(id), info, "content".to_string());
|
||||
}
|
||||
|
||||
let mut document_ids = VecDeque::new();
|
||||
let mut responses = VecDeque::new();
|
||||
let context = FailedDocumentsMessageContext { document_ids: &mut document_ids };
|
||||
handler.process_message(FailedDocumentsMessage::DownloadFailedToLoadDocuments, &mut responses, context);
|
||||
|
||||
// A file name given out twice makes the archive fail to build, which shows an error dialog in place of the download
|
||||
assert!(matches!(responses.front(), Some(Message::Frontend(FrontendMessage::TriggerSaveFile { .. }))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod failed_documents_message;
|
||||
mod failed_documents_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use failed_documents_message::{FailedDocumentsMessage, FailedDocumentsMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use failed_documents_message_handler::{FailedDocumentsMessageContext, FailedDocumentsMessageHandler};
|
||||
@@ -0,0 +1,28 @@
|
||||
use super::utility_types::{IngestAction, TypeFilter};
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, Ingest)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum IngestMessage {
|
||||
Ingest {
|
||||
data: Vec<u8>,
|
||||
action: IngestAction,
|
||||
mime_type: String,
|
||||
path: Option<PathBuf>,
|
||||
},
|
||||
Browse {
|
||||
filters: Vec<TypeFilter>,
|
||||
multiple: bool,
|
||||
action: IngestAction,
|
||||
},
|
||||
Open,
|
||||
Import,
|
||||
SetResourceInput {
|
||||
document_id: DocumentId,
|
||||
node_id: NodeId,
|
||||
input_index: usize,
|
||||
filters: Vec<TypeFilter>,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
use super::utility_types::{DataType, IngestAction, TypeFilter};
|
||||
use crate::messages::frontend::utility_types::{FileDialogOptions, FileFilter};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::IVec2;
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster_nodes::color_lookup_table::{Lut, LutParseError};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct IngestMessageContext {
|
||||
pub document_open: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct IngestMessageHandler {}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandler {
|
||||
fn process_message(&mut self, message: IngestMessage, responses: &mut VecDeque<Message>, context: IngestMessageContext) {
|
||||
match message {
|
||||
IngestMessage::Open => responses.add(IngestMessage::Browse {
|
||||
filters: vec![TypeFilter::documents(), TypeFilter::image()],
|
||||
multiple: true,
|
||||
action: IngestAction::Open,
|
||||
}),
|
||||
IngestMessage::Import => responses.add(IngestMessage::Browse {
|
||||
filters: vec![TypeFilter::image()],
|
||||
multiple: false,
|
||||
action: IngestAction::Import,
|
||||
}),
|
||||
IngestMessage::SetResourceInput {
|
||||
document_id,
|
||||
node_id,
|
||||
input_index,
|
||||
filters,
|
||||
} => {
|
||||
let action = IngestAction::resource_input(document_id, node_id, input_index, &filters);
|
||||
|
||||
responses.add(IngestMessage::Browse { filters, multiple: false, action });
|
||||
}
|
||||
IngestMessage::Browse { filters, multiple, action } => responses.add(FrontendMessage::TriggerBrowse {
|
||||
options: FileDialogOptions {
|
||||
filters: filters.into_iter().map(FileFilter::from).collect(),
|
||||
multiple,
|
||||
},
|
||||
action,
|
||||
}),
|
||||
IngestMessage::Ingest { data, action, mime_type, path } => {
|
||||
let data_type = DataType::detect(&data, &mime_type, path.as_deref());
|
||||
|
||||
let placement = match action {
|
||||
IngestAction::ResourceInput {
|
||||
document_id,
|
||||
node_id,
|
||||
input_index,
|
||||
accepted_types,
|
||||
} => {
|
||||
if let Some(description) = rejection(&data, data_type, &accepted_types) {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unsupported file".into(),
|
||||
description: description.into(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// The file goes to the document that asked for it, which may no longer be active or open once the dialog closes
|
||||
let resource_id = ResourceId::new();
|
||||
let messages = [
|
||||
DocumentMessage::AddTransaction,
|
||||
DocumentMessage::Resource(ResourceMessage::StoreEmbedded { resource_id, data: data.into() }),
|
||||
DocumentMessage::NodeGraph(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: input_index as usize,
|
||||
value: TaggedValue::Resource(resource_id).into(),
|
||||
}),
|
||||
];
|
||||
for message in messages {
|
||||
responses.add(PortfolioMessage::DocumentPassMessage { document_id, message });
|
||||
}
|
||||
return;
|
||||
}
|
||||
IngestAction::Open => None,
|
||||
IngestAction::Import | IngestAction::Paste => Some((None, None)),
|
||||
IngestAction::DropOnCanvas { mouse } => Some((Some(mouse), None)),
|
||||
IngestAction::DropOnLayers { parent, insert_index } => Some((None, Some((parent, insert_index as usize)))),
|
||||
}
|
||||
.filter(|_| context.document_open);
|
||||
|
||||
let name = path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned());
|
||||
let document_path = path.filter(|path| path.is_absolute());
|
||||
|
||||
let (mouse, parent_and_insert_index) = placement.unwrap_or_default();
|
||||
let place_at_origin = placement.is_none();
|
||||
let (insert, artboard_canvas) = match data_type {
|
||||
DataType::GraphiteLegacy => {
|
||||
let Ok(document_serialized_content) = String::from_utf8(data) else {
|
||||
return unsupported(responses);
|
||||
};
|
||||
responses.add(PortfolioMessage::OpenDocumentFile {
|
||||
document_name: name,
|
||||
document_path,
|
||||
document_serialized_content,
|
||||
});
|
||||
return;
|
||||
}
|
||||
DataType::Gdd => {
|
||||
responses.add(PortfolioMessage::OpenGddDocument {
|
||||
document_name: name,
|
||||
document_path,
|
||||
content: data,
|
||||
});
|
||||
return;
|
||||
}
|
||||
DataType::Svg => {
|
||||
let Ok(svg) = String::from_utf8(data) else { return unsupported(responses) };
|
||||
let artboard_canvas = place_at_origin.then(|| svg_canvas(&svg)).flatten();
|
||||
let insert = DocumentMessage::InsertSvg {
|
||||
name: name.clone(),
|
||||
svg,
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
place_at_origin,
|
||||
};
|
||||
(insert, artboard_canvas)
|
||||
}
|
||||
DataType::Raster(_) => {
|
||||
let Some(size) = Image::encoded_size(&data) else { return unsupported(responses) };
|
||||
let insert = DocumentMessage::InsertImage {
|
||||
name: name.clone(),
|
||||
data: data.into(),
|
||||
size: size.into(),
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
place_at_origin,
|
||||
};
|
||||
(insert, None)
|
||||
}
|
||||
// A LUT is only ever the file of a node input
|
||||
DataType::Lut | DataType::Unknown => return unsupported(responses),
|
||||
};
|
||||
|
||||
if !place_at_origin {
|
||||
responses.add(insert);
|
||||
return;
|
||||
}
|
||||
responses.add(PortfolioMessage::NewDocumentWithName { name: name.unwrap_or_default() });
|
||||
responses.add(insert);
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![
|
||||
DocumentMessage::WrapContentInArtboard {
|
||||
place_artboard_at_origin: true,
|
||||
artboard_canvas,
|
||||
}
|
||||
.into(),
|
||||
],
|
||||
});
|
||||
responses.add(DeferMessage::AfterNavigationReady {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actions(&self) -> ActionList {
|
||||
actions!(IngestMessageDiscriminant;)
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported(responses: &mut VecDeque<Message>) {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unsupported format".into(),
|
||||
description: "This file is not a supported document or image format.".into(),
|
||||
});
|
||||
}
|
||||
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image or LUT only if it fully parses.
|
||||
fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> Option<&'static str> {
|
||||
const WRONG_TYPE: &str = "This input does not accept the format of the chosen file.";
|
||||
|
||||
if accepted_types.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !accepted_types.contains(&data_type) {
|
||||
return Some(WRONG_TYPE);
|
||||
}
|
||||
|
||||
match data_type {
|
||||
DataType::Raster(_) => Image::encoded_size(data).is_none().then_some("This file could not be read as an image."),
|
||||
DataType::Lut => Lut::parse(data).err().map(|error| match error {
|
||||
LutParseError::IccProfileClass => {
|
||||
"This ICC profile describes the colors of a device (like a monitor or printer) instead\n\
|
||||
of remapping colors. Only \"abstract\" and \"device link\" profiles work as LUTs."
|
||||
}
|
||||
LutParseError::IccColorSpaces => {
|
||||
"This ICC profile remaps within color spaces that are currently unsupported, such as CMYK.\n\
|
||||
A \"device link\" profile must map RGB to RGB. An \"abstract\" profile must map Lab to Lab."
|
||||
}
|
||||
LutParseError::Unreadable => "This file could not be read as a LUT. It may be corrupted or an unsupported format variant.",
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// The viewBox preserves the full canvas rather than the tighter bounding box of the rendered content
|
||||
fn svg_canvas(svg: &str) -> Option<(IVec2, IVec2)> {
|
||||
usvg::roxmltree::Document::parse(svg)
|
||||
.ok()
|
||||
.and_then(|document| {
|
||||
let numbers: Vec<f64> = document
|
||||
.root_element()
|
||||
.attribute("viewBox")?
|
||||
.split(|character: char| character.is_ascii_whitespace() || character == ',')
|
||||
.filter_map(|number| number.parse().ok())
|
||||
.collect();
|
||||
let [x, y, width, height, ..] = numbers[..] else { return None };
|
||||
Some((IVec2::new(x.round() as i32, y.round() as i32), IVec2::new(width.round() as i32, height.round() as i32)))
|
||||
})
|
||||
.or_else(|| {
|
||||
let size = usvg::Tree::from_str(svg, &usvg::Options::default()).ok()?.size();
|
||||
Some((IVec2::ZERO, IVec2::new(size.width().round() as i32, size.height().round() as i32)))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
|
||||
const REQUESTING_DOCUMENT: DocumentId = DocumentId(3);
|
||||
const IDENTITY_CUBE: &[u8] = b"LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
|
||||
|
||||
fn ingest(data: &[u8], action: IngestAction, document_open: bool) -> VecDeque<Message> {
|
||||
ingest_named(data, None, action, document_open)
|
||||
}
|
||||
|
||||
fn ingest_named(data: &[u8], file_name: Option<&str>, action: IngestAction, document_open: bool) -> VecDeque<Message> {
|
||||
let mut responses = VecDeque::new();
|
||||
let message = IngestMessage::Ingest {
|
||||
data: data.into(),
|
||||
action,
|
||||
mime_type: String::new(),
|
||||
path: file_name.map(Into::into),
|
||||
};
|
||||
IngestMessageHandler::default().process_message(message, &mut responses, IngestMessageContext { document_open });
|
||||
responses
|
||||
}
|
||||
|
||||
fn resource_input(accepted_types: Vec<DataType>) -> IngestAction {
|
||||
IngestAction::ResourceInput {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
node_id: NodeId(7),
|
||||
input_index: 1,
|
||||
accepted_types,
|
||||
}
|
||||
}
|
||||
|
||||
fn stored_resource(message: &Message) -> Option<ResourceId> {
|
||||
match message {
|
||||
Message::Portfolio(PortfolioMessage::DocumentPassMessage {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
message: DocumentMessage::Resource(ResourceMessage::StoreEmbedded { resource_id, .. }),
|
||||
}) => Some(*resource_id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_stores_the_file_and_assigns_it_in_the_requesting_document() {
|
||||
let responses = ingest(b"any bytes", resource_input(Vec::new()), true);
|
||||
let assigned = responses.iter().find_map(|message| match message {
|
||||
Message::Portfolio(PortfolioMessage::DocumentPassMessage {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
message: DocumentMessage::NodeGraph(NodeGraphMessage::SetInputValue { node_id, input_index, value }),
|
||||
}) => Some((*node_id, *input_index, value.clone())),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let stored = responses.iter().find_map(stored_resource).expect("the file should be stored as a resource");
|
||||
assert_eq!(assigned, Some((NodeId(7), 1, TaggedValue::Resource(stored).into())));
|
||||
assert!(
|
||||
responses.iter().all(|message| matches!(message, Message::Portfolio(PortfolioMessage::DocumentPassMessage { .. }))),
|
||||
"nothing should reach whichever document happens to be active"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_rejects_a_file_outside_its_types_before_storing_it() {
|
||||
let png = Image::new(8, 8, Color::WHITE).to_png();
|
||||
let raster = TypeFilter::raster().types;
|
||||
assert!(ingest(&png, resource_input(raster.clone()), true).iter().any(|message| stored_resource(message).is_some()));
|
||||
|
||||
// Text, an SVG, and an image cut off after its intact header
|
||||
for rejected in [b"not an image".as_slice(), b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>".as_slice(), &png[..40]] {
|
||||
let responses = ingest(rejected, resource_input(raster.clone()), true);
|
||||
assert_eq!(responses.len(), 1, "a rejected file should not become a resource");
|
||||
assert!(matches!(responses[0], Message::Dialog(DialogMessage::DisplayDialogError { .. })), "the user should be told why");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browsing_for_a_resource_input_carries_the_action_a_dropped_file_uses() {
|
||||
let filters = vec![TypeFilter::documents(), TypeFilter::raster()];
|
||||
let accepted_types = [TypeFilter::documents().types, TypeFilter::raster().types].concat();
|
||||
let dropped = IngestAction::resource_input(REQUESTING_DOCUMENT, NodeId(7), 1, &filters);
|
||||
assert_eq!(dropped, resource_input(accepted_types));
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
let message = IngestMessage::SetResourceInput {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
node_id: NodeId(7),
|
||||
input_index: 1,
|
||||
filters,
|
||||
};
|
||||
IngestMessageHandler::default().process_message(message, &mut responses, IngestMessageContext { document_open: true });
|
||||
assert!(matches!(&responses[0], Message::Portfolio(PortfolioMessage::Ingest(IngestMessage::Browse { action, .. })) if *action == dropped));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_says_why_an_icc_profile_of_the_wrong_kind_is_refused() {
|
||||
let mut monitor_profile = vec![0; 128];
|
||||
monitor_profile[12..16].copy_from_slice(b"mntr");
|
||||
monitor_profile[36..40].copy_from_slice(b"acsp");
|
||||
|
||||
let refusal = |data: &[u8], file_name: &str| {
|
||||
let responses = ingest_named(data, Some(file_name), resource_input(TypeFilter::lut().types), true);
|
||||
assert_eq!(responses.len(), 1, "a refused file should only show a dialog");
|
||||
match &responses[0] {
|
||||
Message::Dialog(DialogMessage::DisplayDialogError { description, .. }) => description.clone(),
|
||||
_ => panic!("the user should be told why"),
|
||||
}
|
||||
};
|
||||
|
||||
assert!(refusal(&monitor_profile, "display.icc").contains("monitor"));
|
||||
assert!(refusal(b"not a table", "grade.cube").contains("could not be read"));
|
||||
assert!(refusal(IDENTITY_CUBE, "grade.png").contains("does not accept"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_takes_an_image_format_that_has_no_signature() {
|
||||
// A TGA file is only told apart by its name
|
||||
let tga = crate::messages::frontend::utility_types::FileType::Tga.encode(2, 1, vec![255; 8]).unwrap();
|
||||
let stores = |file_name: &str| {
|
||||
let responses = ingest_named(&tga, Some(file_name), resource_input(TypeFilter::raster().types), true);
|
||||
responses.iter().any(|message| stored_resource(message).is_some())
|
||||
};
|
||||
|
||||
assert!(stores("photo.tga"));
|
||||
assert!(!stores("photo.unknown"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_tells_a_corrupt_image_apart_from_a_wrong_type() {
|
||||
let png = Image::new(8, 8, Color::WHITE).to_png();
|
||||
let refusal = |data: &[u8]| {
|
||||
let responses = ingest(data, resource_input(TypeFilter::raster().types), true);
|
||||
assert_eq!(responses.len(), 1, "a refused file should only show a dialog");
|
||||
match &responses[0] {
|
||||
Message::Dialog(DialogMessage::DisplayDialogError { description, .. }) => description.clone(),
|
||||
_ => panic!("the user should be told why"),
|
||||
}
|
||||
};
|
||||
|
||||
assert!(refusal(&png[..40]).contains("could not be read as an image"));
|
||||
assert!(refusal(b"not an image").contains("does not accept"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_takes_a_lookup_table_only_when_it_parses() {
|
||||
let png = Image::new(8, 8, Color::WHITE).to_png();
|
||||
let stores = |data: &[u8], filter: TypeFilter| {
|
||||
let responses = ingest_named(data, Some("grade.cube"), resource_input(filter.types), true);
|
||||
responses.iter().any(|message| stored_resource(message).is_some())
|
||||
};
|
||||
|
||||
assert!(stores(IDENTITY_CUBE, TypeFilter::lut()));
|
||||
|
||||
// A table cut off partway, an image named as a table, and a table offered to an image input
|
||||
assert!(!stores(&IDENTITY_CUBE[..30], TypeFilter::lut()));
|
||||
assert!(!stores(&png, TypeFilter::lut()));
|
||||
assert!(!stores(IDENTITY_CUBE, TypeFilter::raster()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_table_outside_a_node_input_only_shows_a_dialog() {
|
||||
let responses = ingest_named(IDENTITY_CUBE, Some("grade.cube"), IngestAction::Import, true);
|
||||
assert_eq!(responses.len(), 1);
|
||||
assert!(matches!(responses[0], Message::Dialog(DialogMessage::DisplayDialogError { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_image_only_shows_a_dialog() {
|
||||
let png = Image::new(8, 8, Color::WHITE).to_png();
|
||||
let responses = ingest(&png[..40], IngestAction::Paste, true);
|
||||
assert_eq!(responses.len(), 1);
|
||||
assert!(matches!(responses[0], Message::Dialog(DialogMessage::DisplayDialogError { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_file_only_shows_a_dialog() {
|
||||
let responses = ingest(b"just text", IngestAction::Open, true);
|
||||
assert_eq!(responses.len(), 1);
|
||||
assert!(matches!(responses[0], Message::Dialog(DialogMessage::DisplayDialogError { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_without_a_document_opens_one() {
|
||||
let png = Image::new(1, 1, Color::WHITE).to_png();
|
||||
let responses = ingest(&png, IngestAction::Paste, false);
|
||||
assert!(matches!(responses[0], Message::Portfolio(PortfolioMessage::NewDocumentWithName { .. })));
|
||||
assert!(
|
||||
responses
|
||||
.iter()
|
||||
.any(|message| matches!(message, Message::Portfolio(PortfolioMessage::Document(DocumentMessage::InsertImage { place_at_origin: true, .. }))))
|
||||
);
|
||||
|
||||
let responses = ingest(&png, IngestAction::Paste, true);
|
||||
assert!(matches!(
|
||||
responses[0],
|
||||
Message::Portfolio(PortfolioMessage::Document(DocumentMessage::InsertImage { place_at_origin: false, .. }))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
mod ingest_message;
|
||||
mod ingest_message_handler;
|
||||
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use ingest_message::{IngestMessage, IngestMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use ingest_message_handler::{IngestMessageContext, IngestMessageHandler};
|
||||
@@ -0,0 +1,249 @@
|
||||
use crate::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION};
|
||||
use crate::messages::frontend::utility_types::FileFilter;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::DocumentId;
|
||||
use document_container::archive::ArchiveFormat;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::raster_nodes::color_lookup_table::LUT_FILE_EXTENSIONS;
|
||||
use image::ImageFormat;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::Path;
|
||||
|
||||
/// How many leading bytes are inspected to recognize a text format.
|
||||
const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
pub enum IngestAction {
|
||||
Open,
|
||||
Import,
|
||||
Paste,
|
||||
DropOnCanvas {
|
||||
mouse: (f64, f64),
|
||||
},
|
||||
DropOnLayers {
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: u32,
|
||||
},
|
||||
ResourceInput {
|
||||
document_id: DocumentId,
|
||||
node_id: NodeId,
|
||||
input_index: u32,
|
||||
/// The types this input takes, where none means any file.
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
|
||||
accepted_types: Vec<DataType>,
|
||||
},
|
||||
}
|
||||
|
||||
impl IngestAction {
|
||||
/// Sends a file to a node's resource input, which takes only the types that its filters list.
|
||||
pub fn resource_input(document_id: DocumentId, node_id: NodeId, input_index: usize, filters: &[TypeFilter]) -> Self {
|
||||
Self::ResourceInput {
|
||||
document_id,
|
||||
node_id,
|
||||
input_index: input_index as u32,
|
||||
accepted_types: filters.iter().flat_map(|filter| filter.types.iter().copied()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DataType {
|
||||
GraphiteLegacy,
|
||||
Gdd,
|
||||
Svg,
|
||||
Raster(ImageFormat),
|
||||
Lut,
|
||||
#[default]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl DataType {
|
||||
/// The content decides, and the MIME type then the file name only settle what it leaves unknown.
|
||||
pub fn detect(data: &[u8], mime_type: &str, path: Option<&Path>) -> Self {
|
||||
match Self::from_content(data) {
|
||||
Self::Unknown => match Self::from_mime(mime_type) {
|
||||
Self::Unknown => path.map_or(Self::Unknown, Self::from_path),
|
||||
data_type => data_type,
|
||||
},
|
||||
data_type => data_type,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_mime(mime: &str) -> Self {
|
||||
match mime.to_ascii_lowercase().as_str() {
|
||||
"application/graphite+json" => Self::GraphiteLegacy,
|
||||
"application/vnd.graphite.document" => Self::Gdd,
|
||||
"image/svg+xml" => Self::Svg,
|
||||
mime => ImageFormat::from_mime_type(mime).map_or(Self::Unknown, Self::Raster),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_extension(extension: &str) -> Self {
|
||||
match extension.trim_start_matches('.').to_ascii_lowercase().as_str() {
|
||||
FILE_EXTENSION => Self::GraphiteLegacy,
|
||||
GDD_FILE_EXTENSION => Self::Gdd,
|
||||
"svg" => Self::Svg,
|
||||
extension if LUT_FILE_EXTENSIONS.contains(&extension) => Self::Lut,
|
||||
extension => ImageFormat::from_extension(extension).map_or(Self::Unknown, Self::Raster),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_path(path: impl AsRef<Path>) -> Self {
|
||||
path.as_ref().extension().and_then(OsStr::to_str).map_or(Self::Unknown, Self::from_extension)
|
||||
}
|
||||
|
||||
pub fn from_content(data: &[u8]) -> Self {
|
||||
if ArchiveFormat::detect(data).is_some() {
|
||||
return Self::Gdd;
|
||||
}
|
||||
if let Ok(format) = image::guess_format(data) {
|
||||
return Self::Raster(format);
|
||||
}
|
||||
|
||||
// Only the head is read as text, where a character split by the cut is the one invalid sequence tolerated
|
||||
let head = &data[..data.len().min(SNIFFED_TEXT_LENGTH)];
|
||||
let text = match std::str::from_utf8(head) {
|
||||
Ok(text) => text,
|
||||
Err(error) if error.error_len().is_none() => std::str::from_utf8(&head[..error.valid_up_to()]).unwrap_or_default(),
|
||||
Err(_) => return Self::Unknown,
|
||||
};
|
||||
|
||||
let text = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if text.starts_with('{') {
|
||||
Self::GraphiteLegacy
|
||||
} else if text.starts_with('<') && text.contains("<svg") {
|
||||
Self::Svg
|
||||
} else {
|
||||
Self::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mime(self) -> Option<&'static str> {
|
||||
Some(match self {
|
||||
Self::GraphiteLegacy => "application/graphite+json",
|
||||
Self::Gdd => "application/vnd.graphite.document",
|
||||
Self::Svg => "image/svg+xml",
|
||||
Self::Raster(format) => format.to_mime_type(),
|
||||
// The LUT formats share no MIME type
|
||||
Self::Lut | Self::Unknown => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn extensions(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::GraphiteLegacy => &[FILE_EXTENSION],
|
||||
Self::Gdd => &[GDD_FILE_EXTENSION],
|
||||
Self::Svg => &["svg"],
|
||||
Self::Raster(format) => format.extensions_str(),
|
||||
Self::Lut => LUT_FILE_EXTENSIONS,
|
||||
Self::Unknown => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TypeFilter {
|
||||
pub name: String,
|
||||
pub types: Vec<DataType>,
|
||||
}
|
||||
|
||||
impl TypeFilter {
|
||||
pub fn documents() -> Self {
|
||||
Self {
|
||||
name: "Graphite Document".into(),
|
||||
types: vec![DataType::Gdd, DataType::GraphiteLegacy],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raster() -> Self {
|
||||
Self {
|
||||
name: "Image".into(),
|
||||
types: ImageFormat::all().filter(ImageFormat::reading_enabled).map(DataType::Raster).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn image() -> Self {
|
||||
let mut images = Self::raster();
|
||||
images.types.push(DataType::Svg);
|
||||
images
|
||||
}
|
||||
|
||||
pub fn lut() -> Self {
|
||||
Self {
|
||||
name: "LUT".into(),
|
||||
types: vec![DataType::Lut],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TypeFilter> for FileFilter {
|
||||
fn from(filter: TypeFilter) -> Self {
|
||||
Self {
|
||||
name: filter.name,
|
||||
extensions: filter.types.iter().flat_map(|data_type| data_type.extensions()).map(|extension| extension.to_string()).collect(),
|
||||
mime_types: filter.types.iter().filter_map(|data_type| data_type.mime()).map(str::to_string).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
|
||||
#[test]
|
||||
fn data_type_from_content() {
|
||||
assert_eq!(DataType::from_content(&Image::new(1, 1, Color::WHITE).to_png()), DataType::Raster(ImageFormat::Png));
|
||||
assert_eq!(DataType::from_content(b"PK\x03\x04"), DataType::Gdd);
|
||||
assert_eq!(DataType::from_content(b"{\"network_interface\":{}}"), DataType::GraphiteLegacy);
|
||||
assert_eq!(
|
||||
DataType::from_content("\u{feff}<?xml version=\"1.0\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"/>".as_bytes()),
|
||||
DataType::Svg
|
||||
);
|
||||
assert_eq!(DataType::from_content(b"just text"), DataType::Unknown);
|
||||
assert_eq!(DataType::from_content(&[0xff, 0xfe, 0x00]), DataType::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_type_from_content_reads_only_the_head() {
|
||||
let late_svg = format!("<!--{}--><svg/>", " ".repeat(SNIFFED_TEXT_LENGTH));
|
||||
assert_eq!(DataType::from_content(late_svg.as_bytes()), DataType::Unknown);
|
||||
|
||||
// The three-byte euro sign straddles the cut, which must not hide the text before it
|
||||
let straddling = format!("<svg>{}€", " ".repeat(SNIFFED_TEXT_LENGTH - 6));
|
||||
assert_eq!(DataType::from_content(straddling.as_bytes()), DataType::Svg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_type_detect() {
|
||||
let detect = |mime_type: &str, path: &str| DataType::detect(&[], mime_type, Some(Path::new(path)));
|
||||
assert_eq!(detect("", "photo.JPEG"), DataType::Raster(ImageFormat::Jpeg));
|
||||
assert_eq!(detect("image/svg+xml", ""), DataType::Svg);
|
||||
assert_eq!(detect("application/graphite+json", ""), DataType::GraphiteLegacy);
|
||||
assert_eq!(detect("image/png", "document.gdd"), DataType::Raster(ImageFormat::Png));
|
||||
assert_eq!(detect("", "grade.CUBE"), DataType::Lut);
|
||||
assert_eq!(detect("application/vnd.iccprofile", "profile.icm"), DataType::Lut);
|
||||
assert_eq!(detect("text/csv", "table.csv"), DataType::Unknown);
|
||||
assert_eq!(DataType::detect(&[], "", None), DataType::Unknown);
|
||||
|
||||
let png = Image::new(1, 1, Color::WHITE).to_png();
|
||||
assert_eq!(DataType::detect(&png, "image/svg+xml", Some(Path::new("drawing.svg"))), DataType::Raster(ImageFormat::Png));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_filter_to_file_filter() {
|
||||
let filter = FileFilter::from(TypeFilter::image());
|
||||
assert!(filter.extensions.iter().any(|extension| extension == "jpeg") && filter.extensions.iter().any(|extension| extension == "png"));
|
||||
for enabled in ["webp", "tiff", "ico", "tga", "hdr", "exr"] {
|
||||
assert!(filter.extensions.iter().any(|extension| extension == enabled), "{enabled} should be offered");
|
||||
}
|
||||
assert!(filter.extensions.last().is_some_and(|extension| extension == "svg"));
|
||||
assert!(filter.mime_types.contains(&"image/jpeg".to_string()) && filter.mime_types.contains(&"image/svg+xml".to_string()));
|
||||
|
||||
// LUTs are picked by extension alone
|
||||
let filter = FileFilter::from(TypeFilter::lut());
|
||||
assert!(filter.extensions.iter().any(|extension| extension == "cube") && filter.mime_types.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,25 @@ mod portfolio_message_handler;
|
||||
pub mod document;
|
||||
pub mod document_migration;
|
||||
pub mod document_storage_io;
|
||||
pub mod failed_documents;
|
||||
pub mod fonts;
|
||||
pub mod ingest;
|
||||
pub mod persistent_state;
|
||||
pub mod sync;
|
||||
pub mod utility_types;
|
||||
pub mod workspace;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use failed_documents::{FailedDocumentsMessage, FailedDocumentsMessageContext, FailedDocumentsMessageHandler};
|
||||
#[doc(inline)]
|
||||
pub use fonts::{FontsMessage, FontsMessageContext, FontsMessageHandler};
|
||||
#[doc(inline)]
|
||||
pub use ingest::{IngestMessage, IngestMessageContext, IngestMessageHandler};
|
||||
#[doc(inline)]
|
||||
pub use persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
|
||||
#[doc(inline)]
|
||||
pub use portfolio_message::{PortfolioMessage, PortfolioMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use portfolio_message_handler::{PortfolioMessageContext, PortfolioMessageHandler};
|
||||
#[doc(inline)]
|
||||
pub use workspace::{WorkspaceMessage, WorkspaceMessageContext, WorkspaceMessageHandler};
|
||||
@@ -1,10 +1,8 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
||||
use super::sync::SyncMessage;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[impl_message(Message, Portfolio)]
|
||||
@@ -15,9 +13,17 @@ pub enum PortfolioMessage {
|
||||
#[child]
|
||||
Document(DocumentMessage),
|
||||
#[child]
|
||||
FailedDocuments(FailedDocumentsMessage),
|
||||
#[child]
|
||||
Fonts(FontsMessage),
|
||||
#[child]
|
||||
Ingest(IngestMessage),
|
||||
#[child]
|
||||
PersistentState(PersistentStateMessage),
|
||||
#[child]
|
||||
Sync(SyncMessage),
|
||||
#[child]
|
||||
Workspace(WorkspaceMessage),
|
||||
|
||||
// Messages
|
||||
Init,
|
||||
@@ -42,17 +48,18 @@ pub enum PortfolioMessage {
|
||||
DeleteDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Delivers an asynchronously-built `Gdd` working copy into its document, emitted by the mount future
|
||||
/// spawned in `load_document`. The `gdd` payload is non-serializable and a clone carries none
|
||||
/// (`clone_to_none`), so it travels exactly once. `reopened` is true when an existing working copy was
|
||||
/// opened: the persisted cursor is trusted as-is and the mount-time re-commit is skipped, since
|
||||
/// re-committing would stack a spurious interaction on the restored cursor and make the first undo a no-op.
|
||||
/// Delivers an asynchronously-built `Gdd` working copy, with the proto-node declarations its history
|
||||
/// references, into its document. Emitted by the mount future spawned in `load_document`. The `mounted`
|
||||
/// payload is non-serializable and a clone carries none (`clone_to_none`), so it travels exactly once.
|
||||
/// `reopened` is true when an existing working copy was opened: the persisted cursor is trusted as-is
|
||||
/// and the mount-time re-commit is skipped, since re-committing would stack a spurious interaction on
|
||||
/// the restored cursor and make the first undo a no-op.
|
||||
DocumentStorageMounted {
|
||||
document_id: DocumentId,
|
||||
reopened: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
gdd: Option<document_format::GddV1>,
|
||||
mounted: Option<(document_format::GddV1, document_graph_storage::Declarations)>,
|
||||
},
|
||||
DestroyAllDocuments,
|
||||
EditorPreferences,
|
||||
@@ -68,36 +75,10 @@ pub enum PortfolioMessage {
|
||||
document_id: DocumentId,
|
||||
document_serialized_content: String,
|
||||
},
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
ShowFailedToLoadDocumentsDialog,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
DiscardFailedToLoadDocuments,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
DownloadFailedToLoadDocuments,
|
||||
MoveAllPanelTabs {
|
||||
source_group: PanelGroupId,
|
||||
target_group: PanelGroupId,
|
||||
insert_index: usize,
|
||||
},
|
||||
MovePanelTab {
|
||||
source_group: PanelGroupId,
|
||||
target_group: PanelGroupId,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewDocumentWithName {
|
||||
name: String,
|
||||
},
|
||||
NextDocument,
|
||||
Open,
|
||||
Import,
|
||||
OpenFile {
|
||||
path: PathBuf,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
ImportFile {
|
||||
path: PathBuf,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
OpenDocumentFile {
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
@@ -119,17 +100,6 @@ pub enum PortfolioMessage {
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
document: Option<Box<DocumentMessageHandler>>,
|
||||
},
|
||||
/// Delivers the interface rebuilt from the `Gdd` undo/redo cursor so the async rebuild can swap into the
|
||||
/// live document. `interface` is `None` if the rebuild failed (logged at the source). `had_oracle` records
|
||||
/// whether the legacy snapshot applied synchronously, so the swap can debug-compare against it. Travels
|
||||
/// once like [`DocumentStorageMounted`](Self::DocumentStorageMounted).
|
||||
GddUndoRedoRebuilt {
|
||||
document_id: DocumentId,
|
||||
had_oracle: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
interface: Option<Box<crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface>>,
|
||||
},
|
||||
LoadDocument {
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
@@ -138,26 +108,6 @@ pub enum PortfolioMessage {
|
||||
document_is_saved: bool,
|
||||
document_serialized_content: String,
|
||||
},
|
||||
OpenImage {
|
||||
name: Option<String>,
|
||||
image: Image<Color>,
|
||||
},
|
||||
OpenSvg {
|
||||
name: Option<String>,
|
||||
svg: String,
|
||||
},
|
||||
InsertImage {
|
||||
name: Option<String>,
|
||||
image: Image<Color>,
|
||||
mouse: Option<(f64, f64)>,
|
||||
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
|
||||
},
|
||||
InsertSvg {
|
||||
name: Option<String>,
|
||||
svg: String,
|
||||
mouse: Option<(f64, f64)>,
|
||||
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
|
||||
},
|
||||
CenterLayers {
|
||||
layers: Vec<LayerNodeIdentifier>,
|
||||
},
|
||||
@@ -166,23 +116,8 @@ pub enum PortfolioMessage {
|
||||
document_id: DocumentId,
|
||||
new_index: usize,
|
||||
},
|
||||
ReorderPanelGroupTab {
|
||||
group: PanelGroupId,
|
||||
old_index: usize,
|
||||
new_index: usize,
|
||||
},
|
||||
RequestWelcomeScreenButtonsLayout,
|
||||
RequestStatusBarInfoLayout,
|
||||
SetPanelGroupActiveTab {
|
||||
group: PanelGroupId,
|
||||
tab_index: usize,
|
||||
},
|
||||
SplitPanelGroup {
|
||||
target_group: PanelGroupId,
|
||||
direction: DockingSplitDirection,
|
||||
tabs: Vec<PanelType>,
|
||||
active_tab_index: usize,
|
||||
},
|
||||
SelectDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
@@ -197,6 +132,13 @@ pub enum PortfolioMessage {
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
},
|
||||
SaveRasterizedExport {
|
||||
name: String,
|
||||
file_type: FileType,
|
||||
width: u32,
|
||||
height: u32,
|
||||
data: Vec<u8>,
|
||||
},
|
||||
SubmitActiveGraphRender,
|
||||
SubmitGraphRender {
|
||||
document_id: DocumentId,
|
||||
@@ -204,24 +146,13 @@ pub enum PortfolioMessage {
|
||||
},
|
||||
SubmitEyedropperPreviewRender,
|
||||
ToggleResetNodesToDefinitionsOnOpen,
|
||||
ToggleFocusDocument,
|
||||
ToggleDataPanelOpen,
|
||||
TogglePropertiesPanelOpen,
|
||||
ToggleLayersPanelOpen,
|
||||
ToggleRulers,
|
||||
UpdateDocumentWidgets,
|
||||
UpdateOpenDocumentsList,
|
||||
UpdateWorkspacePanelLayout,
|
||||
ResetWorkspaceLayout,
|
||||
SetPanelGroupSizes {
|
||||
/// Path of child indices from the root to the split node whose children's sizes are being set.
|
||||
split_path: Vec<usize>,
|
||||
/// New sizes for the children at that split node.
|
||||
sizes: Vec<f64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Clone helper for the non-serializable `gdd` payload: a cloned mount message carries no `Gdd`.
|
||||
/// Clone helper for non-serializable payloads: a cloned message carries none of the `Gdd` working copy,
|
||||
/// its declarations, or the built document.
|
||||
fn clone_to_none<T>(_: &Option<T>) -> Option<T> {
|
||||
None
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
mod sync_message;
|
||||
mod sync_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
|
||||
@@ -0,0 +1,27 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use peer_transport::TransportPeerId;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, Sync)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SyncMessage {
|
||||
/// Host the active document and hand the frontend a link for others to join.
|
||||
Share,
|
||||
/// Open a new document that follows the session behind `token`.
|
||||
Join { token: String },
|
||||
/// Leave the active document's session.
|
||||
Leave,
|
||||
/// Per frame: apply what peers sent and answer their requests.
|
||||
Poll,
|
||||
/// A document's working copy mounted; attaches it to a pending join.
|
||||
StorageMounted { document_id: DocumentId },
|
||||
/// The transport loop of a document's session ended.
|
||||
Disconnected { document_id: DocumentId },
|
||||
/// A resource a peer asked for was read from the byte store.
|
||||
ResourceLoaded {
|
||||
document_id: DocumentId,
|
||||
to: TransportPeerId,
|
||||
hash: ResourceHash,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use document_graph_storage::UserId;
|
||||
use graph_craft::application_io::resource::LoadResource;
|
||||
use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, Room, SessionToken, SyncTarget};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct SyncMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
}
|
||||
|
||||
/// Drives every document's collaborative session: attaches transports, polls them once per frame,
|
||||
/// and turns remote changes into interface rebuilds.
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct SyncMessageHandler {
|
||||
pending_join: Option<SessionToken>,
|
||||
polling: bool,
|
||||
/// Documents whose registry changed remotely since their interface was last rebuilt.
|
||||
dirty: HashSet<DocumentId>,
|
||||
blocked_reason: HashMap<DocumentId, String>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler {
|
||||
fn process_message(&mut self, message: SyncMessage, responses: &mut VecDeque<Message>, context: SyncMessageContext) {
|
||||
let SyncMessageContext {
|
||||
documents,
|
||||
active_document_id,
|
||||
resource_storage,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
SyncMessage::Share => {
|
||||
let Some(document) = active_document_id.and_then(|id| documents.get_mut(&id)) else { return };
|
||||
let Some(gdd) = document.storage_mut() else {
|
||||
log::warn!("Cannot share a document before its working copy is mounted");
|
||||
return;
|
||||
};
|
||||
if gdd.role().is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let token = SessionToken(random_token_bytes());
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let user = UserId(gdd.session().peer().0);
|
||||
gdd.share(room, user);
|
||||
|
||||
let document_id = active_document_id.expect("checked above");
|
||||
responses.add(driver_future(document_id, driver));
|
||||
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Live session started".into(),
|
||||
description: format!("A link to join was copied to the clipboard.\n\nSession {token}"),
|
||||
});
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
self.start_polling(responses);
|
||||
}
|
||||
SyncMessage::Join { token } => {
|
||||
let token = match token.parse::<SessionToken>() {
|
||||
Ok(token) => token,
|
||||
Err(error) => {
|
||||
log::warn!("Ignoring session link: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.pending_join = Some(token);
|
||||
responses.add(PortfolioMessage::NewDocumentWithName { name: "Shared session".into() });
|
||||
}
|
||||
SyncMessage::StorageMounted { document_id } => {
|
||||
let Some(token) = self.pending_join.take() else { return };
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let user = UserId(gdd.session().peer().0);
|
||||
gdd.join(room, user);
|
||||
|
||||
responses.add(driver_future(document_id, driver));
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
self.start_polling(responses);
|
||||
}
|
||||
SyncMessage::Leave => {
|
||||
let Some(gdd) = active_document_id.and_then(|id| documents.get_mut(&id)).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
gdd.leave();
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
SyncMessage::Disconnected { document_id } => {
|
||||
if let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) {
|
||||
gdd.leave();
|
||||
}
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
SyncMessage::Poll => {
|
||||
let resources = resource_storage.resources_mut();
|
||||
for (&document_id, document) in documents.iter_mut() {
|
||||
let Some(gdd) = document.storage_mut() else { continue };
|
||||
if gdd.role().is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let events = gdd.poll_peers();
|
||||
for event in events {
|
||||
match event {
|
||||
Event::Synced | Event::Changed => {
|
||||
self.dirty.insert(document_id);
|
||||
document.runtime_stale = true;
|
||||
}
|
||||
Event::ResourceRequested { from, hash } => {
|
||||
log::debug!("Peer asked for resource {hash}");
|
||||
responses.add(load_resource_future(document_id, from, hash, resources.clone()));
|
||||
}
|
||||
// The replica already put the bytes in the byte store; only the decoded form is missing.
|
||||
Event::ResourceReceived { hash, bytes } => {
|
||||
log::debug!("Received resource {hash} ({} bytes)", bytes.len());
|
||||
document.cache_declaration_bytes(hash, &bytes);
|
||||
self.dirty.insert(document_id);
|
||||
}
|
||||
Event::PeerJoined { .. } | Event::PeerLeft { .. } => responses.add(PortfolioMessage::UpdateOpenDocumentsList),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild only once every referenced resource is in the app cache, and never underneath an
|
||||
// open transaction, whose un-staged edits the swap would discard.
|
||||
for document_id in self.dirty.clone() {
|
||||
let Some(document) = documents.get_mut(&document_id) else {
|
||||
self.dirty.remove(&document_id);
|
||||
continue;
|
||||
};
|
||||
let Some(gdd) = document.storage() else { continue };
|
||||
let missing = SyncTarget::missing_resources(gdd).len();
|
||||
let transaction = document.network_interface.transaction_status();
|
||||
if missing > 0 || transaction != TransactionStatus::Finished {
|
||||
let reason = format!("missing {missing} transaction {transaction:?}");
|
||||
if self.blocked_reason.get(&document_id) != Some(&reason) {
|
||||
log::debug!("Sync rebuild for {document_id:?} waiting: {reason}");
|
||||
self.blocked_reason.insert(document_id, reason);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.blocked_reason.remove(&document_id);
|
||||
|
||||
self.dirty.remove(&document_id);
|
||||
document.apply_remote_changes(responses);
|
||||
// The swapped-in registry names resources this peer may still have to fetch or resolve.
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
}
|
||||
}
|
||||
SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => {
|
||||
log::debug!("Sending resource {hash} ({} bytes)", bytes.len());
|
||||
let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = gdd.send_resource(to, hash, bytes) {
|
||||
log::warn!("Failed to send resource {hash} to a peer: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(SyncMessageDiscriminant; Share, Leave);
|
||||
}
|
||||
|
||||
impl SyncMessageHandler {
|
||||
fn start_polling(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if self.polling {
|
||||
return;
|
||||
}
|
||||
self.polling = true;
|
||||
responses.add(BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send: Box::new(SyncMessage::Poll.into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn driver_future(document_id: DocumentId, driver: peer_transport::MessageLoopFuture) -> Message {
|
||||
let future = async move {
|
||||
if let Err(error) = driver.await {
|
||||
log::warn!("Session transport for {document_id:?} ended: {error}");
|
||||
}
|
||||
Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Disconnected { document_id }))
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
fn load_resource_future(document_id: DocumentId, to: peer_transport::TransportPeerId, hash: graph_craft::application_io::resource::ResourceHash, resources: ResourcesHandle) -> Message {
|
||||
let future = async move {
|
||||
match resources.load(hash).await {
|
||||
Some(resource) => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::ResourceLoaded {
|
||||
document_id,
|
||||
to,
|
||||
hash,
|
||||
bytes: resource.as_ref().to_vec(),
|
||||
})),
|
||||
None => {
|
||||
log::warn!("A peer asked for resource {hash} which is not in the byte store");
|
||||
Message::NoOp
|
||||
}
|
||||
}
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
fn random_token_bytes() -> [u8; 16] {
|
||||
let mut bytes = [0; 16];
|
||||
bytes[..8].copy_from_slice(&generate_uuid().to_le_bytes());
|
||||
bytes[8..].copy_from_slice(&generate_uuid().to_le_bytes());
|
||||
bytes
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
|
||||
/// Proportional share (0-1) for the document panel's side when splitting adjacent to non-document panels.
|
||||
const DOCUMENT_PANEL_SHARE: f64 = 0.8;
|
||||
/// Proportional share for each side when neither (or both) contain the document panel.
|
||||
@@ -787,16 +784,3 @@ impl PanelLayoutSubdivision {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum FileContent {
|
||||
/// A legacy `.graphite` document (serialized runtime JSON).
|
||||
Document(String),
|
||||
/// A `.gdd` document container (archive bytes).
|
||||
GddDocument(Vec<u8>),
|
||||
/// A bitmap image.
|
||||
Image(Image<Color>),
|
||||
/// An SVG file string.
|
||||
Svg(String),
|
||||
/// Any other unsupported/unrecognized file type.
|
||||
Unsupported,
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod workspace_message;
|
||||
mod workspace_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use workspace_message::{WorkspaceMessage, WorkspaceMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use workspace_message_handler::{WorkspaceMessageContext, WorkspaceMessageHandler};
|
||||
@@ -0,0 +1,44 @@
|
||||
use crate::messages::portfolio::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, Workspace)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WorkspaceMessage {
|
||||
MoveAllPanelTabs {
|
||||
source_group: PanelGroupId,
|
||||
target_group: PanelGroupId,
|
||||
insert_index: usize,
|
||||
},
|
||||
MovePanelTab {
|
||||
source_group: PanelGroupId,
|
||||
target_group: PanelGroupId,
|
||||
insert_index: usize,
|
||||
},
|
||||
ReorderPanelGroupTab {
|
||||
group: PanelGroupId,
|
||||
old_index: usize,
|
||||
new_index: usize,
|
||||
},
|
||||
SetPanelGroupActiveTab {
|
||||
group: PanelGroupId,
|
||||
tab_index: usize,
|
||||
},
|
||||
SplitPanelGroup {
|
||||
target_group: PanelGroupId,
|
||||
direction: DockingSplitDirection,
|
||||
tabs: Vec<PanelType>,
|
||||
active_tab_index: usize,
|
||||
},
|
||||
ToggleFocusDocument,
|
||||
ToggleDataPanelOpen,
|
||||
TogglePropertiesPanelOpen,
|
||||
ToggleLayersPanelOpen,
|
||||
UpdatePanelsLayout,
|
||||
ResetWorkspaceLayout,
|
||||
SetPanelGroupSizes {
|
||||
/// Path of child indices from the root to the split node whose children's sizes are being set.
|
||||
split_path: Vec<usize>,
|
||||
/// New sizes for the children at that split node.
|
||||
sizes: Vec<f64>,
|
||||
},
|
||||
}
|
||||
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user