mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
Merge branch 'upstream/master' into fix-colinear-handles-extension
This commit is contained in:
commit
314e9f7866
255 files changed
+23067
-7785
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
|
||||
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/a40077842627afb0c90858b351112a62b340881d.tar.gz
|
||||
cd454d750d3f47fb2f41abceeacfc0ae59629ca00229dc56df53e3f4db0f6ee7
|
||||
Generated
+3
-4
@@ -913,6 +913,7 @@ dependencies = [
|
||||
"color",
|
||||
"ctor",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam 0.33.10",
|
||||
"graphene-hash",
|
||||
"image",
|
||||
@@ -932,7 +933,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"skrifa 0.42.1",
|
||||
"tinyvec",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -2132,7 +2132,6 @@ dependencies = [
|
||||
"document-container",
|
||||
"document-format",
|
||||
"fern",
|
||||
"futures",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"image",
|
||||
@@ -2168,6 +2167,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"glam 0.33.10",
|
||||
"graphene-hash-derive",
|
||||
"kurbo",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2423,7 +2423,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"simplecss",
|
||||
"snapping",
|
||||
"spin",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tsify",
|
||||
@@ -2431,7 +2430,6 @@ dependencies = [
|
||||
"usvg",
|
||||
"vello",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"wgpu-executor",
|
||||
"zip",
|
||||
@@ -2463,6 +2461,7 @@ dependencies = [
|
||||
"serde-wasm-bindgen",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"spin",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
|
||||
+40
-32
@@ -22,10 +22,11 @@ use crate::input::InputState;
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::spawner::TokioSpawner;
|
||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
@@ -77,14 +78,40 @@ impl App {
|
||||
|
||||
let exiting = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let rendering_app_event_scheduler = app_event_scheduler.clone();
|
||||
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
|
||||
|
||||
let async_runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct tokio runtime");
|
||||
|
||||
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
|
||||
|
||||
let wake_scheduler = app_event_scheduler.clone();
|
||||
let editor_wake = move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
};
|
||||
let runtime_wake_sender = start_render_sender.clone();
|
||||
let runtime_wake = move || {
|
||||
let _ = runtime_wake_sender.try_send(());
|
||||
};
|
||||
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
|
||||
rand::rng().random(),
|
||||
Arc::new(resource_storage),
|
||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
||||
wgpu_context.clone(),
|
||||
TokioSpawner::new(async_runtime.handle().clone()),
|
||||
editor_wake,
|
||||
runtime_wake,
|
||||
);
|
||||
|
||||
let rendering_app_event_scheduler = app_event_scheduler.clone();
|
||||
let exiting_clone = exiting.clone();
|
||||
std::thread::spawn(move || {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
loop {
|
||||
let result = runtime.block_on(DesktopWrapper::execute_node_graph());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::NodeGraphExecutionResult(result));
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
|
||||
if exiting_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
@@ -92,21 +119,6 @@ impl App {
|
||||
}
|
||||
});
|
||||
|
||||
let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage");
|
||||
|
||||
// Wake the winit event loop when an editor future completes.
|
||||
let wake_scheduler = app_event_scheduler.clone();
|
||||
let wake = Arc::new(move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(
|
||||
rand::rng().random(),
|
||||
Arc::new(resource_storage),
|
||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
||||
wgpu_context.clone(),
|
||||
wake,
|
||||
);
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
wgpu_context,
|
||||
@@ -436,19 +448,15 @@ impl App {
|
||||
}
|
||||
}
|
||||
AppEvent::DesktopWrapperMessage(message) => self.dispatch_desktop_wrapper_message(message),
|
||||
AppEvent::NodeGraphExecutionResult(result) => match result {
|
||||
NodeGraphExecutionResult::HasRun(texture) => {
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::PollNodeGraphEvaluation);
|
||||
if let Some(texture) = texture
|
||||
&& let Some(render_state) = self.render_state.as_mut()
|
||||
&& let Some(window) = self.window.as_ref()
|
||||
{
|
||||
render_state.bind_viewport_texture(texture);
|
||||
window.request_redraw();
|
||||
}
|
||||
AppEvent::ViewportTexture(texture) => {
|
||||
if let Some(texture) = texture
|
||||
&& let Some(render_state) = self.render_state.as_mut()
|
||||
&& let Some(window) = self.window.as_ref()
|
||||
{
|
||||
render_state.bind_viewport_texture(texture);
|
||||
window.request_redraw();
|
||||
}
|
||||
NodeGraphExecutionResult::NotRun => {}
|
||||
},
|
||||
}
|
||||
AppEvent::UiUpdate(texture) => {
|
||||
if let Some(render_state) = self.render_state.as_mut() {
|
||||
render_state.bind_ui_texture(texture);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::ui::Cursor;
|
||||
use crate::wrapper::NodeGraphExecutionResult;
|
||||
use crate::wrapper::Texture;
|
||||
use crate::wrapper::messages::DesktopWrapperMessage;
|
||||
|
||||
pub(crate) enum AppEvent {
|
||||
@@ -7,7 +7,7 @@ pub(crate) enum AppEvent {
|
||||
CursorChange(Cursor),
|
||||
WebCommunicationInitialized,
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
ViewportTexture(Option<Texture>),
|
||||
ClipboardRead,
|
||||
ClipboardWrite {
|
||||
content: String,
|
||||
|
||||
@@ -22,6 +22,7 @@ mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
mod socket;
|
||||
mod spawner;
|
||||
mod window;
|
||||
|
||||
pub(crate) mod consts;
|
||||
|
||||
@@ -228,7 +228,7 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::wrapper::{Spawn, Task};
|
||||
|
||||
pub(crate) struct TokioSpawner(tokio::runtime::Handle);
|
||||
impl TokioSpawner {
|
||||
pub(crate) fn new(handle: tokio::runtime::Handle) -> Self {
|
||||
Self(handle)
|
||||
}
|
||||
}
|
||||
impl Spawn for TokioSpawner {
|
||||
fn spawn(&self, task: Task) {
|
||||
self.0.spawn(task);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.queue_editor_message(*message);
|
||||
}
|
||||
DesktopWrapperMessage::Wake => {
|
||||
dispatcher.queue_editor_message(EditorMessage::Future(FutureMessage::Wake));
|
||||
dispatcher.queue_editor_message(EditorMessage::Wake);
|
||||
}
|
||||
DesktopWrapperMessage::Input(message) => {
|
||||
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
|
||||
@@ -35,7 +35,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
|
||||
DesktopWrapperMessage::UpdateMaximized { maximized } => {
|
||||
let message = FrontendMessage::UpdateMaximized { maximized };
|
||||
dispatcher.queue_editor_message(message);
|
||||
|
||||
+26
-18
@@ -1,8 +1,9 @@
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||
use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder};
|
||||
use graphite_editor::messages::frontend::FrontendMessage;
|
||||
use graphite_editor::messages::prelude::Wake;
|
||||
use graphite_editor::node_graph_executor::NodeRuntime;
|
||||
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
@@ -11,6 +12,7 @@ use std::sync::Arc;
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
|
||||
pub use graphite_editor::task::{Spawn, Task};
|
||||
pub use wgpu_executor::Texture;
|
||||
pub use wgpu_executor::WgpuBackends;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
@@ -33,7 +35,15 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
pub fn new(
|
||||
random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn DocumentStore>,
|
||||
wgpu_context: WgpuContext,
|
||||
spawner: impl Spawn + Send + Sync + 'static,
|
||||
editor_wake: impl Fn() + Send + Sync + 'static,
|
||||
runtime_wake: impl Fn() + Send + Sync + 'static,
|
||||
) -> (Self, NodeRuntime) {
|
||||
#[cfg(target_os = "windows")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -43,9 +53,20 @@ impl DesktopWrapper {
|
||||
let env = Environment { platform: Platform::Desktop, host };
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
|
||||
Self {
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
|
||||
}
|
||||
let (editor, runtime) = Builder::new()
|
||||
.with_editor(
|
||||
EditorBuilder::new()
|
||||
.with_wake(editor_wake)
|
||||
.with_environment(env)
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_spawner(spawner)
|
||||
.with_random_seed(random_seed)
|
||||
.build();
|
||||
|
||||
(Self { editor }, runtime)
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec<DesktopFrontendMessage> {
|
||||
@@ -53,19 +74,6 @@ impl DesktopWrapper {
|
||||
executor.queue_desktop_wrapper_message(message);
|
||||
executor.execute()
|
||||
}
|
||||
|
||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||
match result {
|
||||
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
|
||||
(false, _) => NodeGraphExecutionResult::NotRun,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum NodeGraphExecutionResult {
|
||||
HasRun(Option<Texture>),
|
||||
NotRun,
|
||||
}
|
||||
|
||||
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
|
||||
|
||||
@@ -42,18 +42,6 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
self.responses.push(response);
|
||||
}
|
||||
|
||||
pub(super) fn poll_node_graph_evaluation(&mut self) {
|
||||
let mut responses = VecDeque::new();
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||
&& e != "No active document"
|
||||
{
|
||||
tracing::error!("Error polling node graph: {}", e);
|
||||
}
|
||||
while let Some(message) = responses.pop_front() {
|
||||
self.queue_editor_message(message);
|
||||
}
|
||||
}
|
||||
|
||||
fn process_queue(&mut self) {
|
||||
let mut frontend_messages = Vec::new();
|
||||
|
||||
|
||||
@@ -79,7 +79,6 @@ pub enum DesktopWrapperMessage {
|
||||
Input(InputMessage),
|
||||
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
|
||||
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
|
||||
PollNodeGraphEvaluation,
|
||||
UpdateMaximized { maximized: bool },
|
||||
UpdateFullscreen { fullscreen: bool },
|
||||
LoadPersistedState { state: PersistedState },
|
||||
|
||||
@@ -123,6 +123,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -148,6 +149,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -156,6 +158,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
sequence: HotSequence(2),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
@@ -194,6 +197,7 @@ fn last_broadcast_rev_persists_across_reopen() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
@@ -632,6 +636,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
},
|
||||
timestamp: TimeStamp { counter, peer: PeerId(22) },
|
||||
sequence: HotSequence(counter),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
|
||||
@@ -102,10 +102,10 @@ impl Attributes {
|
||||
|
||||
/// Lands a single-key write if it is newer than the key's value, or than the floor for a key the map lacks. A
|
||||
/// deletion leaves a tombstone.
|
||||
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp, force: bool) {
|
||||
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
let decided = self.get(&key).map_or(self.floor, |existing| existing.timestamp);
|
||||
if !force && timestamp <= decided {
|
||||
if timestamp <= decided {
|
||||
return;
|
||||
}
|
||||
let entry = match value {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
pub mod node {
|
||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||
pub const CONTEXT_FEATURES: &str = "context_features";
|
||||
pub const VISIBLE: &str = "visible";
|
||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||
@@ -68,6 +67,7 @@ pub mod network {
|
||||
}
|
||||
|
||||
pub mod delta {
|
||||
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta.
|
||||
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. Also set on
|
||||
/// the last hot op of an interaction.
|
||||
pub const INTERACTION_END: &str = "interaction_end";
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use crate::{
|
||||
Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
|
||||
};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -13,7 +15,8 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
pub reverse: RegistryDelta,
|
||||
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
|
||||
pub reverse: Vec<Prior>,
|
||||
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
|
||||
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
|
||||
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||
@@ -26,7 +29,7 @@ pub struct Delta {
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
|
||||
let id = compute_rev(parent, author, timestamp, &kind);
|
||||
Self {
|
||||
id,
|
||||
@@ -54,7 +57,7 @@ impl Delta {
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
reverse: kind.clone(),
|
||||
reverse: Vec::new(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
@@ -208,6 +211,7 @@ pub enum RegistryDelta {
|
||||
Merge {
|
||||
extra_parents: Vec<Rev>,
|
||||
},
|
||||
Meta,
|
||||
// Allow for future delta types without a model change
|
||||
Other(Value),
|
||||
}
|
||||
@@ -219,26 +223,13 @@ pub struct AttributeDelta {
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||
AttributeDelta {
|
||||
key: delta.key.clone(),
|
||||
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unrecorded_retired_at_costs_one_byte_and_round_trips() {
|
||||
let base = Delta::new(
|
||||
None,
|
||||
PeerId(1),
|
||||
TimeStamp { counter: 1, peer: PeerId(1) },
|
||||
RegistryDelta::Other(Value::None),
|
||||
RegistryDelta::Other(Value::None),
|
||||
);
|
||||
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::Other(Value::None), Vec::new());
|
||||
let mut stamped = base.clone();
|
||||
stamped.retired_at_ms = 1_790_000_000_000;
|
||||
|
||||
|
||||
@@ -3,9 +3,8 @@ use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId, Value, reverse_attribute_delta,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Document {
|
||||
@@ -76,17 +75,12 @@ impl Document {
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||
/// the same timestamp as the forward op it undoes.
|
||||
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
/// Undo `delta` by putting back what it overwrote: in the snapshot, and in the working registry when nothing is hot.
|
||||
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
|
||||
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
|
||||
if self.hot_log.is_empty() {
|
||||
crate::prior::restore(&mut self.working_registry, &delta.reverse);
|
||||
}
|
||||
std::mem::swap(&mut delta.kind, &mut delta.reverse);
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Stage a local op onto the working registry and the hot log, skipping the retired check so local work is never dropped.
|
||||
@@ -190,13 +184,6 @@ impl Document {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
|
||||
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
|
||||
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
|
||||
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
|
||||
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
|
||||
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
|
||||
@@ -206,7 +193,6 @@ impl Document {
|
||||
self.clock.observe(timestamp);
|
||||
|
||||
let strict = mode == ApplyMode::Strict;
|
||||
let force = mode == ApplyMode::Force;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
@@ -215,10 +201,10 @@ impl Document {
|
||||
return Err(CrdtError::NodeAlreadyExists(id));
|
||||
}
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force);
|
||||
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force);
|
||||
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
||||
inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp));
|
||||
@@ -231,12 +217,7 @@ impl Document {
|
||||
.collect();
|
||||
ensure_seen(registry, &referenced, mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force {
|
||||
node.inputs = inputs;
|
||||
node.inputs_timestamp = timestamp;
|
||||
} else {
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
}
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
for referenced in referenced {
|
||||
@@ -251,7 +232,7 @@ impl Document {
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
if force || timestamp > input.timestamp {
|
||||
if timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
@@ -267,7 +248,7 @@ impl Document {
|
||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
if timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
@@ -276,14 +257,14 @@ impl Document {
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
node.attributes.apply_delta(delta, timestamp, force);
|
||||
node.attributes.apply_delta(delta, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
input.attributes.apply_delta(delta, timestamp, force);
|
||||
input.attributes.apply_delta(delta, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
@@ -300,7 +281,7 @@ impl Document {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
}
|
||||
// Past the end of a newer list the slot is gone, as with input slots.
|
||||
if !force && timestamp <= net.exports_timestamp {
|
||||
if timestamp <= net.exports_timestamp {
|
||||
return Ok(());
|
||||
}
|
||||
let shape = net.exports_timestamp;
|
||||
@@ -308,7 +289,7 @@ impl Document {
|
||||
}
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
if timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
@@ -322,20 +303,20 @@ impl Document {
|
||||
if strict && registry.networks.contains_key(&id) {
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force);
|
||||
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force);
|
||||
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
net.attributes.apply_delta(delta, timestamp, force);
|
||||
net.attributes.apply_delta(delta, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
if timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
@@ -344,24 +325,20 @@ impl Document {
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
let value = SourceValue { source, timestamp, deleted: false };
|
||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||
entry.set_source(key, value);
|
||||
});
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if force {
|
||||
entry.force_remove_source(&key);
|
||||
} else {
|
||||
entry.remove_source(&key, timestamp);
|
||||
}
|
||||
entry.remove_source(&key, timestamp);
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddResource { id, entry } => {
|
||||
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp, force);
|
||||
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force);
|
||||
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::RegisterPeer { peer, user } => {
|
||||
// The newest registration of a device wins, whatever order they land in.
|
||||
@@ -370,117 +347,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||
registry.attributes.apply_delta(delta, timestamp, force);
|
||||
registry.attributes.apply_delta(delta, timestamp);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
/// [`RegistryTarget::Retired`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||
/// capture the true pre-op value rather than the hot-polluted working state.
|
||||
///
|
||||
/// A write reads its pre-op value from wherever it lands: the live entity, its tombstone, or for an
|
||||
/// entity never seen, a placeholder.
|
||||
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
|
||||
let registry = self.registry_ref(target);
|
||||
let node = |id: NodeId| registry.node_or_removed(id).map_or_else(|| Cow::Owned(Node::placeholder()), Cow::Borrowed);
|
||||
let unset = InputSlot::unset(TimeStamp::ORIGIN);
|
||||
let network = |id: NetworkId| registry.network_or_removed(id);
|
||||
let resource = |id: ResourceId| registry.resources.get(&id).or_else(|| registry.removed_resources.get(&id).map(|mark| &mark.content));
|
||||
Ok(match delta {
|
||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||
&RegistryDelta::SetNodeInputs { id, .. } => RegistryDelta::SetNodeInputs { id, inputs: node(id).inputs.clone() },
|
||||
&RegistryDelta::SetNodeImplementation { id, .. } => RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node(id).implementation.clone(),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = node(id);
|
||||
let slot = node.inputs().get(input_idx as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: input_idx,
|
||||
new_input: slot.input.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node(id).attributes()),
|
||||
},
|
||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||
let node = node(id);
|
||||
let input = node.inputs().get(index as usize).unwrap_or(&unset);
|
||||
RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
delta: reverse_attribute_delta(delta, &input.attributes),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||
// Absent network or slot: pre-op there was no export to point at.
|
||||
let export_target = network(id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
||||
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
||||
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
||||
let empty = Attributes::new();
|
||||
let current = network(id).map_or(&empty, |net| &net.attributes);
|
||||
RegistryDelta::ChangeNetworkAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, current),
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: reverse_attribute_delta(delta, ®istry.attributes),
|
||||
},
|
||||
// Registrations are append-only and not user-undoable; reverse is the same op,
|
||||
// which applies as a no-op on the already-registered PeerId.
|
||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: resource(id).and_then(|entry| entry.hash),
|
||||
},
|
||||
&RegistryDelta::AddSource { id, key, .. } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
// The slot already held a source: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// The slot was empty: undo removes what this op added.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) {
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// Nothing to restore; reverse is a no-op removal.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
|
||||
// Overwrote an existing entry: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
|
||||
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
|
||||
None => RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: ResourceEntry::default(),
|
||||
},
|
||||
},
|
||||
&RegistryDelta::RemoveResource { id, .. } => {
|
||||
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
|
||||
RegistryDelta::AddResource { id, entry: snapshot }
|
||||
}
|
||||
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
||||
&RegistryDelta::Other(_) => RegistryDelta::Other(Value::None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
||||
@@ -649,7 +522,7 @@ fn slot_for_write(node: &mut Node, index: usize, timestamp: TimeStamp, mode: App
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict {
|
||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
||||
}
|
||||
if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp {
|
||||
if timestamp <= node.inputs_timestamp {
|
||||
return Ok(None);
|
||||
}
|
||||
let shape = node.inputs_timestamp;
|
||||
@@ -688,23 +561,18 @@ fn merge_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead:
|
||||
}
|
||||
|
||||
/// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead.
|
||||
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp, force: bool) {
|
||||
if force {
|
||||
dead.remove(&id);
|
||||
live.insert(id, content);
|
||||
return;
|
||||
}
|
||||
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp) {
|
||||
content.stamp_all(timestamp);
|
||||
merge_entity(live, dead, id, content);
|
||||
}
|
||||
|
||||
/// A removal at `timestamp`: dead unless a newer addition or write holds it live. The snapshot folds in first, so a removal of an
|
||||
/// entity never seen still lands.
|
||||
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) {
|
||||
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp) {
|
||||
merge_entity(live, dead, id, snapshot);
|
||||
if let Some(mark) = dead.get_mut(&id) {
|
||||
mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) };
|
||||
} else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) {
|
||||
mark.timestamp = mark.timestamp.max(timestamp);
|
||||
} else if live.get(&id).is_some_and(|content| timestamp > content.presence()) {
|
||||
let content = live.remove(&id).expect("checked above");
|
||||
dead.insert(
|
||||
id,
|
||||
@@ -728,7 +596,6 @@ fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
||||
missing: impl FnOnce() -> CrdtError,
|
||||
f: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
||||
) -> Result<(), CrdtError> {
|
||||
let force = mode == ApplyMode::Force;
|
||||
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
|
||||
if unseen {
|
||||
if mode == ApplyMode::Strict {
|
||||
@@ -752,9 +619,6 @@ fn write_entity<K: Hash + Eq + Copy, T: Entity>(
|
||||
return Err(error);
|
||||
}
|
||||
content.set_presence(content.presence().max(timestamp));
|
||||
if force && let Some(mark) = dead.remove(&id) {
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
revive_if_newer(live, dead, id);
|
||||
Ok(())
|
||||
}
|
||||
@@ -818,6 +682,4 @@ pub(crate) enum ApplyMode {
|
||||
Strict,
|
||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
||||
Idempotent,
|
||||
/// Silent-zone undo/redo rewind: every write lands, whatever its timestamp.
|
||||
Force,
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::Context;
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -447,9 +446,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
attributes
|
||||
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
|
||||
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
|
||||
attributes
|
||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||
@@ -477,11 +473,6 @@ pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::A
|
||||
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
|
||||
}
|
||||
|
||||
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
|
||||
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
|
||||
}
|
||||
|
||||
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
|
||||
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod document;
|
||||
pub mod history;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod session;
|
||||
@@ -25,6 +26,7 @@ pub use document::*;
|
||||
pub use history::History;
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
use crate::{
|
||||
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
|
||||
Tombstone,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// What a slot held before a delta wrote it, stamps included. Undo puts it back bypassing LWW, so the registry is again
|
||||
/// the fold of history up to the delta's parent. Never sent or applied as an op.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Prior {
|
||||
/// The whole entity, live, tombstoned, or absent. Restoring an absent one leaves no tombstone, so undoing an addition erases it.
|
||||
Node {
|
||||
id: NodeId,
|
||||
node: Node,
|
||||
},
|
||||
RemovedNode {
|
||||
id: NodeId,
|
||||
tombstone: Tombstone<Node>,
|
||||
},
|
||||
AbsentNode {
|
||||
id: NodeId,
|
||||
},
|
||||
Network {
|
||||
id: NetworkId,
|
||||
network: Network,
|
||||
},
|
||||
RemovedNetwork {
|
||||
id: NetworkId,
|
||||
tombstone: Tombstone<Network>,
|
||||
},
|
||||
AbsentNetwork {
|
||||
id: NetworkId,
|
||||
},
|
||||
Resource {
|
||||
id: ResourceId,
|
||||
resource: ResourceEntry,
|
||||
},
|
||||
RemovedResource {
|
||||
id: ResourceId,
|
||||
tombstone: Tombstone<ResourceEntry>,
|
||||
},
|
||||
AbsentResource {
|
||||
id: ResourceId,
|
||||
},
|
||||
/// One field of a live node, and the node's presence, which every write moves.
|
||||
NodeField {
|
||||
id: NodeId,
|
||||
presence: TimeStamp,
|
||||
field: NodeField,
|
||||
},
|
||||
/// One field of a live network, and its presence.
|
||||
NetworkField {
|
||||
id: NetworkId,
|
||||
presence: TimeStamp,
|
||||
field: NetworkField,
|
||||
},
|
||||
DocumentAttribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
PeerUser {
|
||||
peer: PeerId,
|
||||
previous: Option<PeerRegistration>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NodeField {
|
||||
/// Only the presence moved, by a reference from another entity's op.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Input {
|
||||
index: u32,
|
||||
previous: InputSlot,
|
||||
},
|
||||
InputAttribute {
|
||||
index: u32,
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Inputs {
|
||||
previous: Vec<InputSlot>,
|
||||
inputs_timestamp: TimeStamp,
|
||||
},
|
||||
Implementation {
|
||||
previous: Implementation,
|
||||
implementation_timestamp: TimeStamp,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NetworkField {
|
||||
/// Only the presence moved, by a node added to or implemented by it.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Exports {
|
||||
previous: Vec<ExportSlot>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
|
||||
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
|
||||
let mut priors = Vec::new();
|
||||
let node_input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
|
||||
priors.push(whole_node(registry, *id));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
}));
|
||||
priors.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.filter_map(|slot| node_input(&slot.input))
|
||||
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
|
||||
);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::Input {
|
||||
index: *index,
|
||||
previous: slot.clone(),
|
||||
})
|
||||
}));
|
||||
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let Implementation::Network(network) = implementation {
|
||||
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
|
||||
}
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
|
||||
previous: node.implementation.clone(),
|
||||
implementation_timestamp: node.implementation_timestamp,
|
||||
}));
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: node.attributes.get(&delta.key).cloned(),
|
||||
})),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::InputAttribute {
|
||||
index: *index,
|
||||
key: delta.key.clone(),
|
||||
previous: slot.attributes.get(&delta.key).cloned(),
|
||||
})
|
||||
})),
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
|
||||
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: network.attributes.get(&delta.key).cloned(),
|
||||
}));
|
||||
}
|
||||
RegistryDelta::AddResource { id, .. }
|
||||
| RegistryDelta::RemoveResource { id, .. }
|
||||
| RegistryDelta::SetResourceHash { id, .. }
|
||||
| RegistryDelta::AddSource { id, .. }
|
||||
| RegistryDelta::RemoveSource { id, .. } => priors.push(whole_resource(registry, *id)),
|
||||
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
|
||||
peer: *peer,
|
||||
previous: registry.peer_users.get(peer).copied(),
|
||||
}),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
|
||||
key: delta.key.clone(),
|
||||
previous: registry.attributes.get(&delta.key).cloned(),
|
||||
}),
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
priors
|
||||
}
|
||||
|
||||
/// Puts back what `priors` recorded, newest write first.
|
||||
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
|
||||
for prior in priors.iter().rev() {
|
||||
match prior {
|
||||
Prior::Node { id, node } => put_live(&mut registry.node_instances, &mut registry.removed_nodes, *id, node),
|
||||
Prior::RemovedNode { id, tombstone } => put_removed(&mut registry.node_instances, &mut registry.removed_nodes, *id, tombstone),
|
||||
Prior::AbsentNode { id } => put_absent(&mut registry.node_instances, &mut registry.removed_nodes, *id),
|
||||
Prior::Network { id, network } => put_live(&mut registry.networks, &mut registry.removed_networks, *id, network),
|
||||
Prior::RemovedNetwork { id, tombstone } => put_removed(&mut registry.networks, &mut registry.removed_networks, *id, tombstone),
|
||||
Prior::AbsentNetwork { id } => put_absent(&mut registry.networks, &mut registry.removed_networks, *id),
|
||||
Prior::Resource { id, resource } => put_live(&mut registry.resources, &mut registry.removed_resources, *id, resource),
|
||||
Prior::RemovedResource { id, tombstone } => put_removed(&mut registry.resources, &mut registry.removed_resources, *id, tombstone),
|
||||
Prior::AbsentResource { id } => put_absent(&mut registry.resources, &mut registry.removed_resources, *id),
|
||||
Prior::NodeField { id, presence, field } => {
|
||||
let Some(node) = registry.node_instances.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
node.presence = *presence;
|
||||
match field {
|
||||
NodeField::Presence => {}
|
||||
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
|
||||
NodeField::Input { index, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
*slot = previous.clone();
|
||||
}
|
||||
}
|
||||
NodeField::InputAttribute { index, key, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
put_attribute(&mut slot.attributes, key, previous.as_ref());
|
||||
}
|
||||
}
|
||||
NodeField::Inputs { previous, inputs_timestamp } => {
|
||||
node.inputs = previous.clone();
|
||||
node.inputs_timestamp = *inputs_timestamp;
|
||||
}
|
||||
NodeField::Implementation { previous, implementation_timestamp } => {
|
||||
node.implementation = previous.clone();
|
||||
node.implementation_timestamp = *implementation_timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
Prior::NetworkField { id, presence, field } => {
|
||||
let Some(network) = registry.networks.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
network.presence = *presence;
|
||||
match field {
|
||||
NetworkField::Presence => {}
|
||||
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
|
||||
NetworkField::Exports { previous } => network.exports = previous.clone(),
|
||||
}
|
||||
}
|
||||
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
|
||||
Prior::PeerUser { peer, previous } => match previous {
|
||||
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
|
||||
None => _ = registry.peer_users.remove(peer),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
|
||||
if let Some(node) = registry.node_instances.get(&id) {
|
||||
Prior::Node { id, node: node.clone() }
|
||||
} else if let Some(tombstone) = registry.removed_nodes.get(&id) {
|
||||
Prior::RemovedNode { id, tombstone: tombstone.clone() }
|
||||
} else {
|
||||
Prior::AbsentNode { id }
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
|
||||
if let Some(network) = registry.networks.get(&id) {
|
||||
Prior::Network { id, network: network.clone() }
|
||||
} else if let Some(tombstone) = registry.removed_networks.get(&id) {
|
||||
Prior::RemovedNetwork { id, tombstone: tombstone.clone() }
|
||||
} else {
|
||||
Prior::AbsentNetwork { id }
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_resource(registry: &Registry, id: ResourceId) -> Prior {
|
||||
if let Some(resource) = registry.resources.get(&id) {
|
||||
Prior::Resource { id, resource: resource.clone() }
|
||||
} else if let Some(tombstone) = registry.removed_resources.get(&id) {
|
||||
Prior::RemovedResource { id, tombstone: tombstone.clone() }
|
||||
} else {
|
||||
Prior::AbsentResource { id }
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a live node; a write landing on a tombstone or placeholder records the whole entity instead.
|
||||
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
|
||||
match registry.node_instances.get(&id) {
|
||||
Some(node) => Prior::NodeField {
|
||||
id,
|
||||
presence: node.presence,
|
||||
field: field(node),
|
||||
},
|
||||
None => whole_node(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
|
||||
match registry.networks.get(&id) {
|
||||
Some(network) => Prior::NetworkField {
|
||||
id,
|
||||
presence: network.presence,
|
||||
field: field(network),
|
||||
},
|
||||
None => whole_network(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
|
||||
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
|
||||
match node.inputs.get(index as usize) {
|
||||
Some(slot) => field(slot),
|
||||
None => NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn put_live<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: &T) {
|
||||
dead.remove(&id);
|
||||
live.insert(id, content.clone());
|
||||
}
|
||||
|
||||
fn put_removed<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, tombstone: &Tombstone<T>) {
|
||||
live.remove(&id);
|
||||
dead.insert(id, tombstone.clone());
|
||||
}
|
||||
|
||||
fn put_absent<K: Hash + Eq + Copy, T>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
||||
live.remove(&id);
|
||||
dead.remove(&id);
|
||||
}
|
||||
|
||||
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
|
||||
match previous {
|
||||
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
|
||||
None => _ = attributes.remove(key),
|
||||
}
|
||||
}
|
||||
@@ -44,11 +44,13 @@ pub struct Tombstone<T> {
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The network under `id`, live or as it was when removed.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ impl ResourceEntry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(key, value);
|
||||
}
|
||||
@@ -187,17 +187,6 @@ impl ResourceEntry {
|
||||
true
|
||||
}
|
||||
|
||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
|
||||
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
|
||||
pub fn has_embedded_source(&self) -> bool {
|
||||
|
||||
@@ -3,7 +3,8 @@ use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{
|
||||
ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value,
|
||||
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value,
|
||||
to_value,
|
||||
};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -146,15 +147,19 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
|
||||
}
|
||||
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
|
||||
pending.insert(0, (RegistryDelta::RegisterPeer { peer, user }, Attributes::new()));
|
||||
}
|
||||
|
||||
// A reused sequence would fall under the retired marks, so a batch running past the end is refused.
|
||||
@@ -164,12 +169,13 @@ impl Session {
|
||||
|
||||
let sequence_before = self.document.last_hot_sequence;
|
||||
let mut staged = Vec::with_capacity(pending.len());
|
||||
for op in pending {
|
||||
for (op, attributes) in pending {
|
||||
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
|
||||
let hot_op = HotOp {
|
||||
op,
|
||||
timestamp: self.document.clock.tick(),
|
||||
sequence,
|
||||
attributes,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
@@ -214,7 +220,7 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let parent = self.document.head;
|
||||
let author = timestamp.peer;
|
||||
@@ -344,6 +350,60 @@ impl Session {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a
|
||||
/// re-registration possibly before the marker; empty when nothing is open.
|
||||
pub fn end_interaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let peer = self.document.peer;
|
||||
let open = self
|
||||
.document
|
||||
.hot_log
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|hot_op| hot_op.timestamp.peer == peer)
|
||||
.is_some_and(|hot_op| !hot_op.ends_interaction());
|
||||
if !open {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)])
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
pub fn closed_interactions(&self) -> Vec<ClosedInteraction> {
|
||||
let mut by_author: HashMap<PeerId, Vec<&HotOp>> = HashMap::new();
|
||||
for hot_op in &self.document.hot_log {
|
||||
by_author.entry(hot_op.timestamp.peer).or_default().push(hot_op);
|
||||
}
|
||||
|
||||
let mut closed = Vec::new();
|
||||
for (author, mut ops) in by_author {
|
||||
ops.sort_by_key(|hot_op| hot_op.sequence);
|
||||
let mut expected = self.document.retired.retired_up_to.get(&author).copied().unwrap_or(HotSequence::NONE).next();
|
||||
let mut current = Vec::new();
|
||||
let mut contiguous = true;
|
||||
for hot_op in ops {
|
||||
// Retired past a gap: not in the log, but not missing either.
|
||||
while expected < hot_op.sequence && self.document.retired.covers(HotOpId { peer: author, sequence: expected }) {
|
||||
expected = expected.next();
|
||||
}
|
||||
contiguous &= hot_op.sequence == expected;
|
||||
expected = hot_op.sequence.next();
|
||||
current.push(hot_op.id());
|
||||
if hot_op.ends_interaction() {
|
||||
closed.push(ClosedInteraction {
|
||||
author,
|
||||
ops: std::mem::take(&mut current),
|
||||
closed_at: hot_op.timestamp,
|
||||
contiguous,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
closed.sort_by_key(|interaction| interaction.closed_at);
|
||||
closed
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
|
||||
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()
|
||||
@@ -351,7 +411,7 @@ impl Session {
|
||||
|
||||
/// Promote the given hot ops into retired deltas in hot-log order, each keeping its authored stamp.
|
||||
///
|
||||
/// One retired delta per hot op.
|
||||
/// One retired delta per hot op, except a `Meta` op, which commits nothing.
|
||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
|
||||
@@ -359,7 +419,10 @@ impl Session {
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.retired.extend(drained.iter().map(HotOp::id));
|
||||
|
||||
let ops = drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
let ops = drained
|
||||
.into_iter()
|
||||
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta))
|
||||
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
|
||||
@@ -383,33 +446,29 @@ impl Session {
|
||||
self.document.history.annotate(rev, key, value, timestamp)
|
||||
}
|
||||
|
||||
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
|
||||
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
|
||||
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
|
||||
///
|
||||
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
|
||||
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
|
||||
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
|
||||
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
|
||||
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
|
||||
/// Whether the interaction at `head` undoes silently: this user's own, no merge, nothing a peer holds. The document's
|
||||
/// first interaction is not undoable, as opening a document starts with an empty undo history.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
let Some(head) = self.document.head else { return false };
|
||||
if self.document.last_broadcast_rev == Some(head) {
|
||||
return false;
|
||||
}
|
||||
self.interaction_start_parent(head).is_some()
|
||||
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
|
||||
}
|
||||
|
||||
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
|
||||
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
|
||||
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
|
||||
/// stop when the parent is an `interaction_end` boundary or the root.
|
||||
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
|
||||
let mut current = rev;
|
||||
/// Where the cursor rests once the interaction ending at `end` is undone: the previous interaction's end, a merge, or
|
||||
/// another user's delta. `None` for a merge, the first interaction, and for a `silent` undo of another's or a published one.
|
||||
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
|
||||
let history = &self.document.history;
|
||||
let mut current = history.get(end)?;
|
||||
let user = self.user_of(current.author);
|
||||
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
|
||||
return None;
|
||||
}
|
||||
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
|
||||
loop {
|
||||
let parent = self.document.history.get(current)?.parent?;
|
||||
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
|
||||
return Some(parent);
|
||||
if silent && self.document.last_broadcast_rev == Some(current.id) {
|
||||
return None;
|
||||
}
|
||||
let parent = history.get(current.parent?)?;
|
||||
if boundary(parent) {
|
||||
return Some(parent.id);
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -419,37 +478,22 @@ impl Session {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
|
||||
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
|
||||
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
|
||||
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
|
||||
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
|
||||
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
|
||||
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
if !self.can_undo() {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
|
||||
// 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.
|
||||
loop {
|
||||
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
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.head = parent;
|
||||
|
||||
match parent {
|
||||
None => break,
|
||||
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
|
||||
Some(_) => {}
|
||||
}
|
||||
self.document.revert_delta(&delta);
|
||||
self.document.head = delta.parent;
|
||||
}
|
||||
|
||||
// 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();
|
||||
// With ops hot, working is the rewound snapshot plus them.
|
||||
if !self.document.hot_log.is_empty() {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -469,15 +513,19 @@ impl Session {
|
||||
forward.push(delta);
|
||||
}
|
||||
|
||||
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
|
||||
// at the same timestamp. Symmetric with `revert_delta`.
|
||||
// The snapshot is the fold up to `head`, so applying the deltas as retirement did folds them in again.
|
||||
let hot = !self.document.hot_log.is_empty();
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
if !hot {
|
||||
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
}
|
||||
if hot {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -642,9 +690,16 @@ pub struct HotOp {
|
||||
pub timestamp: TimeStamp,
|
||||
/// Position in its author's run. See [`HotSequence`].
|
||||
pub sequence: HotSequence,
|
||||
/// Shared with every peer, unlike `Delta::attributes`. Dropped at retirement.
|
||||
#[serde(default)]
|
||||
pub attributes: Attributes,
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
pub fn ends_interaction(&self) -> bool {
|
||||
self.attributes.get_or(crate::attr::delta::INTERACTION_END, false)
|
||||
}
|
||||
|
||||
/// Identifies the op in the retired marks, which track a contiguous prefix per author.
|
||||
pub fn id(&self) -> HotOpId {
|
||||
HotOpId {
|
||||
@@ -654,6 +709,17 @@ impl HotOp {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ClosedInteraction {
|
||||
pub author: PeerId,
|
||||
/// In the author's order, the marker last.
|
||||
pub ops: Vec<HotOpId>,
|
||||
/// The marker's stamp.
|
||||
pub closed_at: TimeStamp,
|
||||
/// No gap in the author's sequence since its retired frontier.
|
||||
pub contiguous: bool,
|
||||
}
|
||||
|
||||
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
|
||||
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
|
||||
|
||||
@@ -25,6 +25,7 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
|
||||
host.replay_hot_op(late.clone()).expect("the late-stamped op lands first");
|
||||
@@ -83,6 +84,7 @@ fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.replay_hot_op(op.clone()).unwrap();
|
||||
@@ -165,6 +167,7 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 50, peer: PeerId(1) },
|
||||
sequence: crate::HotSequence(7),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut marks = crate::RetiredMarks::default();
|
||||
marks.extend([own.id()]);
|
||||
@@ -176,3 +179,88 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
assert!(next.sequence > own.sequence, "a fresh sequence");
|
||||
assert!(next.timestamp > own.timestamp, "a later stamp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closed_interactions_are_listed_and_the_marker_commits_nothing() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
assert!(host.end_interaction().expect("nothing to close").is_empty(), "no op of this peer is open");
|
||||
|
||||
// The guest's open interaction is stamped before everything the host does.
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
|
||||
|
||||
host.stage_ops([set_attribute("host", 1)]).expect("host op");
|
||||
let marker = host.end_interaction().expect("close").pop().expect("the host's interaction was open");
|
||||
assert!(matches!(marker.op, RegistryDelta::Meta) && marker.ends_interaction());
|
||||
assert!(host.end_interaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1, "the guest's open interaction is not listed: {closed:?}");
|
||||
assert_eq!(closed[0].author, PeerId(1));
|
||||
assert!(closed[0].contiguous);
|
||||
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
|
||||
|
||||
let revs = host.retire_hot_ops(&closed[0].ops).expect("retire");
|
||||
assert_eq!(revs.len(), 2, "the marker commits no delta");
|
||||
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
|
||||
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].author, PeerId(2));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker, op 2 still in flight");
|
||||
host.replay_hot_op(closing(guest_op(13, 4, set_attribute("guest", 2)))).expect("a later interaction");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 2);
|
||||
assert!(!closed[0].contiguous);
|
||||
assert!(!closed[1].contiguous, "the gap is behind the later interaction too");
|
||||
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
|
||||
let closed = host.closed_interactions();
|
||||
assert!(closed.iter().all(|interaction| interaction.contiguous));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flagged_write_closes_its_interaction() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
assert!(host.closed_interactions().is_empty(), "the interaction is open");
|
||||
|
||||
host.replay_hot_op(closing(guest_op(11, 2, set_attribute("guest", 1)))).expect("flagged write");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].ops.len(), 2, "both writes, and no marker of its own");
|
||||
}
|
||||
|
||||
fn closing(mut hot_op: crate::HotOp) -> crate::HotOp {
|
||||
hot_op.attributes.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), crate::TimeStamp::ORIGIN);
|
||||
hot_op
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use graph_craft::concrete;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::InputSlot;
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, RegistryTarget, Session, TimeStamp, Value};
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, Session, TimeStamp, Value};
|
||||
|
||||
fn fresh_document(peer: PeerId) -> Document {
|
||||
Session::with_peer(peer).document
|
||||
@@ -20,7 +20,7 @@ fn remove_node_op(node_id: NodeId) -> RegistryDelta {
|
||||
/// Commit a single op to a document as a retired delta. Mints a fresh timestamp, links to
|
||||
/// current head, applies, records in history, advances head.
|
||||
fn commit_op(document: &mut Document, op: RegistryDelta) {
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &op).expect("compute_reverse_delta failed");
|
||||
let reverse = crate::prior::capture(&document.working_registry, &op);
|
||||
let timestamp = document.clock.tick();
|
||||
let delta = Delta::new(document.head, document.peer, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -41,6 +41,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
op: remove_node_op(NodeId(99)),
|
||||
timestamp: observed,
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
document
|
||||
@@ -420,6 +421,11 @@ fn source_key(priority: f64, peer: u64) -> SourceKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone.
|
||||
fn holds(attributes: &crate::Attributes, key: &str) -> bool {
|
||||
attributes.live().any(|(held, _)| held == key)
|
||||
}
|
||||
|
||||
fn ts(counter: u64, peer: u64) -> TimeStamp {
|
||||
TimeStamp { counter, peer: PeerId(peer) }
|
||||
}
|
||||
@@ -519,85 +525,146 @@ fn register_resource_hash_is_last_writer_wins() {
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().hash, Some(hash_b), "later resolve wins");
|
||||
}
|
||||
|
||||
/// The reverse delta of a RemoveSource restores the prior source body, and applying op-then-reverse
|
||||
/// round-trips the source chain.
|
||||
/// For every kind of op, landing on a live entity, a removed one or one never seen.
|
||||
#[test]
|
||||
fn remove_source_reverse_restores_prior() {
|
||||
fn restoring_what_an_op_overwrote_gives_back_the_registry_exactly() {
|
||||
use crate::{AttributeDelta, Implementation, Network, NodeInput, ROOT_NETWORK};
|
||||
let attribute = |key: &str, value: i64| AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::Int(value.into())),
|
||||
};
|
||||
let reference = |id: u64| NodeInput::Node { id: NodeId(id), index: 0 };
|
||||
let (live, removed, unseen, network, resource) = (NodeId(1), NodeId(2), NodeId(3), NetworkId(7), ResourceId::new());
|
||||
let node = || Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 2);
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
commit_op(
|
||||
&mut document,
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
);
|
||||
|
||||
// Compute the reverse while the body is still present, then apply the removal.
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &RD::RemoveSource { id, key }).unwrap();
|
||||
match &reverse {
|
||||
RD::AddSource { source, .. } => assert_eq!(*source, Value::Str("kept".into()), "reverse of removal re-adds the body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
for (op, at) in [
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: network,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(RD::AddNode { id: live, node: node() }, 2),
|
||||
(RD::AddNode { id: removed, node: node() }, 2),
|
||||
(RD::RemoveNode { id: removed, snapshot: node() }, 3),
|
||||
(
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 1),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(RD::ChangeDocumentAttribute { delta: attribute("kept", 1) }, 4),
|
||||
(
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 0,
|
||||
export: Some(reference(1)),
|
||||
},
|
||||
4,
|
||||
),
|
||||
] {
|
||||
document.apply_op_idempotent(op, ts(at, 2)).unwrap();
|
||||
}
|
||||
|
||||
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
||||
assert!(
|
||||
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
|
||||
"source removed, a tombstone left"
|
||||
);
|
||||
|
||||
// Applying the reverse restores the chain.
|
||||
document.apply_op(reverse, ts(6, 1)).unwrap();
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().source(&key).unwrap().source, Value::Str("kept".into()));
|
||||
}
|
||||
|
||||
/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body.
|
||||
#[test]
|
||||
fn add_source_reverse_depends_on_prior_state() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
// Fresh slot: reverse removes.
|
||||
let reverse_fresh = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("first".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(reverse_fresh, RD::RemoveSource { .. }), "reverse of add-to-empty is remove, got {reverse_fresh:?}");
|
||||
|
||||
// Occupy the slot, then reverse of a new add restores the existing body.
|
||||
document
|
||||
.apply_op(
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("existing".into()),
|
||||
},
|
||||
ts(1, 1),
|
||||
)
|
||||
.unwrap();
|
||||
let reverse_overwrite = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("overwrite".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match reverse_overwrite {
|
||||
RD::AddSource { source, .. } => assert_eq!(source, Value::Str("existing".into()), "reverse restores prior body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
let ops = [
|
||||
RD::AddNode { id: live, node: node() },
|
||||
RD::AddNode { id: unseen, node: node() },
|
||||
RD::RemoveNode { id: live, snapshot: node() },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute { id: live, delta: attribute("new", 2) },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: removed,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute {
|
||||
id: unseen,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 1,
|
||||
new_input: reference(2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 5,
|
||||
new_input: reference(3),
|
||||
},
|
||||
RD::ChangeNodeInputAttribute {
|
||||
id: live,
|
||||
index: 0,
|
||||
delta: attribute("name", 2),
|
||||
},
|
||||
RD::SetNodeInputs {
|
||||
id: live,
|
||||
inputs: vec![crate::InputSlot::unset(TimeStamp::ORIGIN); 3],
|
||||
},
|
||||
RD::SetNodeImplementation {
|
||||
id: live,
|
||||
implementation: Implementation::Network(NetworkId(8)),
|
||||
},
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 3,
|
||||
export: Some(reference(3)),
|
||||
},
|
||||
RD::ChangeNetworkAttribute {
|
||||
id: network,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::RemoveNetwork {
|
||||
id: network,
|
||||
snapshot: Network::default(),
|
||||
},
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("new".into()),
|
||||
},
|
||||
RD::RemoveSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
},
|
||||
RD::SetResourceHash { id: ResourceId::new(), hash: None },
|
||||
RD::RemoveResource {
|
||||
id: resource,
|
||||
snapshot: Default::default(),
|
||||
},
|
||||
RD::ChangeDocumentAttribute { delta: attribute("kept", 2) },
|
||||
RD::RegisterPeer {
|
||||
peer: PeerId(5),
|
||||
user: crate::UserId(5),
|
||||
},
|
||||
];
|
||||
for op in ops {
|
||||
let before = document.working_registry.clone();
|
||||
let priors = crate::prior::capture(&before, &op);
|
||||
let mut after = document.clone();
|
||||
after.apply_op_idempotent(op.clone(), ts(10, 2)).unwrap();
|
||||
assert_ne!(after.working_registry, before, "{op:?} should change something for this to check anything");
|
||||
crate::prior::restore(&mut after.working_registry, &priors);
|
||||
assert_eq!(after.working_registry, before, "restoring {op:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -867,10 +934,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
let delta_reversed = Delta::new(
|
||||
parent,
|
||||
@@ -880,15 +944,22 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
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 `commit_op_for_test` leaves alone.
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
let network = Network::default();
|
||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
||||
@@ -908,6 +979,7 @@ fn hot_op(op: RegistryDelta, counter: u64, peer: u64, sequence: u64) -> HotOp {
|
||||
op,
|
||||
timestamp: ts(counter, peer),
|
||||
sequence,
|
||||
attributes: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -964,6 +1036,31 @@ fn retiring_over_a_gap_lands_beyond_the_prefix() {
|
||||
assert!(marks.covers(second.id()));
|
||||
}
|
||||
|
||||
/// Undo and redo never promote the hot tail, a fold skips undone deltas, and a published commit is not rewound.
|
||||
#[test]
|
||||
fn undo_and_redo_move_only_unpublished_retired_history() {
|
||||
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");
|
||||
|
||||
let mut published = session.clone();
|
||||
published.publish_up_to(published.head_rev().expect("a head"));
|
||||
assert!(session.can_undo() && !published.can_undo());
|
||||
|
||||
let retired = |session: &Session, key| holds(&session.retired_registry().attributes, key);
|
||||
session.undo().expect("undo");
|
||||
assert!(!retired(&session, "second") && !retired(&session, "hot"));
|
||||
let folded = session.snapshot_from_history().expect("fold");
|
||||
assert!(holds(&folded.attributes, "first") && !holds(&folded.attributes, "second"));
|
||||
|
||||
session.redo().expect("redo");
|
||||
assert!(retired(&session, "second") && !retired(&session, "hot"));
|
||||
assert!(holds(&session.registry().attributes, "hot"));
|
||||
}
|
||||
|
||||
/// So the snapshot and a replay keep the LWW winner the live view did, whether the straggler retires with it or after.
|
||||
#[test]
|
||||
fn retirement_preserves_the_live_lww_winner() {
|
||||
@@ -985,7 +1082,7 @@ fn retirement_preserves_the_live_lww_winner() {
|
||||
}
|
||||
|
||||
/// Random ops over a few colliding ids fold to one registry in any order. Removal snapshots are constant or, as a remover
|
||||
/// sends them, a fold of some earlier ops.
|
||||
/// sends them, a fold of some earlier ops; restoring each op's priors gives back the registry it applied to.
|
||||
#[test]
|
||||
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
|
||||
@@ -999,11 +1096,17 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the ops in order.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
|
||||
/// Folds the ops in order; `check_restore` also checks each op's priors restore the registry it applied to.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)], check_restore: bool) -> crate::Registry {
|
||||
let mut document = fresh_document(PeerId(9));
|
||||
for (op, at) in ops {
|
||||
let before = check_restore.then(|| (document.working_registry.clone(), crate::prior::capture(&document.working_registry, op)));
|
||||
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
|
||||
if let Some((registry, priors)) = before {
|
||||
let mut restored = document.working_registry.clone();
|
||||
crate::prior::restore(&mut restored, &priors);
|
||||
assert_eq!(restored, registry, "restoring what {op:?} overwrote");
|
||||
}
|
||||
}
|
||||
document.working_registry
|
||||
}
|
||||
@@ -1033,7 +1136,7 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
};
|
||||
// What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value,
|
||||
// which a fabricated snapshot only does by being constant.
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>());
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>(), false);
|
||||
match rng.below(22) {
|
||||
0 => {
|
||||
// An export list of its own, so additions of different lengths meet.
|
||||
@@ -1181,14 +1284,18 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
ops.push((op, at));
|
||||
}
|
||||
|
||||
let reference = fold(&ops);
|
||||
let reference = fold(&ops, true);
|
||||
for _ in 0..6 {
|
||||
let mut shuffled = ops.clone();
|
||||
for i in (1..shuffled.len()).rev() {
|
||||
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
|
||||
}
|
||||
let order: Vec<u64> = shuffled.iter().map(|(_, at)| at.counter).collect();
|
||||
assert_eq!(fold(&shuffled), reference, "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}");
|
||||
assert_eq!(
|
||||
fold(&shuffled, false),
|
||||
reference,
|
||||
"seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
@@ -244,11 +243,6 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies {
|
||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
@@ -258,7 +252,6 @@ fn test_metadata_preservation() {
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||
call_argument: concrete!(String),
|
||||
context_features,
|
||||
visible: false, // Non-default value
|
||||
skip_deduplication: true, // Non-default value
|
||||
..Default::default()
|
||||
@@ -292,9 +285,6 @@ fn test_metadata_preservation() {
|
||||
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
||||
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
||||
|
||||
// Verify context_features is preserved
|
||||
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
|
||||
|
||||
// Verify visible is preserved
|
||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||
|
||||
@@ -353,11 +343,6 @@ fn test_demo_artwork_round_trip() {
|
||||
"{}: call_argument should be preserved for node {:?}",
|
||||
artwork_name, node_id
|
||||
);
|
||||
assert_eq!(
|
||||
orig_node.context_features, conv_node.context_features,
|
||||
"{}: context_features should be preserved for node {:?}",
|
||||
artwork_name, node_id
|
||||
);
|
||||
assert_eq!(orig_node.visible, conv_node.visible, "{}: visible should be preserved for node {:?}", artwork_name, node_id);
|
||||
assert_eq!(
|
||||
orig_node.skip_deduplication, conv_node.skip_deduplication,
|
||||
|
||||
@@ -334,8 +334,8 @@ fn convert_node(
|
||||
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_dependencies: None,
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ once_cell = { workspace = true }
|
||||
web-sys = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
spin = { workspace = true }
|
||||
image = { workspace = true }
|
||||
color = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
@@ -69,9 +68,6 @@ wasm-bindgen = { workspace = true, optional = true }
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
tokio = { workspace = true }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
env_logger = { workspace = true }
|
||||
|
||||
+24
-59
@@ -1,76 +1,17 @@
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
pub use graphene_std::uuid::*;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
pub struct Editor {
|
||||
pub dispatcher: Dispatcher,
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
pub fn new(
|
||||
environment: Environment,
|
||||
uuid_random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
||||
mut application_io: PlatformApplicationIo,
|
||||
wake: Wake,
|
||||
) -> Self {
|
||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||
|
||||
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
|
||||
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
crate::node_graph_executor::replace_application_io(application_io);
|
||||
|
||||
Self { dispatcher }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_local_executor() -> (Self, crate::node_graph_executor::NodeRuntime) {
|
||||
let _ = ENVIRONMENT.set(*Editor::environment());
|
||||
graphene_std::uuid::set_uuid_seed(0);
|
||||
|
||||
let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime();
|
||||
let editor = Self {
|
||||
dispatcher: Dispatcher::with_executor(executor),
|
||||
};
|
||||
|
||||
let mut application_io = PlatformApplicationIo::default();
|
||||
application_io.inject_resource_proxy(editor.dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
runtime.replace_application_io(application_io);
|
||||
|
||||
(editor, runtime)
|
||||
}
|
||||
|
||||
pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Vec<FrontendMessage> {
|
||||
self.dispatcher.handle_message(message, true);
|
||||
|
||||
std::mem::take(&mut self.dispatcher.responses)
|
||||
}
|
||||
|
||||
pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
self.dispatcher.poll_node_graph_evaluation(responses)
|
||||
}
|
||||
}
|
||||
|
||||
static ENVIRONMENT: OnceLock<Environment> = OnceLock::new();
|
||||
impl Editor {
|
||||
#[cfg(not(test))]
|
||||
pub fn environment() -> &'static Environment {
|
||||
ENVIRONMENT.get().expect("Editor environment accessed before initialization")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn environment() -> &'static Environment {
|
||||
&Environment {
|
||||
platform: Platform::Desktop,
|
||||
host: Host::Linux,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -78,6 +19,11 @@ pub struct Environment {
|
||||
pub platform: Platform,
|
||||
pub host: Host,
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) const DEFAULT_ENVIRONMENT: Environment = Environment {
|
||||
platform: Platform::Desktop,
|
||||
host: Host::Linux,
|
||||
};
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Platform {
|
||||
Desktop,
|
||||
@@ -107,6 +53,25 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EnvironmentDisplay {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter, environment: Environment) -> std::fmt::Result;
|
||||
|
||||
fn display(&self, environment: Environment) -> WithEnvironment<'_, Self> {
|
||||
WithEnvironment { value: self, environment }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WithEnvironment<'a, T: ?Sized> {
|
||||
value: &'a T,
|
||||
environment: Environment,
|
||||
}
|
||||
|
||||
impl<T: EnvironmentDisplay + ?Sized> std::fmt::Display for WithEnvironment<'_, T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
self.value.fmt(f, self.environment)
|
||||
}
|
||||
}
|
||||
|
||||
pub const GRAPHITE_RELEASE_SERIES: &str = env!("GRAPHITE_RELEASE_SERIES");
|
||||
pub const GRAPHITE_GIT_COMMIT_BRANCH: Option<&str> = option_env!("GRAPHITE_GIT_COMMIT_BRANCH");
|
||||
pub const GRAPHITE_GIT_COMMIT_HASH: &str = env!("GRAPHITE_GIT_COMMIT_HASH");
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
use crate::task::{Spawn, Spawner};
|
||||
use document_container::store::DocumentStore;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type ReadyEditorBuilder = EditorBuilder<Wake, Environment, Arc<dyn ResourceStorage>, Arc<dyn DocumentStore>>;
|
||||
pub type ReadyRuntimeBuilder = RuntimeBuilder<Wake, PlatformApplicationIo>;
|
||||
|
||||
pub struct Builder<E = (), R = (), S = (), N = ()> {
|
||||
editor: E,
|
||||
runtime: R,
|
||||
spawner: S,
|
||||
random_seed: N,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
editor: (),
|
||||
runtime: (),
|
||||
spawner: (),
|
||||
random_seed: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Builder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, S, N> Builder<(), R, S, N> {
|
||||
pub fn with_editor(self, editor: ReadyEditorBuilder) -> Builder<ReadyEditorBuilder, R, S, N> {
|
||||
Builder {
|
||||
editor,
|
||||
runtime: self.runtime,
|
||||
spawner: self.spawner,
|
||||
random_seed: self.random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, S, N> Builder<E, (), S, N> {
|
||||
pub fn with_runtime(self, runtime: ReadyRuntimeBuilder) -> Builder<E, ReadyRuntimeBuilder, S, N> {
|
||||
Builder {
|
||||
editor: self.editor,
|
||||
runtime,
|
||||
spawner: self.spawner,
|
||||
random_seed: self.random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R, N> Builder<E, R, (), N> {
|
||||
pub fn with_spawner(self, spawner: impl Spawn + Send + Sync + 'static) -> Builder<E, R, Spawner, N> {
|
||||
Builder {
|
||||
editor: self.editor,
|
||||
runtime: self.runtime,
|
||||
spawner: Arc::new(spawner),
|
||||
random_seed: self.random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R, S> Builder<E, R, S, ()> {
|
||||
pub fn with_random_seed(self, random_seed: u64) -> Builder<E, R, S, u64> {
|
||||
Builder {
|
||||
editor: self.editor,
|
||||
runtime: self.runtime,
|
||||
spawner: self.spawner,
|
||||
random_seed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
pub fn build(self) -> (Editor, NodeRuntime) {
|
||||
let Self {
|
||||
editor,
|
||||
runtime,
|
||||
spawner,
|
||||
random_seed,
|
||||
} = self;
|
||||
let EditorBuilder {
|
||||
wake: editor_wake,
|
||||
environment,
|
||||
resource_storage,
|
||||
document_store,
|
||||
} = editor;
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
|
||||
let (executor, mut node_runtime) = NodeGraphExecutor::new(editor_wake.clone());
|
||||
|
||||
let future_message_handler = FutureMessageHandler::new(spawner.clone(), editor_wake);
|
||||
let dispatcher = Dispatcher::new(environment, resource_storage, document_store, executor, future_message_handler);
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EditorBuilder<W = (), E = (), R = (), D = ()> {
|
||||
wake: W,
|
||||
environment: E,
|
||||
resource_storage: R,
|
||||
document_store: D,
|
||||
}
|
||||
|
||||
impl EditorBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
wake: (),
|
||||
environment: (),
|
||||
resource_storage: (),
|
||||
document_store: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EditorBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R, D> EditorBuilder<(), E, R, D> {
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> EditorBuilder<Wake, E, R, D> {
|
||||
EditorBuilder {
|
||||
wake: Arc::new(wake),
|
||||
environment: self.environment,
|
||||
resource_storage: self.resource_storage,
|
||||
document_store: self.document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, R, D> EditorBuilder<W, (), R, D> {
|
||||
pub fn with_environment(self, environment: Environment) -> EditorBuilder<W, Environment, R, D> {
|
||||
EditorBuilder {
|
||||
wake: self.wake,
|
||||
environment,
|
||||
resource_storage: self.resource_storage,
|
||||
document_store: self.document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, E, D> EditorBuilder<W, E, (), D> {
|
||||
pub fn with_resource_storage(self, resource_storage: Arc<dyn ResourceStorage>) -> EditorBuilder<W, E, Arc<dyn ResourceStorage>, D> {
|
||||
EditorBuilder {
|
||||
wake: self.wake,
|
||||
environment: self.environment,
|
||||
resource_storage,
|
||||
document_store: self.document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
pub fn with_document_store(self, document_store: Arc<dyn DocumentStore>) -> EditorBuilder<W, E, R, Arc<dyn DocumentStore>> {
|
||||
EditorBuilder {
|
||||
wake: self.wake,
|
||||
environment: self.environment,
|
||||
resource_storage: self.resource_storage,
|
||||
document_store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RuntimeBuilder<W = (), A = ()> {
|
||||
wake: W,
|
||||
application_io: A,
|
||||
}
|
||||
|
||||
impl RuntimeBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self { wake: (), application_io: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<A> RuntimeBuilder<(), A> {
|
||||
/// Called from any thread when a graph task has completed, to run the runtime again as soon as possible.
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> RuntimeBuilder<Wake, A> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> RuntimeBuilder<W, ()> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
|
||||
RuntimeBuilder { wake: self.wake, application_io }
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ pub const STACK_VERTICAL_GAP: i32 = 3;
|
||||
pub const LAYER_INDENT_OFFSET: i32 = 8;
|
||||
/// Horizontal grid width of a non-layer node in a chain.
|
||||
pub const NODE_CHAIN_WIDTH: i32 = 7;
|
||||
/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance.
|
||||
pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
|
||||
|
||||
// VIEWPORT
|
||||
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
|
||||
@@ -134,11 +136,10 @@ pub const BRUSH_FLOW_DEFAULT: f64 = 100.;
|
||||
pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11;
|
||||
|
||||
// GIZMOS
|
||||
pub const POINT_RADIUS_HANDLE_SNAP_THRESHOLD: f64 = 8.;
|
||||
pub const SPIRAL_END_HOVER_RADIUS: f64 = 8.;
|
||||
pub const POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD: f64 = 7.9;
|
||||
pub const NUMBER_OF_POINTS_DIAL_SPOKE_EXTENSION: f64 = 1.2;
|
||||
pub const NUMBER_OF_POINTS_DIAL_SPOKE_LENGTH: f64 = 10.;
|
||||
pub const ARC_SNAP_THRESHOLD: f64 = 5.;
|
||||
pub const ARC_SWEEP_GIZMO_RADIUS: f64 = 14.;
|
||||
pub const ARC_SWEEP_GIZMO_TEXT_HEIGHT: f64 = 12.;
|
||||
pub const GIZMO_HIDE_THRESHOLD: f64 = 20.;
|
||||
@@ -178,6 +179,8 @@ pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
// INPUT
|
||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
/// How far, in viewport pixels, the second press of a double-click can land from the first, and how far the first can travel before its release.
|
||||
pub const DOUBLE_CLICK_ALLOWED_TRAVEL: f64 = 4.;
|
||||
/// Maximum duration of the whole double-tap gesture, measured from the first tap's key-down to the second tap's key-up.
|
||||
pub const DOUBLE_TAP_MILLISECONDS: u64 = 1000;
|
||||
|
||||
|
||||
+63
-43
@@ -1,3 +1,4 @@
|
||||
use crate::application::Environment;
|
||||
use crate::messages::debug::utility_types::MessageLoggingVerbosity;
|
||||
use crate::messages::defer::DeferMessageContext;
|
||||
use crate::messages::dialog::DialogMessageContext;
|
||||
@@ -7,18 +8,20 @@ use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Debug)]
|
||||
pub struct Dispatcher {
|
||||
environment: Environment,
|
||||
message_queues: Vec<VecDeque<Message>>,
|
||||
pub responses: Vec<FrontendMessage>,
|
||||
pub frontend_update_messages: Vec<Message>,
|
||||
pub message_handlers: DispatcherMessageHandlers,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Debug)]
|
||||
pub struct DispatcherMessageHandlers {
|
||||
animation_message_handler: AnimationMessageHandler,
|
||||
app_window_message_handler: AppWindowMessageHandler,
|
||||
@@ -42,17 +45,27 @@ pub struct DispatcherMessageHandlers {
|
||||
}
|
||||
|
||||
impl DispatcherMessageHandlers {
|
||||
pub fn with_resource_storage(resource_storage: Arc<dyn ResourceStorage>) -> Self {
|
||||
fn new(environment: Environment, executor: NodeGraphExecutor, document_store: Arc<dyn document_container::store::DocumentStore>, future_message_handler: FutureMessageHandler) -> Self {
|
||||
Self {
|
||||
resource_storage_message_handler: ResourceStorageMessageHandler::new(resource_storage),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
Self {
|
||||
portfolio_message_handler: PortfolioMessageHandler::with_executor(executor),
|
||||
..Self::default()
|
||||
animation_message_handler: Default::default(),
|
||||
app_window_message_handler: Default::default(),
|
||||
future_message_handler,
|
||||
broadcast_message_handler: Default::default(),
|
||||
clipboard_message_handler: Default::default(),
|
||||
color_picker_message_handler: Default::default(),
|
||||
debug_message_handler: Default::default(),
|
||||
defer_message_handler: Default::default(),
|
||||
dialog_message_handler: Default::default(),
|
||||
input_preprocessor_message_handler: Default::default(),
|
||||
key_mapping_message_handler: KeyMappingMessageHandler::new(environment),
|
||||
layout_message_handler: Default::default(),
|
||||
menu_bar_message_handler: Default::default(),
|
||||
network_message_handler: Default::default(),
|
||||
portfolio_message_handler: PortfolioMessageHandler::new(executor, document_store),
|
||||
preferences_message_handler: Default::default(),
|
||||
resource_storage_message_handler: Default::default(),
|
||||
tool_message_handler: Default::default(),
|
||||
viewport_message_handler: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +81,7 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
NodeGraphMessageDiscriminant::UpdateLayerPanel,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateVisibleNodes,
|
||||
))),
|
||||
@@ -102,20 +116,21 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
|
||||
let mut s = Self::default();
|
||||
pub fn new(
|
||||
environment: Environment,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn document_container::store::DocumentStore>,
|
||||
executor: NodeGraphExecutor,
|
||||
future_message_handler: FutureMessageHandler,
|
||||
) -> Self {
|
||||
let mut s = Self {
|
||||
environment,
|
||||
message_queues: Vec::new(),
|
||||
responses: Vec::new(),
|
||||
frontend_update_messages: Vec::new(),
|
||||
message_handlers: DispatcherMessageHandlers::new(environment, executor, document_store, future_message_handler),
|
||||
};
|
||||
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
||||
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
let mut s = Self::new(
|
||||
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
|
||||
Arc::new(document_container::store::MemoryStore::default()),
|
||||
);
|
||||
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
|
||||
s
|
||||
}
|
||||
|
||||
@@ -144,13 +159,6 @@ impl Dispatcher {
|
||||
pub fn handle_message<T: Into<Message>>(&mut self, message: T, process_after_all_current: bool) {
|
||||
let message = message.into();
|
||||
|
||||
// Drain async results into the queue before processing the new message.
|
||||
let mut async_results = VecDeque::new();
|
||||
self.message_handlers.future_message_handler.drain_results(&mut async_results);
|
||||
if !async_results.is_empty() {
|
||||
Self::schedule_execution(&mut self.message_queues, true, async_results);
|
||||
}
|
||||
|
||||
// If we are not maintaining the buffer, simply add to the current queue
|
||||
Self::schedule_execution(&mut self.message_queues, process_after_all_current, [message]);
|
||||
|
||||
@@ -201,7 +209,7 @@ impl Dispatcher {
|
||||
self.message_handlers.app_window_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::Future(message) => {
|
||||
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
|
||||
self.message_handlers.future_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::Clipboard(message) => {
|
||||
@@ -237,6 +245,7 @@ impl Dispatcher {
|
||||
message,
|
||||
&mut queue,
|
||||
InputPreprocessorMessageContext {
|
||||
environment: self.environment,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
},
|
||||
);
|
||||
@@ -245,13 +254,22 @@ impl Dispatcher {
|
||||
let input = &self.message_handlers.input_preprocessor_message_handler;
|
||||
let actions = self.collect_actions();
|
||||
|
||||
self.message_handlers
|
||||
.key_mapping_message_handler
|
||||
.process_message(message, &mut queue, KeyMappingMessageContext { input, actions });
|
||||
self.message_handlers.key_mapping_message_handler.process_message(
|
||||
message,
|
||||
&mut queue,
|
||||
KeyMappingMessageContext {
|
||||
environment: self.environment,
|
||||
input,
|
||||
actions,
|
||||
},
|
||||
);
|
||||
}
|
||||
Message::Layout(message) => {
|
||||
let action_input_mapping = &|action_to_find: &MessageDiscriminant| self.message_handlers.key_mapping_message_handler.action_input_mapping(action_to_find);
|
||||
let context = LayoutMessageContext { action_input_mapping };
|
||||
let action_input_mapping = &|action_to_find: &MessageDiscriminant| self.message_handlers.key_mapping_message_handler.action_input_mapping(action_to_find, self.environment);
|
||||
let context = LayoutMessageContext {
|
||||
environment: self.environment,
|
||||
action_input_mapping,
|
||||
};
|
||||
|
||||
self.message_handlers.layout_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
@@ -268,6 +286,7 @@ impl Dispatcher {
|
||||
message,
|
||||
&mut queue,
|
||||
PortfolioMessageContext {
|
||||
environment: self.environment,
|
||||
ipp: &self.message_handlers.input_preprocessor_message_handler,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
@@ -377,10 +396,15 @@ impl Dispatcher {
|
||||
Message::Viewport(message) => {
|
||||
self.message_handlers.viewport_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::NoOp => {}
|
||||
// Messages
|
||||
Message::Wake => {
|
||||
queue.add(PortfolioMessage::PollNodeGraphEvaluation);
|
||||
queue.add(FutureMessage::Drain);
|
||||
}
|
||||
Message::Batched { messages } => {
|
||||
messages.into_iter().for_each(|message| self.handle_message(message, false));
|
||||
}
|
||||
Message::NoOp => {}
|
||||
}
|
||||
|
||||
// If there are child messages, append the queue to the list of queues
|
||||
@@ -411,10 +435,6 @@ impl Dispatcher {
|
||||
list
|
||||
}
|
||||
|
||||
pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
self.message_handlers.portfolio_message_handler.poll_node_graph_evaluation(responses)
|
||||
}
|
||||
|
||||
/// Create the tree structure for logging the messages as a tree
|
||||
fn create_indents(queues: &[VecDeque<Message>]) -> String {
|
||||
String::from_iter(queues.iter().enumerate().skip(1).map(|(index, queue)| {
|
||||
|
||||
@@ -11,10 +11,12 @@ mod macros;
|
||||
extern crate log;
|
||||
|
||||
pub mod application;
|
||||
pub mod builder;
|
||||
pub mod consts;
|
||||
pub mod dispatcher;
|
||||
pub mod messages;
|
||||
pub mod node_graph_executor;
|
||||
pub mod task;
|
||||
#[cfg(test)]
|
||||
pub mod test_utils;
|
||||
pub mod utility_traits;
|
||||
|
||||
@@ -86,8 +86,8 @@ pub enum AppWindowPlatform {
|
||||
Linux,
|
||||
}
|
||||
|
||||
impl From<&Environment> for AppWindowPlatform {
|
||||
fn from(environment: &Environment) -> Self {
|
||||
impl From<Environment> for AppWindowPlatform {
|
||||
fn from(environment: Environment) -> Self {
|
||||
match (environment.platform, environment.host) {
|
||||
(Platform::Web, _) => AppWindowPlatform::Web,
|
||||
(Platform::Desktop, Host::Linux) => AppWindowPlatform::Linux,
|
||||
|
||||
@@ -12,8 +12,9 @@ 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::list::List;
|
||||
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
|
||||
use graphite_proc_macros::{ExtractField, message_handler_data};
|
||||
use kurbo::ParamCurve;
|
||||
use std::sync::Arc;
|
||||
@@ -127,7 +128,11 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}));
|
||||
}
|
||||
|
||||
let copies = chain_nodes
|
||||
// The dots on wires between the copied chain nodes go along with them, so pasting them loose keeps those wires
|
||||
let chain_nodes_with_dots = active_document.network_interface.selection_with_bridging_dots(chain_nodes, &[]);
|
||||
let other_nodes = other_nodes.into_iter().filter(|node_id| !chain_nodes_with_dots.contains(node_id)).collect::<Vec<_>>();
|
||||
|
||||
let copies = chain_nodes_with_dots
|
||||
.iter()
|
||||
.filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[]))
|
||||
.collect::<Vec<_>>();
|
||||
@@ -434,18 +439,27 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
|
||||
|
||||
// Create new point ids and add those into the existing Vector path
|
||||
// Materialize the copied snapshot so its points and segments can replay with fresh IDs
|
||||
let (mut pasted_vector, mut pasted_paths) = (Vector::default(), List::new());
|
||||
new_vector.apply(&mut pasted_vector, &mut pasted_paths);
|
||||
|
||||
// Create new point IDs and add those into the existing Vector path
|
||||
let mut points_map = HashMap::new();
|
||||
for (point, position) in new_vector.point_domain.iter() {
|
||||
for index in pasted_vector.anchor_indices(&pasted_paths) {
|
||||
let (Some(point), Some(position)) = (pasted_vector.point_id_at(index as u32), pasted_vector.position(index)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let new_point_id = PointId::generate();
|
||||
points_map.insert(point, new_point_id);
|
||||
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Create new segment ids and add the segments into the existing Vector path
|
||||
// Create new segment IDs and add the segments into the existing Vector path
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, segment, start, end) in new_vector.segment_iter() {
|
||||
let path_beginnings = pasted_vector.path_beginnings(&pasted_paths);
|
||||
for (segment_id, segment, start, end) in pasted_vector.segment_iter(&pasted_paths) {
|
||||
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
|
||||
warn!("Skipping pasted vector segment with an unknown endpoint");
|
||||
continue;
|
||||
@@ -465,10 +479,19 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let points = [start_point, end_point];
|
||||
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
|
||||
// Every pasted path stays a path of its own, even where it sets out from the end of another
|
||||
if path_beginnings.contains(&segment_id) {
|
||||
let modification_type = VectorModificationType::SetPathBreak {
|
||||
segment: new_segment_id,
|
||||
breaks: true,
|
||||
};
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
|
||||
// Set G1 continuity
|
||||
for handles in new_vector.colinear_manipulators {
|
||||
for handles in pasted_vector.colinear_pairs(&pasted_paths) {
|
||||
let to_new_handle = |handle: HandleId| -> Option<HandleId> {
|
||||
Some(HandleId {
|
||||
ty: handle.ty,
|
||||
|
||||
@@ -5,7 +5,7 @@ use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::VectorModification;
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardContentRaw {
|
||||
@@ -20,7 +20,7 @@ pub enum ClipboardContent {
|
||||
Image { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
|
||||
pub type ClipboardVectorEntry = (LayerNodeIdentifier, VectorModification, DAffine2);
|
||||
|
||||
/// An entry in the `graphite:` clipboard payload.
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState, RenderStatus};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
@@ -235,6 +235,20 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "exportIndex")]
|
||||
index: Option<usize>,
|
||||
},
|
||||
/// The wire a dragged node would be inserted onto if dropped now, keyed by the node and index of the input it feeds (the max node ID for an export).
|
||||
UpdateWireInsertionPreview {
|
||||
wire: Option<(NodeId, usize)>,
|
||||
},
|
||||
/// How far each node, and the imports and exports, gliding into the place it moved to is drawn from that place, in node graph space.
|
||||
UpdateGlideOffsets {
|
||||
nodes: Vec<(NodeId, (f64, f64))>,
|
||||
imports: (f64, f64),
|
||||
exports: (f64, f64),
|
||||
},
|
||||
/// The connector a press at the pointer would grab, by its center in node graph space.
|
||||
UpdateHoveredConnector {
|
||||
center: Option<(f64, f64)>,
|
||||
},
|
||||
UpdateLayerWidths {
|
||||
#[serde(rename = "layerWidths")]
|
||||
layer_widths: HashMap<NodeId, u32>,
|
||||
@@ -246,6 +260,9 @@ pub enum FrontendMessage {
|
||||
UpdateDocumentArtwork {
|
||||
svg: String,
|
||||
},
|
||||
UpdateRenderStatus {
|
||||
status: RenderStatus,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<RasterizedImage>,
|
||||
},
|
||||
@@ -291,8 +308,8 @@ pub enum FrontendMessage {
|
||||
UpdateNodeGraphNodes {
|
||||
nodes: Vec<FrontendNode>,
|
||||
},
|
||||
UpdateNodeGraphErrorDiagnostic {
|
||||
error: Option<NodeGraphErrorDiagnostic>,
|
||||
UpdateNodeGraphErrorDiagnostics {
|
||||
errors: Vec<NodeGraphErrorDiagnostic>,
|
||||
},
|
||||
UpdateVisibleNodes {
|
||||
nodes: Vec<NodeId>,
|
||||
@@ -312,6 +329,9 @@ pub enum FrontendMessage {
|
||||
id: NodeId,
|
||||
value: String,
|
||||
},
|
||||
ClearNodeThumbnails {
|
||||
ids: Vec<NodeId>,
|
||||
},
|
||||
UpdateOpenDocumentsList {
|
||||
#[serde(rename = "openDocuments")]
|
||||
open_documents: Vec<DocumentInfo>,
|
||||
@@ -319,6 +339,12 @@ pub enum FrontendMessage {
|
||||
UpdateWirePathInProgress {
|
||||
#[serde(rename = "wirePath")]
|
||||
wire_path: Option<WirePath>,
|
||||
/// Where the wire meets the connector it's dragged from, in node graph space.
|
||||
#[serde(rename = "draggedFrom")]
|
||||
dragged_from: Option<(f64, f64)>,
|
||||
/// Where the wire's loose end meets a connector it has snapped onto, in node graph space.
|
||||
#[serde(rename = "snappedTo")]
|
||||
snapped_to: Option<(f64, f64)>,
|
||||
},
|
||||
UpdatePlatform {
|
||||
platform: AppWindowPlatform,
|
||||
|
||||
@@ -42,6 +42,15 @@ pub enum MouseCursorIcon {
|
||||
Rotate,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum RenderStatus {
|
||||
#[default]
|
||||
Rendering,
|
||||
Error,
|
||||
Panic,
|
||||
}
|
||||
|
||||
#[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 {
|
||||
|
||||
@@ -11,6 +11,5 @@ pub enum FutureMessage {
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
future: MessageFuture,
|
||||
},
|
||||
/// Sent by a wake callback to nudge an idle event loop into a dispatch tick.
|
||||
Wake,
|
||||
Drain,
|
||||
}
|
||||
@@ -6,19 +6,16 @@ use dyn_any::WasmNotSend;
|
||||
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
|
||||
|
||||
use crate::messages::prelude::*;
|
||||
use crate::task::Spawner;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + 'static>>;
|
||||
|
||||
/// Invoked by the spawner after a result is sent, to wake the platform event loop.
|
||||
/// Invoked after a result is sent, to wake the platform event loop.
|
||||
pub type Wake = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
fn noop_wake() -> Wake {
|
||||
Arc::new(|| {})
|
||||
}
|
||||
|
||||
/// One-shot async work whose result re-enters the dispatcher as a [`Message`].
|
||||
/// Resolves to [`Message::NoOp`] if polled after the inner future has already been taken.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -62,52 +59,24 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Platform-specific async-task executor.
|
||||
/// Runs `future`, sends the resolved message on `results`, then calls `wake`.
|
||||
pub trait MessageSpawner: Send + Sync {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake);
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FutureMessageContext {}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct FutureMessageHandler {
|
||||
#[cfg_attr(test, expect(dead_code))]
|
||||
spawner: Arc<dyn MessageSpawner>,
|
||||
spawner: Spawner,
|
||||
wake: Wake,
|
||||
#[cfg_attr(test, expect(dead_code))]
|
||||
results_sender: UnboundedSender<Message>,
|
||||
results_receiver: UnboundedReceiver<Message>,
|
||||
}
|
||||
|
||||
impl FutureMessageHandler {
|
||||
pub fn with_wake(wake: Wake) -> Self {
|
||||
pub fn new(spawner: Spawner, wake: Wake) -> Self {
|
||||
let (results_sender, results_receiver) = unbounded();
|
||||
Self {
|
||||
spawner: default_spawner(),
|
||||
spawner,
|
||||
wake,
|
||||
results_sender,
|
||||
results_receiver,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_wake(&mut self, wake: Wake) {
|
||||
self.wake = wake;
|
||||
}
|
||||
|
||||
/// Pull every resolved async result into `out`.
|
||||
pub fn drain_results(&mut self, out: &mut VecDeque<Message>) {
|
||||
while let Ok(Some(message)) = self.results_receiver.try_next() {
|
||||
out.push_back(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FutureMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self::with_wake(noop_wake())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FutureMessageHandler {
|
||||
@@ -117,87 +86,25 @@ impl std::fmt::Debug for FutureMessageHandler {
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandler {
|
||||
fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque<Message>, _context: FutureMessageContext) {
|
||||
impl MessageHandler<FutureMessage, ()> for FutureMessageHandler {
|
||||
fn process_message(&mut self, message: FutureMessage, responses: &mut VecDeque<Message>, _context: ()) {
|
||||
match message {
|
||||
FutureMessage::Await { future } => {
|
||||
#[cfg(not(test))]
|
||||
self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone());
|
||||
|
||||
// For tests, block on the future to ensure the result is available when validating editor state afterwards.
|
||||
#[cfg(test)]
|
||||
{
|
||||
let message = futures::executor::block_on(future.into_future());
|
||||
_responses.push_back(message);
|
||||
}
|
||||
let results = self.results_sender.clone();
|
||||
let wake = self.wake.clone();
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
}));
|
||||
}
|
||||
FutureMessage::Wake => {
|
||||
// Tick-only message: the dispatcher's top-of-tick drain handles the real work.
|
||||
FutureMessage::Drain => {
|
||||
while let Ok(Some(message)) = self.results_receiver.try_next() {
|
||||
responses.push_back(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(FutureMessageDiscriminant;);
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(TokioSpawner::default())
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(WasmSpawner)
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
struct TokioSpawner {
|
||||
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
|
||||
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Default for TokioSpawner {
|
||||
fn default() -> Self {
|
||||
Self { runtime: std::sync::OnceLock::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl TokioSpawner {
|
||||
fn runtime(&self) -> &tokio::runtime::Runtime {
|
||||
self.runtime.get_or_init(|| {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct async-message tokio runtime")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl MessageSpawner for TokioSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
self.runtime().spawn(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
struct WasmSpawner;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl MessageSpawner for WasmSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,4 @@ mod future_message_handler;
|
||||
#[doc(inline)]
|
||||
pub use future_message::{FutureMessage, FutureMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use future_message_handler::{FutureMessageContext, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
|
||||
pub use future_message_handler::{FutureMessageHandler, MessageFuture, Wake};
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::utility_types::keyboard::KeysGroup;
|
||||
use super::utility_types::misc::Mapping;
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{self, Key};
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -11,7 +11,7 @@ pub struct InputMapperMessageContext<'a> {
|
||||
pub actions: ActionList,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct InputMapperMessageHandler {
|
||||
mapping: Mapping,
|
||||
}
|
||||
@@ -29,11 +29,15 @@ impl MessageHandler<InputMapperMessage, InputMapperMessageContext<'_>> for Input
|
||||
}
|
||||
|
||||
impl InputMapperMessageHandler {
|
||||
pub fn new(mapping: Mapping) -> Self {
|
||||
Self { mapping }
|
||||
}
|
||||
|
||||
pub fn set_mapping(&mut self, mapping: Mapping) {
|
||||
self.mapping = mapping;
|
||||
}
|
||||
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option<KeysGroup> {
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option<KeysGroup> {
|
||||
let all_key_mapping_entries = std::iter::empty()
|
||||
.chain(self.mapping.key_up.iter())
|
||||
.chain(self.mapping.key_down.iter())
|
||||
@@ -49,7 +53,7 @@ impl InputMapperMessageHandler {
|
||||
let found_actions = all_mapping_entries.filter(|entry| entry.action.to_discriminant() == *action_to_find);
|
||||
|
||||
// Get the `Key` for this platform's accelerator key
|
||||
let platform_accel_key = if Editor::environment().is_mac() { Key::Command } else { Key::Control };
|
||||
let platform_accel_key = if environment.is_mac() { Key::Command } else { Key::Control };
|
||||
|
||||
let entry_to_key = |entry: &MappingEntry| {
|
||||
// Get the modifier keys for the entry (and convert them to Key)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates};
|
||||
@@ -13,20 +13,20 @@ use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpd
|
||||
use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
|
||||
use glam::DVec2;
|
||||
|
||||
impl From<MappingVariant> for Mapping {
|
||||
fn from(value: MappingVariant) -> Self {
|
||||
match value {
|
||||
MappingVariant::Default => input_mappings(false),
|
||||
MappingVariant::ZoomWithScroll => input_mappings(true),
|
||||
impl Mapping {
|
||||
pub fn new(variant: MappingVariant, environment: Environment) -> Self {
|
||||
match variant {
|
||||
MappingVariant::Default => input_mappings(false, environment),
|
||||
MappingVariant::ZoomWithScroll => input_mappings(true, environment),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mapping {
|
||||
use InputMapperMessage::*;
|
||||
use Key::*;
|
||||
|
||||
let is_mac = Editor::environment().is_mac();
|
||||
let is_mac = environment.is_mac();
|
||||
|
||||
// NOTICE:
|
||||
// If a new mapping you added here isn't working (and perhaps another lower-precedence one is instead), make sure to advertise
|
||||
@@ -89,10 +89,10 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Up, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Right, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowLeft); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Left, rubber_band: false }),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||
entry!(KeyDown(ArrowLeft); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Left }),
|
||||
//
|
||||
// TransformLayerMessage
|
||||
entry!(KeyDown(Enter); action_dispatch=TransformLayerMessage::ApplyTransformOperation { final_transform: true }),
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::input_mapper_message_handler::InputMapperMessageContext;
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::misc::Mapping;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct KeyMappingMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub input: &'a InputPreprocessorMessageHandler,
|
||||
pub actions: ActionList,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct KeyMappingMessageHandler {
|
||||
mapping_handler: InputMapperMessageHandler,
|
||||
}
|
||||
@@ -16,21 +20,27 @@ pub struct KeyMappingMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<KeyMappingMessage, KeyMappingMessageContext<'_>> for KeyMappingMessageHandler {
|
||||
fn process_message(&mut self, message: KeyMappingMessage, responses: &mut VecDeque<Message>, context: KeyMappingMessageContext) {
|
||||
let KeyMappingMessageContext { input, actions } = context;
|
||||
let KeyMappingMessageContext { environment, input, actions } = context;
|
||||
|
||||
match message {
|
||||
// Sub-messages
|
||||
KeyMappingMessage::Lookup(input_message) => self.mapping_handler.process_message(input_message, responses, InputMapperMessageContext { input, actions }),
|
||||
|
||||
// Messages
|
||||
KeyMappingMessage::ModifyMapping { mapping } => self.mapping_handler.set_mapping(mapping.into()),
|
||||
KeyMappingMessage::ModifyMapping { mapping } => self.mapping_handler.set_mapping(Mapping::new(mapping, environment)),
|
||||
}
|
||||
}
|
||||
advertise_actions!();
|
||||
}
|
||||
|
||||
impl KeyMappingMessageHandler {
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option<KeysGroup> {
|
||||
self.mapping_handler.action_input_mapping(action_to_find)
|
||||
pub fn new(environment: Environment) -> Self {
|
||||
Self {
|
||||
mapping_handler: InputMapperMessageHandler::new(Mapping::new(MappingVariant::Default, environment)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option<KeysGroup> {
|
||||
self.mapping_handler.action_input_mapping(action_to_find, environment)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::{Environment, EnvironmentDisplay};
|
||||
use crate::messages::prelude::*;
|
||||
use bitflags::bitflags;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
@@ -243,9 +243,9 @@ pub enum Key {
|
||||
_KeysVariantCount, // This has to be the last element in the enum
|
||||
}
|
||||
|
||||
impl fmt::Display for Key {
|
||||
impl EnvironmentDisplay for Key {
|
||||
// TODO: Relevant key labels should be localized when we get around to implementing localization/internationalization
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
|
||||
fn fmt(&self, f: &mut fmt::Formatter, environment: Environment) -> std::fmt::Result {
|
||||
let key_name = format!("{self:?}");
|
||||
|
||||
// Writing system keys
|
||||
@@ -258,7 +258,7 @@ impl fmt::Display for Key {
|
||||
return write!(f, "{}", key_name.chars().skip(KEY_PREFIX.len()).collect::<String>());
|
||||
}
|
||||
|
||||
let is_mac = Editor::environment().is_mac();
|
||||
let is_mac = environment.is_mac();
|
||||
|
||||
let name = match self {
|
||||
// Writing system keys
|
||||
@@ -345,36 +345,10 @@ pub const NUMBER_OF_KEYS: usize = Key::_KeysVariantCount as usize - 1;
|
||||
// =========
|
||||
|
||||
/// Only `Key`s that exist on a physical keyboard should be used.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KeysGroup(pub Vec<Key>);
|
||||
|
||||
impl fmt::Display for KeysGroup {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
const JOINER_MARK: &str = " ";
|
||||
|
||||
let mut joined = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|key| {
|
||||
let key_is_modifier = matches!(*key, Key::Control | Key::Command | Key::Alt | Key::Shift | Key::Meta | Key::Accel);
|
||||
|
||||
if Editor::environment().is_mac() && key_is_modifier {
|
||||
key.to_string()
|
||||
} else {
|
||||
key.to_string() + JOINER_MARK
|
||||
}
|
||||
})
|
||||
.collect::<String>();
|
||||
|
||||
// Cut the joining character off the end, if present
|
||||
if joined.ends_with(JOINER_MARK) {
|
||||
joined.truncate(joined.len() - JOINER_MARK.len());
|
||||
}
|
||||
|
||||
write!(f, "{joined}")
|
||||
}
|
||||
}
|
||||
|
||||
// ==========
|
||||
// LabeledKey
|
||||
// ==========
|
||||
@@ -425,13 +399,16 @@ pub enum LabeledKeyOrMouseMotion {
|
||||
MouseMotion(MouseMotion),
|
||||
}
|
||||
|
||||
impl From<Key> for LabeledKeyOrMouseMotion {
|
||||
fn from(key: Key) -> Self {
|
||||
impl LabeledKeyOrMouseMotion {
|
||||
pub fn new(key: Key, environment: Environment) -> Self {
|
||||
match key {
|
||||
Key::MouseLeft => Self::MouseMotion(MouseMotion::Lmb),
|
||||
Key::MouseRight => Self::MouseMotion(MouseMotion::Rmb),
|
||||
Key::MouseMiddle => Self::MouseMotion(MouseMotion::Mmb),
|
||||
_ => Self::Key(LabeledKey { key, label: key.to_string() }),
|
||||
_ => Self::Key(LabeledKey {
|
||||
key,
|
||||
label: key.display(environment).to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -444,9 +421,9 @@ impl From<Key> for LabeledKeyOrMouseMotion {
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct LabeledShortcut(pub Vec<LabeledKeyOrMouseMotion>);
|
||||
|
||||
impl From<KeysGroup> for LabeledShortcut {
|
||||
fn from(keys_group: KeysGroup) -> Self {
|
||||
Self(keys_group.0.into_iter().map(|key| key.into()).collect())
|
||||
impl LabeledShortcut {
|
||||
pub fn new(keys_group: KeysGroup, environment: Environment) -> Self {
|
||||
Self(keys_group.0.into_iter().map(|key| LabeledKeyOrMouseMotion::new(key, environment)).collect())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -163,8 +163,8 @@ macro_rules! action_shortcut {
|
||||
|
||||
macro_rules! action_shortcut_manual {
|
||||
($($keys:expr),*) => {
|
||||
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Shortcut(
|
||||
crate::messages::input_mapper::utility_types::keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
|
||||
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Keys(
|
||||
crate::messages::input_mapper::utility_types::keyboard::KeysGroup(vec![$($keys),*]),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{KeyStates, NUMBER_OF_KEYS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::NUMBER_OF_MOUSE_BUTTONS;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -18,12 +18,6 @@ pub struct Mapping {
|
||||
pub pointer_shake: KeyMappingEntries,
|
||||
}
|
||||
|
||||
impl Default for Mapping {
|
||||
fn default() -> Self {
|
||||
MappingVariant::Default.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn match_input_message(&self, message: InputMapperMessage, keyboard_state: &KeyStates, actions: ActionList) -> Option<Message> {
|
||||
let list = self.associated_entries(&message);
|
||||
@@ -113,19 +107,20 @@ pub struct MappingEntry {
|
||||
pub enum ActionShortcut {
|
||||
#[serde(skip)]
|
||||
Action(MessageDiscriminant),
|
||||
#[serde(skip)]
|
||||
Keys(KeysGroup),
|
||||
#[serde(rename = "shortcut")]
|
||||
Shortcut(LabeledShortcut),
|
||||
}
|
||||
|
||||
impl ActionShortcut {
|
||||
pub fn realize_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
if let Self::Action(action) = self {
|
||||
if let Some(keys) = action_input_mapping(action) {
|
||||
*self = Self::Shortcut(keys.into());
|
||||
} else {
|
||||
*self = Self::Shortcut(KeysGroup::default().into());
|
||||
}
|
||||
}
|
||||
pub fn realize_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>, environment: Environment) {
|
||||
let keys = match self {
|
||||
Self::Action(action) => action_input_mapping(action).unwrap_or_default(),
|
||||
Self::Keys(keys) => std::mem::take(keys),
|
||||
Self::Shortcut(_) => return,
|
||||
};
|
||||
*self = Self::Shortcut(LabeledShortcut::new(keys, environment));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
@@ -8,6 +8,7 @@ use std::time::Duration;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct InputPreprocessorMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
@@ -35,12 +36,12 @@ enum DoubleTapState {
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext<'a>> for InputPreprocessorMessageHandler {
|
||||
fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>, context: InputPreprocessorMessageContext<'a>) {
|
||||
let InputPreprocessorMessageContext { viewport } = context;
|
||||
let InputPreprocessorMessageContext { environment, viewport } = context;
|
||||
|
||||
match message {
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -57,7 +58,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
}
|
||||
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
self.keyboard.set(key as usize);
|
||||
|
||||
if !key_repeat {
|
||||
@@ -80,7 +81,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
responses.add(InputMapperMessage::KeyDown(key));
|
||||
}
|
||||
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
self.keyboard.unset(key as usize);
|
||||
if !key_repeat {
|
||||
responses.add(InputMapperMessage::KeyUpNoRepeat(key));
|
||||
@@ -101,7 +102,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -109,7 +110,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.translate_mouse_event(pointer_state, true, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -121,7 +122,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -129,7 +130,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -143,7 +144,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.double_tap_state = DoubleTapState::Idle;
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
self.update_states_of_modifier_keys(modifier_keys, environment, responses);
|
||||
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
@@ -161,6 +162,11 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
|
||||
impl InputPreprocessorMessageHandler {
|
||||
/// When the first of the pointer buttons now held was pressed, in milliseconds, timed by its pointer event or else, lacking a timestamp, the latest animation frame.
|
||||
pub fn pointer_down_time(&self) -> f64 {
|
||||
self.pointer_down_time
|
||||
}
|
||||
|
||||
fn translate_mouse_event(&mut self, mut new_state: PointerState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
|
||||
let click_mappings = [
|
||||
(MouseKeys::LEFT, Key::MouseLeft),
|
||||
@@ -199,7 +205,7 @@ impl InputPreprocessorMessageHandler {
|
||||
self.mouse = new_state;
|
||||
}
|
||||
|
||||
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, responses: &mut VecDeque<Message>) {
|
||||
fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, environment: Environment, responses: &mut VecDeque<Message>) {
|
||||
let is_key_pressed = |key_to_check: ModifierKeys| pressed_modifier_keys.contains(key_to_check);
|
||||
|
||||
// Update the state of the concrete modifier keys based on the source state
|
||||
@@ -208,14 +214,14 @@ impl InputPreprocessorMessageHandler {
|
||||
self.update_modifier_key(Key::Control, is_key_pressed(ModifierKeys::CONTROL), responses);
|
||||
|
||||
// Update the state of either the concrete Meta or the Command keys based on which one is applicable for this platform
|
||||
let meta_or_command = match Editor::environment().is_mac() {
|
||||
let meta_or_command = match environment.is_mac() {
|
||||
true => Key::Command,
|
||||
false => Key::Meta,
|
||||
};
|
||||
self.update_modifier_key(meta_or_command, is_key_pressed(ModifierKeys::META_OR_COMMAND), responses);
|
||||
|
||||
// Update the state of the virtual Accel key (the primary accelerator key) based on the source state of the Control or Command key, whichever is relevant on this platform
|
||||
let accel_virtual_key_state = match Editor::environment().is_mac() {
|
||||
let accel_virtual_key_state = match environment.is_mac() {
|
||||
true => is_key_pressed(ModifierKeys::META_OR_COMMAND),
|
||||
false => is_key_pressed(ModifierKeys::CONTROL),
|
||||
};
|
||||
@@ -238,6 +244,7 @@ impl InputPreprocessorMessageHandler {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::DoubleTapState;
|
||||
use crate::application::DEFAULT_ENVIRONMENT;
|
||||
use crate::consts::DOUBLE_TAP_MILLISECONDS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys};
|
||||
@@ -257,6 +264,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -276,6 +284,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -295,6 +304,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -316,6 +326,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -336,6 +347,7 @@ mod test {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
@@ -381,6 +393,7 @@ mod test {
|
||||
message,
|
||||
responses,
|
||||
InputPreprocessorMessageContext {
|
||||
environment: DEFAULT_ENVIRONMENT,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::application::Environment;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::math_expression::{
|
||||
MathExpressionTokens, math_expression_completions, math_expression_error, math_expression_error_ranges, math_expression_number, math_expression_tokens,
|
||||
@@ -12,6 +13,7 @@ use std::collections::HashMap;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct LayoutMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub action_input_mapping: &'a dyn Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
}
|
||||
|
||||
@@ -23,6 +25,7 @@ pub struct LayoutMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHandler {
|
||||
fn process_message(&mut self, message: LayoutMessage, responses: &mut std::collections::VecDeque<Message>, context: LayoutMessageContext) {
|
||||
let environment = context.environment;
|
||||
let action_input_mapping = &context.action_input_mapping;
|
||||
|
||||
match message {
|
||||
@@ -36,7 +39,7 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
return;
|
||||
};
|
||||
// Resend that diff
|
||||
self.send_diff(vec![diff], layout_target, responses, action_input_mapping);
|
||||
self.send_diff(vec![diff], layout_target, responses, action_input_mapping, environment);
|
||||
}
|
||||
LayoutMessage::ResendAllLayouts => {
|
||||
// Collect non-empty layouts and their indices, then clear the stored copies so diffs compute as full re-sends
|
||||
@@ -49,11 +52,11 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
.collect();
|
||||
|
||||
for (layout_target, layout) in layouts_to_resend {
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping, environment);
|
||||
}
|
||||
}
|
||||
LayoutMessage::SendLayout { layout, layout_target } => {
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
|
||||
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping, environment);
|
||||
}
|
||||
LayoutMessage::DestroyLayout { layout_target } => {
|
||||
if let Some(layout) = self.layouts.get_mut(layout_target as usize) {
|
||||
@@ -575,6 +578,7 @@ impl LayoutMessageHandler {
|
||||
mut new_layout: Layout,
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
environment: Environment,
|
||||
) {
|
||||
// Collect CheckboxId mappings from new layout
|
||||
let mut checkbox_map = HashMap::new();
|
||||
@@ -605,12 +609,19 @@ impl LayoutMessageHandler {
|
||||
}];
|
||||
}
|
||||
|
||||
self.send_diff(widget_diffs, layout_target, responses, action_input_mapping);
|
||||
self.send_diff(widget_diffs, layout_target, responses, action_input_mapping, environment);
|
||||
}
|
||||
|
||||
/// Send a diff to the frontend based on the layout target.
|
||||
fn send_diff(&self, mut diff: Vec<WidgetDiff>, layout_target: LayoutTarget, responses: &mut VecDeque<Message>, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping));
|
||||
fn send_diff(
|
||||
&self,
|
||||
mut diff: Vec<WidgetDiff>,
|
||||
layout_target: LayoutTarget,
|
||||
responses: &mut VecDeque<Message>,
|
||||
action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>,
|
||||
environment: Environment,
|
||||
) {
|
||||
diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping, environment));
|
||||
|
||||
if matches!(layout_target, LayoutTarget::_LayoutTargetLength) {
|
||||
panic!("`_LayoutTargetLength` is not a valid `LayoutTarget` and is used for array indexing");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::widgets::button_widgets::*;
|
||||
use super::widgets::input_widgets::*;
|
||||
use super::widgets::label_widgets::*;
|
||||
use crate::application::generate_uuid;
|
||||
use crate::application::{Environment, generate_uuid};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
@@ -423,9 +423,15 @@ pub struct NodeSection {
|
||||
/// For a section in the chain feeding another section's input, the wire drawn up to the section above, which its node's output feeds.
|
||||
#[serde(rename = "outputWire")]
|
||||
pub output_wire: Option<SectionWire>,
|
||||
/// Whether this section only refers to its node with a row like the Data panel's, in place of its header and parameters (for the layer whose stack feeds the bottom of a chain).
|
||||
/// Whether this section only refers to its node with a row like the Data panel's, in place of its header and parameters (for a layer feeding a chain, or feeding or fed by the selected layer).
|
||||
#[serde(rename = "nodeReference")]
|
||||
pub node_reference: bool,
|
||||
/// For a section referring to layers that take the wire from the section below into their content, rather than from their bottom, that wire turning in from the left past its indent.
|
||||
#[serde(rename = "contentWire")]
|
||||
pub content_wire: Option<SectionWire>,
|
||||
/// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom.
|
||||
#[serde(rename = "contentWireContinues")]
|
||||
pub content_wire_continues: bool,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose Inspector section this is.
|
||||
@@ -477,6 +483,8 @@ impl LayoutGroup {
|
||||
chain_wire: None,
|
||||
output_wire: None,
|
||||
node_reference: false,
|
||||
content_wire: None,
|
||||
content_wire_continues: false,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -582,6 +590,8 @@ impl Diffable for LayoutGroup {
|
||||
chain_wire: current_chain_wire,
|
||||
output_wire: current_output_wire,
|
||||
node_reference: current_node_reference,
|
||||
content_wire: current_content_wire,
|
||||
content_wire_continues: current_content_wire_continues,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
@@ -596,6 +606,8 @@ impl Diffable for LayoutGroup {
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -613,6 +625,8 @@ impl Diffable for LayoutGroup {
|
||||
|| *current_chain_wire != new_chain_wire
|
||||
|| *current_output_wire != new_output_wire
|
||||
|| *current_node_reference != new_node_reference
|
||||
|| *current_content_wire != new_content_wire
|
||||
|| *current_content_wire_continues != new_content_wire_continues
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
@@ -626,6 +640,8 @@ impl Diffable for LayoutGroup {
|
||||
*current_chain_wire = new_chain_wire;
|
||||
*current_output_wire = new_output_wire;
|
||||
*current_node_reference = new_node_reference;
|
||||
*current_content_wire = new_content_wire;
|
||||
*current_content_wire_continues = new_content_wire_continues;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
@@ -641,6 +657,8 @@ impl Diffable for LayoutGroup {
|
||||
chain_wire: new_chain_wire,
|
||||
output_wire: new_output_wire,
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -996,7 +1014,7 @@ pub enum DiffUpdate {
|
||||
|
||||
impl DiffUpdate {
|
||||
/// Append the keyboard shortcut to the tooltip where applicable
|
||||
pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>, environment: Environment) {
|
||||
// Go through each widget to convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` and append the key combination to the widget tooltip
|
||||
let convert_tooltip = |widget_instance: &mut WidgetInstance| {
|
||||
// Handle all the widgets that have tooltips
|
||||
@@ -1033,7 +1051,7 @@ impl DiffUpdate {
|
||||
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
if let Some(tooltip_shortcut) = tooltip_shortcut {
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping);
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping, environment);
|
||||
}
|
||||
|
||||
// Handle RadioInput separately because its tooltips are children of the widget
|
||||
@@ -1041,23 +1059,23 @@ impl DiffUpdate {
|
||||
for radio_entry_data in &mut radio_input.entries {
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
if let Some(tooltip_shortcut) = radio_entry_data.tooltip_shortcut.as_mut() {
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping);
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping, environment);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Recursively fill menu list entries with their realized shortcut keys specific to the current bindings and platform
|
||||
fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>) {
|
||||
fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option<KeysGroup>, environment: Environment) {
|
||||
for entries in entry_sections {
|
||||
for entry in entries {
|
||||
// Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut`
|
||||
if let Some(tooltip_shortcut) = &mut entry.tooltip_shortcut {
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping);
|
||||
tooltip_shortcut.realize_shortcut(action_input_mapping, environment);
|
||||
}
|
||||
|
||||
// Recursively call this function on the menu's children
|
||||
apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping);
|
||||
apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping, environment);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1065,29 +1083,39 @@ impl DiffUpdate {
|
||||
// Apply shortcut conversions to all widgets that have menu lists
|
||||
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
|
||||
Widget::DropdownInput(dropdown_input) => {
|
||||
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping);
|
||||
apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping, environment);
|
||||
dropdown_input.entries_hash = hash_menu_list_entry_sections(&dropdown_input.entries);
|
||||
}
|
||||
Widget::TextButton(text_button) => {
|
||||
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping);
|
||||
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping, environment);
|
||||
text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
match self {
|
||||
Self::Layout(layout) => layout.0.iter_mut().flat_map(|layout_group| layout_group.iter_mut()).for_each(|widget_instance| {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
}),
|
||||
Self::LayoutGroup(layout_group) => layout_group.iter_mut().for_each(|widget_instance| {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
}),
|
||||
Self::Widget(widget_instance) => {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
let convert = |widget_instance: &mut WidgetInstance| {
|
||||
convert_tooltip(widget_instance);
|
||||
convert_menu_lists(widget_instance);
|
||||
};
|
||||
|
||||
fn convert_layout_group(layout_group: &mut LayoutGroup, convert: &impl Fn(&mut WidgetInstance)) {
|
||||
match layout_group {
|
||||
LayoutGroup::Column(WidgetColumn { widgets }) | LayoutGroup::Row(WidgetRow { widgets }) => widgets.iter_mut().for_each(|widget_instance| convert_widget(widget_instance, convert)),
|
||||
LayoutGroup::Table(WidgetTable { rows, .. }) => rows.iter_mut().flatten().flatten().for_each(|widget_instance| convert_widget(widget_instance, convert)),
|
||||
LayoutGroup::NodeSection(NodeSection { layout, .. }) => layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, convert)),
|
||||
}
|
||||
}
|
||||
fn convert_widget(widget_instance: &mut WidgetInstance, convert: &impl Fn(&mut WidgetInstance)) {
|
||||
convert(widget_instance);
|
||||
if let Widget::PopoverButton(popover_button) = &mut *widget_instance.widget {
|
||||
popover_button.popover_layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, convert));
|
||||
}
|
||||
}
|
||||
|
||||
match self {
|
||||
Self::Layout(layout) => layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, &convert)),
|
||||
Self::LayoutGroup(layout_group) => convert_layout_group(layout_group, &convert),
|
||||
Self::Widget(widget_instance) => convert_widget(widget_instance, &convert),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -331,7 +331,7 @@ pub struct NodeCatalog {
|
||||
|
||||
// Behavior
|
||||
#[serde(rename = "initialSearchTerm")]
|
||||
pub intial_search: String,
|
||||
pub initial_search: String,
|
||||
|
||||
// Callbacks
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -47,6 +47,7 @@ pub enum Message {
|
||||
Viewport(ViewportMessage),
|
||||
|
||||
// Messages
|
||||
Wake,
|
||||
Batched {
|
||||
messages: Box<[Message]>,
|
||||
},
|
||||
|
||||
@@ -20,10 +20,6 @@ pub enum DataPanelMessage {
|
||||
TruncateElementPath {
|
||||
len: usize,
|
||||
},
|
||||
|
||||
ViewVectorTableTab {
|
||||
tab: VectorTableTab,
|
||||
},
|
||||
}
|
||||
|
||||
/// One hop in the breadcrumb path through nested data the Data panel is displaying.
|
||||
@@ -33,11 +29,3 @@ pub enum PathStep {
|
||||
Element(usize),
|
||||
Attribute { row: usize, key: String },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum VectorTableTab {
|
||||
#[default]
|
||||
Points,
|
||||
Segments,
|
||||
Handles,
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use super::VectorTableTab;
|
||||
use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup, LayoutTarget};
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessage, PathStep};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -25,14 +24,14 @@ 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,
|
||||
SpiralType,
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, Context, Cover, Coverage, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -51,7 +50,6 @@ pub struct DataPanelMessageHandler {
|
||||
introspected_node_path: Vec<NodeId>,
|
||||
introspected_data: Option<Arc<dyn Any + Send + Sync>>,
|
||||
element_path: Vec<PathStep>,
|
||||
active_vector_table_tab: VectorTableTab,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -67,7 +65,6 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
self.introspected_node_path.clear();
|
||||
self.introspected_data = None;
|
||||
self.element_path.clear();
|
||||
self.active_vector_table_tab = VectorTableTab::default();
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
DataPanelMessage::Refresh => {
|
||||
@@ -85,11 +82,6 @@ impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanel
|
||||
self.element_path.truncate(len);
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
|
||||
DataPanelMessage::ViewVectorTableTab { tab } => {
|
||||
self.active_vector_table_tab = tab;
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +106,6 @@ impl DataPanelMessageHandler {
|
||||
node_lookup_network_path: Vec::new(),
|
||||
gradient_settings: GradientSettings::default(),
|
||||
breadcrumbs: Vec::new(),
|
||||
vector_table_tab: self.active_vector_table_tab,
|
||||
};
|
||||
|
||||
// Main data visualization
|
||||
@@ -172,7 +163,6 @@ struct LayoutData<'a> {
|
||||
/// rather than in the stop list itself. The enclosing `Item`/`List` sets it to the owning row's attributes.
|
||||
gradient_settings: GradientSettings,
|
||||
breadcrumbs: Vec<String>,
|
||||
vector_table_tab: VectorTableTab,
|
||||
}
|
||||
|
||||
macro_rules! generate_layout_downcast {
|
||||
@@ -219,7 +209,8 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
List<StrokeJoin>,
|
||||
List<StrokeAlign>,
|
||||
List<StrokeCap>,
|
||||
List<MergeByDistanceAlgorithm>,
|
||||
List<WeldMethod>,
|
||||
List<UnweldMethod>,
|
||||
List<ExtrudeJoiningAlgorithm>,
|
||||
List<PointSpacingType>,
|
||||
List<StringCapitalization>,
|
||||
@@ -273,7 +264,8 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Item<StrokeJoin>,
|
||||
Item<StrokeAlign>,
|
||||
Item<StrokeCap>,
|
||||
Item<MergeByDistanceAlgorithm>,
|
||||
Item<WeldMethod>,
|
||||
Item<UnweldMethod>,
|
||||
Item<ExtrudeJoiningAlgorithm>,
|
||||
Item<PointSpacingType>,
|
||||
Item<StringCapitalization>,
|
||||
@@ -655,70 +647,42 @@ impl TableItemLayout for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// The pool is a plain point list with its IDs riding its attributes, so the generic list layout shows it as-is
|
||||
impl TableItemLayout for Vector {
|
||||
fn type_name() -> &'static str {
|
||||
"Vector"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!(
|
||||
"Vector ({} point{}, {} segment{})",
|
||||
self.point_domain.ids().len(),
|
||||
if self.point_domain.ids().len() == 1 { "" } else { "s" },
|
||||
self.segment_domain.ids().len(),
|
||||
if self.segment_domain.ids().len() == 1 { "" } else { "s" }
|
||||
)
|
||||
self.0.identifier()
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Handles]
|
||||
.into_iter()
|
||||
.map(|tab| {
|
||||
RadioEntryData::new(format!("{tab:?}"))
|
||||
.label(format!("{tab:?}"))
|
||||
.on_update(move |_| DataPanelMessage::ViewVectorTableTab { tab }.into())
|
||||
})
|
||||
.collect();
|
||||
let table_tabs = vec![RadioInput::new(table_tab_entries).selected_index(Some(data.vector_table_tab as u32)).widget_instance()];
|
||||
self.0.value_page(data)
|
||||
}
|
||||
}
|
||||
|
||||
let mut table_rows = Vec::new();
|
||||
match data.vector_table_tab {
|
||||
VectorTableTab::Handles => {
|
||||
table_rows.push(column_headings(&["", "colinear_manipulators[0]", "colinear_manipulators[1]"]));
|
||||
table_rows.extend(self.colinear_manipulators.iter().enumerate().map(|(index, [a, b])| {
|
||||
vec![
|
||||
TextLabel::new(format!("{index}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{a}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{b}")).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Points => {
|
||||
table_rows.push(column_headings(&["", "position"]));
|
||||
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format_dvec2(position)).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Segments => {
|
||||
table_rows.push(column_headings(&["", "start_point", "end_point", "handles"]));
|
||||
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
|
||||
let handles = match handles {
|
||||
BezierHandles::Linear => "Linear".to_string(),
|
||||
BezierHandles::Quadratic { handle } => format!("Quadratic — {}", format_dvec2(handle)),
|
||||
BezierHandles::Cubic { handle_start, handle_end } => format!("Cubic — start: {}, end: {}", format_dvec2(handle_start), format_dvec2(handle_end)),
|
||||
};
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("Point {start}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("Point {end}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(handles).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
}
|
||||
// A path is its list of point references, with segment IDs and smooth flags riding its attributes
|
||||
impl TableItemLayout for Path {
|
||||
fn type_name() -> &'static str {
|
||||
"Path"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
self.0.identifier()
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.value_page(data)
|
||||
}
|
||||
}
|
||||
|
||||
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
|
||||
// Only the click target attribute holds a bezpath, so it's named for what it does
|
||||
impl TableItemLayout for BezPath {
|
||||
fn type_name() -> &'static str {
|
||||
"Click Target"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
Self::type_name().to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1019,7 +983,8 @@ impl_table_item_layout_for_choice_enum!(
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
MergeByDistanceAlgorithm,
|
||||
WeldMethod,
|
||||
UnweldMethod,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
@@ -1082,7 +1047,7 @@ pub fn node_reference_button(
|
||||
network_path: &[NodeId],
|
||||
selection_network_path: &[NodeId],
|
||||
select: impl Fn() -> Message + Send + Sync + 'static,
|
||||
) -> WidgetInstance {
|
||||
) -> TextButton {
|
||||
let is_layer = network_interface.is_layer(&node_id, network_path);
|
||||
let icon = network_interface.node_icon(&node_id, network_path);
|
||||
let name = network_interface.display_name(&node_id, network_path);
|
||||
@@ -1101,7 +1066,6 @@ pub fn node_reference_button(
|
||||
(true, false, _) => "",
|
||||
})
|
||||
.on_update(move |_| select())
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
impl TableItemLayout for NodeId {
|
||||
@@ -1135,7 +1099,7 @@ impl TableItemLayout for NodeId {
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into(),
|
||||
]),
|
||||
};
|
||||
vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select)]
|
||||
vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))]
|
||||
@@ -1151,6 +1115,7 @@ macro_rules! known_item_types {
|
||||
List<Artboard>,
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Path>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
@@ -1170,6 +1135,8 @@ macro_rules! known_item_types {
|
||||
bool,
|
||||
String,
|
||||
Vector,
|
||||
Path,
|
||||
BezPath,
|
||||
Raster<CPU>,
|
||||
Raster<GPU>,
|
||||
Graphic,
|
||||
@@ -1189,7 +1156,8 @@ macro_rules! known_item_types {
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
MergeByDistanceAlgorithm,
|
||||
WeldMethod,
|
||||
UnweldMethod,
|
||||
ExtrudeJoiningAlgorithm,
|
||||
PointSpacingType,
|
||||
StringCapitalization,
|
||||
@@ -1230,6 +1198,15 @@ fn display_value_override(any: &dyn Any) -> Option<String> {
|
||||
if let Some(value) = any.downcast_ref::<BlendMode>() {
|
||||
return Some(value.to_string());
|
||||
}
|
||||
if let Some(value) = any.downcast_ref::<PointId>() {
|
||||
return Some(if *value == PointId::UNNAMED { String::new() } else { value.inner().to_string() });
|
||||
}
|
||||
if let Some(value) = any.downcast_ref::<SegmentId>() {
|
||||
return Some(if *value == SegmentId::ZERO { String::new() } else { value.inner().to_string() });
|
||||
}
|
||||
if let Some(value) = any.downcast_ref::<CurveType>() {
|
||||
return Some(value.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
@@ -266,8 +266,8 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume
|
||||
if expected.skip_deduplication != actual.skip_deduplication {
|
||||
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
|
||||
}
|
||||
if expected.context_features != actual.context_features {
|
||||
let _ = writeln!(out, " context_features: expected={:?} actual={:?}", expected.context_features, actual.context_features);
|
||||
if expected.context_dependencies != actual.context_dependencies {
|
||||
let _ = writeln!(out, " context_dependencies: expected={:?} actual={:?}", expected.context_dependencies, actual.context_dependencies);
|
||||
}
|
||||
if expected.original_location != actual.original_location {
|
||||
let _ = writeln!(out, " original_location differs (recomputed at load, not stored):");
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
@@ -199,9 +200,19 @@ pub enum DocumentMessage {
|
||||
SetGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
/// Renames a layer in the network the node graph is showing, which may be a subgraph.
|
||||
SetLayerNameInGraph {
|
||||
node_id: NodeId,
|
||||
name: String,
|
||||
},
|
||||
SetLayersPanelHoveredLayer {
|
||||
id: Option<NodeId>,
|
||||
},
|
||||
/// The layers with a row in view in the Layers panel, and among them those it lacks the details of, which it's sent.
|
||||
SetLayersPanelView {
|
||||
layers: Vec<NodeId>,
|
||||
layers_missing_details: Vec<NodeId>,
|
||||
},
|
||||
SetNodePinned {
|
||||
node_id: NodeId,
|
||||
pinned: bool,
|
||||
@@ -263,6 +274,10 @@ pub enum DocumentMessage {
|
||||
ToggleLayerChainExpanded {
|
||||
layer_id: NodeId,
|
||||
},
|
||||
/// Hides or shows a node in the network holding the selection, which may be a subgraph.
|
||||
ToggleNodeVisibility {
|
||||
node_id: NodeId,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
ToggleSelectedLocked,
|
||||
ToggleGridVisibility,
|
||||
@@ -286,11 +301,12 @@ pub enum DocumentMessage {
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
UpdateVectorData {
|
||||
vector_data: HashMap<NodeId, Arc<Vector>>,
|
||||
},
|
||||
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it.
|
||||
// `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
||||
// `UpdateVectorData` and `UpdateAppearanceAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so they never reach that serialization point.
|
||||
#[serde(skip)]
|
||||
UpdateVectorData {
|
||||
vector_data: HashMap<NodeId, Arc<Item<Vector>>>,
|
||||
},
|
||||
#[serde(skip)]
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use super::document_diff::diff_networks;
|
||||
use super::node_graph::{document_node_definitions, node_inspector};
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::layers_in_view::LayersInView;
|
||||
use super::utility_types::misc::{ANGLE_STEP_MAX, ANGLE_STEP_MIN, GroupFolderType, SNAPPING_OPTION_GROUPS, 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::application::{Environment, 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,
|
||||
};
|
||||
@@ -21,7 +22,7 @@ use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
@@ -58,6 +59,7 @@ use std::time::Duration;
|
||||
#[derive(ExtractField)]
|
||||
pub struct DocumentMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
pub environment: Environment,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub current_tool: &'a ToolType,
|
||||
@@ -187,6 +189,9 @@ pub struct DocumentMessageHandler {
|
||||
/// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport.
|
||||
#[serde(skip)]
|
||||
layers_panel_hovered_layer: Option<LayerNodeIdentifier>,
|
||||
/// The layers the frontend shows in view, the only ones it's sent the details and thumbnails of.
|
||||
#[serde(skip)]
|
||||
pub layers_in_view: LayersInView,
|
||||
/// Whether or not the editor has executed the network to render the document yet. If this is opened as an inactive tab, it won't be loaded initially because the active tab is prioritized.
|
||||
#[serde(skip)]
|
||||
pub is_loaded: bool,
|
||||
@@ -236,6 +241,7 @@ impl Default for DocumentMessageHandler {
|
||||
layer_range_selection_reference: None,
|
||||
chain_node_range_selection_reference: None,
|
||||
layers_panel_hovered_layer: None,
|
||||
layers_in_view: LayersInView::default(),
|
||||
is_loaded: false,
|
||||
}
|
||||
}
|
||||
@@ -246,6 +252,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
fn process_message(&mut self, message: DocumentMessage, responses: &mut VecDeque<Message>, context: DocumentMessageContext) {
|
||||
let DocumentMessageContext {
|
||||
document_id,
|
||||
environment,
|
||||
ipp,
|
||||
executor,
|
||||
viewport,
|
||||
@@ -263,6 +270,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
// Sub-messages
|
||||
DocumentMessage::Navigation(message) => {
|
||||
let context = NavigationMessageContext {
|
||||
environment,
|
||||
network_interface: &mut self.network_interface,
|
||||
breadcrumb_network_path: &self.breadcrumb_network_path,
|
||||
ipp,
|
||||
@@ -319,6 +327,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
inspector_collapsed_sections: &mut self.inspector_collapsed_sections,
|
||||
inspector_expanded_input_chains: &mut self.inspector_expanded_input_chains,
|
||||
layers_panel_expanded_chains: &mut self.layers_panel_expanded_chains,
|
||||
layers_in_view: &mut self.layers_in_view,
|
||||
ipp,
|
||||
graph_view_overlay_open: self.graph_view_overlay_open,
|
||||
graph_fade_artwork_percentage: self.graph_fade_artwork_percentage,
|
||||
@@ -626,12 +635,23 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
|
||||
}
|
||||
DocumentMessage::Escape => {
|
||||
// The same Esc cancels the pan, tilt, or zoom drag through its own binding
|
||||
if self.navigation_handler.is_navigating() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Abort dragging nodes
|
||||
if self.node_graph_handler.drag_start.is_some() {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
self.node_graph_handler.drag_start = None;
|
||||
self.node_graph_handler.select_if_not_dragged = None;
|
||||
self.node_graph_handler.duplicated_in_drag = false;
|
||||
self.node_graph_handler.nodes_added_in_drag = false;
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
responses.add(NodeGraphMessage::UpdateWireInsertionPreview);
|
||||
}
|
||||
// Abort dragging a dot out of a connector, before the dot has appeared
|
||||
else if self.node_graph_handler.dot_drag_out.is_some() {
|
||||
self.node_graph_handler.dot_drag_out = None;
|
||||
}
|
||||
// Abort box selection
|
||||
else if self.node_graph_handler.box_selection_start.is_some() {
|
||||
@@ -755,6 +775,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(ToolMessage::ActivateTool { tool_type: *current_tool });
|
||||
responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed
|
||||
|
||||
self.layers_in_view.set_node_graph(HashSet::new(), responses);
|
||||
}
|
||||
}
|
||||
DocumentMessage::GraphViewOverlayToggle => {
|
||||
@@ -886,6 +908,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::PasteChainNodes { copies } => {
|
||||
// A chain wires its nodes straight to one another, so the dots bending the wires between the copies only come along to a loose paste
|
||||
let (dot_copies, copies): (Vec<_>, Vec<_>) = copies.into_iter().partition(ChainNodeCopy::is_redirect_dot);
|
||||
|
||||
// Layers and their chains live in the document network, so a nested one open in the graph has no chain to paste into
|
||||
let (chain_nodes, layers) = if self.selection_network_path.is_empty() {
|
||||
let layers = self.network_interface.selected_nodes().selected_layers(self.metadata()).map(|layer| layer.to_node()).collect();
|
||||
@@ -909,9 +934,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
// Each selected layer gets all the copies at the end of its chain
|
||||
insertions.extend(layers.into_iter().map(|layer| (ChainInsertionPoint::BesideLayer(layer), copies.clone())));
|
||||
|
||||
// With no chain to go in, such as over an empty selection, the copies are pasted loose into the graph and shown there
|
||||
// With no chain to go in, such as over an empty selection, the copies are pasted loose into the graph and shown there, still wired to one another
|
||||
if insertions.is_empty() {
|
||||
let nodes = copies.into_iter().map(|copy| (copy.source, copy.into_loose_template())).collect();
|
||||
let pasted = copies.iter().chain(&dot_copies).map(|copy| copy.source).collect::<HashSet<_>>();
|
||||
let nodes = copies.into_iter().chain(dot_copies).map(|copy| (copy.source, copy.into_loose_template(&pasted))).collect();
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
responses.add(DocumentMessage::ShowSelectionInGraph);
|
||||
return;
|
||||
@@ -1485,6 +1511,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.graph_fade_artwork_percentage = percentage;
|
||||
responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage });
|
||||
}
|
||||
DocumentMessage::SetLayerNameInGraph { node_id, name } => {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path: self.breadcrumb_network_path.clone(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
});
|
||||
}
|
||||
DocumentMessage::SetLayersPanelHoveredLayer { id } => {
|
||||
let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked);
|
||||
if layer != self.layers_panel_hovered_layer {
|
||||
@@ -1492,6 +1526,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
}
|
||||
DocumentMessage::SetLayersPanelView { layers, layers_missing_details } => {
|
||||
self.layers_in_view.set_layers_panel(layers.into_iter().collect(), responses);
|
||||
if !layers_missing_details.is_empty() {
|
||||
responses.add(NodeGraphMessage::SendLayerPanelDetails { layers: layers_missing_details });
|
||||
}
|
||||
}
|
||||
DocumentMessage::SetNodePinned { node_id, pinned } => {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
|
||||
@@ -1715,6 +1755,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateLayerPanel);
|
||||
responses.add(DocumentMessage::DocumentStructureChanged);
|
||||
}
|
||||
DocumentMessage::ToggleNodeVisibility { node_id } => {
|
||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: self.selection_network_path.clone(),
|
||||
});
|
||||
}
|
||||
DocumentMessage::ToggleSelectedLocked => responses.add(NodeGraphMessage::ToggleSelectedLocked),
|
||||
DocumentMessage::ToggleSelectedVisibility => {
|
||||
@@ -1933,6 +1980,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(NodeGraphMessage::UpdateBoxSelection);
|
||||
responses.add(NodeGraphMessage::UpdateHoveredConnector);
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
|
||||
responses.add(FrontendMessage::UpdateNodeGraphTransform {
|
||||
@@ -2589,11 +2637,21 @@ impl DocumentMessageHandler {
|
||||
false
|
||||
};
|
||||
|
||||
let chain_rows = if self.layers_panel_expanded_chains.contains(&layer_id) {
|
||||
self.network_interface.layer_chain_nodes(layer_id, &[]).len() as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
LayerStructureEntry {
|
||||
layer_id,
|
||||
children,
|
||||
children_present,
|
||||
descendant_selected,
|
||||
selected: selected_layers.contains(&layer_id),
|
||||
visible: self.network_interface.is_visible(&layer_id, &[]),
|
||||
unlocked: !self.network_interface.is_locked(&layer_id, &[]),
|
||||
chain_rows,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2768,6 +2826,8 @@ impl DocumentMessageHandler {
|
||||
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let network_interface = self.history.pop_undo()?;
|
||||
// Settled first, so the interface stored for redo keeps none of the offsets of a glide underway
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
let previous_network = self.install_history_snapshot(network_interface, viewport);
|
||||
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
@@ -2794,6 +2854,8 @@ impl DocumentMessageHandler {
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let network_interface = self.history.pop_redo()?;
|
||||
// Settled first, as when undoing
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
let previous_network = self.install_history_snapshot(network_interface, viewport);
|
||||
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
@@ -2879,6 +2941,8 @@ impl DocumentMessageHandler {
|
||||
pub fn partition_selection(&self) -> SelectionParts {
|
||||
let selected_nodes = self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path).unwrap_or_default();
|
||||
let selected_nodes = selected_nodes.selected_nodes().copied().collect::<Vec<_>>();
|
||||
// Redirect dots are part of their wires, so they are copied only along with the nodes they connect
|
||||
let selected_nodes = self.network_interface.selection_with_bridging_dots(selected_nodes, &self.selection_network_path);
|
||||
if !self.selection_network_path.is_empty() {
|
||||
return SelectionParts {
|
||||
layers: Vec::new(),
|
||||
@@ -2902,6 +2966,9 @@ impl DocumentMessageHandler {
|
||||
|
||||
chain_nodes = self.selected_reorderable_chain_nodes().into_iter().filter(|node_id| other_nodes.contains(node_id)).collect();
|
||||
other_nodes.retain(|node_id| !chain_nodes.contains(node_id));
|
||||
|
||||
// Dots leading to a layer or chain node are dropped, since those nodes go separately
|
||||
other_nodes = self.network_interface.selection_with_bridging_dots(other_nodes, &[]);
|
||||
}
|
||||
|
||||
SelectionParts { layers, chain_nodes, other_nodes }
|
||||
@@ -3807,7 +3874,7 @@ impl DocumentMessageHandler {
|
||||
});
|
||||
|
||||
let mut node_chooser = NodeCatalog::new();
|
||||
node_chooser.intial_search = compatible_type.unwrap_or("".to_string());
|
||||
node_chooser.initial_search = compatible_type.unwrap_or("".to_string());
|
||||
|
||||
let node_chooser = node_chooser
|
||||
.on_update(move |node_type| {
|
||||
@@ -4317,6 +4384,7 @@ fn deserialize_collapsed_layers<'de, D: serde::Deserializer<'de>>(deserializer:
|
||||
mod document_message_handler_tests {
|
||||
use super::*;
|
||||
use crate::consts::{BIG_NUDGE_AMOUNT, NUDGE_AMOUNT};
|
||||
use crate::messages::frontend::utility_types::RenderStatus;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GridType;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
@@ -4557,8 +4625,8 @@ mod document_message_handler_tests {
|
||||
.unwrap();
|
||||
editor.runtime.run().await;
|
||||
|
||||
let mut messages = VecDeque::new();
|
||||
editor.editor.poll_node_graph_evaluation(&mut messages).unwrap();
|
||||
let frontend_messages = editor.editor.handle_message(Message::Wake);
|
||||
assert!(!frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -147,8 +147,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
|
||||
pub fn insert_vector(&mut self, bezpath: BezPath, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
|
||||
let vector = Vector::from_bezpath(bezpath);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
let (vector, paths) = Vector::from_bezpath(&bezpath);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector, &paths));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
.expect("Path node does not exist")
|
||||
@@ -247,14 +247,15 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
/// Clear the whole-expanse paint one tool left on a layer so the other can start its own chain there.
|
||||
/// Severing at the attachment detaches the layer from whatever the walk stopped at, which is the only part a node
|
||||
/// the rest of the graph also draws from is subjected to, since such a node is never among those deleted.
|
||||
/// Severing at the attachment detaches the layer from the old chain, which is all that a node the rest of
|
||||
/// the graph also draws from is subjected to, since such a node is never among those deleted.
|
||||
fn clear_paint_chain(&mut self, paint_chain: &ReplaceablePaintChain) {
|
||||
self.network_interface.disconnect_input(&paint_chain.attachment_input, &[]);
|
||||
|
||||
if !paint_chain.nodes.is_empty() {
|
||||
self.network_interface.delete_nodes(paint_chain.nodes.clone(), false, &[]);
|
||||
}
|
||||
self.network_interface.remove_orphaned_dots(&[]);
|
||||
}
|
||||
|
||||
/// Wire a node that paints the layer's whole expanse into the start of its chain,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::Editor;
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
@@ -16,6 +16,7 @@ use graph_craft::document::NodeId;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct NavigationMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub network_interface: &'a mut NodeNetworkInterface,
|
||||
pub breadcrumb_network_path: &'a [NodeId],
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
@@ -39,6 +40,7 @@ pub struct NavigationMessageHandler {
|
||||
impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for NavigationMessageHandler {
|
||||
fn process_message(&mut self, message: NavigationMessage, responses: &mut VecDeque<Message>, context: NavigationMessageContext) {
|
||||
let NavigationMessageContext {
|
||||
environment,
|
||||
network_interface,
|
||||
breadcrumb_network_path,
|
||||
ipp,
|
||||
@@ -189,7 +191,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
NavigationMessage::CanvasPanMouseWheel { use_y_as_x, .. } => {
|
||||
// On Mac, the OS already converts Shift+scroll into horizontal scrolling
|
||||
let delta = if use_y_as_x && !Editor::environment().is_mac() {
|
||||
let delta = if use_y_as_x && !environment.is_mac() {
|
||||
(ipp.mouse.scroll_delta.y, 0.).into()
|
||||
} else {
|
||||
ipp.mouse.scroll_delta.as_dvec2()
|
||||
@@ -529,6 +531,11 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
|
||||
impl NavigationMessageHandler {
|
||||
/// Whether a pan, tilt, or zoom drag is in progress.
|
||||
pub fn is_navigating(&self) -> bool {
|
||||
self.navigation_operation != NavigationOperation::None
|
||||
}
|
||||
|
||||
pub fn snapped_tilt(&self, tilt: f64) -> f64 {
|
||||
let increment_radians: f64 = VIEWPORT_ROTATE_SNAP_INTERVAL.to_radians();
|
||||
if matches!(self.navigation_operation, NavigationOperation::Tilt { snap: true, .. }) {
|
||||
|
||||
@@ -1001,14 +1001,13 @@ fn static_input_inspector() -> InputInspector {
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let node_metadata = registry::NODE_METADATA.lock().unwrap();
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| node_metadata.get(proto_node_identifier))
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
@@ -1531,8 +1530,8 @@ 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.
|
||||
/// Check if a type reaches the constraint through any `input_adapter`, which converts or embeds a convertible element (such as a color literal feeding a
|
||||
/// `Graphic` paint wire) ahead of an input registered with one ranked type. Whether this input is one that gets an adapter isn't checked.
|
||||
#[must_use]
|
||||
fn satisfies_through_input_adapter(&self, ty: &Type) -> bool {
|
||||
let provided = Self::type_name(ty);
|
||||
@@ -1620,7 +1619,8 @@ impl InputTypeConstraint {
|
||||
pub fn collect_node_types() -> Vec<FrontendNodeType> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.filter(|(_, definition)| !registry::is_hidden_category(definition.category))
|
||||
// A Passthrough is placed as a redirect dot on a wire, so it isn't offered as a node
|
||||
.filter(|(identifier, definition)| !registry::is_hidden_category(definition.category) && **identifier != DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER))
|
||||
.map(|(identifier, definition)| {
|
||||
let mut name = definition.node_template.display_name.clone();
|
||||
if name.is_empty() {
|
||||
@@ -1722,6 +1722,19 @@ mod test {
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
}
|
||||
|
||||
// Guards the `optional_f64` widget override against holding the node metadata lock while building rows that lock it again
|
||||
#[tokio::test]
|
||||
async fn optional_f64_inspector_row_builds() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let node_id = editor
|
||||
.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::qr_code::IDENTIFIER))
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
|
||||
editor.handle_message(InspectorMessage::Refresh).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
-2
@@ -42,7 +42,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
fields,
|
||||
description,
|
||||
inspector,
|
||||
context_features,
|
||||
output_fields,
|
||||
..
|
||||
} = metadata;
|
||||
@@ -90,7 +89,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
context_features: ContextDependencies::from(context_features.as_slice()),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::utility_types::Direction;
|
||||
use super::utility_types::{Direction, NodeEvaluationError};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -25,10 +25,6 @@ pub enum NodeGraphMessage {
|
||||
import_index: usize,
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
/// Inserts a Passthrough node beside the import that takes over the wires it fed, so nodes can be placed in front of all of them at once.
|
||||
AddImportPassthrough {
|
||||
import_index: usize,
|
||||
},
|
||||
AddExport,
|
||||
AddPrimaryExport,
|
||||
AddSecondaryExport,
|
||||
@@ -53,6 +49,11 @@ pub enum NodeGraphMessage {
|
||||
output_connector: OutputConnector,
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
/// Wires an output into several inputs together, so the exports among them share one redirect dot if the output is an import.
|
||||
CreateWires {
|
||||
output_connector: OutputConnector,
|
||||
input_connectors: Vec<InputConnector>,
|
||||
},
|
||||
ConnectUpstreamOutputToInput {
|
||||
downstream_input: InputConnector,
|
||||
input_connector: InputConnector,
|
||||
@@ -65,6 +66,8 @@ pub enum NodeGraphMessage {
|
||||
DeleteSelectedNodes {
|
||||
delete_children: bool,
|
||||
},
|
||||
/// Removes each redirect dot that the preceding operation left without a wire.
|
||||
RemoveOrphanedDots,
|
||||
DisconnectInput {
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
@@ -102,6 +105,20 @@ pub enum NodeGraphMessage {
|
||||
input_connector: InputConnector,
|
||||
insert_node_input_index: usize,
|
||||
},
|
||||
/// Splits the wire feeding an input with a new redirect dot centered on a grid point.
|
||||
InsertDotOnWire {
|
||||
node_id: NodeId,
|
||||
input_connector: InputConnector,
|
||||
x: i32,
|
||||
y: i32,
|
||||
},
|
||||
/// Runs the wires leaving an output through a new redirect dot centered on a grid point, so they fan out from the dot instead.
|
||||
InsertDotOnOutput {
|
||||
node_id: NodeId,
|
||||
output_connector: OutputConnector,
|
||||
x: i32,
|
||||
y: i32,
|
||||
},
|
||||
MergeSelectedNodes,
|
||||
MoveLayerToStack {
|
||||
layer: LayerNodeIdentifier,
|
||||
@@ -154,6 +171,10 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||
SendGlide,
|
||||
/// Sent every frame while nodes glide into their grid cells, to bring them closer.
|
||||
GlideTick,
|
||||
ShakeNode,
|
||||
UpdateNodeGraphWidth,
|
||||
RemoveImport {
|
||||
@@ -227,13 +248,21 @@ pub enum NodeGraphMessage {
|
||||
x: i32,
|
||||
y: i32,
|
||||
},
|
||||
/// Moves the selected nodes one grid cell with the arrow keys, as an undo step of its own.
|
||||
NudgeSelectedNodes {
|
||||
direction: Direction,
|
||||
},
|
||||
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
|
||||
ShiftSelectedNodes {
|
||||
direction: Direction,
|
||||
rubber_band: bool,
|
||||
glide: bool,
|
||||
},
|
||||
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
|
||||
ShiftSelectedNodesByAmount {
|
||||
graph_delta: IVec2,
|
||||
rubber_band: bool,
|
||||
glide: bool,
|
||||
},
|
||||
TogglePreview {
|
||||
node_id: NodeId,
|
||||
@@ -292,8 +321,17 @@ pub enum NodeGraphMessage {
|
||||
network_path: Vec<NodeId>,
|
||||
},
|
||||
UpdateBoxSelection,
|
||||
/// Shows hovered the connector a press at the pointer would grab, or none.
|
||||
UpdateHoveredConnector,
|
||||
/// Highlights the wire a dragged node would be inserted onto if dropped where it is, or stops highlighting one.
|
||||
UpdateWireInsertionPreview,
|
||||
UpdateImportsExports,
|
||||
/// Sends the Layers panel the details of every layer it has a row in view for.
|
||||
UpdateLayerPanel,
|
||||
/// Sends the Layers panel the details of the given layers.
|
||||
SendLayerPanelDetails {
|
||||
layers: Vec<NodeId>,
|
||||
},
|
||||
UpdateNewNodeGraph,
|
||||
UpdateTypes {
|
||||
#[serde(skip)]
|
||||
@@ -301,6 +339,9 @@ pub enum NodeGraphMessage {
|
||||
#[serde(skip)]
|
||||
node_graph_errors: GraphErrors,
|
||||
},
|
||||
UpdateEvaluationErrors {
|
||||
errors: Vec<NodeEvaluationError>,
|
||||
},
|
||||
UpdateActionButtons,
|
||||
UpdateGraphBarRight,
|
||||
UpdateInSelectedNetwork,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -33,7 +33,7 @@ use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
@@ -137,6 +137,10 @@ pub(crate) fn input_chain(node_id: NodeId, input_index: usize, network_interface
|
||||
if network_interface.is_layer(&chain_node_id, network_path) {
|
||||
return Some((chain, Some(chain_node_id)));
|
||||
}
|
||||
// A redirect dot only bends a wire, so it gets no section, but the chain carries on through it
|
||||
if network_interface.is_redirect_dot(&chain_node_id, network_path) {
|
||||
continue;
|
||||
}
|
||||
chain.push(chain_node_id);
|
||||
}
|
||||
|
||||
@@ -426,7 +430,8 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<WeldMethod>(x) => enum_choice::<WeldMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<UnweldMethod>(x) => enum_choice::<UnweldMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
@@ -448,7 +453,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
},
|
||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||
Type::Fn(_, out) => return inspector_row_from_type(node_id, index, out, options, context),
|
||||
Type::Future(out) => return inspector_row_from_type(node_id, index, out, options, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -3087,15 +3091,6 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn node_no_inspector_content(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
let text = if context.network_interface.is_layer(&node_id, context.selection_network_path) {
|
||||
"Layer has no parameters"
|
||||
} else {
|
||||
"Node has no parameters"
|
||||
};
|
||||
string_inspector(text)
|
||||
}
|
||||
|
||||
pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> LayoutGroup {
|
||||
let mut layout = Vec::new();
|
||||
|
||||
@@ -3184,10 +3179,6 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
}
|
||||
|
||||
if layout.is_empty() {
|
||||
layout = node_no_inspector_content(node_id, context);
|
||||
}
|
||||
|
||||
let display_name = context
|
||||
.network_interface
|
||||
.node_metadata(&node_id, context.selection_network_path)
|
||||
@@ -3238,16 +3229,12 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
// That layer is only referred to, as in the Data panel, rather than shown with its own parameters and chain
|
||||
if let Some(layer) = stack_layer {
|
||||
let button = node_reference_button(layer, context.network_interface, network_path, network_path, move || {
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }.into()
|
||||
});
|
||||
let name = context.network_interface.display_name(&layer, network_path);
|
||||
let visible = context.network_interface.is_visible(&layer, network_path);
|
||||
|
||||
let mut reference_section = LayoutGroup::section(name, None, "", visible, false, true, layer.0, Layout(vec![LayoutGroup::row(vec![button])]));
|
||||
let feeds_content = input_index == LAYER_SECONDARY_INPUT_INDEX && context.network_interface.is_layer(&node_id, network_path);
|
||||
let tooltip_label = if feeds_content { "Select Child Layer" } else { "Select Layer" };
|
||||
if let Some(layer) = stack_layer
|
||||
&& let Some(mut reference_section) = layer_references_section(&[layer], tooltip_label, context)
|
||||
{
|
||||
if let LayoutGroup::NodeSection(section) = &mut reference_section {
|
||||
section.node_reference = true;
|
||||
section.output_wire = Some(output_section_wire(layer, context));
|
||||
}
|
||||
|
||||
@@ -3262,8 +3249,35 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
section
|
||||
}
|
||||
|
||||
/// A section only referring to layers, as the Data panel does, with a row of buttons that each select one rather than showing its parameters and chain.
|
||||
/// Their tooltip label names how the layers relate to the section they're shown beside.
|
||||
pub(crate) fn layer_references_section(layers: &[NodeId], tooltip_label: &str, context: &NodeInspectorContext) -> Option<LayoutGroup> {
|
||||
let network_path = context.selection_network_path;
|
||||
let &first_layer = layers.first()?;
|
||||
|
||||
let mut buttons = Vec::with_capacity(layers.len() * 2);
|
||||
for &layer in layers {
|
||||
if !buttons.is_empty() {
|
||||
buttons.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
}
|
||||
let button = node_reference_button(layer, context.network_interface, network_path, network_path, move || {
|
||||
NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }.into()
|
||||
});
|
||||
buttons.push(button.tooltip_label(tooltip_label).widget_instance());
|
||||
}
|
||||
|
||||
let name = context.network_interface.display_name(&first_layer, network_path);
|
||||
let visible = context.network_interface.is_visible(&first_layer, network_path);
|
||||
|
||||
let mut section = LayoutGroup::section(name, None, "", visible, false, true, first_layer.0, Layout(vec![LayoutGroup::row(buttons)]));
|
||||
if let LayoutGroup::NodeSection(node_section) = &mut section {
|
||||
node_section.node_reference = true;
|
||||
}
|
||||
Some(section)
|
||||
}
|
||||
|
||||
/// The wire drawn up from a node's section in a chain to the section above, which its output feeds.
|
||||
fn output_section_wire(node_id: NodeId, context: &NodeInspectorContext) -> SectionWire {
|
||||
pub(crate) fn output_section_wire(node_id: NodeId, context: &NodeInspectorContext) -> SectionWire {
|
||||
let output_type = context.network_interface.output_type(&OutputConnector::node(node_id, 0), context.selection_network_path);
|
||||
|
||||
SectionWire {
|
||||
@@ -3867,8 +3881,8 @@ mod tests {
|
||||
#[test]
|
||||
fn wire_element_reads_every_spelling_down_to_the_element() {
|
||||
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
|
||||
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
|
||||
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
|
||||
let row = Type::Fn(Box::new(concrete!(())), Box::new(item!(f64)));
|
||||
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(list!(f64)));
|
||||
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
|
||||
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
|
||||
}
|
||||
|
||||
@@ -79,6 +79,9 @@ pub struct FrontendNode {
|
||||
pub is_layer: bool,
|
||||
#[serde(rename = "canBeLayer")]
|
||||
pub can_be_layer: bool,
|
||||
/// Whether the node is a redirect dot, which is a Passthrough node drawn as a small dot bending the wire running through it.
|
||||
#[serde(rename = "isRedirectDot")]
|
||||
pub is_redirect_dot: bool,
|
||||
pub reference: Option<String>,
|
||||
#[serde(rename = "displayName")]
|
||||
pub display_name: String,
|
||||
@@ -189,10 +192,19 @@ pub struct ContextMenuInformation {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeGraphErrorDiagnostic {
|
||||
/// The node the error is shown beside, which it follows as the node glides into place.
|
||||
#[serde(rename = "nodeId")]
|
||||
pub node_id: NodeId,
|
||||
pub position: (i32, i32),
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeEvaluationError {
|
||||
pub node_path: Vec<NodeId>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendClickTargets {
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::messages::tool::common_functionality::utility_functions::closest_open
|
||||
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorGeometry};
|
||||
use kurbo::{Affine, ParamCurve, PathSeg};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(target_family = "wasm")]
|
||||
@@ -44,7 +44,7 @@ pub fn selected_segments(network_interface: &NodeNetworkInterface, shape_editor:
|
||||
map
|
||||
}
|
||||
|
||||
pub fn selected_segments_for_layer(vector: &Vector, state: &SelectedLayerState) -> Vec<SegmentId> {
|
||||
pub fn selected_segments_for_layer(vector: &VectorGeometry, state: &SelectedLayerState) -> Vec<SegmentId> {
|
||||
let selected_anchors = state
|
||||
.selected_points()
|
||||
.filter_map(|point| if let ManipulatorPointId::Anchor(p) = point { Some(p) } else { None })
|
||||
@@ -195,7 +195,7 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
|
||||
}
|
||||
|
||||
if display_anchors {
|
||||
for (&id, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) {
|
||||
for (id, position) in vector.anchors() {
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(ManipulatorPointId::Anchor(id)), None);
|
||||
}
|
||||
}
|
||||
@@ -226,7 +226,7 @@ pub fn open_path_endpoint_overlays(document: &DocumentMessageHandler, shape_edit
|
||||
if hovered.is_some_and(|(hovered_layer, hovered_id, _)| hovered_layer == layer && hovered_id == id) {
|
||||
continue;
|
||||
}
|
||||
let Some(position) = vector.point_domain.position_from_id(id) else { continue };
|
||||
let Some(position) = vector.position_from_id(id) else { continue };
|
||||
|
||||
overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(layer, id), None);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ use graphene_std::math::quad::Quad;
|
||||
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, paths_from_list_row_attributes};
|
||||
use kurbo::{self, BezPath, ParamCurve};
|
||||
use kurbo::{Affine, PathSeg};
|
||||
use std::collections::HashMap;
|
||||
@@ -379,7 +379,7 @@ impl OverlayContext {
|
||||
}
|
||||
|
||||
/// Used by the Pen and Path tools to outline the path of the shape.
|
||||
pub fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) {
|
||||
pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) {
|
||||
self.internal().outline_vector(vector, transform);
|
||||
}
|
||||
|
||||
@@ -930,7 +930,7 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
/// Used by the Pen and Path tools to outline the path of the shape.
|
||||
fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) {
|
||||
fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) {
|
||||
let vello_transform = self.get_transform();
|
||||
let mut path = BezPath::new();
|
||||
|
||||
@@ -1148,7 +1148,8 @@ impl OverlayContextInternal {
|
||||
let transform: DAffine2 = text_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
|
||||
let Some(element) = text_list.element(index) else { continue };
|
||||
for (_, bezier, start_id, end_id) in element.segment_iter() {
|
||||
let paths = paths_from_list_row_attributes(text_list, index).unwrap_or_else(|| no_paths());
|
||||
for (_, bezier, start_id, end_id) in element.segment_iter(paths) {
|
||||
let move_to = last_point != Some(start_id);
|
||||
last_point = Some(end_id);
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ use glam::{DAffine2, DVec2};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorGeometry};
|
||||
use kurbo::{self, Affine, BezPath, CubicBez, ParamCurve, PathSeg};
|
||||
use std::collections::HashMap;
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
@@ -854,7 +854,7 @@ impl OverlayContext {
|
||||
}
|
||||
|
||||
/// Used by the Pen and Path tools to outline the path of the shape.
|
||||
pub fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) {
|
||||
pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) {
|
||||
self.start_dpi_aware_transform();
|
||||
|
||||
self.render_context.begin_path();
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::test_utils::EditorTestUtils;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
|
||||
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
editor.editor.handle_message(message)
|
||||
editor.dispatch(message)
|
||||
}
|
||||
|
||||
fn portfolio(editor: &EditorTestUtils) -> &PortfolioMessageHandler {
|
||||
|
||||
@@ -716,6 +716,57 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
|
||||
/// Manual edits ride a saved document as a folded `VectorModification`, so opening the artworks carrying the most
|
||||
/// of them is what proves the stored format still reads and applies. Their Path nodes sit on pen-drawn layers, so
|
||||
/// each layer's geometry, curves included, comes from its stored modification alone.
|
||||
#[tokio::test]
|
||||
async fn demo_artwork_vector_modifications_still_apply() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
for name in ["red-dress", "isometric-fountain", "valley-of-spires"] {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
let data = std::fs::read(format!("../demo-artwork/{name}.graphite")).expect("read demo artwork");
|
||||
editor
|
||||
.handle_message(IngestMessage::Ingest {
|
||||
data,
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some(format!("{name}.graphite").into()),
|
||||
})
|
||||
.await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let network = &document.network_interface;
|
||||
let path_definition = DefinitionIdentifier::Network("Path".into());
|
||||
let mut path_layers = 0;
|
||||
let mut any_curve = false;
|
||||
|
||||
for layer in document.metadata().all_layers() {
|
||||
let Some(path_node) = NodeGraphLayer::new(layer, network).upstream_visible_node_id_from_name_in_layer(&path_definition) else {
|
||||
continue;
|
||||
};
|
||||
path_layers += 1;
|
||||
|
||||
let stored = network.document_network().nodes.get(&path_node).and_then(|node| node.inputs.get(1)).and_then(|input| input.as_value());
|
||||
let Some(TaggedValue::VectorModification(modification)) = stored else {
|
||||
panic!("{name} layer {layer:?} has a Path node without a stored modification");
|
||||
};
|
||||
assert!(!modification.is_empty(), "{name} layer {layer:?} stored a modification that changes nothing");
|
||||
|
||||
let upstream = document.metadata().vector_modify.get(&path_node).expect("the graph run should capture what reaches the Path node");
|
||||
assert!(upstream.anchor_points().next().is_none(), "{name} layer {layer:?} has geometry upstream of its Path node");
|
||||
|
||||
let geometry = network.compute_modified_vector(layer).expect("a layer with a Path node should have a vector");
|
||||
assert!(geometry.anchor_points().next().is_some(), "{name} layer {layer:?} surfaced no anchors from its stored modification");
|
||||
any_curve |= geometry.segment_iter().any(|(_, segment, ..)| !matches!(segment, kurbo::PathSeg::Line(_)));
|
||||
}
|
||||
|
||||
assert!(path_layers > 0, "{name} has no layers edited through a Path node");
|
||||
assert!(any_curve, "{name} drew no curves from its stored modifications");
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's single Fill node, as `(network_path, node_id)`.
|
||||
fn find_fill_node(document: &DocumentMessageHandler) -> (Vec<graph_craft::document::NodeId>, graph_craft::document::NodeId) {
|
||||
node_paths(&document.network_interface)
|
||||
|
||||
@@ -7,10 +7,11 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::{Vector, VectorGeometry, no_paths, paths_from_item_attributes};
|
||||
use kurbo::BezPath;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::num::NonZeroU64;
|
||||
@@ -37,10 +38,10 @@ pub struct DocumentMetadata {
|
||||
/// The Text tool composes this with `transform_to_viewport(layer)` to position its drag cage.
|
||||
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_modify: HashMap<NodeId, Vector>,
|
||||
pub vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// Transform from document space to viewport space.
|
||||
@@ -243,13 +244,14 @@ impl DocumentMetadata {
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based
|
||||
/// bounds for non-vector layers (groups, raster, text, color, gradient).
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
if let Some(vector) = self.layer_vector_data.get(&layer) {
|
||||
if let Some(item) = self.layer_vector_data.get(&layer) {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
.get(&layer)
|
||||
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
|
||||
.map(graphene_std::Coverage::stroke_params);
|
||||
if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) {
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
if let Some(bounds) = item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref()) {
|
||||
return Some(bounds);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// The layers the frontend shows in view, as rows of the Layers panel and as nodes in the node graph, which are the only ones it's sent the thumbnails of.
|
||||
/// The latest thumbnail of every layer waits here for whenever the layer comes into view.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LayersInView {
|
||||
/// The layers with a row in view in the Layers panel, which is also sent their details.
|
||||
layers_panel: HashSet<NodeId>,
|
||||
/// The nodes in view in the node graph while it's open.
|
||||
node_graph: HashSet<NodeId>,
|
||||
/// The latest thumbnail of each layer, as rendered by the graph runtime.
|
||||
thumbnails: HashMap<NodeId, String>,
|
||||
/// The layers whose latest thumbnail the frontend has.
|
||||
thumbnails_sent: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
impl LayersInView {
|
||||
pub fn layers_panel(&self) -> &HashSet<NodeId> {
|
||||
&self.layers_panel
|
||||
}
|
||||
|
||||
/// Sets the layers with a row in view in the Layers panel, sending the thumbnails it lacks for them.
|
||||
pub fn set_layers_panel(&mut self, layers: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
|
||||
self.layers_panel = layers;
|
||||
self.send_thumbnails_in_view(responses);
|
||||
}
|
||||
|
||||
/// Sets the nodes in view in the node graph, sending the thumbnails it lacks for those that are layers.
|
||||
pub fn set_node_graph(&mut self, nodes: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph = nodes;
|
||||
self.send_thumbnails_in_view(responses);
|
||||
}
|
||||
|
||||
/// Keeps a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view.
|
||||
pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: String, responses: &mut VecDeque<Message>) {
|
||||
if self.in_view(&layer) {
|
||||
responses.add(FrontendMessage::UpdateNodeThumbnail { id: layer, value: thumbnail.clone() });
|
||||
self.thumbnails_sent.insert(layer);
|
||||
} else {
|
||||
// Out of view, the frontend's copy is now stale until the layer comes back into view
|
||||
self.thumbnails_sent.remove(&layer);
|
||||
}
|
||||
|
||||
self.thumbnails.insert(layer, thumbnail);
|
||||
}
|
||||
|
||||
/// Forgets the thumbnails the graph runtime dropped, which it renders anew for any layer that returns, and has the frontend drop its copies too.
|
||||
pub fn forget_thumbnails(&mut self, layers: &[NodeId], responses: &mut VecDeque<Message>) {
|
||||
// Only this document's, since the frontend keeps a background document's copies for switching back
|
||||
let ids = layers.iter().copied().filter(|layer| self.thumbnails.contains_key(layer)).collect::<Vec<_>>();
|
||||
self.forget_thumbnails_in_background(&ids);
|
||||
|
||||
if !ids.is_empty() {
|
||||
responses.add(FrontendMessage::ClearNodeThumbnails { ids });
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the thumbnails the graph runtime dropped while this document is in the background, leaving the frontend its copies for when it's active again.
|
||||
pub fn forget_thumbnails_in_background(&mut self, layers: &[NodeId]) {
|
||||
for layer in layers {
|
||||
self.thumbnails.remove(layer);
|
||||
self.thumbnails_sent.remove(layer);
|
||||
}
|
||||
}
|
||||
|
||||
fn in_view(&self, layer: &NodeId) -> bool {
|
||||
self.layers_panel.contains(layer) || self.node_graph.contains(layer)
|
||||
}
|
||||
|
||||
// O(layers in view)
|
||||
fn send_thumbnails_in_view(&mut self, responses: &mut VecDeque<Message>) {
|
||||
for &layer in self.layers_panel.iter().chain(&self.node_graph) {
|
||||
if self.thumbnails_sent.contains(&layer) {
|
||||
continue;
|
||||
}
|
||||
let Some(thumbnail) = self.thumbnails.get(&layer) else { continue };
|
||||
|
||||
responses.add(FrontendMessage::UpdateNodeThumbnail { id: layer, value: thumbnail.clone() });
|
||||
self.thumbnails_sent.insert(layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn thumbnails_sent(responses: VecDeque<Message>) -> Vec<(NodeId, String)> {
|
||||
responses
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Frontend(FrontendMessage::UpdateNodeThumbnail { id, value }) => Some((id, value)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thumbnail_waits_until_its_layer_comes_into_view() {
|
||||
let (layer, other) = (NodeId(1), NodeId(2));
|
||||
let mut layers_in_view = LayersInView::default();
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.receive_thumbnail(layer, "first".to_string(), &mut responses);
|
||||
layers_in_view.receive_thumbnail(layer, "latest".to_string(), &mut responses);
|
||||
assert!(thumbnails_sent(responses).is_empty(), "out of view, a thumbnail isn't sent");
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_layers_panel(HashSet::from([layer, other]), &mut responses);
|
||||
assert_eq!(thumbnails_sent(responses), vec![(layer, "latest".to_string())], "coming into view, only the latest thumbnail is sent");
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_node_graph(HashSet::from([layer]), &mut responses);
|
||||
assert!(thumbnails_sent(responses).is_empty(), "a thumbnail the frontend already has isn't sent again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thumbnail_changed_out_of_view_is_sent_once_back_in_view() {
|
||||
let layer = NodeId(1);
|
||||
let mut layers_in_view = LayersInView::default();
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
|
||||
layers_in_view.receive_thumbnail(layer, "in view".to_string(), &mut responses);
|
||||
assert_eq!(thumbnails_sent(responses), vec![(layer, "in view".to_string())], "in view, a thumbnail is sent as it's received");
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_layers_panel(HashSet::new(), &mut responses);
|
||||
layers_in_view.receive_thumbnail(layer, "changed".to_string(), &mut responses);
|
||||
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
|
||||
assert_eq!(thumbnails_sent(responses), vec![(layer, "changed".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thumbnail_the_runtime_dropped_is_forgotten_until_rendered_again() {
|
||||
let (layer, other_documents_layer) = (NodeId(1), NodeId(2));
|
||||
let mut layers_in_view = LayersInView::default();
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
|
||||
layers_in_view.receive_thumbnail(layer, "before".to_string(), &mut responses);
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.forget_thumbnails(&[layer, other_documents_layer], &mut responses);
|
||||
let cleared = responses.into_iter().find_map(|message| match message {
|
||||
Message::Frontend(FrontendMessage::ClearNodeThumbnails { ids }) => Some(ids),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(cleared, Some(vec![layer]), "the frontend drops only this document's copies");
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_layers_panel(HashSet::new(), &mut responses);
|
||||
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
|
||||
assert!(thumbnails_sent(responses).is_empty(), "a forgotten thumbnail isn't sent again");
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.receive_thumbnail(layer, "after".to_string(), &mut responses);
|
||||
assert_eq!(thumbnails_sent(responses), vec![(layer, "after".to_string())], "rendered anew, it's sent as before");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod document_metadata;
|
||||
pub mod error;
|
||||
pub mod layers_in_view;
|
||||
pub mod misc;
|
||||
pub mod network_interface;
|
||||
pub mod nodes;
|
||||
|
||||
@@ -25,7 +25,6 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use resolved_types::type_feeds_connector;
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use template::*;
|
||||
@@ -39,7 +38,7 @@ use crate::consts::{
|
||||
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, HALF_GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH,
|
||||
STACK_VERTICAL_GAP,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{Direction, FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
@@ -53,7 +52,6 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::ContextDependencies;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::registry::MULTI_OUTPUT_NODES;
|
||||
use graphene_std::transform::Footprint;
|
||||
@@ -101,6 +99,10 @@ pub struct NodeNetworkInterface {
|
||||
/// Whether `transaction_edited_nodes` changed since `update_transaction_edited_nodes` last reported it.
|
||||
#[serde(skip)]
|
||||
transaction_edited_nodes_changed: bool,
|
||||
/// The redirect dots in each network that an edit took a wire from, and on which side, since `remove_orphaned_dots` last judged them there.
|
||||
/// Only these are judged, so a Passthrough left without a wire by anything other than an edit (like one a migration made from a removed node) is left in place.
|
||||
#[serde(skip)]
|
||||
dots_that_lost_a_wire: HashMap<Vec<NodeId>, HashSet<(NodeId, DotSide)>>,
|
||||
}
|
||||
|
||||
impl Clone for NodeNetworkInterface {
|
||||
@@ -115,6 +117,7 @@ impl Clone for NodeNetworkInterface {
|
||||
transaction_edited_nodes: HashSet::new(),
|
||||
transaction_edited_nodes_scanned: 0,
|
||||
transaction_edited_nodes_changed: false,
|
||||
dots_that_lost_a_wire: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,16 +73,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
|
||||
network_path,
|
||||
node_id,
|
||||
context_features,
|
||||
}) => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_context_features(*context_features);
|
||||
}
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
|
||||
if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.replace_metadata((**metadata).clone());
|
||||
|
||||
@@ -266,6 +266,20 @@ impl NodeNetworkInterface {
|
||||
*network_metadata.transient_metadata.drag_offsets.borrow_mut().entry(*node_id).or_insert(0) += delta;
|
||||
}
|
||||
|
||||
pub fn glide_offsets(&self, network_path: &[NodeId]) -> GlideOffsets {
|
||||
self.network_metadata(network_path)
|
||||
.map(|network_metadata| network_metadata.transient_metadata.glide_offsets.borrow().clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn set_glide_offsets(&self, glide_offsets: GlideOffsets, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in set_glide_offsets");
|
||||
return;
|
||||
};
|
||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||
}
|
||||
|
||||
/// Discards all drag offsets when the drag ends.
|
||||
pub fn clear_drag_offsets(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
@@ -382,9 +396,44 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
};
|
||||
transient.all_nodes_bounding_box.unload();
|
||||
transient.import_export_clearance.unload();
|
||||
self.unload_import_export_ports(network_path);
|
||||
}
|
||||
|
||||
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_clearance");
|
||||
return None;
|
||||
};
|
||||
|
||||
network_metadata
|
||||
.transient_metadata
|
||||
.import_export_clearance
|
||||
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
|
||||
}
|
||||
|
||||
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
|
||||
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
let mut clearance = ImportExportClearance::default();
|
||||
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
||||
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
let center = (top_left.x + bottom_right.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
|
||||
}
|
||||
}
|
||||
|
||||
Some(clearance)
|
||||
}
|
||||
|
||||
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
||||
self.load_outward_wires(network_path);
|
||||
|
||||
@@ -616,26 +665,32 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
|
||||
// While previewing, the export's wire leads to the temporarily previewed node
|
||||
let dashed = *input == InputConnector::Export(0) && matches!(self.previewing(network_path), Previewing::Yes { .. });
|
||||
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
|
||||
let Some(wire_update) = self.wire_update_from_input(input, graph_wire_style, &GlideOffsets::default(), network_path) else {
|
||||
log::error!("Could not load wire path from input");
|
||||
return;
|
||||
};
|
||||
let (id, input_index) = match input {
|
||||
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
|
||||
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
|
||||
};
|
||||
let wire_update = WirePathUpdate {
|
||||
id,
|
||||
input_index,
|
||||
wire_path_update: Some(wire),
|
||||
};
|
||||
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else { return };
|
||||
network_metadata.transient_metadata.wires.borrow_mut().insert(*input, wire_update);
|
||||
}
|
||||
|
||||
/// The wire into the input as the frontend draws it, with its ends following anything drawn gliding into place.
|
||||
pub fn wire_update_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
// While previewing, the export's wire leads to the temporarily previewed node
|
||||
let dashed = *input == InputConnector::Export(0) && matches!(self.previewing(network_path), Previewing::Yes { .. });
|
||||
let wire = self.wire_path_from_input(input, graph_wire_style, dashed, glide_offsets, network_path)?;
|
||||
let (id, input_index) = match input {
|
||||
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
|
||||
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
|
||||
};
|
||||
|
||||
Some(WirePathUpdate {
|
||||
id,
|
||||
input_index,
|
||||
wire_path_update: Some(wire),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn all_input_connectors(&self, network_path: &[NodeId]) -> Vec<InputConnector> {
|
||||
let mut input_connectors = Vec::new();
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
@@ -701,7 +756,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// When previewing, there may be a second path to the root node.
|
||||
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
let input = InputConnector::Export(0);
|
||||
let current_export = self.upstream_output_connector(&input, network_path)?;
|
||||
|
||||
@@ -717,11 +772,13 @@ impl NodeNetworkInterface {
|
||||
log::error!("Could not get input position for wire end in root node: {input:?}");
|
||||
return None;
|
||||
};
|
||||
let input_position = input_position + glide_offsets.input(&input);
|
||||
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
|
||||
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
|
||||
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
|
||||
return None;
|
||||
};
|
||||
let output_position = output_position + glide_offsets.output(&upstream_output);
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
@@ -752,10 +809,16 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
|
||||
pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
|
||||
self.gliding_vector_wire_from_input(input, wire_style, &GlideOffsets::default(), network_path)
|
||||
}
|
||||
|
||||
/// Like [`Self::vector_wire_from_input`], but with its ends following anything drawn gliding into place.
|
||||
pub(crate) fn gliding_vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
|
||||
let Some(input_position) = self.get_input_center(input, network_path) else {
|
||||
log::error!("Could not get dom rect for wire end: {input:?}");
|
||||
return None;
|
||||
};
|
||||
let input_position = input_position + glide_offsets.input(input);
|
||||
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector
|
||||
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
|
||||
return Some((BezPath::new(), BezPath::new(), false));
|
||||
@@ -764,6 +827,7 @@ impl NodeNetworkInterface {
|
||||
log::error!("Could not get output port for wire start: {upstream_output:?}");
|
||||
return None;
|
||||
};
|
||||
let output_position = output_position + glide_offsets.output(&upstream_output);
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
@@ -772,8 +836,8 @@ impl NodeNetworkInterface {
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
pub fn wire_path_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, network_path: &[NodeId]) -> Option<WirePath> {
|
||||
let (vector_wire, center_line, thick) = self.vector_wire_from_input(input, graph_wire_style, network_path)?;
|
||||
pub fn wire_path_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePath> {
|
||||
let (vector_wire, center_line, thick) = self.gliding_vector_wire_from_input(input, graph_wire_style, glide_offsets, network_path)?;
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let (data_type, is_list) = self
|
||||
|
||||
+1483
-44
File diff suppressed because it is too large.
Load diff
-11
@@ -211,17 +211,6 @@ impl EditorDelta {
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
|
||||
network_path,
|
||||
node_id,
|
||||
context_features,
|
||||
}) => {
|
||||
ops.push(RegistryDelta::ChangeNodeAttribute {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
delta: document_graph_storage::from_runtime::encode_context_features(context_features)?,
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
|
||||
construct_metadata_snapshot(network_path, *node_id, metadata, batch, &context.resolver, ops)?;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,28 @@ impl NodeNetworkInterface {
|
||||
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
let mut port_click_targets = Ports::new();
|
||||
|
||||
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
|
||||
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
const DOT_HALF_WIDTH: f64 = 15.;
|
||||
const DOT_HALF_HEIGHT: f64 = 8.;
|
||||
|
||||
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
|
||||
port_click_targets.insert_dot_ports(center);
|
||||
let path = rounded_rectangle_path(
|
||||
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
[DOT_HALF_HEIGHT; 4],
|
||||
);
|
||||
|
||||
return Some(DocumentNodeClickTargets {
|
||||
node_click_target: ClickTarget::new_with_path(path, 0.),
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
});
|
||||
}
|
||||
|
||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||
let mut input_row_count = 0;
|
||||
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
||||
@@ -176,10 +198,15 @@ impl NodeNetworkInterface {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let port_center = |click_target: &ClickTarget| click_target.bounding_box().map(|[min, max]| (min + max) / 2.);
|
||||
let Some((import_centers, export_centers)) = self.with_import_export_ports(network_path, |import_exports| {
|
||||
let import_centers: Vec<_> = import_exports.output_ports().filter_map(|(index, click_target)| Some((*index, port_center(click_target)?))).collect();
|
||||
let export_centers: Vec<_> = import_exports.input_ports().filter_map(|(index, click_target)| Some((*index, port_center(click_target)?))).collect();
|
||||
let import_centers: Vec<_> = import_exports
|
||||
.output_ports()
|
||||
.filter_map(|(index, _)| Some((*index, import_exports.output_port_position(*index)?)))
|
||||
.collect();
|
||||
let export_centers: Vec<_> = import_exports
|
||||
.input_ports()
|
||||
.filter_map(|(index, _)| Some((*index, import_exports.input_port_position(*index)?)))
|
||||
.collect();
|
||||
(import_centers, export_centers)
|
||||
}) else {
|
||||
return Vec::new();
|
||||
@@ -289,6 +316,11 @@ impl NodeNetworkInterface {
|
||||
log::error!("Could not get all nodes bounding box in import_export_position");
|
||||
return None;
|
||||
};
|
||||
// Horizontally, the imports and exports keep their distance from the sides of the nodes, but only a grid cell from a redirect dot
|
||||
let Some(clearance) = self.import_export_clearance(network_path) else {
|
||||
log::error!("Could not get the import and export clearance in import_export_position");
|
||||
return None;
|
||||
};
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
log::error!("Could not get current network in import_export_position");
|
||||
return None;
|
||||
@@ -322,7 +354,10 @@ impl NodeNetworkInterface {
|
||||
DVec2::new(-4. * GRID_SIZE as f64, 0.)
|
||||
};
|
||||
|
||||
let bounding_box_top_left = DVec2::new((all_nodes_bounding_box[0].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.) + offset_from_top_left;
|
||||
let bounding_box_top_left = DVec2::new(
|
||||
clearance.import_limit(offset_from_top_left.x),
|
||||
(all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24. + offset_from_top_left.y,
|
||||
);
|
||||
let import_top_left = DVec2::new(top_left_inner_bound.x.min(bounding_box_top_left.x), top_left_inner_bound.y.min(bounding_box_top_left.y));
|
||||
let rounded_import_top_left = DVec2::new((import_top_left.x / 24.).round() * 24., (import_top_left.y / 24.).round() * 24.);
|
||||
|
||||
@@ -353,8 +388,10 @@ impl NodeNetworkInterface {
|
||||
DVec2::new(4. * GRID_SIZE as f64, 0.)
|
||||
};
|
||||
|
||||
let mut bounding_box_top_right = DVec2::new((all_nodes_bounding_box[1].x / 24. + 0.5).floor() * 24., (all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24.);
|
||||
bounding_box_top_right += offset_from_top_right;
|
||||
let bounding_box_top_right = DVec2::new(
|
||||
clearance.export_limit(offset_from_top_right.x),
|
||||
(all_nodes_bounding_box[0].y / 24. + 0.5).floor() * 24. + offset_from_top_right.y,
|
||||
);
|
||||
let export_top_right = DVec2::new(top_right_inner_bound.x.max(bounding_box_top_right.x), top_right_inner_bound.y.min(bounding_box_top_right.y));
|
||||
let rounded_export_top_right = DVec2::new((export_top_right.x / 24.).round() * 24., (export_top_right.y / 24.).round() * 24.);
|
||||
|
||||
|
||||
+97
-27
@@ -1,4 +1,6 @@
|
||||
use super::*;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, ParamCurveNearest};
|
||||
|
||||
// Helper functions for mutable getters
|
||||
impl NodeNetworkInterface {
|
||||
@@ -134,27 +136,29 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let nodes = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||
let clicked_nodes = nodes
|
||||
.iter()
|
||||
.filter(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point)
|
||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
||||
}) == Some(true)
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
// Since nodes are placed on top of layer chains, find the first non layer node that was clicked, and if there way no non layer nodes clicked, then find the first layer node that was clicked
|
||||
clicked_nodes
|
||||
.iter()
|
||||
.find_map(|node_id| {
|
||||
let Some(node_metadata) = self.network_metadata(network_path)?.persistent_metadata.node_metadata.get(node_id) else {
|
||||
log::error!("Could not get node_metadata for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
if !node_metadata.persistent_metadata.is_layer() { Some(*node_id) } else { None }
|
||||
})
|
||||
.or_else(|| clicked_nodes.into_iter().next())
|
||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||
let drawing_layer = |node_id: &NodeId| {
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
0
|
||||
} else if self.is_layer(node_id, network_path) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
}
|
||||
};
|
||||
clicked_nodes.into_iter().min_by_key(drawing_layer)
|
||||
}
|
||||
|
||||
pub fn layer_click_target_from_click(&self, click: DVec2, click_target_type: LayerClickTargetTypes, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
@@ -168,11 +172,13 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let node_ids: Vec<_> = network.nodes.keys().copied().collect();
|
||||
|
||||
node_ids
|
||||
.iter()
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
|
||||
match click_target_type {
|
||||
@@ -192,74 +198,137 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
||||
pub fn empty_import_export_connector_at(&self, point: DVec2, is_import: bool, network_path: &[NodeId]) -> Option<(usize, DVec2)> {
|
||||
// The same reach as an import or export port's click target
|
||||
const CONNECTOR_RADIUS: f64 = 8.;
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let point = point - if is_import { glide_offsets.imports } else { glide_offsets.exports };
|
||||
|
||||
// The same reach as an import (output) or export (input) port's click target
|
||||
self.empty_import_export_connectors(is_import, network_path)
|
||||
.into_iter()
|
||||
.find(|(_, center)| center.distance(point) <= CONNECTOR_RADIUS)
|
||||
.find(|(_, center)| port_click_target(side_port_bounds(*center, !is_import)).intersect_point_no_stroke(point))
|
||||
}
|
||||
|
||||
/// The import or export with its name under `point`, given in node graph space.
|
||||
pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<ImportOrExport> {
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
self.import_export_name_bounds(network_path)
|
||||
.into_iter()
|
||||
.find(|(_, [name_min, name_max])| name_min.cmple(point).all() && point.cmple(*name_max).all())
|
||||
.find(|(import_or_export, [name_min, name_max])| {
|
||||
let point = point
|
||||
- match import_or_export {
|
||||
ImportOrExport::Import(_) => glide_offsets.imports,
|
||||
ImportOrExport::Export(_) => glide_offsets.exports,
|
||||
};
|
||||
name_min.cmple(point).all() && point.cmple(*name_max).all()
|
||||
})
|
||||
.map(|(import_or_export, _)| import_or_export)
|
||||
}
|
||||
|
||||
/// The input connector for a wire to attach to at this point, which also counts the body of a redirect dot, as its wires attach at its center.
|
||||
pub fn input_connector_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
self.input_port_from_click(click, network_path)
|
||||
.or_else(|| self.redirect_dot_from_click(click, network_path).map(InputConnector::primary_input))
|
||||
.filter(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
}
|
||||
|
||||
/// The output connector for a wire to attach to at this point, which also counts the body of a redirect dot, as its wires attach at its center.
|
||||
pub fn output_connector_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<OutputConnector> {
|
||||
self.output_port_from_click(click, network_path)
|
||||
.or_else(|| self.redirect_dot_from_click(click, network_path).map(OutputConnector::primary_output))
|
||||
}
|
||||
|
||||
fn redirect_dot_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
self.node_from_click(click, network_path).filter(|node_id| self.is_redirect_dot(node_id, network_path))
|
||||
}
|
||||
|
||||
/// Whether this is the input of a redirect dot that a wire already feeds. A dot is part of its wire rather than a node to rewire,
|
||||
/// so that wire is neither picked up from the dot nor replaced by dropping another onto it. Only its output can start or take a wire.
|
||||
fn is_wired_dot_input(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
input_connector.node_id().is_some_and(|node_id| self.is_redirect_dot(&node_id, network_path)) && self.upstream_output_connector(input_connector, network_path).is_some()
|
||||
}
|
||||
|
||||
/// The input fed by a wire passing within `tolerance` of the point (in node graph space), for placing a dot on it. Only wires a dot can bend are found.
|
||||
pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let target = dvec2_to_point(point);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
self.node_graph_input_connectors(network_path)
|
||||
.into_iter()
|
||||
.filter(|input| self.can_bend_wire_into(input, network_path))
|
||||
.filter_map(|input| {
|
||||
let (wire, _, _) = self.gliding_vector_wire_from_input(&input, wire_style, &glide_offsets, network_path)?;
|
||||
let distance = wire
|
||||
.segments()
|
||||
.map(|segment| segment.nearest(target, DEFAULT_ACCURACY).distance_sq.sqrt())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
(distance <= tolerance).then_some((input, distance))
|
||||
})
|
||||
.min_by(|(_, a), (_, b)| a.total_cmp(b))
|
||||
.map(|(input, _)| input)
|
||||
}
|
||||
|
||||
/// The input connector with its own click target at this point, which is where a wire is picked up from.
|
||||
pub fn input_port_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in input_connector_from_click");
|
||||
log::error!("Could not get nested network_metadata in input_port_from_click");
|
||||
return None;
|
||||
};
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
log::error!("Could not get nested network in input_connector_from_click");
|
||||
log::error!("Could not get nested network in input_port_from_click");
|
||||
return None;
|
||||
};
|
||||
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let covering_dot = self.redirect_dot_from_click(click, network_path);
|
||||
network
|
||||
.nodes
|
||||
.keys()
|
||||
.copied()
|
||||
.collect::<Vec<_>>()
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_input_port_from_point(point)
|
||||
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|port| InputConnector::node_at_index(*node_id, port))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
.or_else(|| {
|
||||
self.with_import_export_ports(network_path, |import_export_ports| import_export_ports.clicked_input_port_from_point(point).map(InputConnector::Export))
|
||||
.flatten()
|
||||
self.with_import_export_ports(network_path, |import_export_ports| {
|
||||
import_export_ports.clicked_input_port_from_point(point - glide_offsets.exports).map(InputConnector::Export)
|
||||
})
|
||||
.flatten()
|
||||
.filter(|_| covering_dot.is_none())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn output_connector_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<OutputConnector> {
|
||||
/// The output connector with its own click target at this point, which is where a new wire is dragged out from.
|
||||
pub fn output_port_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<OutputConnector> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in output_connector_from_click");
|
||||
log::error!("Could not get nested network_metadata in output_port_from_click");
|
||||
return None;
|
||||
};
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
log::error!("Could not get nested network in output_connector_from_click");
|
||||
log::error!("Could not get nested network in output_port_from_click");
|
||||
return None;
|
||||
};
|
||||
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
// A redirect dot is drawn above everything else, so where it covers other ports, only its own can be pressed
|
||||
let covering_dot = self.redirect_dot_from_click(click, network_path);
|
||||
let nodes = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||
nodes
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_output_port_from_point(point)
|
||||
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
||||
})
|
||||
.flatten()
|
||||
@@ -267,9 +336,10 @@ impl NodeNetworkInterface {
|
||||
.next()
|
||||
.or_else(|| {
|
||||
self.with_import_export_ports(network_path, |import_export_ports| {
|
||||
import_export_ports.clicked_output_port_from_point(point).map(OutputConnector::Import)
|
||||
import_export_ports.clicked_output_port_from_point(point - glide_offsets.imports).map(OutputConnector::Import)
|
||||
})
|
||||
.flatten()
|
||||
.filter(|_| covering_dot.is_none())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -174,6 +174,11 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Sets the position of a node to a chain position
|
||||
pub fn set_chain_position(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
// A redirect dot isn't chain-positioned, since that would absorb it into the layer's background area
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node_metadata for node {node_id}");
|
||||
return;
|
||||
@@ -203,7 +208,7 @@ impl NodeNetworkInterface {
|
||||
.skip(1)
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
if self.is_layer(&upstream_node, network_path) || self.hidden_primary_output(&upstream_node, network_path) {
|
||||
if self.is_layer(&upstream_node, network_path) || self.hidden_primary_output(&upstream_node, network_path) || self.is_redirect_dot(&upstream_node, network_path) {
|
||||
break;
|
||||
}
|
||||
let downstream_connection_count = self
|
||||
@@ -282,6 +287,7 @@ impl NodeNetworkInterface {
|
||||
pub fn force_set_upstream_to_chain(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
for upstream_id in &self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).collect::<Vec<_>>() {
|
||||
if !self.is_layer(upstream_id, network_path)
|
||||
&& !self.is_redirect_dot(upstream_id, network_path)
|
||||
&& self
|
||||
.outward_wires(network_path)
|
||||
.is_some_and(|outward_wires| outward_wires.get(&OutputConnector::primary_output(*upstream_id)).is_some_and(|outward_wires| outward_wires.len() == 1))
|
||||
@@ -950,6 +956,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
// Disconnect layer to move
|
||||
self.stop_previewing(network_path);
|
||||
self.remove_references_from_network(&layer.to_node(), network_path);
|
||||
|
||||
let post_node = self.post_node_with_index(parent, insert_index, network_path);
|
||||
@@ -1074,6 +1081,8 @@ impl NodeNetworkInterface {
|
||||
self.take_over_outward_wires(layer.to_node(), network_path);
|
||||
}
|
||||
self.unload_upstream_node_click_targets(vec![layer.to_node()], network_path);
|
||||
|
||||
self.remove_orphaned_dots(network_path);
|
||||
}
|
||||
|
||||
/// Shifts `upstream_node_id` and everything stacked below it down until a layer needing
|
||||
@@ -1307,9 +1316,9 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Duplicates a node into its primary flow (wires into primary inputs, layers' chain inputs, and exports): a node feeding the flow gets its copy right after it,
|
||||
/// taking over what it fed there, and a node only fed by the flow gets its copy appended to extend the chain. A layer's copy brings a copy of its content.
|
||||
/// Returns the copy, or `None` for a node in no flow (a solo node, or a generator without a primary input), which is left to be duplicated loose.
|
||||
/// Returns the copy, or `None` for a node in no flow (a solo node, a generator without a primary input, or a redirect dot), which is left to be duplicated loose.
|
||||
pub fn duplicate_node_in_flow(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
if !self.has_primary_input(node_id, network_path) {
|
||||
if !self.has_primary_input(node_id, network_path) || self.is_redirect_dot(node_id, network_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1418,10 +1427,12 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// All nodes in a layer's chain, ordered from the layer outward, stopping where the next layer begins (since flow turns from horizontal to vertical there).
|
||||
/// Redirect dots are left out, since they only bend a wire and are neither shown beside the layer nor part of the order its chain nodes can be rearranged in.
|
||||
pub fn layer_chain_nodes(&self, layer: NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
self.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
|
||||
.filter(|upstream_id| !self.is_redirect_dot(upstream_id, network_path))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1535,12 +1546,14 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Rewires a layer's chain to run through `new_order` from the layer outward, with the last node fed by `tail_input`.
|
||||
/// Returns whether that took, since a connection that would close a cycle is refused.
|
||||
/// The chain's nodes are wired straight to one another, so redirect dots between them go with the wires they bent.
|
||||
fn rewire_chain(&mut self, layer: NodeId, new_order: &[NodeId], tail_input: NodeInput, network_path: &[NodeId]) -> bool {
|
||||
let intended_chain = Some((new_order.to_vec(), tail_input.clone()));
|
||||
|
||||
// With no nodes left in the chain, the layer is fed directly by what fed its upstream end
|
||||
let (Some(&first), Some(&last)) = (new_order.first(), new_order.last()) else {
|
||||
self.set_input(&InputConnector::layer_secondary_input(layer), tail_input, network_path);
|
||||
self.remove_orphaned_dots(network_path);
|
||||
return self.layer_chain(layer, network_path) == intended_chain;
|
||||
};
|
||||
|
||||
@@ -1559,6 +1572,7 @@ impl NodeNetworkInterface {
|
||||
// Re-establish chain positioning for the rewired nodes
|
||||
self.force_set_upstream_to_chain(&first, network_path);
|
||||
|
||||
self.remove_orphaned_dots(network_path);
|
||||
self.layer_chain(layer, network_path) == intended_chain
|
||||
}
|
||||
}
|
||||
+197
-24
@@ -101,6 +101,7 @@ impl NodeNetworkInterface {
|
||||
if let Some(encapsulating_transient) = self.encapsulating_network_transient_mut(network_path) {
|
||||
encapsulating_transient.outward_wires.unload();
|
||||
encapsulating_transient.all_nodes_bounding_box.unload();
|
||||
encapsulating_transient.import_export_clearance.unload();
|
||||
}
|
||||
|
||||
// Update the click targets for the encapsulating node, if it exists. There is no encapsulating node if the network is the document network
|
||||
@@ -221,6 +222,8 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.remove_orphaned_dots(network_path);
|
||||
self.remove_orphaned_dots(&encapsulating_network_path);
|
||||
|
||||
if self.remove_export_slot(network_path, export_index).is_none() {
|
||||
return;
|
||||
@@ -263,6 +266,10 @@ impl NodeNetworkInterface {
|
||||
for (output_connector, input_wire) in new_import_mapping {
|
||||
self.create_wire(&output_connector, &input_wire, network_path);
|
||||
}
|
||||
// The subgraph node's input for the import goes too, along with the wire feeding it
|
||||
self.disconnect_input(&InputConnector::node_at_index(*parent_id, import_index), encapsulating_network_path);
|
||||
self.remove_orphaned_dots(network_path);
|
||||
self.remove_orphaned_dots(encapsulating_network_path);
|
||||
|
||||
let parent_id = *parent_id;
|
||||
let encapsulating_network_path = encapsulating_network_path.to_vec();
|
||||
@@ -515,14 +522,6 @@ impl NodeNetworkInterface {
|
||||
node.set_call_argument(call_argument);
|
||||
}
|
||||
|
||||
pub fn set_context_features(&mut self, node_id: &NodeId, network_path: &[NodeId], context_features: ContextDependencies) {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node {node_id} in set_context_features");
|
||||
return;
|
||||
};
|
||||
node.set_context_features(context_features);
|
||||
}
|
||||
|
||||
/// Lightweight version of `set_input` for bulk import operations.
|
||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||
@@ -590,6 +589,19 @@ impl NodeNetworkInterface {
|
||||
|
||||
self.transaction_modified();
|
||||
|
||||
// A dot that lost a wire, whether the one feeding it or one it feeds, is left for `remove_orphaned_dots` to judge once the operation is done
|
||||
let dot_losing_its_feed = input_connector
|
||||
.node_id()
|
||||
.filter(|node_id| matches!(old_input, NodeInput::Node { .. } | NodeInput::Import { .. }) && self.is_redirect_dot(node_id, network_path))
|
||||
.map(|dot| (dot, DotSide::Incoming));
|
||||
let dot_losing_a_consumer = old_input
|
||||
.as_node()
|
||||
.filter(|upstream_id| self.is_redirect_dot(upstream_id, network_path))
|
||||
.map(|dot| (dot, DotSide::Outgoing));
|
||||
for lost_wire in dot_losing_its_feed.into_iter().chain(dot_losing_a_consumer) {
|
||||
self.dots_that_lost_a_wire.entry(network_path.to_vec()).or_default().insert(lost_wire);
|
||||
}
|
||||
|
||||
// A node that no longer satisfies the layer shape is shown as a node instead
|
||||
let layer_node_path = match input_connector {
|
||||
InputConnector::Node { node_id, .. } => Some((node_id, network_path)),
|
||||
@@ -759,7 +771,19 @@ impl NodeNetworkInterface {
|
||||
self.set_input(input_connector, value_input, network_path);
|
||||
}
|
||||
|
||||
/// Wires the output into the input, as [`Self::create_wires`] does.
|
||||
pub fn create_wire(&mut self, output_connector: &OutputConnector, input_connector: &InputConnector, network_path: &[NodeId]) {
|
||||
self.create_wires(output_connector, &[*input_connector], network_path);
|
||||
}
|
||||
|
||||
/// Wires the output into each input. Wires from an import into exports run through one new redirect dot that fans out to them,
|
||||
/// since a network needs at least one node in it to pass an import out (https://github.com/GraphiteEditor/Graphite/issues/1762).
|
||||
pub fn create_wires(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) {
|
||||
let (exports_fed_by_import, direct_inputs): (Vec<_>, Vec<_>) = input_connectors
|
||||
.iter()
|
||||
.copied()
|
||||
.partition(|input_connector| matches!((output_connector, input_connector), (OutputConnector::Import(_), InputConnector::Export(_))));
|
||||
|
||||
let input = match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => NodeInput::node(*node_id, *output_index),
|
||||
OutputConnector::Import(import_index) => NodeInput::Import {
|
||||
@@ -767,8 +791,69 @@ impl NodeNetworkInterface {
|
||||
import_index: *import_index,
|
||||
},
|
||||
};
|
||||
for input_connector in &direct_inputs {
|
||||
self.set_input(input_connector, input.clone(), network_path);
|
||||
}
|
||||
|
||||
self.set_input(input_connector, input, network_path);
|
||||
if !exports_fed_by_import.is_empty() {
|
||||
self.create_wires_through_dot(output_connector, &exports_fed_by_import, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Wires the output into the inputs through one new redirect dot placed midway between them, which fans out to the inputs.
|
||||
fn create_wires_through_dot(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) {
|
||||
let output_center = self.get_output_center(output_connector, network_path);
|
||||
let input_centers = input_connectors
|
||||
.iter()
|
||||
.map(|input_connector| self.get_input_center(input_connector, network_path))
|
||||
.collect::<Option<Vec<_>>>();
|
||||
let center = match output_center.zip(input_centers) {
|
||||
Some((output_center, input_centers)) => {
|
||||
let inputs_center = input_centers.iter().sum::<DVec2>() / input_centers.len() as f64;
|
||||
((output_center + inputs_center) / 2. / GRID_SIZE as f64).round().as_ivec2()
|
||||
}
|
||||
None => {
|
||||
log::error!("Could not get the connector positions to place the dot between in create_wires_through_dot");
|
||||
IVec2::ZERO
|
||||
}
|
||||
};
|
||||
|
||||
self.insert_dot(NodeId::new(), center, output_connector, input_connectors, network_path);
|
||||
}
|
||||
|
||||
/// Splits the wire feeding the input with a new redirect dot centered on a grid point.
|
||||
pub fn insert_dot_on_wire(&mut self, dot: NodeId, input_connector: &InputConnector, center: IVec2, network_path: &[NodeId]) {
|
||||
let Some(upstream_output) = self.upstream_output_connector(input_connector, network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.insert_dot(dot, center, &upstream_output, &[*input_connector], network_path);
|
||||
}
|
||||
|
||||
/// Runs every wire leaving the output that a redirect dot can bend through a new dot centered on a grid point, so they fan out from the dot instead.
|
||||
pub fn insert_dot_on_output(&mut self, dot: NodeId, output_connector: &OutputConnector, center: IVec2, network_path: &[NodeId]) {
|
||||
let fed_inputs = self.inputs_fed_through_bendable_wires(output_connector, network_path);
|
||||
if !fed_inputs.is_empty() {
|
||||
self.insert_dot(dot, center, output_connector, &fed_inputs, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a new redirect dot centered on a grid point, fed by the output and feeding the inputs.
|
||||
fn insert_dot(&mut self, dot: NodeId, center: IVec2, output_connector: &OutputConnector, fed_inputs: &[InputConnector], network_path: &[NodeId]) {
|
||||
let Some(passthrough_definition) = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER) else {
|
||||
log::error!("Could not resolve the Passthrough node to insert a redirect dot");
|
||||
return;
|
||||
};
|
||||
|
||||
// The dot's center sits a grid row below its position
|
||||
let mut dot_template = passthrough_definition.default_node_template();
|
||||
dot_template.node_type_metadata = NodeTypePersistentMetadata::node(center - IVec2::Y);
|
||||
self.insert_node(dot, dot_template, network_path);
|
||||
|
||||
self.create_wire(output_connector, &InputConnector::primary_input(dot), network_path);
|
||||
for fed_input in fed_inputs {
|
||||
self.create_wire(&OutputConnector::primary_output(dot), fed_input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to insert a group of nodes into the network
|
||||
@@ -812,10 +897,79 @@ impl NodeNetworkInterface {
|
||||
previous_entry
|
||||
}
|
||||
|
||||
/// Deletes all nodes in `node_ids` and any sole dependents in the horizontal chain if the node to delete is a layer node.
|
||||
/// Removes each redirect dot an edit left with nothing feeding it or nothing taking its output, since a dot is only a bend in a wire.
|
||||
/// Operations that can take a wire away end with this, since their steps (like disconnecting an input to reconnect it) can leave a dot briefly unwired.
|
||||
pub fn remove_orphaned_dots(&mut self, network_path: &[NodeId]) {
|
||||
let mut undeletable = HashSet::new();
|
||||
|
||||
// Removing one dot takes the wire it shared with the next along a run of dots, which is then judged in turn
|
||||
while let Some(lost_wires) = self.dots_that_lost_a_wire.remove(network_path) {
|
||||
let orphans = lost_wires
|
||||
.into_iter()
|
||||
.filter(|(dot, side)| !undeletable.contains(dot) && self.is_orphaned_dot(dot, *side, network_path))
|
||||
.map(|(dot, _)| dot)
|
||||
.collect::<HashSet<_>>();
|
||||
if orphans.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Removing a dot the preview shows or restores the export to ends the preview, as deleting any node does
|
||||
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
|
||||
let previewed = self.upstream_output_connector(&InputConnector::Export(0), network_path).and_then(|output| output.node_id());
|
||||
let restored = root_node_to_restore.map(|root_node| root_node.node_id);
|
||||
if orphans.iter().any(|dot| Some(*dot) == previewed || Some(*dot) == restored) {
|
||||
self.stop_previewing(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
self.delete_nodes_leaving_dots(orphans.iter().copied().collect(), false, network_path);
|
||||
|
||||
// A dot that failed to be deleted isn't judged again, so this always comes to an end
|
||||
undeletable.extend(
|
||||
orphans
|
||||
.into_iter()
|
||||
.filter(|dot| self.nested_network(network_path).is_some_and(|network| network.nodes.contains_key(dot))),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the node is a redirect dot left with no wire on the given side.
|
||||
pub(super) fn is_orphaned_dot(&self, node_id: &NodeId, side: DotSide, network_path: &[NodeId]) -> bool {
|
||||
// A dot deleted by the operation that took its wire, or in a network since deleted, has nothing left to judge
|
||||
let exists = self.document_network().nested_network(network_path).is_some_and(|network| network.nodes.contains_key(node_id));
|
||||
if !exists || !self.is_redirect_dot(node_id, network_path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
match side {
|
||||
DotSide::Incoming => self.upstream_output_connector(&InputConnector::primary_input(*node_id), network_path).is_none(),
|
||||
DotSide::Outgoing => {
|
||||
// The export a preview will restore to the dot still counts as taking its output
|
||||
let restored_by_preview = matches!(self.previewing(network_path), Previewing::Yes { root_node_to_restore: Some(root_node) } if root_node.node_id == *node_id);
|
||||
let consumed = self
|
||||
.with_outward_wires(network_path, |outward_wires| {
|
||||
outward_wires.get(&OutputConnector::primary_output(*node_id)).is_some_and(|inputs| !inputs.is_empty())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
!restored_by_preview && !consumed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes the nodes and any sole dependents in the horizontal chain if the node to delete is a layer node,
|
||||
/// along with any redirect dots left without a wire once they're gone.
|
||||
pub fn delete_nodes(&mut self, nodes_to_delete: Vec<NodeId>, delete_children: bool, network_path: &[NodeId]) {
|
||||
// TODO: Add more logic to support retaining preview when removing references. Since there are so many edge cases/possible crashes, for now the preview is ended.
|
||||
self.stop_previewing(network_path);
|
||||
|
||||
self.delete_nodes_leaving_dots(nodes_to_delete, delete_children, network_path);
|
||||
self.remove_orphaned_dots(network_path);
|
||||
}
|
||||
|
||||
/// Deletes the nodes like [`Self::delete_nodes`], but leaves any dots this orphans for the caller to remove.
|
||||
fn delete_nodes_leaving_dots(&mut self, nodes_to_delete: Vec<NodeId>, delete_children: bool, network_path: &[NodeId]) {
|
||||
if self.outward_wires(network_path).is_none() {
|
||||
log::error!("Could not get outward wires in delete_nodes");
|
||||
log::error!("Could not get outward wires in delete_nodes_leaving_dots");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -936,9 +1090,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Removes all references to the node with the given id from the network, and reconnects the input to the node below.
|
||||
pub fn remove_references_from_network(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
// TODO: Add more logic to support retaining preview when removing references. Since there are so many edge cases/possible crashes, for now the preview is ended.
|
||||
self.stop_previewing(network_path);
|
||||
|
||||
// The wire the downstream inputs reconnect to, which is the first exposed input of the node being removed
|
||||
let reconnect_to_input = self.document_node(node_id, network_path).and_then(|node| {
|
||||
node.inputs
|
||||
@@ -960,18 +1111,26 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
let mut reconnect_node = None;
|
||||
let mut exports_fed_by_import = Vec::new();
|
||||
|
||||
for downstream_input in &downstream_inputs_to_disconnect {
|
||||
self.disconnect_input(downstream_input, network_path);
|
||||
// Prevent reconnecting export to import until https://github.com/GraphiteEditor/Graphite/issues/1762 is solved
|
||||
if !(matches!(reconnect_to_input, Some(NodeInput::Import { .. })) && matches!(downstream_input, InputConnector::Export(_)))
|
||||
&& let Some(reconnect_input) = &reconnect_to_input
|
||||
{
|
||||
if let Some(reconnect_input) = &reconnect_to_input {
|
||||
reconnect_node = reconnect_input.as_node().filter(|&node_id| self.is_stack(&node_id, network_path));
|
||||
self.disconnect_input(&InputConnector::primary_input(*node_id), network_path);
|
||||
self.set_input(downstream_input, reconnect_input.clone(), network_path);
|
||||
|
||||
// An import can't feed an export directly, so the exports it takes over share one new redirect dot, wired below
|
||||
match (reconnect_input, downstream_input) {
|
||||
(NodeInput::Import { .. }, InputConnector::Export(_)) => exports_fed_by_import.push(*downstream_input),
|
||||
_ => self.set_input(downstream_input, reconnect_input.clone(), network_path),
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(NodeInput::Import { import_index, .. }) = reconnect_to_input
|
||||
&& !exports_fed_by_import.is_empty()
|
||||
{
|
||||
self.create_wires(&OutputConnector::Import(import_index), &exports_fed_by_import, network_path);
|
||||
}
|
||||
|
||||
// Shift the reconnected node up to collapse space
|
||||
if let Some(reconnect_node) = &reconnect_node {
|
||||
@@ -1021,7 +1180,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_previewing(&mut self, network_path: &[NodeId]) {
|
||||
pub(super) fn stop_previewing(&mut self, network_path: &[NodeId]) {
|
||||
if let Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node_to_restore),
|
||||
} = self.previewing(network_path)
|
||||
@@ -1037,6 +1196,15 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
fn set_previewing_state(&mut self, previewing: Previewing, network_path: &[NodeId]) {
|
||||
// A dot the preview was to restore the export to may be left with nothing taking its output
|
||||
if let Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node),
|
||||
} = self.previewing(network_path)
|
||||
&& self.is_redirect_dot(&root_node.node_id, network_path)
|
||||
{
|
||||
self.dots_that_lost_a_wire.entry(network_path.to_vec()).or_default().insert((root_node.node_id, DotSide::Outgoing));
|
||||
}
|
||||
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in set_previewing_state");
|
||||
return;
|
||||
@@ -1291,8 +1459,13 @@ impl NodeNetworkInterface {
|
||||
new_export = root_node_to_restore.map(|root_node| root_node.to_connector());
|
||||
new_previewing_state = Previewing::No;
|
||||
}
|
||||
// The export is clicked and there is no preview
|
||||
// The export is clicked and there is no preview, so it already shows the primary output a preview would
|
||||
else if previous_output_index == 0 {
|
||||
return;
|
||||
}
|
||||
// The export is clicked and there is no preview, but it comes from another output, so preview the primary one and restore that afterward
|
||||
else {
|
||||
new_export = Some(OutputConnector::primary_output(toggle_id));
|
||||
new_previewing_state = Previewing::Yes {
|
||||
root_node_to_restore: Some(RootNode {
|
||||
node_id: previous_export_id,
|
||||
@@ -1309,10 +1482,10 @@ impl NodeNetworkInterface {
|
||||
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
|
||||
// There is also a solid line being drawn
|
||||
if let Some(root_node_to_restore) = root_node_to_restore {
|
||||
// If the node with the solid line is clicked, then start previewing that node without restore
|
||||
// If the node with the solid line is clicked, then end the preview by restoring it
|
||||
if root_node_to_restore.node_id == toggle_id {
|
||||
new_export = Some(OutputConnector::primary_output(toggle_id));
|
||||
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
|
||||
new_export = Some(root_node_to_restore.to_connector());
|
||||
new_previewing_state = Previewing::No;
|
||||
} else {
|
||||
// Root node to restore does not change
|
||||
new_previewing_state = Previewing::Yes {
|
||||
|
||||
@@ -173,6 +173,12 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "has_primary_input", |view| view.has_primary_input(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The input a node is spliced into a wire by, which is its first exposed input. That's its primary input unless the primary input is hidden.
|
||||
pub fn first_exposed_input(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let input_index = self.document_node(node_id, network_path)?.inputs.iter().position(|input| input.is_exposed())?;
|
||||
Some(InputConnector::node_at_index(*node_id, input_index))
|
||||
}
|
||||
|
||||
/// Grid rows the node body spans, which is the greater of its input rows and its output count.
|
||||
pub fn displayed_row_count(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
|
||||
self.query(network_path, "displayed_row_count", |view| view.displayed_row_count(node_id)).unwrap_or(1)
|
||||
@@ -182,6 +188,93 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "number_of_outputs", |view| view.number_of_outputs(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The output a wire is really drawn from when picked up at the end of a run of dots that nothing else uses.
|
||||
/// Picking it up removes those dots, so the wire in hand continues from where the run began.
|
||||
pub fn output_past_sole_dots(&self, mut output: OutputConnector, network_path: &[NodeId]) -> OutputConnector {
|
||||
let mut visited = HashSet::new();
|
||||
while let OutputConnector::Node { node_id, .. } = output
|
||||
&& self.is_redirect_dot(&node_id, network_path)
|
||||
&& visited.insert(node_id)
|
||||
{
|
||||
let sole_consumer = self
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&output).is_some_and(|consumers| consumers.len() == 1))
|
||||
.unwrap_or_default();
|
||||
if !sole_consumer {
|
||||
break;
|
||||
}
|
||||
|
||||
let Some(upstream) = self.upstream_output_connector(&InputConnector::primary_input(node_id), network_path) else {
|
||||
break;
|
||||
};
|
||||
output = upstream;
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Whether a redirect dot can bend the wire feeding the input. The export's wire to a previewed node can't be, since ending the preview takes it away.
|
||||
pub fn can_bend_wire_into(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
let has_wire = self.upstream_output_connector(input_connector, network_path).is_some();
|
||||
let preview_wire = *input_connector == InputConnector::Export(0) && matches!(self.previewing(network_path), Previewing::Yes { .. });
|
||||
|
||||
has_wire && !preview_wire
|
||||
}
|
||||
|
||||
/// The inputs fed by the output through wires a redirect dot can bend.
|
||||
pub fn inputs_fed_through_bendable_wires(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<InputConnector> {
|
||||
let fed_inputs = self.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).cloned()).flatten();
|
||||
fed_inputs.unwrap_or_default().into_iter().filter(|input| self.can_bend_wire_into(input, network_path)).collect()
|
||||
}
|
||||
|
||||
/// The nodes to copy or duplicate for a selection. A dot is part of a wire and can't exist on its own, so the selected dots are dropped,
|
||||
/// and every dot on a wire between two of the kept nodes is added, selected or not, so the copies stay wired together.
|
||||
pub fn selection_with_bridging_dots(&self, selected: Vec<NodeId>, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut kept = selected.into_iter().filter(|node_id| !self.is_redirect_dot(node_id, network_path)).collect::<Vec<_>>();
|
||||
let Some(network) = self.nested_network(network_path) else { return kept };
|
||||
let kept_set = kept.iter().copied().collect::<HashSet<_>>();
|
||||
|
||||
let dots = network.nodes.keys().copied().filter(|node_id| self.is_redirect_dot(node_id, network_path)).collect::<Vec<_>>();
|
||||
for dot in dots {
|
||||
// Follow the wire upstream through any dots to the node feeding it
|
||||
let mut source = self.upstream_output_connector(&InputConnector::primary_input(dot), network_path).and_then(|output| output.node_id());
|
||||
let mut visited = HashSet::new();
|
||||
while let Some(source_id) = source
|
||||
&& self.is_redirect_dot(&source_id, network_path)
|
||||
&& visited.insert(source_id)
|
||||
{
|
||||
source = self
|
||||
.upstream_output_connector(&InputConnector::primary_input(source_id), network_path)
|
||||
.and_then(|output| output.node_id());
|
||||
}
|
||||
if !source.is_some_and(|source_id| kept_set.contains(&source_id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Walk on through any dots that follow to the nodes the wire finally reaches
|
||||
let mut pending = vec![dot];
|
||||
let mut visited = HashSet::from([dot]);
|
||||
let mut reaches_copied_node = false;
|
||||
while let Some(current) = pending.pop() {
|
||||
let consumers = self
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(current)).cloned())
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
for consumer in consumers.into_iter().filter_map(|consumer| consumer.node_id()) {
|
||||
if self.is_redirect_dot(&consumer, network_path) {
|
||||
if visited.insert(consumer) {
|
||||
pending.push(consumer);
|
||||
}
|
||||
} else if kept_set.contains(&consumer) {
|
||||
reaches_copied_node = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if reaches_copied_node {
|
||||
kept.push(dot);
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// Creates a copy for each node by disconnecting nodes which are not connected to other copied nodes.
|
||||
/// Returns an iterator of all persistent metadata for a node and their ids
|
||||
pub fn copy_nodes<'a>(&'a self, new_ids: &'a HashMap<NodeId, NodeId>, network_path: &'a [NodeId]) -> impl Iterator<Item = (NodeId, NodeTemplate)> + 'a {
|
||||
@@ -660,6 +753,11 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "hidden_primary_import", |view| Ok(view.hidden_primary_import())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the node is a redirect dot, which is a Passthrough node that the node graph draws as a small dot bending the wire running through it.
|
||||
pub fn is_redirect_dot(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
self.query(network_path, "is_redirect_dot", |view| view.is_redirect_dot(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn is_absolute(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
self.query(network_path, "is_absolute", |view| view.is_absolute(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
+302
-46
@@ -2,31 +2,96 @@ use std::collections::{HashMap, HashSet};
|
||||
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors, Promotion};
|
||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
|
||||
use graphene_std::NodeIOTypes;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
|
||||
/// Whether a `source` type can feed a `connector` type, directly or through the `input_adapter` node the compiler inserts to convert elements (such as `Color` into `Graphic`).
|
||||
pub fn type_feeds_connector(source: &Type, connector: &Type) -> bool {
|
||||
let source = source.nested_type();
|
||||
let connector = connector.nested_type();
|
||||
if source == connector {
|
||||
return true;
|
||||
/// The source types an `input_adapter` converts into each destination type, keyed by destination.
|
||||
type AdapterConversions = HashMap<Type, HashSet<Type>>;
|
||||
|
||||
/// The conversions of every `input_adapter` in the registry.
|
||||
static ADAPTER_CONVERSIONS: Lazy<HashMap<ProtoNodeIdentifier, AdapterConversions>> = Lazy::new(|| {
|
||||
let mut adapter_conversions: HashMap<ProtoNodeIdentifier, AdapterConversions> = HashMap::new();
|
||||
|
||||
for (identifier, implementations) in NODE_REGISTRY.iter().filter(|(identifier, _)| identifier.as_str().starts_with("input_adapter<")) {
|
||||
let conversions = adapter_conversions.entry(identifier.clone()).or_default();
|
||||
for node_io in implementations.keys() {
|
||||
if let Some(source) = node_io.inputs.first() {
|
||||
conversions.entry(node_io.return_value.nested_type().clone()).or_default().insert(source.nested_type().clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (Type::Item(element) | Type::List(element)) = connector else { return false };
|
||||
let adapter = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{}>", element.identifier_name()));
|
||||
NODE_REGISTRY.get(&adapter).is_some_and(|implementations| {
|
||||
implementations
|
||||
.keys()
|
||||
.any(|node_io| node_io.return_value.nested_type() == connector && node_io.inputs.first().is_some_and(|input| input.nested_type() == source))
|
||||
})
|
||||
adapter_conversions
|
||||
});
|
||||
|
||||
/// For each input of each proto node, the conversions of the `input_adapter` the compiler places ahead of it, or `None` where wires pass through unconverted.
|
||||
static INPUT_CONVERSIONS: Lazy<HashMap<ProtoNodeIdentifier, Vec<Option<&'static AdapterConversions>>>> = Lazy::new(|| {
|
||||
// Initialized before the registry locks below, since its own initialization takes them
|
||||
let adapter_conversions = &*ADAPTER_CONVERSIONS;
|
||||
let (Ok(node_registry), Ok(node_metadata)) = (graphene_std::registry::NODE_REGISTRY.lock(), graphene_std::registry::NODE_METADATA.lock()) else {
|
||||
log::error!("Could not lock the node registry to read the input adapter of each input");
|
||||
return HashMap::new();
|
||||
};
|
||||
|
||||
// O(nodes * inputs * implementations), once
|
||||
node_metadata
|
||||
.keys()
|
||||
.filter_map(|identifier| {
|
||||
let implementations = node_registry.get(identifier)?;
|
||||
let number_of_inputs = implementations.iter().map(|(_, node_io)| node_io.inputs.len()).max().unwrap_or_default();
|
||||
|
||||
let conversions = (0..number_of_inputs)
|
||||
.map(|index| {
|
||||
let input_types = implementations.iter().filter_map(|(_, node_io)| node_io.inputs.get(index).cloned()).collect();
|
||||
preprocessor::input_adapter_identifier(&input_types, &NODE_REGISTRY).and_then(|adapter| adapter_conversions.get(&adapter))
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some((identifier.clone(), conversions))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
|
||||
/// Proto nodes whose every implementation returns its one input's type unchanged (like Monitor and Memoize), so a wire through one is constrained by what it feeds.
|
||||
static TYPE_PRESERVING_NODES: Lazy<HashSet<ProtoNodeIdentifier>> = Lazy::new(|| {
|
||||
NODE_REGISTRY
|
||||
.iter()
|
||||
.filter(|(_, implementations)| {
|
||||
!implementations.is_empty()
|
||||
&& implementations
|
||||
.keys()
|
||||
.all(|node_io| matches!(node_io.inputs.as_slice(), [input] if input.nested_type() == node_io.return_value.nested_type()))
|
||||
})
|
||||
.map(|(identifier, _)| identifier.clone())
|
||||
// The compiler removes passthrough nodes, so they're absent from the registry, but their output carries their input's type too
|
||||
.chain(std::iter::once(graphene_std::ops::passthrough::IDENTIFIER))
|
||||
.collect()
|
||||
});
|
||||
|
||||
/// The conversions ahead of each input of a proto node, indexed by input.
|
||||
fn input_conversions(proto_node_identifier: &ProtoNodeIdentifier) -> &'static [Option<&'static AdapterConversions>] {
|
||||
INPUT_CONVERSIONS.get(proto_node_identifier).map(Vec::as_slice).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether a `source` type can feed an input registered as `connector`, through the `conversions` the compiler places ahead of that input
|
||||
/// and any rank promotion (such as raising an item onto a list input) that type resolution inserts after them.
|
||||
fn type_feeds_input(source: &Type, connector: &Type, conversions: Option<&AdapterConversions>) -> bool {
|
||||
let (source, connector) = (source.nested_type(), connector.nested_type());
|
||||
|
||||
// The types the wire can leave the input adapter as: unchanged, or converted into any destination accepting it
|
||||
let converted = conversions.into_iter().flatten().filter(|(_, sources)| sources.contains(source)).map(|(destination, _)| destination);
|
||||
|
||||
std::iter::once(source)
|
||||
.chain(converted)
|
||||
.any(|adapted| adapted == connector || Promotion::exists_between(adapted, connector))
|
||||
}
|
||||
|
||||
// This file contains utility methods for interfacing with the resolved types returned from the compiler
|
||||
@@ -297,16 +362,7 @@ impl NodeNetworkInterface {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let intersection: HashSet<Type> = inputs_from_import
|
||||
.iter()
|
||||
.map(|input_connector| self.potential_valid_input_types(input_connector, &nested_path).into_iter().collect::<HashSet<_>>())
|
||||
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
|
||||
Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()),
|
||||
None => Some(set),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
intersection.into_iter().collect::<Vec<_>>()
|
||||
self.types_accepted_by_all(&inputs_from_import, &nested_path)
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => self
|
||||
.implementations_matching_inputs(proto_node_identifier, node_id, Some(*input_index), network_path)
|
||||
@@ -319,6 +375,126 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a wire of `source_type` can feed the input given the node's other inputs, directly or through what the compiler converts and promotes.
|
||||
pub fn input_accepts_type(&self, input_connector: &InputConnector, source_type: &Type, network_path: &[NodeId]) -> bool {
|
||||
let InputConnector::Node { node_id, input_index } = input_connector else {
|
||||
return self.type_acceptor(input_connector, network_path)(source_type);
|
||||
};
|
||||
|
||||
match self.implementation(node_id, network_path) {
|
||||
Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) => {
|
||||
let conversions = input_conversions(proto_node_identifier).get(*input_index).copied().flatten();
|
||||
self.implementations_matching_inputs(proto_node_identifier, node_id, Some(*input_index), network_path)
|
||||
.filter_map(|node_io| node_io.inputs.get(*input_index))
|
||||
.any(|connector| type_feeds_input(source_type, connector, conversions))
|
||||
}
|
||||
// The wire reaches every interior input fed by the import, so each of them has to accept it
|
||||
Some(DocumentNodeImplementation::Network(_)) => {
|
||||
let nested_path = [network_path, &[*node_id]].concat();
|
||||
let interior_inputs = self
|
||||
.with_outward_wires(&nested_path, |outward_wires| outward_wires.get(&OutputConnector::Import(*input_index)).cloned())
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
|
||||
!interior_inputs.is_empty() && interior_inputs.iter().all(|interior_input| self.type_acceptor(interior_input, &nested_path)(source_type))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A check of which wire types an input accepts, built once so testing many types searches the node's matching implementations only once.
|
||||
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Monitor) also needs the inputs it feeds to accept the type.
|
||||
fn type_acceptor(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Box<dyn Fn(&Type) -> bool> {
|
||||
let accepts_here: Box<dyn Fn(&Type) -> bool> = match input_connector {
|
||||
InputConnector::Export(export_index) => match network_path.split_last() {
|
||||
// The document network's export is the canvas, which takes anything
|
||||
None => Box::new(|_| true),
|
||||
// A subgraph's export passes the wire on out of its node's output, so it accepts only what that output feeds in the parent network
|
||||
Some((subgraph_node_id, parent_path)) => {
|
||||
let consumers = self
|
||||
.with_outward_wires(parent_path, |outward_wires| outward_wires.get(&OutputConnector::node(*subgraph_node_id, *export_index)).cloned())
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
let consumer_acceptors = consumers.iter().map(|consumer| self.type_acceptor(consumer, parent_path)).collect::<Vec<_>>();
|
||||
|
||||
Box::new(move |source_type| consumer_acceptors.iter().all(|accepts| accepts(source_type)))
|
||||
}
|
||||
},
|
||||
InputConnector::Node { node_id, input_index } => match self.implementation(node_id, network_path) {
|
||||
// A passthrough node takes anything itself, leaving the inputs it feeds to constrain the wire
|
||||
Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) if *proto_node_identifier == graphene_std::ops::passthrough::IDENTIFIER => Box::new(|_| true),
|
||||
Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) => {
|
||||
let conversions = input_conversions(proto_node_identifier).get(*input_index).copied().flatten();
|
||||
let connectors = self
|
||||
.implementations_matching_inputs(proto_node_identifier, node_id, Some(*input_index), network_path)
|
||||
.filter_map(|node_io| node_io.inputs.get(*input_index))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Box::new(move |source_type| connectors.iter().any(|connector| type_feeds_input(source_type, connector, conversions)))
|
||||
}
|
||||
// The wire reaches every interior input fed by the import, so each of them has to accept it
|
||||
Some(DocumentNodeImplementation::Network(_)) => {
|
||||
let nested_path = [network_path, &[*node_id]].concat();
|
||||
let interior_inputs = self
|
||||
.with_outward_wires(&nested_path, |outward_wires| outward_wires.get(&OutputConnector::Import(*input_index)).cloned())
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
let interior_acceptors = interior_inputs.iter().map(|interior_input| self.type_acceptor(interior_input, &nested_path)).collect::<Vec<_>>();
|
||||
|
||||
Box::new(move |source_type| !interior_acceptors.is_empty() && interior_acceptors.iter().all(|accepts| accepts(source_type)))
|
||||
}
|
||||
_ => Box::new(|_| false),
|
||||
},
|
||||
};
|
||||
|
||||
let Some(fed_inputs) = self.inputs_fed_by_type_preserving_node(input_connector, network_path) else {
|
||||
return accepts_here;
|
||||
};
|
||||
let fed_acceptors = fed_inputs.iter().map(|fed_input| self.type_acceptor(fed_input, network_path)).collect::<Vec<_>>();
|
||||
Box::new(move |source_type| accepts_here(source_type) && fed_acceptors.iter().all(|accepts| accepts(source_type)))
|
||||
}
|
||||
|
||||
/// The inputs fed by the node of `input_connector`, if that node passes its input's type through unchanged, since those constrain a wire through it more
|
||||
/// than the node's own broad set of types.
|
||||
fn inputs_fed_by_type_preserving_node(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<Vec<InputConnector>> {
|
||||
let InputConnector::Node { node_id, .. } = input_connector else { return None };
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return None;
|
||||
};
|
||||
if !TYPE_PRESERVING_NODES.contains(proto_node_identifier) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fed_inputs = self
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id)).cloned())
|
||||
.flatten();
|
||||
Some(fed_inputs.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The types that every one of `input_connectors` accepts, which is what a single wire feeding all of them can carry.
|
||||
fn types_accepted_by_all(&self, input_connectors: &[InputConnector], network_path: &[NodeId]) -> Vec<Type> {
|
||||
input_connectors
|
||||
.iter()
|
||||
.map(|input_connector| {
|
||||
let valid_types = self.potential_valid_input_types(input_connector, network_path).into_iter();
|
||||
match self.inputs_fed_by_type_preserving_node(input_connector, network_path) {
|
||||
// A node passing its input's type through unchanged accepts only what the inputs it feeds accept
|
||||
Some(fed_inputs) => {
|
||||
let fed_acceptors = fed_inputs.iter().map(|fed_input| self.type_acceptor(fed_input, network_path)).collect::<Vec<_>>();
|
||||
valid_types.filter(|valid_type| fed_acceptors.iter().all(|accepts| accepts(valid_type))).collect::<HashSet<_>>()
|
||||
}
|
||||
None => valid_types.collect(),
|
||||
}
|
||||
})
|
||||
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
|
||||
Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()),
|
||||
None => Some(set),
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The types an output could produce: its compiled type, or else what [`Self::possible_output_types`] finds.
|
||||
pub fn potential_output_types(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
if let Some(compiled_type) = self.output_type(output_connector, network_path).compiled_nested_type() {
|
||||
@@ -381,13 +557,14 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
let conversions = input_conversions(proto_node_identifier);
|
||||
implementations.into_iter().flat_map(|implementations| implementations.keys()).filter(move |node_io| {
|
||||
(0..number_of_inputs).filter(|index| Some(*index) != disregarded_input_index).all(|index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, index), network_path);
|
||||
// TODO: Fix type checking for different call arguments
|
||||
// For example a node input of (Footprint) -> Vector would not be compatible with a node that is called with () and returns Vector
|
||||
match (input_type.compiled_nested_type(), node_io.inputs.get(index)) {
|
||||
(Some(source), Some(connector)) => type_feeds_connector(source, connector),
|
||||
(Some(source), Some(connector)) => type_feeds_input(source, connector, conversions.get(index).copied().flatten()),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
@@ -526,37 +703,116 @@ impl NodeNetworkInterface {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let intersection = inputs_from_import
|
||||
.iter()
|
||||
.map(|input_connector| self.potential_valid_input_types(input_connector, network_path).into_iter().collect::<HashSet<_>>())
|
||||
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
|
||||
Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()),
|
||||
None => Some(set),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
intersection.into_iter().collect::<Vec<_>>()
|
||||
self.types_accepted_by_all(&inputs_from_import, network_path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::type_feeds_connector;
|
||||
use graph_craft::item;
|
||||
use graphene_std::vector::style::DashPattern;
|
||||
use graphene_std::{Color, Graphic};
|
||||
use super::{input_conversions, type_feeds_input};
|
||||
use graph_craft::{item, list};
|
||||
use graphene_std::vector::fill::{ContentInput, PaintInput};
|
||||
use graphene_std::{Color, Graphic, NodeParameter};
|
||||
|
||||
#[test]
|
||||
fn input_adapter_conversions_feed_connectors() {
|
||||
assert!(type_feeds_connector(&item!(f64), &item!(f64)), "identical types should match directly");
|
||||
fn only_inputs_with_an_input_adapter_convert() {
|
||||
let fill_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER);
|
||||
let paint_conversions = fill_conversions.get(PaintInput::INDEX).copied().flatten();
|
||||
let content_conversions = fill_conversions.get(ContentInput::INDEX).copied().flatten();
|
||||
|
||||
assert!(type_feeds_input(&item!(f64), &item!(f64), None), "identical types should match without an input adapter");
|
||||
assert!(
|
||||
type_feeds_connector(&item!(Color), &item!(Graphic)),
|
||||
"a color paint should feed a graphic paint connector through its input adapter"
|
||||
type_feeds_input(&item!(Color), &item!(Graphic), paint_conversions),
|
||||
"a color should feed Fill's paint input, registered with one type, through its input adapter"
|
||||
);
|
||||
assert!(
|
||||
type_feeds_connector(&item!(f64), &item!(DashPattern)),
|
||||
"a number should feed a dash pattern connector through its input adapter"
|
||||
!type_feeds_input(&item!(Color), &item!(Graphic), content_conversions),
|
||||
"Fill's content input is registered with several types, so it gets no input adapter to convert a color"
|
||||
);
|
||||
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_promote_onto_list_inputs() {
|
||||
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
|
||||
|
||||
assert!(type_feeds_input(&item!(f64), &list!(f64), None), "a number should be raised onto a list input as a one-element list");
|
||||
assert!(
|
||||
type_feeds_input(&item!(Color), &list!(Graphic), paint_conversions),
|
||||
"a color should feed Fill's list paint input by converting through its input adapter and then being raised to a list"
|
||||
);
|
||||
assert!(!type_feeds_input(&list!(f64), &item!(f64), None), "a list has no promotion down to an item");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subgraph_inputs_look_through_type_preserving_nodes() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let path_node_id = editor.create_node_by_name(DefinitionIdentifier::Network("Path".into())).await;
|
||||
|
||||
// The Path subgraph's content goes through a Monitor node, which accepts most types, before the node that needs a vector
|
||||
let content_types = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.potential_valid_input_types(&InputConnector::node_at_index(path_node_id, 0), &[])
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
assert!(content_types.iter().any(|ty| ty == "Vector"), "Path's content should accept a vector, found {content_types:?}");
|
||||
assert!(
|
||||
!content_types.iter().any(|ty| ty == "Color"),
|
||||
"Path's content should not accept a color just because its Monitor does, found {content_types:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_subgraph_input_passed_through_to_its_export_accepts_only_what_the_subgraph_output_feeds() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let merge = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 0, 0).await;
|
||||
let fill = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER), 20, 0)
|
||||
.await;
|
||||
let fill_content = InputConnector::node_at_index(fill, 0);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(merge, 0),
|
||||
input_connector: fill_content,
|
||||
})
|
||||
.await;
|
||||
|
||||
// A new import passed straight through to Merge's export, which the editor bridges with a Passthrough node
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: merge }).await;
|
||||
let import_index = editor.active_document().network_interface.number_of_imports(&[merge]);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::AddImportAndConnect {
|
||||
import_index,
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let passed_through = InputConnector::node_at_index(merge, import_index);
|
||||
let fill_content_type = network_interface
|
||||
.potential_valid_input_types(&fill_content, &[])
|
||||
.first()
|
||||
.cloned()
|
||||
.expect("Fill's content should accept some type");
|
||||
assert!(
|
||||
network_interface.input_accepts_type(&passed_through, &fill_content_type, &[]),
|
||||
"the input should accept what the Fill fed by Merge's output takes"
|
||||
);
|
||||
assert!(
|
||||
!network_interface.input_accepts_type(&passed_through, &item!(f64), &[]),
|
||||
"the input should reject a number, which the Fill fed by Merge's output can't take"
|
||||
);
|
||||
assert!(!type_feeds_connector(&item!(f64), &item!(Graphic)), "a number has no conversion into a graphic");
|
||||
}
|
||||
}
|
||||
-15
@@ -193,21 +193,6 @@ impl NodeMut<'_> {
|
||||
changed
|
||||
}
|
||||
|
||||
/// The Extract and Inject annotations the node declares for the Context.
|
||||
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
|
||||
let changed = self.node.context_features != context_features;
|
||||
self.node.context_features = context_features;
|
||||
if changed {
|
||||
let delta = RuntimeDelta::SetContextFeatures {
|
||||
network_path: self.deltas.network_path(),
|
||||
node_id: self.deltas.node_id(),
|
||||
context_features: self.node.context_features,
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The user-chosen name for this instance, empty when it has none.
|
||||
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
|
||||
let changed = self.metadata.display_name != display_name;
|
||||
|
||||
@@ -354,10 +354,12 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Drops what the writes since the last drain changed, for writes that are not edits to the document,
|
||||
/// after reading it for the nodes an open transaction has written to.
|
||||
/// The redirect dots those writes took wires from are forgotten too, so no later edit removes them.
|
||||
pub(crate) fn discard_deltas(&mut self) {
|
||||
self.scan_transaction_edited_nodes();
|
||||
self.transaction_edited_nodes_scanned = 0;
|
||||
self.deltas.clear();
|
||||
self.dots_that_lost_a_wire.clear();
|
||||
}
|
||||
|
||||
/// Records the open transaction's bookkeeping, so writes that are undone before [`Self::restore_transaction_checkpoint`] don't count toward it.
|
||||
|
||||
+12
-13
@@ -1,30 +1,32 @@
|
||||
use super::*;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::vector::VectorGeometry;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<Vector> {
|
||||
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
|
||||
|
||||
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
|
||||
&& let Some(vector) = self.document_metadata.vector_modify.get(&path_node)
|
||||
&& let Some(geometry) = self.document_metadata.vector_modify.get(&path_node)
|
||||
{
|
||||
let mut modified = vector.clone();
|
||||
let mut modified = geometry.clone();
|
||||
|
||||
let path_node = self.document_network().nodes.get(&path_node);
|
||||
let modification_input = path_node.and_then(|node: &DocumentNode| node.inputs.get(1)).and_then(|input| input.as_value());
|
||||
if let Some(TaggedValue::VectorModification(modification)) = modification_input {
|
||||
modification.apply(&mut modified);
|
||||
modification.apply(&mut modified.vector, &mut modified.paths);
|
||||
}
|
||||
return Some(modified);
|
||||
}
|
||||
|
||||
self.document_metadata.layer_vector_data.get(&layer).map(|arc| arc.as_ref().clone())
|
||||
self.document_metadata.layer_vector_data.get(&layer).map(|item| VectorGeometry::from_item(item))
|
||||
}
|
||||
|
||||
/// The vector geometry an upstream Path node would surface for editing.
|
||||
/// This is the result of `compute_modified_vector`, but only if a visible 'Path' node is actually upstream.
|
||||
/// Useful for tool overlays and snap target collection usages that want to match the Path tool's view
|
||||
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing.
|
||||
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<Vector> {
|
||||
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
|
||||
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
|
||||
self.compute_modified_vector(layer)
|
||||
@@ -46,11 +48,8 @@ impl NodeNetworkInterface {
|
||||
targets.push(ClickTargetType::Path(combined));
|
||||
}
|
||||
|
||||
for &point_id in vector.point_domain.ids() {
|
||||
if !vector.any_connected(point_id) {
|
||||
let position = vector.point_domain.position_from_id(point_id).unwrap_or_default();
|
||||
targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position)));
|
||||
}
|
||||
for (point_id, position) in vector.free_points() {
|
||||
targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position)));
|
||||
}
|
||||
|
||||
Some(targets)
|
||||
@@ -183,13 +182,13 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// Update the vector modify of the layers
|
||||
pub fn update_vector_modify(&mut self, new_vector_modify: HashMap<NodeId, Vector>) {
|
||||
pub fn update_vector_modify(&mut self, new_vector_modify: HashMap<NodeId, VectorGeometry>) {
|
||||
self.document_metadata.mark_changed();
|
||||
self.document_metadata.vector_modify = new_vector_modify;
|
||||
}
|
||||
|
||||
/// Update the layer vector data (for layers without Path nodes)
|
||||
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>) {
|
||||
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
|
||||
self.document_metadata.mark_changed();
|
||||
self.document_metadata.layer_vector_data = new_layer_vector_data;
|
||||
}
|
||||
|
||||
@@ -23,8 +23,6 @@ pub struct NodeTemplate {
|
||||
pub visible: bool,
|
||||
/// Prevents identical proto nodes from being deduplicated during compilation, e.g. for monitor nodes.
|
||||
pub skip_deduplication: bool,
|
||||
/// List of Extract and Inject annotations for the Context.
|
||||
pub context_features: ContextDependencies,
|
||||
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed in italics.
|
||||
pub display_name: String,
|
||||
/// Metadata to override the Inspector widgets for each input. Kept the same length as `inputs`.
|
||||
@@ -60,7 +58,6 @@ impl Default for NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::default(),
|
||||
visible: true,
|
||||
skip_deduplication: false,
|
||||
context_features: ContextDependencies::default(),
|
||||
display_name: String::new(),
|
||||
input_metadata: Vec::new(),
|
||||
output_names: Vec::new(),
|
||||
@@ -117,7 +114,7 @@ impl NodeTemplate {
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
context_features,
|
||||
context_dependencies: _,
|
||||
original_location: _,
|
||||
} = document_node;
|
||||
let DocumentNodePersistentMetadata {
|
||||
@@ -163,7 +160,6 @@ impl NodeTemplate {
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
context_features,
|
||||
display_name,
|
||||
input_metadata,
|
||||
output_names,
|
||||
@@ -182,7 +178,6 @@ impl NodeTemplate {
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
context_features,
|
||||
display_name,
|
||||
mut input_metadata,
|
||||
output_names,
|
||||
@@ -203,7 +198,7 @@ impl NodeTemplate {
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
context_features,
|
||||
context_dependencies: None,
|
||||
original_location: Default::default(),
|
||||
};
|
||||
let persistent_node_metadata = DocumentNodePersistentMetadata {
|
||||
|
||||
@@ -40,11 +40,20 @@ pub struct ChainNodeCopy {
|
||||
}
|
||||
|
||||
impl ChainNodeCopy {
|
||||
/// The copied node with each of its wired inputs taking its fallback value, placed offset from its original, for pasting outside any flow.
|
||||
pub fn into_loose_template(self) -> NodeTemplate {
|
||||
/// Whether the copied node is a redirect dot, which comes along only to bend a wire between the other copies.
|
||||
pub fn is_redirect_dot(&self) -> bool {
|
||||
let passthrough = matches!(&self.template.implementation, NodeTemplateImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER);
|
||||
passthrough && matches!(self.template.node_type_metadata, NodeTypePersistentMetadata::Node(_))
|
||||
}
|
||||
|
||||
/// The copied node, placed offset from its original, for pasting outside any flow along with the copies of the nodes in `pasted`.
|
||||
/// Its inputs stay wired to those copies, and each of its other wired inputs takes its fallback value.
|
||||
pub fn into_loose_template(self, pasted: &HashSet<NodeId>) -> NodeTemplate {
|
||||
let mut template = self.template;
|
||||
for (index, fallback_value) in self.fallback_values {
|
||||
if let Some(input) = template.inputs.get_mut(index) {
|
||||
if let Some(input) = template.inputs.get_mut(index)
|
||||
&& !input.as_node().is_some_and(|node_id| pasted.contains(&node_id))
|
||||
{
|
||||
*input = fallback_value;
|
||||
}
|
||||
}
|
||||
@@ -262,10 +271,49 @@ impl OutputConnector {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which side of a redirect dot an edit took a wire from, since each side leaves the dot orphaned only once it has no wire left there.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum DotSide {
|
||||
/// The wire feeding the dot.
|
||||
Incoming,
|
||||
/// One of the wires the dot feeds.
|
||||
Outgoing,
|
||||
}
|
||||
|
||||
/// The corners of the click target for a connector on a node or layer's left or right side, or an import or export.
|
||||
/// It fills its row's height and reaches further away from the node than into it, leaving the node body grabbable.
|
||||
pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
||||
const INWARD_REACH: f64 = 8.;
|
||||
const OUTWARD_REACH: f64 = 12.;
|
||||
const HALF_HEIGHT: f64 = 12.;
|
||||
|
||||
// Inputs face left and outputs face right
|
||||
let (left_reach, right_reach) = if is_input { (OUTWARD_REACH, INWARD_REACH) } else { (INWARD_REACH, OUTWARD_REACH) };
|
||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||
}
|
||||
|
||||
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
|
||||
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
|
||||
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
|
||||
[center - HALF_SIZE, center + HALF_SIZE]
|
||||
}
|
||||
|
||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||
const CORNER_RADIUS: f64 = 4.;
|
||||
|
||||
let path = rounded_rectangle_path(corner1, corner2, [CORNER_RADIUS; 4]);
|
||||
ClickTarget::new_with_path(path, 0.)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Ports {
|
||||
pub(crate) input_ports: Vec<(usize, ClickTarget)>,
|
||||
pub(crate) output_ports: Vec<(usize, ClickTarget)>,
|
||||
/// Where a wire attaches to an input port with a click target not centered on that point.
|
||||
pub(crate) input_anchors: Vec<(usize, DVec2)>,
|
||||
/// Where a wire attaches to an output port with a click target not centered on that point.
|
||||
pub(crate) output_anchors: Vec<(usize, DVec2)>,
|
||||
}
|
||||
|
||||
impl Default for Ports {
|
||||
@@ -279,6 +327,8 @@ impl Ports {
|
||||
Ports {
|
||||
input_ports: Vec::new(),
|
||||
output_ports: Vec::new(),
|
||||
input_anchors: Vec::new(),
|
||||
output_anchors: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,8 +348,8 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
let path = ellipse_path(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_input_port(input_index, ClickTarget::new_with_path(path, 0.));
|
||||
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
||||
self.input_anchors.push((input_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||
@@ -307,8 +357,8 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||
let path = ellipse_path(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_output_port(output_index, ClickTarget::new_with_path(path, 0.));
|
||||
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
||||
self.output_anchors.push((output_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||
@@ -328,18 +378,19 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
|
||||
let center = if input_index == 0 {
|
||||
node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.)
|
||||
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
|
||||
if input_index == 0 {
|
||||
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
|
||||
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
|
||||
} else {
|
||||
node_top_left + DVec2::new(0., 24. * 1.)
|
||||
};
|
||||
self.insert_input_port_at_center(input_index, center);
|
||||
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
// The center of the click target is 8 px above the layer, over its thumbnail
|
||||
let center = node_top_left + DVec2::new(2. * 24., -8.);
|
||||
self.insert_output_port_at_center(0, center);
|
||||
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
|
||||
}
|
||||
|
||||
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
||||
@@ -350,13 +401,34 @@ impl Ports {
|
||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
|
||||
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
|
||||
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
|
||||
const GUTTER_OFFSET: f64 = 10.;
|
||||
const GUTTER_RADIUS: f64 = 5.;
|
||||
|
||||
let gutter = |x_offset: f64| {
|
||||
let gutter_center = center + DVec2::new(x_offset, 0.);
|
||||
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
|
||||
};
|
||||
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
|
||||
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
|
||||
self.input_anchors.push((0, center));
|
||||
self.output_anchors.push((0, center));
|
||||
}
|
||||
|
||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.input_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
}
|
||||
|
||||
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.output_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
@@ -523,6 +595,8 @@ pub struct NodeNetworkTransientMetadata {
|
||||
pub(crate) stack_dependents: TransientCache<HashMap<NodeId, LayerOwner>>,
|
||||
/// Cache for the bounding box around all nodes in node graph space.
|
||||
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
|
||||
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
|
||||
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
|
||||
/// Cache for all outward wire connections
|
||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||
/// All export connector click targets
|
||||
@@ -532,6 +606,82 @@ pub struct NodeNetworkTransientMetadata {
|
||||
pub(crate) wires: std::cell::RefCell<HashMap<InputConnector, WirePathUpdate>>,
|
||||
/// Drag-session state: how far each unowned stack dependent has been pushed vertically from its resting position. Cleared when the drag ends.
|
||||
pub(crate) drag_offsets: std::cell::RefCell<HashMap<NodeId, i32>>,
|
||||
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
||||
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
||||
}
|
||||
|
||||
/// How far the nodes, imports, and exports gliding into the grid cells they just moved to are drawn from those cells, in node graph space.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct GlideOffsets {
|
||||
pub nodes: HashMap<NodeId, DVec2>,
|
||||
pub imports: DVec2,
|
||||
pub exports: DVec2,
|
||||
}
|
||||
|
||||
impl GlideOffsets {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.imports == DVec2::ZERO && self.exports == DVec2::ZERO
|
||||
}
|
||||
|
||||
pub fn node(&self, node_id: &NodeId) -> DVec2 {
|
||||
self.nodes.get(node_id).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn input(&self, input: &InputConnector) -> DVec2 {
|
||||
match input {
|
||||
InputConnector::Node { node_id, .. } => self.node(node_id),
|
||||
InputConnector::Export(_) => self.exports,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output(&self, output: &OutputConnector) -> DVec2 {
|
||||
match output {
|
||||
OutputConnector::Node { node_id, .. } => self.node(node_id),
|
||||
OutputConnector::Import(_) => self.imports,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shrinks every offset to the given fraction of itself, settling those left too small to see.
|
||||
pub fn shrink(&mut self, remaining_fraction: f64) {
|
||||
const SMALLEST_VISIBLE_OFFSET: f64 = 0.5;
|
||||
|
||||
let shrink = |offset: &mut DVec2| {
|
||||
*offset *= remaining_fraction;
|
||||
if offset.length() < SMALLEST_VISIBLE_OFFSET {
|
||||
*offset = DVec2::ZERO;
|
||||
}
|
||||
};
|
||||
self.nodes.values_mut().for_each(shrink);
|
||||
self.nodes.retain(|_, offset| *offset != DVec2::ZERO);
|
||||
shrink(&mut self.imports);
|
||||
shrink(&mut self.exports);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the imports and exports keep their distance from horizontally, in node graph space. They keep a few grid cells from the sides of a node,
|
||||
/// but just one from a redirect dot, which only bends a wire, so the dots are measured apart from the other nodes.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct ImportExportClearance {
|
||||
/// The leftmost and rightmost sides of the nodes other than redirect dots.
|
||||
pub node_sides: Option<[f64; 2]>,
|
||||
/// The leftmost and rightmost centers of the redirect dots.
|
||||
pub dot_centers: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
impl ImportExportClearance {
|
||||
/// The furthest right the imports can sit: `node_gap` (a negative distance) from the leftmost node's side rounded to the grid, or a grid cell left of the leftmost dot.
|
||||
pub fn import_limit(&self, node_gap: f64) -> f64 {
|
||||
let beside_nodes = self.node_sides.map(|[left, _]| (left / GRID_SIZE as f64 + 0.5).floor() * GRID_SIZE as f64 + node_gap);
|
||||
let beside_dots = self.dot_centers.map(|[left, _]| left - GRID_SIZE as f64);
|
||||
beside_nodes.into_iter().chain(beside_dots).reduce(f64::min).unwrap_or(node_gap)
|
||||
}
|
||||
|
||||
/// The furthest left the exports can sit: `node_gap` from the rightmost node's side rounded to the grid, or a grid cell right of the rightmost dot.
|
||||
pub fn export_limit(&self, node_gap: f64) -> f64 {
|
||||
let beside_nodes = self.node_sides.map(|[_, right]| (right / GRID_SIZE as f64 + 0.5).floor() * GRID_SIZE as f64 + node_gap);
|
||||
let beside_dots = self.dot_centers.map(|[_, right]| right + GRID_SIZE as f64);
|
||||
beside_nodes.into_iter().chain(beside_dots).reduce(f64::max).unwrap_or(node_gap)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -994,7 +1144,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_click_targets_are_clickable_at_their_center() {
|
||||
fn port_click_targets_reach_around_the_connector_where_wires_attach() {
|
||||
let center = DVec2::new(100., 50.);
|
||||
let mut ports = Ports::new();
|
||||
ports.insert_input_port_at_center(0, center);
|
||||
@@ -1002,9 +1152,14 @@ mod tests {
|
||||
|
||||
assert_eq!(ports.clicked_input_port_from_point(center), Some(0));
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(5., 5.)), Some(0));
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(20., 0.)), None);
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(0., 11.)), Some(0));
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(-11., 0.)), Some(0));
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(10., 0.)), None);
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(0., 13.)), None);
|
||||
|
||||
assert_eq!(ports.clicked_output_port_from_point(center + DVec2::new(200., 0.)), Some(0));
|
||||
assert_eq!(ports.clicked_output_port_from_point(center), None);
|
||||
|
||||
assert_eq!(ports.input_port_position(0), Some(center), "wires should attach at the connector's center, not the click target's");
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -3,7 +3,7 @@ use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeN
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Checks the structural invariants between the document network and its parallel metadata tree at every nesting level.
|
||||
/// Checks the structural invariants of the document network, its parallel metadata tree, and its redirect dots at every nesting level.
|
||||
/// Returns a description of each violation found, or an empty list if the interface is internally consistent.
|
||||
/// Intended for tests and debugging; violations indicate a desync bug in the mutation methods, not a user error.
|
||||
// O(nodes + wires) summed across all nesting levels, plus an acyclicity walk per network
|
||||
@@ -11,9 +11,19 @@ impl NodeNetworkInterface {
|
||||
let mut violations = Vec::new();
|
||||
validate_network(self.document_network(), &self.network_metadata, &mut Vec::new(), 0, &mut violations);
|
||||
self.validate_outward_wires(&mut Vec::new(), &mut violations);
|
||||
self.validate_dots_stay_on_wires(&mut violations);
|
||||
violations
|
||||
}
|
||||
|
||||
/// A redirect dot an edit took a wire from must be gone by the time the edit is done if that left it orphaned.
|
||||
fn validate_dots_stay_on_wires(&self, violations: &mut Vec<String>) {
|
||||
for (network_path, lost_wires) in &self.dots_that_lost_a_wire {
|
||||
for (dot, side) in lost_wires.iter().filter(|(dot, side)| self.is_orphaned_dot(dot, *side, network_path)) {
|
||||
violations.push(format!("Redirect dot {dot} in network {network_path:?} lost its {side:?} wire to an edit that left it behind"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded outward wire cache must match a fresh computation from the network.
|
||||
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, violations: &mut Vec<String>) {
|
||||
let Some(network) = self.nested_network(path) else { return };
|
||||
|
||||
@@ -174,14 +174,24 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
.is_some_and(|upstream_id| self.is_layer(&upstream_id).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn is_passthrough(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
Ok(matches!(self.implementation(node_id)?, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER))
|
||||
}
|
||||
|
||||
/// Whether the node is a redirect dot, which is a Passthrough node that the node graph draws as a small dot bending the wire running through it.
|
||||
pub fn is_redirect_dot(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
Ok(self.is_passthrough(node_id)? && !self.is_layer(node_id)?)
|
||||
}
|
||||
|
||||
/// Whether the node's signature fits the layer form: one output, at most two exposed leading inputs, and no exposed parameters.
|
||||
/// A Passthrough never fits, since it's drawn as a redirect dot.
|
||||
pub fn is_eligible_to_be_layer(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
let node = self.node(node_id)?;
|
||||
let input_count = node.inputs.iter().take(2).filter(|input| input.is_exposed()).count();
|
||||
let parameters_hidden = node.inputs.iter().skip(2).all(|input| !input.is_exposed());
|
||||
let output_count = self.number_of_outputs(node_id)?;
|
||||
|
||||
Ok(!self.hidden_primary_output(node_id)? && output_count == 1 && (input_count <= 2) && parameters_hidden)
|
||||
Ok(!self.is_passthrough(node_id)? && !self.hidden_primary_output(node_id)? && output_count == 1 && (input_count <= 2) && parameters_hidden)
|
||||
}
|
||||
|
||||
pub fn is_locked(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
|
||||
@@ -21,6 +21,14 @@ pub struct LayerStructureEntry {
|
||||
/// Whether any descendant layer in the graph is selected, including through collapsed subtrees not listed in `children`.
|
||||
#[serde(rename = "descendantSelected")]
|
||||
pub descendant_selected: bool,
|
||||
pub selected: bool,
|
||||
/// Whether the layer itself is visible, which the frontend passes down to its children's rows as inherited visibility.
|
||||
pub visible: bool,
|
||||
/// Whether the layer itself is unlocked, which the frontend passes down to its children's rows as an inherited lock.
|
||||
pub unlocked: bool,
|
||||
/// The rows listing the layer's chain nodes beneath its own row, one per node while its chain is expanded and otherwise none.
|
||||
#[serde(rename = "chainRows")]
|
||||
pub chain_rows: u32,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
|
||||
@@ -102,7 +102,7 @@ impl OriginalTransforms {
|
||||
|
||||
// Anchors also move their handles
|
||||
let anchor_ids = selected_points.iter().filter_map(|point| point.as_anchor());
|
||||
let anchors = anchor_ids.filter_map(|id| vector.point_domain.position_from_id(id).map(|pos| (id, AnchorPoint { initial: pos, current: pos })));
|
||||
let anchors = anchor_ids.filter_map(|id| vector.position_from_id(id).map(|pos| (id, AnchorPoint { initial: pos, current: pos })));
|
||||
let anchors = anchors.collect();
|
||||
|
||||
let selected_handles = selected_points.iter().filter_map(|point| point.as_handle());
|
||||
@@ -112,13 +112,13 @@ impl OriginalTransforms {
|
||||
|
||||
let handles = all_handles
|
||||
.filter_map(|id| {
|
||||
let anchor = id.to_manipulator_point().get_anchor(&vector)?;
|
||||
let initial = id.to_manipulator_point().get_position(&vector)?;
|
||||
let relative = vector.point_domain.position_from_id(anchor)?;
|
||||
let anchor = vector.anchor_of(id.to_manipulator_point())?;
|
||||
let initial = vector.position_of(id.to_manipulator_point())?;
|
||||
let relative = vector.position_from_id(anchor)?;
|
||||
let other_handle = vector
|
||||
.other_colinear_handle(id)
|
||||
.filter(|other| !selected_points.contains(&other.to_manipulator_point()) && !selected_points.contains(&ManipulatorPointId::Anchor(anchor)));
|
||||
let mirror = other_handle.and_then(|id| Some((id, id.to_manipulator_point().get_position(&vector)?)));
|
||||
let mirror = other_handle.and_then(|id| Some((id, vector.position_of(id.to_manipulator_point())?)));
|
||||
|
||||
Some((id, HandlePoint { initial, relative, anchor, mirror }))
|
||||
})
|
||||
|
||||
@@ -21,7 +21,7 @@ use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
|
||||
@@ -801,11 +801,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::vector_nodes::SplitPathNode", "graphene_core::vector::SplitPathNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::cut_segments::IDENTIFIER,
|
||||
node: graphene_std::vector::unweld::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_core::vector::vector_nodes::SplitSegmentsNode",
|
||||
"graphene_core::vector::SplitSegmentsNode",
|
||||
"graphene_core::vector::CutSegmentsNode",
|
||||
"core_types::vector::CutSegmentsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -901,8 +902,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::JitterPointsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::merge_by_distance::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::MergeByDistanceNode"],
|
||||
node: graphene_std::vector::weld::IDENTIFIER,
|
||||
aliases: &["graphene_core::vector::MergeByDistanceNode", "core_types::vector::MergeByDistanceNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::mirror::IDENTIFIER,
|
||||
@@ -1634,6 +1635,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
create_layer_stacks(document);
|
||||
follow_segments_turned_on_load(document);
|
||||
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
|
||||
// identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input
|
||||
@@ -2773,7 +2775,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::merge_by_distance::IDENTIFIER) && inputs_count == 2 {
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::weld::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);
|
||||
|
||||
@@ -2783,13 +2785,28 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 2),
|
||||
NodeInput::value(TaggedValue::MergeByDistanceAlgorithm(graphene_std::vector::misc::MergeByDistanceAlgorithm::Topological), false),
|
||||
NodeInput::value(TaggedValue::WeldMethod(graphene_std::vector::misc::WeldMethod::Connected), false),
|
||||
network_path,
|
||||
);
|
||||
reset_default_display_name(document, node_id, network_path, "Merge by Distance");
|
||||
}
|
||||
|
||||
// A Merge by Distance node saved with its "Algorithm" input takes Weld's input names and descriptions, keeping its inputs
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::weld::IDENTIFIER)
|
||||
&& inputs_count == 3
|
||||
&& document
|
||||
.network_interface
|
||||
.persistent_input_metadata(node_id, 2, network_path)
|
||||
.is_some_and(|metadata| metadata.input_name == "Algorithm")
|
||||
{
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
node_template.inputs = node.inputs.clone();
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
reset_default_display_name(document, node_id, network_path, "Merge by Distance");
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::SpatialMergeByDistanceNode")) {
|
||||
let mut node_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::merge_by_distance::IDENTIFIER))?.default_node_template();
|
||||
let mut node_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::weld::IDENTIFIER))?.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)?;
|
||||
@@ -2798,9 +2815,22 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 2),
|
||||
NodeInput::value(TaggedValue::MergeByDistanceAlgorithm(graphene_std::vector::misc::MergeByDistanceAlgorithm::Spatial), false),
|
||||
NodeInput::value(TaggedValue::WeldMethod(graphene_std::vector::misc::WeldMethod::All), false),
|
||||
network_path,
|
||||
);
|
||||
reset_default_display_name(document, node_id, network_path, "Spatial Merge by Distance");
|
||||
}
|
||||
|
||||
// Cut Segments became Unweld, keeping its content and taking the All method that splits every anchor as it did
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::unweld::IDENTIFIER) && inputs_count == 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
node_template.inputs = vec![
|
||||
node.inputs[0].clone(),
|
||||
NodeInput::value(TaggedValue::UnweldMethod(graphene_std::vector::misc::UnweldMethod::All), false),
|
||||
];
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
reset_default_display_name(document, node_id, network_path, "Cut Segments");
|
||||
reset_default_display_name(document, node_id, network_path, "Split Segments");
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::Network("Sample Points".into()) && inputs_count == 5 {
|
||||
@@ -3213,15 +3243,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// Add context features to nodes that don't have them (fine-grained context caching migration)
|
||||
if node.context_features == graphene_std::ContextDependencies::default()
|
||||
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
|
||||
&& let Some(node_definition) = resolve_document_node_type(&reference)
|
||||
{
|
||||
let context_features = node_definition.node_template.context_features;
|
||||
document.network_interface.set_context_features(node_id, network_path, context_features);
|
||||
}
|
||||
|
||||
// Add the "Scale Type" parameter to the "Decompose Scale" node
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -3347,6 +3368,136 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
Some(())
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Older stored edits are turned around where they chain into paths on load. Edits naming those segments by side (a handle,
|
||||
/// an endpoint, or a G1 pair) in the Path nodes downstream of the one that turned them are turned with them, so each stays on
|
||||
/// the side it was made on. Segment IDs are only unique within one shape, so nodes not downstream are left alone.
|
||||
fn follow_segments_turned_on_load(document: &mut DocumentMessageHandler) {
|
||||
for (network_path, node_id, index, input) in modifications_following_turned_segments(document.network_interface.document_network()) {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(node_id, index), input, &network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The stored edits to rewrite after loading, each with its network path, node, and input index: those that turned segments,
|
||||
/// with their record taken, and those downstream of them, turned to follow. Costs O(nodes + wires) per node that turned any.
|
||||
fn modifications_following_turned_segments(network: &graph_craft::document::NodeNetwork) -> Vec<(Vec<NodeId>, NodeId, usize, NodeInput)> {
|
||||
type Location = (Vec<NodeId>, NodeId);
|
||||
|
||||
// The nodes reading each node's data, wired straight to the node producing it through nested networks' imports and exports
|
||||
let mut readers: HashMap<Location, Vec<Location>> = HashMap::new();
|
||||
let mut turned_by: Vec<(Location, HashSet<graphene_std::vector::SegmentId>)> = Vec::new();
|
||||
for (node_id, node, network_path) in network.recursive_nodes() {
|
||||
let here = (network_path.clone(), *node_id);
|
||||
|
||||
for input in &node.inputs {
|
||||
if let NodeInput::Value { tagged_value, .. } = input
|
||||
&& let TaggedValue::VectorModification(modification) = &**tagged_value
|
||||
&& !modification.segments_turned_on_load().is_empty()
|
||||
{
|
||||
turned_by.push((here.clone(), modification.segments_turned_on_load().clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// A network node's inputs only pass through to the nodes inside it, which are wired as readers themselves
|
||||
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
|
||||
continue;
|
||||
}
|
||||
for input in &node.inputs {
|
||||
if let Some(producer) = producing_node(network, &network_path, input, 0) {
|
||||
readers.entry(producer).or_default().push(here.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if turned_by.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Each node's turned segments reach the nodes reading its output, then their readers, and so on
|
||||
let mut following: HashMap<Location, HashSet<graphene_std::vector::SegmentId>> = HashMap::new();
|
||||
for (origin, turned) in &turned_by {
|
||||
let (origin_path, origin_id) = origin;
|
||||
let Some(origin_node) = network.nested_network(origin_path).and_then(|nested| nested.nodes.get(origin_id)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Where the output comes from: the node itself, or the nodes a network node exports
|
||||
let sources: Vec<Location> = match &origin_node.implementation {
|
||||
DocumentNodeImplementation::Network(nested) => (0..nested.exports.len())
|
||||
.filter_map(|output| producing_node(network, origin_path, &NodeInput::node(*origin_id, output), 0))
|
||||
.collect(),
|
||||
_ => vec![origin.clone()],
|
||||
};
|
||||
|
||||
let mut reached = HashSet::new();
|
||||
let mut pending: Vec<Location> = sources.iter().flat_map(|source| readers.get(source).into_iter().flatten().cloned()).collect();
|
||||
while let Some(location) = pending.pop() {
|
||||
if reached.insert(location.clone()) {
|
||||
pending.extend(readers.get(&location).into_iter().flatten().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
// An edit follows when the node holding it, or a node inside it, reads the turned data
|
||||
for (path, node_id) in reached {
|
||||
let enclosing = (0..path.len()).map(|depth| (path[..depth].to_vec(), path[depth]));
|
||||
for holder in enclosing.chain([(path.clone(), node_id)]).filter(|holder| holder != origin) {
|
||||
following.entry(holder).or_default().extend(turned.iter().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut rewritten = Vec::new();
|
||||
for (node_id, node, network_path) in network.recursive_nodes() {
|
||||
let location = (network_path.clone(), *node_id);
|
||||
let follows = following.get(&location);
|
||||
|
||||
for (index, input) in node.inputs.iter().enumerate() {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { continue };
|
||||
let TaggedValue::VectorModification(modification) = &**tagged_value else { continue };
|
||||
let had_record = !modification.segments_turned_on_load().is_empty();
|
||||
if !had_record && follows.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut modification = modification.clone();
|
||||
modification.take_segments_turned_on_load();
|
||||
let changed = follows.is_some_and(|turned| modification.follow_segments_turned_elsewhere(turned));
|
||||
|
||||
if had_record || changed {
|
||||
let input = NodeInput::value(TaggedValue::VectorModification(modification), *exposed);
|
||||
rewritten.push((network_path.clone(), *node_id, index, input));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rewritten
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The node, not itself a network, producing the data an input reads, looking through the imports and exports of nested networks.
|
||||
fn producing_node(network: &graph_craft::document::NodeNetwork, network_path: &[NodeId], input: &NodeInput, depth: usize) -> Option<(Vec<NodeId>, NodeId)> {
|
||||
// Nesting is shallow in practice, so this only guards against a malformed document wiring a network back into itself
|
||||
if depth > 64 {
|
||||
return None;
|
||||
}
|
||||
|
||||
match input {
|
||||
NodeInput::Node { node_id, output_index } => {
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
match &node.implementation {
|
||||
DocumentNodeImplementation::Network(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
|
||||
_ => Some((network_path.to_vec(), *node_id)),
|
||||
}
|
||||
}
|
||||
NodeInput::Import { import_index, .. } => {
|
||||
let (parent, parent_path) = network_path.split_last()?;
|
||||
let parent_node = network.nested_network(parent_path)?.nodes.get(parent)?;
|
||||
producing_node(network, parent_path, parent_node.inputs.get(*import_index)?, depth + 1)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure layers are positioned as stacks if they are upstream siblings of another layer
|
||||
fn create_layer_stacks(document: &mut DocumentMessageHandler) {
|
||||
document.network_interface.load_structure();
|
||||
@@ -4081,4 +4232,269 @@ mod tests {
|
||||
panic!("Duplicate entries in `NODE_REPLACEMENTS`: {duplicates:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// Segment IDs repeat across shapes, so a segment turned on load is followed only by the stored edits downstream of the node that turned it
|
||||
#[test]
|
||||
fn turned_segments_are_followed_only_downstream() {
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graphene_std::vector::misc::HandleId;
|
||||
use graphene_std::vector::{SegmentId, VectorModification, VectorModificationType};
|
||||
|
||||
let segment = SegmentId::generate();
|
||||
let turned = VectorModification::default().with_segments_turned_on_load(HashSet::from([segment]));
|
||||
let edited_on = |handle: HandleId| {
|
||||
let mut modification = VectorModification::default();
|
||||
modification.modify(&VectorModificationType::SetHandlePosition { handle, relative_position: DVec2::X });
|
||||
modification
|
||||
};
|
||||
let value = |modification: VectorModification| NodeInput::value(TaggedValue::VectorModification(Box::new(modification)), false);
|
||||
let node = |inputs: Vec<NodeInput>| DocumentNode { inputs, ..Default::default() };
|
||||
|
||||
// One turned Path node feeds another directly, and a second sits inside a nested network whose export feeds a third
|
||||
let [turning, following, unrelated, group, following_group] = [1, 2, 3, 4, 5].map(NodeId);
|
||||
let nested = NodeNetwork {
|
||||
exports: vec![NodeInput::node(turning, 0)],
|
||||
nodes: [(turning, node(vec![value(turned.clone())]))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [
|
||||
(turning, node(vec![value(turned)])),
|
||||
(following, node(vec![NodeInput::node(turning, 0), value(edited_on(HandleId::primary(segment)))])),
|
||||
(unrelated, node(vec![value(edited_on(HandleId::primary(segment)))])),
|
||||
(
|
||||
group,
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(nested),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(following_group, node(vec![NodeInput::node(group, 0), value(edited_on(HandleId::primary(segment)))])),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let rewritten = modifications_following_turned_segments(&network);
|
||||
let rewritten_at = |location: (&[NodeId], NodeId)| rewritten.iter().find(|(path, node_id, ..)| (path.as_slice(), *node_id) == location);
|
||||
|
||||
assert!(rewritten_at((&[], turning)).is_some(), "the record of what turned is taken");
|
||||
assert!(rewritten_at((&[group], turning)).is_some(), "the nested record of what turned is taken");
|
||||
assert!(rewritten_at((&[], unrelated)).is_none(), "an edit not downstream stays as it was");
|
||||
|
||||
let expected = value(edited_on(HandleId::end(segment)));
|
||||
for downstream in [following, following_group] {
|
||||
let (.., index, input) = rewritten_at((&[], downstream)).expect("an edit downstream follows the turn");
|
||||
assert_eq!(*index, 1);
|
||||
assert_eq!(*input, expected);
|
||||
}
|
||||
}
|
||||
|
||||
// Inside a network fed by a turned node on one input and something else on another, only the edit reading the turned input follows
|
||||
#[test]
|
||||
fn turned_segments_follow_only_the_network_input_they_enter() {
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graphene_std::vector::misc::HandleId;
|
||||
use graphene_std::vector::{SegmentId, VectorModification, VectorModificationType};
|
||||
|
||||
let segment = SegmentId::generate();
|
||||
let turned = VectorModification::default().with_segments_turned_on_load(HashSet::from([segment]));
|
||||
let mut edited = VectorModification::default();
|
||||
edited.modify(&VectorModificationType::SetHandlePosition {
|
||||
handle: HandleId::primary(segment),
|
||||
relative_position: DVec2::X,
|
||||
});
|
||||
let value = |modification: VectorModification| NodeInput::value(TaggedValue::VectorModification(Box::new(modification)), false);
|
||||
let import = |import_index: usize| NodeInput::Import {
|
||||
import_type: concrete!(()),
|
||||
import_index,
|
||||
};
|
||||
let node = |inputs: Vec<NodeInput>| DocumentNode { inputs, ..Default::default() };
|
||||
|
||||
let [turning, other, group, reads_turned, reads_other] = [1, 2, 3, 4, 5].map(NodeId);
|
||||
let nested = NodeNetwork {
|
||||
exports: vec![NodeInput::node(reads_turned, 0)],
|
||||
nodes: [(reads_turned, node(vec![import(0), value(edited.clone())])), (reads_other, node(vec![import(1), value(edited)]))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [
|
||||
(turning, node(vec![value(turned)])),
|
||||
(other, node(Vec::new())),
|
||||
(
|
||||
group,
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(turning, 0), NodeInput::node(other, 0)],
|
||||
implementation: DocumentNodeImplementation::Network(nested),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let rewritten = modifications_following_turned_segments(&network);
|
||||
let rewritten_at = |node_id: NodeId| rewritten.iter().any(|(path, rewritten_id, ..)| path.as_slice() == [group] && *rewritten_id == node_id);
|
||||
assert!(rewritten_at(reads_turned));
|
||||
assert!(!rewritten_at(reads_other));
|
||||
}
|
||||
|
||||
// Values saved for Merge by Distance load as the methods of the Weld node it became
|
||||
#[test]
|
||||
fn merge_by_distance_values_load_as_weld_methods() {
|
||||
use graphene_std::vector::misc::WeldMethod;
|
||||
|
||||
let load = |json: &str| serde_json::from_str::<TaggedValue>(json).ok();
|
||||
assert_eq!(load(r#"{"MergeByDistanceAlgorithm":"Spatial"}"#), Some(TaggedValue::WeldMethod(WeldMethod::All)));
|
||||
assert_eq!(load(r#"{"MergeByDistanceAlgorithm":"Topological"}"#), Some(TaggedValue::WeldMethod(WeldMethod::Connected)));
|
||||
assert_eq!(load(r#"{"WeldMethod":"FlowEnds"}"#), Some(TaggedValue::WeldMethod(WeldMethod::FlowEnds)));
|
||||
}
|
||||
|
||||
// Every kind of Merge by Distance node older editors saved opens as a Weld node, with the method it had and Weld's own title and inputs
|
||||
#[test]
|
||||
fn merge_by_distance_nodes_open_as_weld_nodes() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::capture_logged_errors;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::vector::misc::WeldMethod;
|
||||
|
||||
let weld = graphene_std::vector::weld::IDENTIFIER;
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(weld.clone())).expect("the Weld definition should exist");
|
||||
let content = definition.default_node_template().inputs[0].clone();
|
||||
let distance = NodeInput::value(TaggedValue::Number(2.), false);
|
||||
|
||||
// Older nodes stored their title and input names, with any "Algorithm" choice saved here as a placeholder method
|
||||
let legacy_node = |identifier: &'static str, display_name: &str, placeholder_method: Option<WeldMethod>| {
|
||||
let mut inputs = vec![content.clone(), distance.clone()];
|
||||
inputs.extend(placeholder_method.map(|method| NodeInput::value(TaggedValue::WeldMethod(method), false)));
|
||||
let input_names: &[&str] = if placeholder_method.is_some() {
|
||||
&["Content", "Distance", "Algorithm"]
|
||||
} else {
|
||||
&["Source", "Distance"]
|
||||
};
|
||||
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs,
|
||||
display_name: display_name.to_string(),
|
||||
input_metadata: input_names.iter().map(|name| (*name, "").into()).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let legacy_nodes = [
|
||||
legacy_node("core_types::vector::MergeByDistanceNode", "Merge by Distance", Some(WeldMethod::All)),
|
||||
legacy_node("graphene_core::vector::MergeByDistanceNode", "Merge by Distance", Some(WeldMethod::Connected)),
|
||||
legacy_node("graphene_core::vector::MergeByDistanceNode", "Merge by Distance", None),
|
||||
legacy_node("graphene_core::vector::SpatialMergeByDistanceNode", "Spatial Merge by Distance", None),
|
||||
];
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
for (index, node_template) in legacy_nodes.into_iter().enumerate() {
|
||||
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
|
||||
}
|
||||
|
||||
// The placeholder methods are saved under the old value names, which load as the methods they became
|
||||
let mut serialized = document.serialize_document();
|
||||
assert!(!serialized.contains("WeldNode"), "the saved document should name only the old node identifiers");
|
||||
for (placeholder, saved) in [("All", "Topological"), ("Connected", "Spatial")] {
|
||||
let placeholder = format!(r#"{{"WeldMethod":"{placeholder}"}}"#);
|
||||
assert_eq!(serialized.matches(&placeholder).count(), 1);
|
||||
serialized = serialized.replace(&placeholder, &format!(r#"{{"MergeByDistanceAlgorithm":"{saved}"}}"#));
|
||||
}
|
||||
|
||||
let (opened, errors) = capture_logged_errors(|| load_legacy_document(serialized, &HashMapResourceStorage::new(), false));
|
||||
let opened = opened.expect("the document should open");
|
||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||
|
||||
let definition_inputs: Vec<(String, String)> = definition
|
||||
.node_template
|
||||
.input_metadata
|
||||
.iter()
|
||||
.map(|metadata| (metadata.persistent_metadata.input_name.clone(), metadata.persistent_metadata.input_description.clone()))
|
||||
.collect();
|
||||
assert_eq!(definition_inputs.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["Content", "Distance", "Method"]);
|
||||
|
||||
for (node_id, method) in [(1, WeldMethod::Connected), (2, WeldMethod::All), (3, WeldMethod::Connected), (4, WeldMethod::All)].map(|(id, method)| (NodeId(id), method)) {
|
||||
let interface = &opened.network_interface;
|
||||
let node = interface.document_node(&node_id, &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(weld.clone()), "node {node_id}");
|
||||
assert_eq!(node.inputs[1].as_value(), Some(&TaggedValue::Number(2.)), "node {node_id}");
|
||||
assert_eq!(node.inputs[2].as_value(), Some(&TaggedValue::WeldMethod(method)), "node {node_id}");
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Weld", "node {node_id}");
|
||||
|
||||
let inputs: Vec<(String, String)> = (0..node.inputs.len()).map(|index| interface.displayed_input_name_and_description(&node_id, index, &[])).collect();
|
||||
assert_eq!(inputs, definition_inputs, "node {node_id}");
|
||||
}
|
||||
}
|
||||
|
||||
// Cut Segments nodes open as Unweld nodes splitting every anchor, still wired to the node feeding them
|
||||
#[test]
|
||||
fn cut_segments_nodes_open_as_unweld_nodes() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::capture_logged_errors;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::vector::misc::UnweldMethod;
|
||||
|
||||
let unweld = graphene_std::vector::unweld::IDENTIFIER;
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(unweld.clone())).expect("the Unweld definition should exist");
|
||||
let rectangle = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)).expect("the Rectangle definition should exist");
|
||||
|
||||
// The current Cut Segments node and its oldest form, which stored their titles and single content input
|
||||
let content = definition.default_node_template().inputs[0].clone();
|
||||
let legacy_node = |identifier: &'static str, display_name: &str| NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![content.clone()],
|
||||
display_name: display_name.to_string(),
|
||||
input_metadata: vec![("Content", "").into()],
|
||||
..Default::default()
|
||||
};
|
||||
let (upstream, cut_segments, split_segments) = (NodeId(1), NodeId(2), NodeId(3));
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(upstream, rectangle.default_node_template(), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(cut_segments, legacy_node("core_types::vector::CutSegmentsNode", "Cut Segments"), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(split_segments, legacy_node("graphene_core::vector::vector_nodes::SplitSegmentsNode", "Split Segments"), &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(cut_segments, 0), NodeInput::node(upstream, 0), &[]);
|
||||
|
||||
let serialized = document.serialize_document();
|
||||
assert!(!serialized.contains("UnweldNode"), "the saved document should name only the old node identifiers");
|
||||
|
||||
let (opened, errors) = capture_logged_errors(|| load_legacy_document(serialized, &HashMapResourceStorage::new(), false));
|
||||
let mut opened = opened.expect("the document should open");
|
||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||
|
||||
let definition_inputs: Vec<(String, String)> = definition
|
||||
.node_template
|
||||
.input_metadata
|
||||
.iter()
|
||||
.map(|metadata| (metadata.persistent_metadata.input_name.clone(), metadata.persistent_metadata.input_description.clone()))
|
||||
.collect();
|
||||
for node_id in [cut_segments, split_segments] {
|
||||
let interface = &opened.network_interface;
|
||||
let node = interface.document_node(&node_id, &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(unweld.clone()), "node {node_id}");
|
||||
assert_eq!(
|
||||
node.inputs.get(1).and_then(|input| input.as_value()),
|
||||
Some(&TaggedValue::UnweldMethod(UnweldMethod::All)),
|
||||
"node {node_id}"
|
||||
);
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Unweld", "node {node_id}");
|
||||
|
||||
let inputs: Vec<(String, String)> = (0..node.inputs.len()).map(|index| interface.displayed_input_name_and_description(&node_id, index, &[])).collect();
|
||||
assert_eq!(inputs, definition_inputs, "node {node_id}");
|
||||
}
|
||||
|
||||
// The wire from the upstream node survives in both directions
|
||||
let cut_segments_content = opened.network_interface.document_node(&cut_segments, &[]).map(|node| node.inputs[0].clone());
|
||||
assert!(matches!(cut_segments_content, Some(NodeInput::Node { node_id, output_index: 0, .. }) if node_id == upstream));
|
||||
let outward_wires = opened.network_interface.outward_wires(&[]).and_then(|wires| wires.get(&OutputConnector::node(upstream, 0)).cloned());
|
||||
assert_eq!(outward_wires.as_deref(), Some([InputConnector::node_at_index(cut_segments, 0)].as_slice()));
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,7 @@ pub enum PortfolioMessage {
|
||||
ignore_hash: bool,
|
||||
},
|
||||
SubmitEyedropperPreviewRender,
|
||||
PollNodeGraphEvaluation,
|
||||
ToggleResetNodesToDefinitionsOnOpen,
|
||||
ToggleRulers,
|
||||
UpdateDocumentWidgets,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
|
||||
use super::utility_types::PanelType;
|
||||
use crate::application::{Editor, generate_uuid};
|
||||
use crate::application::{Environment, generate_uuid};
|
||||
use crate::consts::DEFAULT_DOCUMENT_NAME;
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledShortcut};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageContext;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
@@ -34,6 +35,7 @@ use std::vec;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct PortfolioMessageContext<'a> {
|
||||
pub environment: Environment,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub animation: &'a AnimationMessageHandler,
|
||||
@@ -45,7 +47,7 @@ pub struct PortfolioMessageContext<'a> {
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct PortfolioMessageHandler {
|
||||
pub documents: HashMap<DocumentId, DocumentMessageHandler>,
|
||||
loading_documents: HashMap<DocumentId, DocumentInfo>,
|
||||
@@ -69,6 +71,7 @@ pub struct PortfolioMessageHandler {
|
||||
impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for PortfolioMessageHandler {
|
||||
fn process_message(&mut self, message: PortfolioMessage, responses: &mut VecDeque<Message>, context: PortfolioMessageContext) {
|
||||
let PortfolioMessageContext {
|
||||
environment,
|
||||
ipp,
|
||||
preferences,
|
||||
animation,
|
||||
@@ -88,6 +91,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
{
|
||||
let document_inputs = DocumentMessageContext {
|
||||
document_id,
|
||||
environment,
|
||||
ipp,
|
||||
fonts: &self.fonts,
|
||||
executor: &mut self.executor,
|
||||
@@ -143,9 +147,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PersistentStateMessage::ReadState);
|
||||
|
||||
// Initialize the frontend with environment information
|
||||
responses.add(FrontendMessage::UpdatePlatform {
|
||||
platform: Editor::environment().into(),
|
||||
});
|
||||
responses.add(FrontendMessage::UpdatePlatform { platform: environment.into() });
|
||||
|
||||
// Before loading any documents, initially prepare the welcome screen buttons layout
|
||||
responses.add(PortfolioMessage::RequestWelcomeScreenButtonsLayout);
|
||||
@@ -162,16 +164,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// Request status bar info layout
|
||||
responses.add(PortfolioMessage::RequestStatusBarInfoLayout);
|
||||
|
||||
// Send shortcuts for widgets created in the frontend which need shortcut tooltips
|
||||
// Send shortcuts for widgets created in the frontend which need shortcut tooltips, labeled here since they bypass the layout system
|
||||
let shortcut = |keys: &[Key]| Some(ActionShortcut::Shortcut(LabeledShortcut::new(KeysGroup(keys.to_vec()), environment)));
|
||||
responses.add(FrontendMessage::SendShortcutFullscreen {
|
||||
shortcut: action_shortcut_manual!(Key::F11),
|
||||
shortcut_mac: action_shortcut_manual!(Key::Control, Key::Command, Key::KeyF),
|
||||
shortcut: shortcut(&[Key::F11]),
|
||||
shortcut_mac: shortcut(&[Key::Control, Key::Command, Key::KeyF]),
|
||||
});
|
||||
responses.add(FrontendMessage::SendShortcutAltClick {
|
||||
shortcut: action_shortcut_manual!(Key::Alt, Key::MouseLeft),
|
||||
shortcut: shortcut(&[Key::Alt, Key::MouseLeft]),
|
||||
});
|
||||
responses.add(FrontendMessage::SendShortcutShiftClick {
|
||||
shortcut: action_shortcut_manual!(Key::Shift, Key::MouseLeft),
|
||||
shortcut: shortcut(&[Key::Shift, Key::MouseLeft]),
|
||||
});
|
||||
|
||||
// Send the information for tooltips and categories for each node/input.
|
||||
@@ -185,6 +188,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
if let Some(document) = self.documents.get_mut(&document_id) {
|
||||
let document_inputs = DocumentMessageContext {
|
||||
document_id,
|
||||
environment,
|
||||
ipp,
|
||||
fonts: &self.fonts,
|
||||
executor: &mut self.executor,
|
||||
@@ -802,6 +806,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
return;
|
||||
}
|
||||
|
||||
// The document we are leaving won't get the frames that settle what glides in its graph, so it settles at once
|
||||
if self.active_document_id != Some(document_id)
|
||||
&& let Some(document) = self.active_document_mut()
|
||||
{
|
||||
document.node_graph_handler.stop_gliding(&document.network_interface, responses);
|
||||
}
|
||||
|
||||
// Auto-save the document we are leaving
|
||||
let mut node_graph_open = false;
|
||||
if let Some(document) = self.active_document() {
|
||||
@@ -994,6 +1005,19 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
Ok(message) => responses.add_front(message),
|
||||
}
|
||||
}
|
||||
PortfolioMessage::PollNodeGraphEvaluation => {
|
||||
let Some(document_id) = self.active_document_id else { return };
|
||||
let Some(active_document) = self.documents.get_mut(&document_id) else { return };
|
||||
|
||||
let dropped_thumbnails = self.executor.poll_node_graph_evaluation(active_document, document_id, responses);
|
||||
|
||||
// The runtime keeps the thumbnails of only the active document, rendering them all anew when another becomes active
|
||||
if !dropped_thumbnails.is_empty() {
|
||||
for (_, document) in self.documents.iter_mut().filter(|(id, _)| **id != document_id) {
|
||||
document.layers_in_view.forget_thumbnails_in_background(&dropped_thumbnails);
|
||||
}
|
||||
}
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
@@ -1050,12 +1074,25 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
|
||||
impl PortfolioMessageHandler {
|
||||
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
|
||||
Self { executor, ..Default::default() }
|
||||
}
|
||||
|
||||
pub fn set_document_store(&mut self, store: Arc<dyn document_container::store::DocumentStore>) {
|
||||
self.document_store = DocumentStoreHandle::new(store);
|
||||
pub fn new(executor: NodeGraphExecutor, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
|
||||
Self {
|
||||
documents: Default::default(),
|
||||
loading_documents: Default::default(),
|
||||
document_ids: Default::default(),
|
||||
active_document_id: Default::default(),
|
||||
failed_documents: Default::default(),
|
||||
persistent_state: Default::default(),
|
||||
fonts: Default::default(),
|
||||
ingest: Default::default(),
|
||||
executor,
|
||||
selection_mode: Default::default(),
|
||||
reset_node_definitions_on_open: Default::default(),
|
||||
workspace: Default::default(),
|
||||
document_store: DocumentStoreHandle::new(document_store),
|
||||
pending_opens: Default::default(),
|
||||
restore_select: Default::default(),
|
||||
store_unavailable: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1224,30 +1261,6 @@ impl PortfolioMessageHandler {
|
||||
self.document_ids.iter().position(|id| id == &document_id).expect("Active document is missing from document ids")
|
||||
}
|
||||
|
||||
pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
let Some(document_id) = self.active_document_id else {
|
||||
return Err("No active document".to_string());
|
||||
};
|
||||
let Some(active_document) = self.documents.get_mut(&document_id) else {
|
||||
return Err("No active document".to_string());
|
||||
};
|
||||
|
||||
let result = self.executor.poll_node_graph_evaluation(active_document, document_id, responses);
|
||||
if result.is_err() {
|
||||
let error = r#"
|
||||
<rect x="50%" y="50%" width="460" height="100" transform="translate(-230 -50)" rx="4" fill="var(--color-warning-yellow)" />
|
||||
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
|
||||
<tspan x="50%" dy="-24" font-weight="bold">The document cannot render in its current state.</tspan>
|
||||
<tspan x="50%" dy="24">Undo to go back, if available, or check for error details</tspan>
|
||||
<tspan x="50%" dy="24">by clicking the <tspan font-style="italic">Node Graph</tspan> button up at the top right.</tspan>
|
||||
/text>"#
|
||||
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
|
||||
.to_string();
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg: error });
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn document_details(&self, document_id: DocumentId) -> Option<DocumentInfo> {
|
||||
if let Some(document) = self.documents.get(&document_id) {
|
||||
Some(DocumentInfo {
|
||||
|
||||
@@ -16,7 +16,7 @@ pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage,
|
||||
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
|
||||
pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler};
|
||||
pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant};
|
||||
pub use crate::messages::future::{FutureMessage, FutureMessageContext, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
|
||||
pub use crate::messages::future::{FutureMessage, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, Wake};
|
||||
pub use crate::messages::input_mapper::key_mapping::{KeyMappingMessage, KeyMappingMessageContext, KeyMappingMessageDiscriminant, KeyMappingMessageHandler};
|
||||
pub use crate::messages::input_mapper::{InputMapperMessage, InputMapperMessageContext, InputMapperMessageDiscriminant, InputMapperMessageHandler};
|
||||
pub use crate::messages::input_preprocessor::{InputPreprocessorMessage, InputPreprocessorMessageContext, InputPreprocessorMessageDiscriminant, InputPreprocessorMessageHandler};
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::messages::tool::common_functionality::shapes::polygon_shape::PolygonG
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeGizmoHandler;
|
||||
use crate::messages::tool::common_functionality::shapes::spiral_shape::SpiralGizmoHandler;
|
||||
use crate::messages::tool::common_functionality::shapes::star_shape::StarGizmoHandler;
|
||||
use crate::messages::tool::common_functionality::snap_session::{SnapSession, SnapView};
|
||||
use glam::DVec2;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -89,14 +90,14 @@ impl ShapeGizmoHandlers {
|
||||
}
|
||||
|
||||
/// Updates the gizmo state while the user is dragging a handle (e.g., adjusting radius).
|
||||
pub fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque<Message>) {
|
||||
match self {
|
||||
Self::Star(h) => h.handle_update(drag_start, document, input, responses),
|
||||
Self::Polygon(h) => h.handle_update(drag_start, document, input, responses),
|
||||
Self::Arc(h) => h.handle_update(drag_start, document, input, responses),
|
||||
Self::Circle(h) => h.handle_update(drag_start, document, input, responses),
|
||||
Self::Grid(h) => h.handle_update(drag_start, document, input, responses),
|
||||
Self::Spiral(h) => h.handle_update(drag_start, document, input, responses),
|
||||
Self::Star(h) => h.handle_update(drag_start, view, snap_session, responses),
|
||||
Self::Polygon(h) => h.handle_update(drag_start, view, snap_session, responses),
|
||||
Self::Arc(h) => h.handle_update(drag_start, view, snap_session, responses),
|
||||
Self::Circle(h) => h.handle_update(drag_start, view, snap_session, responses),
|
||||
Self::Grid(h) => h.handle_update(drag_start, view, snap_session, responses),
|
||||
Self::Spiral(h) => h.handle_update(drag_start, view, snap_session, responses),
|
||||
Self::None => {}
|
||||
}
|
||||
}
|
||||
@@ -269,9 +270,9 @@ impl GizmoManager {
|
||||
}
|
||||
|
||||
/// Passes drag update data to the active gizmo to update shape parameters live.
|
||||
pub fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque<Message>) {
|
||||
if let Some(handle) = &mut self.active_shape_handler {
|
||||
handle.handle_update(drag_start, document, input, responses);
|
||||
handle.handle_update(drag_start, view, snap_session, responses);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+78
-8
@@ -4,10 +4,11 @@ use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::prelude::{FrontendMessage, Responses};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_arc_id, get_stroke_width};
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_arc_parameters, extract_circle_radius};
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_arc_parameters, extract_circle_radius, extract_polygon_parameters, extract_star_parameters};
|
||||
use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -16,6 +17,9 @@ use graphene_std::core_types::FallibleVec2Operations;
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
/// How many of the round shapes nearest the dragged one offer their radius to snap to.
|
||||
const MAX_EQUAL_RADII: usize = 32;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub enum RadiusHandleState {
|
||||
#[default]
|
||||
@@ -28,6 +32,10 @@ pub enum RadiusHandleState {
|
||||
pub struct RadiusHandle {
|
||||
pub layer: Option<LayerNodeIdentifier>,
|
||||
initial_radius: f64,
|
||||
/// The radius the pointer asks for, before any snap.
|
||||
free_radius: f64,
|
||||
/// The radii of the other round shapes, gathered once a drag begins.
|
||||
equal_radii: Option<Vec<ValueCandidate>>,
|
||||
handle_state: RadiusHandleState,
|
||||
angle: f64,
|
||||
previous_mouse_position: DVec2,
|
||||
@@ -37,6 +45,7 @@ impl RadiusHandle {
|
||||
pub fn cleanup(&mut self) {
|
||||
self.handle_state = RadiusHandleState::Inactive;
|
||||
self.layer = None;
|
||||
self.equal_radii = None;
|
||||
}
|
||||
|
||||
pub fn hovered(&self) -> bool {
|
||||
@@ -98,6 +107,7 @@ impl RadiusHandle {
|
||||
if Self::check_if_inside_dash_lines(angle, mouse_position, viewport, radius.abs(), document, layer) {
|
||||
self.layer = Some(layer);
|
||||
self.initial_radius = radius;
|
||||
self.free_radius = radius;
|
||||
self.previous_mouse_position = mouse_position;
|
||||
self.angle = angle;
|
||||
|
||||
@@ -148,10 +158,11 @@ impl RadiusHandle {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_inner_radius(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>, drag_start: DVec2) {
|
||||
pub fn update_inner_radius(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque<Message>, drag_start: DVec2) {
|
||||
let SnapView { document, input, .. } = view;
|
||||
let Some(layer) = self.layer else { return };
|
||||
|
||||
// This gizmo serves both Circle and Arc layers, so resolve which node is present to know whose radius parameter to write
|
||||
// This gizmo serves both Circle and Arc layers, so resolve which node is present to know which radius parameter to write
|
||||
let (node_id, radius_parameter) = if let Some(node_id) = graph_modification_utils::get_circle_id(layer, &document.network_interface) {
|
||||
(node_id, ParameterRef::from(graphene_std::vector::generator_nodes::circle::RadiusInput))
|
||||
} else if let Some(node_id) = get_arc_id(layer, &document.network_interface) {
|
||||
@@ -159,9 +170,6 @@ impl RadiusHandle {
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
let Some(current_radius) = extract_circle_radius(layer, document).or(extract_arc_parameters(Some(layer), document).map(|(r, _, _, _)| r)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport_transform = document.network_interface.document_metadata().transform_to_viewport(layer);
|
||||
let center = viewport_transform.transform_point2(DVec2::ZERO);
|
||||
@@ -173,14 +181,76 @@ impl RadiusHandle {
|
||||
let net_delta = delta_vector.length() * sign * self.initial_radius.signum();
|
||||
self.previous_mouse_position = input.mouse.position;
|
||||
|
||||
// Kept apart from the radius written, which a snap may have moved
|
||||
self.free_radius += net_delta;
|
||||
|
||||
// The handle is where the pointer took hold of the rim, which moves out along that angle as the radius grows
|
||||
let spoke = calculate_circle_point_position(self.angle, 1.);
|
||||
let equal_radii = self.equal_radii.get_or_insert_with(|| equal_radius_candidates(document, layer, spoke));
|
||||
let on_screen_per_unit = viewport_transform.transform_vector2(spoke).length();
|
||||
let to_document = document.metadata().document_to_viewport.inverse() * viewport_transform;
|
||||
let position_of = |radius: f64| to_document.transform_point2(spoke * radius);
|
||||
|
||||
// The size is snapped, which keeps whichever sign the radius has come to
|
||||
let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum();
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, radius_parameter),
|
||||
input: NodeInput::value(TaggedValue::Number(current_radius + net_delta), false),
|
||||
input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sizes of the radii of the visible circles, arcs, polygons, and stars nearest a dragged one, in its units.
|
||||
/// Each is measured in document space along the dragged handle's spoke, since a stretched shape reaches a different distance in each direction.
|
||||
/// O(n) in the document's layers.
|
||||
fn equal_radius_candidates(document: &DocumentMessageHandler, dragged: LayerNodeIdentifier, spoke: DVec2) -> Vec<ValueCandidate> {
|
||||
let metadata = document.metadata();
|
||||
|
||||
// The spoke's direction in document space, and how far the handle moves along it per unit of radius
|
||||
let dragged_to_document = metadata.transform_to_document(dragged);
|
||||
let document_spoke = dragged_to_document.transform_vector2(spoke);
|
||||
let Some(direction) = document_spoke.try_normalize() else { return Vec::new() };
|
||||
let dragged_scale = document_spoke.length();
|
||||
let dragged_center = dragged_to_document.transform_point2(DVec2::ZERO);
|
||||
|
||||
// A star offers its outer radius
|
||||
let radius_of = |layer: LayerNodeIdentifier| {
|
||||
extract_circle_radius(layer, document)
|
||||
.or_else(|| extract_arc_parameters(Some(layer), document).map(|(radius, ..)| radius))
|
||||
.or_else(|| extract_polygon_parameters(Some(layer), document).map(|(_, radius)| radius))
|
||||
.or_else(|| extract_star_parameters(Some(layer), document).map(|(_, radius1, radius2)| radius1.abs().max(radius2.abs())))
|
||||
};
|
||||
|
||||
let mut nearest: Vec<(f64, ValueCandidate)> = metadata
|
||||
.all_layers()
|
||||
.filter(|&layer| layer != dragged && document.network_interface.is_layer_visible(layer))
|
||||
.filter_map(|layer| {
|
||||
// The rim lies a radius out in the layer's own space, where the direction has its own length
|
||||
let to_document = metadata.transform_to_document(layer);
|
||||
if to_document.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
let rim_along_direction = radius_of(layer)?.abs() / to_document.matrix2.inverse().mul_vec2(direction).length();
|
||||
let value = rim_along_direction / dragged_scale;
|
||||
let distance = to_document.transform_point2(DVec2::ZERO).distance(dragged_center);
|
||||
let candidate = ValueCandidate {
|
||||
value,
|
||||
kind: Kind::EqualRadius,
|
||||
identity: layer.to_node().0,
|
||||
};
|
||||
(value.is_finite() && value != 0.).then_some((distance, candidate))
|
||||
})
|
||||
.collect();
|
||||
|
||||
if nearest.len() > MAX_EQUAL_RADII {
|
||||
nearest.select_nth_unstable_by(MAX_EQUAL_RADII, |a, b| a.0.total_cmp(&b.0));
|
||||
nearest.truncate(MAX_EQUAL_RADII);
|
||||
}
|
||||
nearest.into_iter().map(|(_, candidate)| candidate).collect()
|
||||
}
|
||||
|
||||
fn calculate_circle_point_position(theta: f64, radius: f64) -> DVec2 {
|
||||
DVec2::new(radius * theta.cos(), -radius * theta.sin())
|
||||
}
|
||||
+41
-26
@@ -1,5 +1,5 @@
|
||||
use crate::consts::COLOR_OVERLAY_RED;
|
||||
use crate::consts::GIZMO_HIDE_THRESHOLD;
|
||||
use crate::consts::{COLOR_OVERLAY_RED, POINT_RADIUS_HANDLE_SNAP_THRESHOLD};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
@@ -7,11 +7,12 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::{overlays::utility_types::OverlayContext, utility_types::network_interface::InputConnector};
|
||||
use crate::messages::prelude::FrontendMessage;
|
||||
use crate::messages::prelude::Responses;
|
||||
use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{draw_snapping_ticks, extract_polygon_parameters, polygon_outline, polygon_vertex_position, star_outline};
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_star_parameters, star_vertex_position};
|
||||
use glam::DVec2;
|
||||
use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::ParameterRef;
|
||||
@@ -397,29 +398,41 @@ impl PointRadiusHandle {
|
||||
snap_radii
|
||||
}
|
||||
|
||||
fn check_snapping(&self, new_radius: f64, original_radius: f64) -> Option<(usize, f64)> {
|
||||
self.snap_radii
|
||||
/// Snaps a radius to the ones in `snap_radii`, judged by how far the handle moves along its spoke on screen.
|
||||
fn snap_radius(&self, view: SnapView, snap_session: &mut SnapSession, layer: LayerNodeIdentifier, free_radius: f64) -> f64 {
|
||||
let document = view.document;
|
||||
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
|
||||
let point = self.point as i32;
|
||||
|
||||
// The unit spoke the handle moves along in the layer's space
|
||||
let spoke = if let Some((sides, _, _)) = extract_star_parameters(Some(layer), document) {
|
||||
star_vertex_position(DAffine2::IDENTITY, point, sides, 1., 1.)
|
||||
} else if let Some((sides, _)) = extract_polygon_parameters(Some(layer), document) {
|
||||
polygon_vertex_position(DAffine2::IDENTITY, point, sides, 1.)
|
||||
} else {
|
||||
return free_radius;
|
||||
};
|
||||
|
||||
// The first two radii give the star right-angled tips, and the rest line the tips up with other vertices
|
||||
let candidates: Vec<ValueCandidate> = self
|
||||
.snap_radii
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, rad)| (**rad - new_radius).abs() < POINT_RADIUS_HANDLE_SNAP_THRESHOLD)
|
||||
.min_by(|(i_a, a), (i_b, b)| {
|
||||
let dist_a = (**a - new_radius).abs();
|
||||
let dist_b = (**b - new_radius).abs();
|
||||
|
||||
// Check if either index is 0 or 1 and prioritize them
|
||||
match (*i_a == 0 || *i_a == 1, *i_b == 0 || *i_b == 1) {
|
||||
// `a` is priority index, `b` is not
|
||||
(true, false) => std::cmp::Ordering::Less,
|
||||
// `b` is priority index, `a` is not
|
||||
(false, true) => std::cmp::Ordering::Greater,
|
||||
// Normal comparison
|
||||
_ => dist_a.partial_cmp(&dist_b).unwrap_or(std::cmp::Ordering::Equal),
|
||||
}
|
||||
.map(|(index, &value)| ValueCandidate {
|
||||
value,
|
||||
kind: if index < 2 { Kind::RightAngle } else { Kind::Through },
|
||||
identity: index as u64,
|
||||
})
|
||||
.map(|(i, rad)| (i, *rad - original_radius))
|
||||
.collect();
|
||||
|
||||
let on_screen_per_unit = layer_to_viewport.transform_vector2(spoke).length();
|
||||
let to_document = document.metadata().document_to_viewport.inverse() * layer_to_viewport;
|
||||
let position_of = |radius: f64| to_document.transform_point2(spoke * radius);
|
||||
snap_session.snap_value(view, position_of, free_radius, on_screen_per_unit, &candidates)
|
||||
}
|
||||
|
||||
pub fn update_inner_radius(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>, drag_start: DVec2) {
|
||||
pub fn update_inner_radius(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque<Message>, drag_start: DVec2) {
|
||||
let SnapView { document, input, .. } = view;
|
||||
let Some(layer) = self.layer else { return };
|
||||
let Some(radius_parameter) = self.radius_parameter.clone() else { return };
|
||||
|
||||
@@ -438,21 +451,23 @@ impl PointRadiusHandle {
|
||||
let projection = delta.project_onto(radius);
|
||||
let sign = radius.dot(delta).signum();
|
||||
|
||||
let mut net_delta = projection.length() * sign * original_radius.signum();
|
||||
let net_delta = projection.length() * sign * original_radius.signum();
|
||||
let new_radius = original_radius + net_delta;
|
||||
|
||||
self.update_state(PointRadiusHandleState::Dragging);
|
||||
|
||||
self.check_if_radius_flipped(original_radius, new_radius, document, layer, &radius_parameter);
|
||||
|
||||
if let Some((index, snapped_delta)) = self.check_snapping(new_radius, original_radius) {
|
||||
net_delta = snapped_delta;
|
||||
self.update_state(PointRadiusHandleState::Snapped(index));
|
||||
// A snap's identity is the index of its radius, which picks the guides drawn for it
|
||||
let snapped_radius = self.snap_radius(view, snap_session, layer, new_radius);
|
||||
let engaged = snap_session.shown().and_then(|shown| shown.outcome.engaged_candidates().next());
|
||||
if let Some(candidate) = engaged {
|
||||
self.update_state(PointRadiusHandleState::Snapped(candidate.key.identity[0] as usize));
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, radius_parameter),
|
||||
input: NodeInput::value(TaggedValue::Number(original_radius + net_delta), false),
|
||||
input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user